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.

279354 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  213. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  214. */
  215. #ifndef JUCE_DIRECT2D
  216. #define JUCE_DIRECT2D 0
  217. #endif
  218. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  219. If your app doesn't need to read FLAC files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_FLAC
  223. #define JUCE_USE_FLAC 1
  224. #endif
  225. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  226. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  227. reduce the size of your codebase and build time.
  228. */
  229. #ifndef JUCE_USE_OGGVORBIS
  230. #define JUCE_USE_OGGVORBIS 1
  231. #endif
  232. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-burning, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  237. #define JUCE_USE_CDBURNER 0
  238. #endif
  239. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  240. Unless you're using CD-reading, you should probably turn this flag off to
  241. reduce code size.
  242. */
  243. #ifndef JUCE_USE_CDREADER
  244. #define JUCE_USE_CDREADER 0
  245. #endif
  246. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  247. */
  248. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  249. #define JUCE_USE_CAMERA 0
  250. #endif
  251. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  252. gets repainted will flash in a random colour, so that you can check exactly how much and how
  253. often your components are being drawn.
  254. */
  255. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  256. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  257. #endif
  258. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  259. Unless you specifically want to disable this, it's best to leave this option turned on.
  260. */
  261. #ifndef JUCE_USE_XINERAMA
  262. #define JUCE_USE_XINERAMA 1
  263. #endif
  264. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  265. turned on unless you have a good reason to disable it.
  266. */
  267. #ifndef JUCE_USE_XSHM
  268. #define JUCE_USE_XSHM 1
  269. #endif
  270. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  271. */
  272. #ifndef JUCE_USE_XRENDER
  273. #define JUCE_USE_XRENDER 0
  274. #endif
  275. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  276. unless you have a good reason to disable it.
  277. */
  278. #ifndef JUCE_USE_XCURSOR
  279. #define JUCE_USE_XCURSOR 1
  280. #endif
  281. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  282. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  283. you're building a plugin hosting app.
  284. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  285. */
  286. #ifndef JUCE_PLUGINHOST_VST
  287. #define JUCE_PLUGINHOST_VST 0
  288. #endif
  289. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  290. of course, and should only be enabled if you're building a plugin hosting app.
  291. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  292. */
  293. #ifndef JUCE_PLUGINHOST_AU
  294. #define JUCE_PLUGINHOST_AU 0
  295. #endif
  296. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  297. This should be enabled if you're writing a console application.
  298. */
  299. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  300. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  301. #endif
  302. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  303. If you're not using any embedded web-pages, turning this off may reduce your code size.
  304. */
  305. #ifndef JUCE_WEB_BROWSER
  306. #define JUCE_WEB_BROWSER 1
  307. #endif
  308. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  309. Carbon isn't required for a normal app, but may be needed by specialised classes like
  310. plugin-hosts, which support older APIs.
  311. */
  312. #ifndef JUCE_SUPPORT_CARBON
  313. #define JUCE_SUPPORT_CARBON 1
  314. #endif
  315. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  316. You might need to tweak this if you're linking to an external zlib library in your app,
  317. but for normal apps, this option should be left alone.
  318. */
  319. #ifndef JUCE_INCLUDE_ZLIB_CODE
  320. #define JUCE_INCLUDE_ZLIB_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_FLAC_CODE
  323. #define JUCE_INCLUDE_FLAC_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  326. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  327. #endif
  328. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  329. #define JUCE_INCLUDE_PNGLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  332. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  333. #endif
  334. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  335. (Currently, this only affects Windows builds in debug mode).
  336. */
  337. #ifndef JUCE_CHECK_MEMORY_LEAKS
  338. #define JUCE_CHECK_MEMORY_LEAKS 1
  339. #endif
  340. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  341. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  342. are passed to the JUCEApplication::unhandledException() callback for logging.
  343. */
  344. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  345. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  346. #endif
  347. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  348. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  349. #undef JUCE_QUICKTIME
  350. #define JUCE_QUICKTIME 0
  351. #undef JUCE_OPENGL
  352. #define JUCE_OPENGL 0
  353. #undef JUCE_USE_CDBURNER
  354. #define JUCE_USE_CDBURNER 0
  355. #undef JUCE_USE_CDREADER
  356. #define JUCE_USE_CDREADER 0
  357. #undef JUCE_WEB_BROWSER
  358. #define JUCE_WEB_BROWSER 0
  359. #undef JUCE_PLUGINHOST_AU
  360. #define JUCE_PLUGINHOST_AU 0
  361. #undef JUCE_PLUGINHOST_VST
  362. #define JUCE_PLUGINHOST_VST 0
  363. #endif
  364. #endif
  365. /*** End of inlined file: juce_Config.h ***/
  366. // FORCE_AMALGAMATOR_INCLUDE
  367. #ifndef JUCE_BUILD_CORE
  368. #define JUCE_BUILD_CORE 1
  369. #endif
  370. #ifndef JUCE_BUILD_MISC
  371. #define JUCE_BUILD_MISC 1
  372. #endif
  373. #ifndef JUCE_BUILD_GUI
  374. #define JUCE_BUILD_GUI 1
  375. #endif
  376. #ifndef JUCE_BUILD_NATIVE
  377. #define JUCE_BUILD_NATIVE 1
  378. #endif
  379. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  380. #undef JUCE_BUILD_MISC
  381. #undef JUCE_BUILD_GUI
  382. #endif
  383. //==============================================================================
  384. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  385. #if JUCE_WINDOWS
  386. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  387. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  388. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  389. #ifndef STRICT
  390. #define STRICT 1
  391. #endif
  392. #undef WIN32_LEAN_AND_MEAN
  393. #define WIN32_LEAN_AND_MEAN 1
  394. #if JUCE_MSVC
  395. #pragma warning (push)
  396. #pragma warning (disable : 4100 4201 4514 4312 4995)
  397. #endif
  398. #define _WIN32_WINNT 0x0500
  399. #define _UNICODE 1
  400. #define UNICODE 1
  401. #ifndef _WIN32_IE
  402. #define _WIN32_IE 0x0400
  403. #endif
  404. #include <windows.h>
  405. #include <windowsx.h>
  406. #include <commdlg.h>
  407. #include <shellapi.h>
  408. #include <mmsystem.h>
  409. #include <vfw.h>
  410. #include <tchar.h>
  411. #include <stddef.h>
  412. #include <ctime>
  413. #include <wininet.h>
  414. #include <nb30.h>
  415. #include <iphlpapi.h>
  416. #include <mapi.h>
  417. #include <float.h>
  418. #include <process.h>
  419. #include <Exdisp.h>
  420. #include <exdispid.h>
  421. #include <shlobj.h>
  422. #if ! JUCE_MINGW
  423. #include <crtdbg.h>
  424. #include <comutil.h>
  425. #endif
  426. #if JUCE_OPENGL
  427. #include <gl/gl.h>
  428. #endif
  429. #undef PACKED
  430. #if JUCE_ASIO
  431. /*
  432. This is very frustrating - we only need to use a handful of definitions from
  433. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  434. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  435. implementation...
  436. ..unfortunately that would break Steinberg's license agreement for use of
  437. their SDK, so I'm not allowed to do this.
  438. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  439. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  440. (see www.steinberg.net/Steinberg/Developers.asp).
  441. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  442. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  443. if you prefer). Make sure that your header search path will find the
  444. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  445. files are actually needed - so to simplify things, you could just copy
  446. these into your JUCE directory).
  447. If you're compiling and you get an error here because you don't have the
  448. ASIO SDK installed, you can disable ASIO support by commenting-out the
  449. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  450. */
  451. #include "iasiodrv.h"
  452. #endif
  453. #if JUCE_USE_CDBURNER
  454. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  455. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  456. flag in juce_Config.h to avoid these includes.
  457. */
  458. #include <imapi.h>
  459. #include <imapierror.h>
  460. #endif
  461. #if JUCE_USE_CAMERA
  462. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  463. These files are provided in the normal Windows SDK, but some Microsoft plonker
  464. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  465. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  466. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  467. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  468. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  469. The dummy file just needs to contain the following content:
  470. #define __IDxtCompositor_INTERFACE_DEFINED__
  471. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  472. #define __IDxtJpeg_INTERFACE_DEFINED__
  473. #define __IDxtKey_INTERFACE_DEFINED__
  474. ..and that should be enough to convince qedit.h that you have the SDK!
  475. */
  476. #include <dshow.h>
  477. #include <qedit.h>
  478. #include <dshowasf.h>
  479. #endif
  480. #if JUCE_WASAPI
  481. #include <MMReg.h>
  482. #include <mmdeviceapi.h>
  483. #include <Audioclient.h>
  484. #include <Avrt.h>
  485. #include <functiondiscoverykeys.h>
  486. #endif
  487. #if JUCE_QUICKTIME
  488. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  489. add its header directory to your include path.
  490. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  491. flag in juce_Config.h
  492. */
  493. #include <Movies.h>
  494. #include <QTML.h>
  495. #include <QuickTimeComponents.h>
  496. #include <MediaHandlers.h>
  497. #include <ImageCodec.h>
  498. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  499. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  500. your include search path to make these import statements work.
  501. */
  502. #import <QTOLibrary.dll>
  503. #import <QTOControl.dll>
  504. #endif
  505. #if JUCE_MSVC
  506. #pragma warning (pop)
  507. #endif
  508. #if JUCE_DIRECT2D
  509. #include <d2d1.h>
  510. #include <dwrite.h>
  511. #endif
  512. /** A simple COM smart pointer.
  513. Avoids having to include ATL just to get one of these.
  514. */
  515. template <class ComClass>
  516. class ComSmartPtr
  517. {
  518. public:
  519. ComSmartPtr() throw() : p (0) {}
  520. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  521. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  522. ~ComSmartPtr() { if (p != 0) p->Release(); }
  523. operator ComClass*() const throw() { return p; }
  524. ComClass& operator*() const throw() { return *p; }
  525. ComClass** operator&() throw() { return &p; }
  526. ComClass* operator->() const throw() { return p; }
  527. ComClass* operator= (ComClass* const newP)
  528. {
  529. if (newP != 0) newP->AddRef();
  530. if (p != 0) p->Release();
  531. p = newP;
  532. return newP;
  533. }
  534. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  535. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  536. {
  537. #ifndef __MINGW32__
  538. operator= (0);
  539. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  540. #else
  541. return S_FALSE;
  542. #endif
  543. }
  544. private:
  545. ComClass* p;
  546. };
  547. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  548. */
  549. template <class ComClass>
  550. class ComBaseClassHelper : public ComClass
  551. {
  552. public:
  553. ComBaseClassHelper() : refCount (1) {}
  554. virtual ~ComBaseClassHelper() {}
  555. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  556. {
  557. #ifndef __MINGW32__
  558. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  559. #endif
  560. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  561. *result = 0;
  562. return E_NOINTERFACE;
  563. }
  564. ULONG __stdcall AddRef() { return ++refCount; }
  565. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  566. protected:
  567. int refCount;
  568. };
  569. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  570. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  571. #elif JUCE_LINUX
  572. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  573. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  574. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  575. /*
  576. This file wraps together all the linux-specific headers, so
  577. that we can include them all just once, and compile all our
  578. platform-specific stuff in one big lump, keeping it out of the
  579. way of the rest of the codebase.
  580. */
  581. #include <sched.h>
  582. #include <pthread.h>
  583. #include <sys/time.h>
  584. #include <errno.h>
  585. #include <sys/stat.h>
  586. #include <sys/dir.h>
  587. #include <sys/ptrace.h>
  588. #include <sys/vfs.h>
  589. #include <sys/wait.h>
  590. #include <fnmatch.h>
  591. #include <utime.h>
  592. #include <pwd.h>
  593. #include <fcntl.h>
  594. #include <dlfcn.h>
  595. #include <netdb.h>
  596. #include <arpa/inet.h>
  597. #include <netinet/in.h>
  598. #include <sys/types.h>
  599. #include <sys/ioctl.h>
  600. #include <sys/socket.h>
  601. #include <net/if.h>
  602. #include <sys/sysinfo.h>
  603. #include <sys/file.h>
  604. #include <signal.h>
  605. /* Got a build error here? You'll need to install the freetype library...
  606. The name of the package to install is "libfreetype6-dev".
  607. */
  608. #include <ft2build.h>
  609. #include FT_FREETYPE_H
  610. #include <X11/Xlib.h>
  611. #include <X11/Xatom.h>
  612. #include <X11/Xresource.h>
  613. #include <X11/Xutil.h>
  614. #include <X11/Xmd.h>
  615. #include <X11/keysym.h>
  616. #include <X11/cursorfont.h>
  617. #if JUCE_USE_XINERAMA
  618. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  619. #include <X11/extensions/Xinerama.h>
  620. #endif
  621. #if JUCE_USE_XSHM
  622. #include <X11/extensions/XShm.h>
  623. #include <sys/shm.h>
  624. #include <sys/ipc.h>
  625. #endif
  626. #if JUCE_USE_XRENDER
  627. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  628. #include <X11/extensions/Xrender.h>
  629. #include <X11/extensions/Xcomposite.h>
  630. #endif
  631. #if JUCE_USE_XCURSOR
  632. // If you're missing this header, try installing the libxcursor-dev package
  633. #include <X11/Xcursor/Xcursor.h>
  634. #endif
  635. #if JUCE_OPENGL
  636. /* Got an include error here?
  637. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  638. and "freeglut3-dev".
  639. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  640. want to disable it.
  641. */
  642. #include <GL/glx.h>
  643. #endif
  644. #undef KeyPress
  645. #if JUCE_ALSA
  646. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  647. not got your paths set up correctly to find its header files.
  648. The package you need to install to get ASLA support is "libasound2-dev".
  649. If you don't have the ALSA library and don't want to build Juce with audio support,
  650. just disable the JUCE_ALSA flag in juce_Config.h
  651. */
  652. #include <alsa/asoundlib.h>
  653. #endif
  654. #if JUCE_JACK
  655. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  656. installed, or you've not got your paths set up correctly to find its header files.
  657. The package you need to install to get JACK support is "libjack-dev".
  658. If you don't have the jack-audio-connection-kit library and don't want to build
  659. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  660. */
  661. #include <jack/jack.h>
  662. //#include <jack/transport.h>
  663. #endif
  664. #undef SIZEOF
  665. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  666. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  667. #elif JUCE_MAC || JUCE_IPHONE
  668. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  669. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  670. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  671. /*
  672. This file wraps together all the mac-specific code, so that
  673. we can include all the native headers just once, and compile all our
  674. platform-specific stuff in one big lump, keeping it out of the way of
  675. the rest of the codebase.
  676. */
  677. #define USE_COREGRAPHICS_RENDERING 1
  678. #if JUCE_IOS
  679. #import <Foundation/Foundation.h>
  680. #import <UIKit/UIKit.h>
  681. #import <AudioToolbox/AudioToolbox.h>
  682. #import <AVFoundation/AVFoundation.h>
  683. #import <CoreData/CoreData.h>
  684. #import <MobileCoreServices/MobileCoreServices.h>
  685. #import <QuartzCore/QuartzCore.h>
  686. #include <sys/fcntl.h>
  687. #if JUCE_OPENGL
  688. #include <OpenGLES/ES1/gl.h>
  689. #include <OpenGLES/ES1/glext.h>
  690. #endif
  691. #else
  692. #import <Cocoa/Cocoa.h>
  693. #import <CoreAudio/HostTime.h>
  694. #import <CoreAudio/AudioHardware.h>
  695. #import <CoreMIDI/MIDIServices.h>
  696. #import <QTKit/QTKit.h>
  697. #import <WebKit/WebKit.h>
  698. #import <DiscRecording/DiscRecording.h>
  699. #import <IOKit/IOKitLib.h>
  700. #import <IOKit/IOCFPlugIn.h>
  701. #import <IOKit/hid/IOHIDLib.h>
  702. #import <IOKit/hid/IOHIDKeys.h>
  703. #import <IOKit/pwr_mgt/IOPMLib.h>
  704. #include <Carbon/Carbon.h>
  705. #include <sys/dir.h>
  706. #endif
  707. #include <sys/socket.h>
  708. #include <sys/sysctl.h>
  709. #include <sys/stat.h>
  710. #include <sys/param.h>
  711. #include <sys/mount.h>
  712. #include <fnmatch.h>
  713. #include <utime.h>
  714. #include <dlfcn.h>
  715. #include <ifaddrs.h>
  716. #include <net/if_dl.h>
  717. #include <mach/mach_time.h>
  718. #include <mach-o/dyld.h>
  719. #if MACOS_10_4_OR_EARLIER
  720. #include <GLUT/glut.h>
  721. #endif
  722. #if ! CGFLOAT_DEFINED
  723. #define CGFloat float
  724. #endif
  725. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  726. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  727. #else
  728. #error "Unknown platform!"
  729. #endif
  730. #endif
  731. //==============================================================================
  732. #define DONT_SET_USING_JUCE_NAMESPACE 1
  733. #undef max
  734. #undef min
  735. #define NO_DUMMY_DECL
  736. #if JUCE_BUILD_NATIVE
  737. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  738. #endif
  739. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  740. #pragma warning (disable: 4309 4305)
  741. #endif
  742. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  743. BEGIN_JUCE_NAMESPACE
  744. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  745. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  746. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  747. /**
  748. Creates a floating carbon window that can be used to hold a carbon UI.
  749. This is a handy class that's designed to be inlined where needed, e.g.
  750. in the audio plugin hosting code.
  751. */
  752. class CarbonViewWrapperComponent : public Component,
  753. public ComponentMovementWatcher,
  754. public Timer
  755. {
  756. public:
  757. CarbonViewWrapperComponent()
  758. : ComponentMovementWatcher (this),
  759. wrapperWindow (0),
  760. embeddedView (0),
  761. recursiveResize (false)
  762. {
  763. }
  764. virtual ~CarbonViewWrapperComponent()
  765. {
  766. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  767. }
  768. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  769. virtual void removeView (HIViewRef embeddedView) = 0;
  770. virtual void mouseDown (int, int) {}
  771. virtual void paint() {}
  772. virtual bool getEmbeddedViewSize (int& w, int& h)
  773. {
  774. if (embeddedView == 0)
  775. return false;
  776. HIRect bounds;
  777. HIViewGetBounds (embeddedView, &bounds);
  778. w = jmax (1, roundToInt (bounds.size.width));
  779. h = jmax (1, roundToInt (bounds.size.height));
  780. return true;
  781. }
  782. void createWindow()
  783. {
  784. if (wrapperWindow == 0)
  785. {
  786. Rect r;
  787. r.left = getScreenX();
  788. r.top = getScreenY();
  789. r.right = r.left + getWidth();
  790. r.bottom = r.top + getHeight();
  791. CreateNewWindow (kDocumentWindowClass,
  792. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  793. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  794. &r, &wrapperWindow);
  795. jassert (wrapperWindow != 0);
  796. if (wrapperWindow == 0)
  797. return;
  798. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  799. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  800. [ownerWindow addChildWindow: carbonWindow
  801. ordered: NSWindowAbove];
  802. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  803. EventTypeSpec windowEventTypes[] =
  804. {
  805. { kEventClassWindow, kEventWindowGetClickActivation },
  806. { kEventClassWindow, kEventWindowHandleDeactivate },
  807. { kEventClassWindow, kEventWindowBoundsChanging },
  808. { kEventClassMouse, kEventMouseDown },
  809. { kEventClassMouse, kEventMouseMoved },
  810. { kEventClassMouse, kEventMouseDragged },
  811. { kEventClassMouse, kEventMouseUp},
  812. { kEventClassWindow, kEventWindowDrawContent },
  813. { kEventClassWindow, kEventWindowShown },
  814. { kEventClassWindow, kEventWindowHidden }
  815. };
  816. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  817. InstallWindowEventHandler (wrapperWindow, upp,
  818. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  819. windowEventTypes, this, &eventHandlerRef);
  820. setOurSizeToEmbeddedViewSize();
  821. setEmbeddedWindowToOurSize();
  822. creationTime = Time::getCurrentTime();
  823. }
  824. }
  825. void deleteWindow()
  826. {
  827. removeView (embeddedView);
  828. embeddedView = 0;
  829. if (wrapperWindow != 0)
  830. {
  831. RemoveEventHandler (eventHandlerRef);
  832. DisposeWindow (wrapperWindow);
  833. wrapperWindow = 0;
  834. }
  835. }
  836. void setOurSizeToEmbeddedViewSize()
  837. {
  838. int w, h;
  839. if (getEmbeddedViewSize (w, h))
  840. {
  841. if (w != getWidth() || h != getHeight())
  842. {
  843. startTimer (50);
  844. setSize (w, h);
  845. if (getParentComponent() != 0)
  846. getParentComponent()->setSize (w, h);
  847. }
  848. else
  849. {
  850. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  851. }
  852. }
  853. else
  854. {
  855. stopTimer();
  856. }
  857. }
  858. void setEmbeddedWindowToOurSize()
  859. {
  860. if (! recursiveResize)
  861. {
  862. recursiveResize = true;
  863. if (embeddedView != 0)
  864. {
  865. HIRect r;
  866. r.origin.x = 0;
  867. r.origin.y = 0;
  868. r.size.width = (float) getWidth();
  869. r.size.height = (float) getHeight();
  870. HIViewSetFrame (embeddedView, &r);
  871. }
  872. if (wrapperWindow != 0)
  873. {
  874. Rect wr;
  875. wr.left = getScreenX();
  876. wr.top = getScreenY();
  877. wr.right = wr.left + getWidth();
  878. wr.bottom = wr.top + getHeight();
  879. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  880. ShowWindow (wrapperWindow);
  881. }
  882. recursiveResize = false;
  883. }
  884. }
  885. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  886. {
  887. setEmbeddedWindowToOurSize();
  888. }
  889. void componentPeerChanged()
  890. {
  891. deleteWindow();
  892. createWindow();
  893. }
  894. void componentVisibilityChanged (Component&)
  895. {
  896. if (isShowing())
  897. createWindow();
  898. else
  899. deleteWindow();
  900. setEmbeddedWindowToOurSize();
  901. }
  902. static void recursiveHIViewRepaint (HIViewRef view)
  903. {
  904. HIViewSetNeedsDisplay (view, true);
  905. HIViewRef child = HIViewGetFirstSubview (view);
  906. while (child != 0)
  907. {
  908. recursiveHIViewRepaint (child);
  909. child = HIViewGetNextView (child);
  910. }
  911. }
  912. void timerCallback()
  913. {
  914. setOurSizeToEmbeddedViewSize();
  915. // To avoid strange overpainting problems when the UI is first opened, we'll
  916. // repaint it a few times during the first second that it's on-screen..
  917. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  918. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  919. }
  920. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  921. EventRef event)
  922. {
  923. switch (GetEventKind (event))
  924. {
  925. case kEventWindowHandleDeactivate:
  926. ActivateWindow (wrapperWindow, TRUE);
  927. return noErr;
  928. case kEventWindowGetClickActivation:
  929. {
  930. getTopLevelComponent()->toFront (false);
  931. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  932. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  933. sizeof (ClickActivationResult), &howToHandleClick);
  934. HIViewSetNeedsDisplay (embeddedView, true);
  935. return noErr;
  936. }
  937. }
  938. return eventNotHandledErr;
  939. }
  940. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  941. EventRef event, void* userData)
  942. {
  943. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  944. }
  945. protected:
  946. WindowRef wrapperWindow;
  947. HIViewRef embeddedView;
  948. bool recursiveResize;
  949. Time creationTime;
  950. EventHandlerRef eventHandlerRef;
  951. };
  952. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  953. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  954. END_JUCE_NAMESPACE
  955. #endif
  956. #define JUCE_AMALGAMATED_TEMPLATE 1
  957. //==============================================================================
  958. #if JUCE_BUILD_CORE
  959. /*** Start of inlined file: juce_FileLogger.cpp ***/
  960. BEGIN_JUCE_NAMESPACE
  961. FileLogger::FileLogger (const File& logFile_,
  962. const String& welcomeMessage,
  963. const int maxInitialFileSizeBytes)
  964. : logFile (logFile_)
  965. {
  966. if (maxInitialFileSizeBytes >= 0)
  967. trimFileSize (maxInitialFileSizeBytes);
  968. if (! logFile_.exists())
  969. {
  970. // do this so that the parent directories get created..
  971. logFile_.create();
  972. }
  973. logStream = logFile_.createOutputStream (256);
  974. jassert (logStream != 0);
  975. String welcome;
  976. welcome << "\r\n**********************************************************\r\n"
  977. << welcomeMessage
  978. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  979. << "\r\n";
  980. logMessage (welcome);
  981. }
  982. FileLogger::~FileLogger()
  983. {
  984. }
  985. void FileLogger::logMessage (const String& message)
  986. {
  987. if (logStream != 0)
  988. {
  989. DBG (message);
  990. const ScopedLock sl (logLock);
  991. (*logStream) << message << "\r\n";
  992. logStream->flush();
  993. }
  994. }
  995. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  996. {
  997. if (maxFileSizeBytes <= 0)
  998. {
  999. logFile.deleteFile();
  1000. }
  1001. else
  1002. {
  1003. const int64 fileSize = logFile.getSize();
  1004. if (fileSize > maxFileSizeBytes)
  1005. {
  1006. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1007. jassert (in != 0);
  1008. if (in != 0)
  1009. {
  1010. in->setPosition (fileSize - maxFileSizeBytes);
  1011. String content;
  1012. {
  1013. MemoryBlock contentToSave;
  1014. contentToSave.setSize (maxFileSizeBytes + 4);
  1015. contentToSave.fillWith (0);
  1016. in->read (contentToSave.getData(), maxFileSizeBytes);
  1017. in = 0;
  1018. content = contentToSave.toString();
  1019. }
  1020. int newStart = 0;
  1021. while (newStart < fileSize
  1022. && content[newStart] != '\n'
  1023. && content[newStart] != '\r')
  1024. ++newStart;
  1025. logFile.deleteFile();
  1026. logFile.appendText (content.substring (newStart), false, false);
  1027. }
  1028. }
  1029. }
  1030. }
  1031. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1032. const String& logFileName,
  1033. const String& welcomeMessage,
  1034. const int maxInitialFileSizeBytes)
  1035. {
  1036. #if JUCE_MAC
  1037. File logFile ("~/Library/Logs");
  1038. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1039. .getChildFile (logFileName);
  1040. #else
  1041. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1042. if (logFile.isDirectory())
  1043. {
  1044. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1045. .getChildFile (logFileName);
  1046. }
  1047. #endif
  1048. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1049. }
  1050. END_JUCE_NAMESPACE
  1051. /*** End of inlined file: juce_FileLogger.cpp ***/
  1052. /*** Start of inlined file: juce_Logger.cpp ***/
  1053. BEGIN_JUCE_NAMESPACE
  1054. Logger::Logger()
  1055. {
  1056. }
  1057. Logger::~Logger()
  1058. {
  1059. }
  1060. Logger* Logger::currentLogger = 0;
  1061. void Logger::setCurrentLogger (Logger* const newLogger,
  1062. const bool deleteOldLogger)
  1063. {
  1064. Logger* const oldLogger = currentLogger;
  1065. currentLogger = newLogger;
  1066. if (deleteOldLogger)
  1067. delete oldLogger;
  1068. }
  1069. void Logger::writeToLog (const String& message)
  1070. {
  1071. if (currentLogger != 0)
  1072. currentLogger->logMessage (message);
  1073. else
  1074. outputDebugString (message);
  1075. }
  1076. #if JUCE_LOG_ASSERTIONS
  1077. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1078. {
  1079. String m ("JUCE Assertion failure in ");
  1080. m << filename << ", line " << lineNum;
  1081. Logger::writeToLog (m);
  1082. }
  1083. #endif
  1084. END_JUCE_NAMESPACE
  1085. /*** End of inlined file: juce_Logger.cpp ***/
  1086. /*** Start of inlined file: juce_Random.cpp ***/
  1087. BEGIN_JUCE_NAMESPACE
  1088. Random::Random (const int64 seedValue) throw()
  1089. : seed (seedValue)
  1090. {
  1091. }
  1092. Random::~Random() throw()
  1093. {
  1094. }
  1095. void Random::setSeed (const int64 newSeed) throw()
  1096. {
  1097. seed = newSeed;
  1098. }
  1099. void Random::combineSeed (const int64 seedValue) throw()
  1100. {
  1101. seed ^= nextInt64() ^ seedValue;
  1102. }
  1103. void Random::setSeedRandomly()
  1104. {
  1105. combineSeed ((int64) (pointer_sized_int) this);
  1106. combineSeed (Time::getMillisecondCounter());
  1107. combineSeed (Time::getHighResolutionTicks());
  1108. combineSeed (Time::getHighResolutionTicksPerSecond());
  1109. combineSeed (Time::currentTimeMillis());
  1110. }
  1111. int Random::nextInt() throw()
  1112. {
  1113. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1114. return (int) (seed >> 16);
  1115. }
  1116. int Random::nextInt (const int maxValue) throw()
  1117. {
  1118. jassert (maxValue > 0);
  1119. return (nextInt() & 0x7fffffff) % maxValue;
  1120. }
  1121. int64 Random::nextInt64() throw()
  1122. {
  1123. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1124. }
  1125. bool Random::nextBool() throw()
  1126. {
  1127. return (nextInt() & 0x80000000) != 0;
  1128. }
  1129. float Random::nextFloat() throw()
  1130. {
  1131. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1132. }
  1133. double Random::nextDouble() throw()
  1134. {
  1135. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1136. }
  1137. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1138. {
  1139. BigInteger n;
  1140. do
  1141. {
  1142. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1143. }
  1144. while (n >= maximumValue);
  1145. return n;
  1146. }
  1147. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1148. {
  1149. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1150. while ((startBit & 31) != 0 && numBits > 0)
  1151. {
  1152. arrayToChange.setBit (startBit++, nextBool());
  1153. --numBits;
  1154. }
  1155. while (numBits >= 32)
  1156. {
  1157. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1158. startBit += 32;
  1159. numBits -= 32;
  1160. }
  1161. while (--numBits >= 0)
  1162. arrayToChange.setBit (startBit + numBits, nextBool());
  1163. }
  1164. Random& Random::getSystemRandom() throw()
  1165. {
  1166. static Random sysRand (1);
  1167. return sysRand;
  1168. }
  1169. END_JUCE_NAMESPACE
  1170. /*** End of inlined file: juce_Random.cpp ***/
  1171. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1172. BEGIN_JUCE_NAMESPACE
  1173. RelativeTime::RelativeTime (const double seconds_) throw()
  1174. : seconds (seconds_)
  1175. {
  1176. }
  1177. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1178. : seconds (other.seconds)
  1179. {
  1180. }
  1181. RelativeTime::~RelativeTime() throw()
  1182. {
  1183. }
  1184. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1185. {
  1186. return RelativeTime (milliseconds * 0.001);
  1187. }
  1188. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1189. {
  1190. return RelativeTime (milliseconds * 0.001);
  1191. }
  1192. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1193. {
  1194. return RelativeTime (numberOfMinutes * 60.0);
  1195. }
  1196. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1197. {
  1198. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1199. }
  1200. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1201. {
  1202. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1203. }
  1204. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1205. {
  1206. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1207. }
  1208. int64 RelativeTime::inMilliseconds() const throw()
  1209. {
  1210. return (int64) (seconds * 1000.0);
  1211. }
  1212. double RelativeTime::inMinutes() const throw()
  1213. {
  1214. return seconds / 60.0;
  1215. }
  1216. double RelativeTime::inHours() const throw()
  1217. {
  1218. return seconds / (60.0 * 60.0);
  1219. }
  1220. double RelativeTime::inDays() const throw()
  1221. {
  1222. return seconds / (60.0 * 60.0 * 24.0);
  1223. }
  1224. double RelativeTime::inWeeks() const throw()
  1225. {
  1226. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1227. }
  1228. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1229. {
  1230. if (seconds < 0.001 && seconds > -0.001)
  1231. return returnValueForZeroTime;
  1232. String result;
  1233. if (seconds < 0)
  1234. result = "-";
  1235. int fieldsShown = 0;
  1236. int n = abs ((int) inWeeks());
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" week ")
  1240. : TRANS(" weeks "));
  1241. ++fieldsShown;
  1242. }
  1243. n = abs ((int) inDays()) % 7;
  1244. if (n > 0)
  1245. {
  1246. result << n << ((n == 1) ? TRANS(" day ")
  1247. : TRANS(" days "));
  1248. ++fieldsShown;
  1249. }
  1250. if (fieldsShown < 2)
  1251. {
  1252. n = abs ((int) inHours()) % 24;
  1253. if (n > 0)
  1254. {
  1255. result << n << ((n == 1) ? TRANS(" hr ")
  1256. : TRANS(" hrs "));
  1257. ++fieldsShown;
  1258. }
  1259. if (fieldsShown < 2)
  1260. {
  1261. n = abs ((int) inMinutes()) % 60;
  1262. if (n > 0)
  1263. {
  1264. result << n << ((n == 1) ? TRANS(" min ")
  1265. : TRANS(" mins "));
  1266. ++fieldsShown;
  1267. }
  1268. if (fieldsShown < 2)
  1269. {
  1270. n = abs ((int) inSeconds()) % 60;
  1271. if (n > 0)
  1272. {
  1273. result << n << ((n == 1) ? TRANS(" sec ")
  1274. : TRANS(" secs "));
  1275. ++fieldsShown;
  1276. }
  1277. if (fieldsShown < 1)
  1278. {
  1279. n = abs ((int) inMilliseconds()) % 1000;
  1280. if (n > 0)
  1281. {
  1282. result << n << TRANS(" ms");
  1283. ++fieldsShown;
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. return result.trimEnd();
  1290. }
  1291. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1292. {
  1293. seconds = other.seconds;
  1294. return *this;
  1295. }
  1296. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1297. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1298. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1299. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1300. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1301. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1302. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1303. {
  1304. return RelativeTime (seconds + timeToAdd.seconds);
  1305. }
  1306. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1307. {
  1308. return RelativeTime (seconds - timeToSubtract.seconds);
  1309. }
  1310. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1311. {
  1312. return RelativeTime (seconds + secondsToAdd);
  1313. }
  1314. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1315. {
  1316. return RelativeTime (seconds - secondsToSubtract);
  1317. }
  1318. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1319. {
  1320. seconds += timeToAdd.seconds;
  1321. return *this;
  1322. }
  1323. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1324. {
  1325. seconds -= timeToSubtract.seconds;
  1326. return *this;
  1327. }
  1328. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1329. {
  1330. seconds += secondsToAdd;
  1331. return *this;
  1332. }
  1333. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1334. {
  1335. seconds -= secondsToSubtract;
  1336. return *this;
  1337. }
  1338. END_JUCE_NAMESPACE
  1339. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1340. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1341. BEGIN_JUCE_NAMESPACE
  1342. SystemStats::CPUFlags SystemStats::cpuFlags;
  1343. const String SystemStats::getJUCEVersion()
  1344. {
  1345. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1346. + "." + String (JUCE_MINOR_VERSION)
  1347. + "." + String (JUCE_BUILDNUMBER);
  1348. }
  1349. const StringArray SystemStats::getMACAddressStrings()
  1350. {
  1351. int64 macAddresses [16];
  1352. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1353. StringArray s;
  1354. for (int i = 0; i < numAddresses; ++i)
  1355. {
  1356. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1357. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1358. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1359. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1360. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1361. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1362. }
  1363. return s;
  1364. }
  1365. #ifdef JUCE_DLL
  1366. void* juce_Malloc (const int size)
  1367. {
  1368. return malloc (size);
  1369. }
  1370. void* juce_Calloc (const int size)
  1371. {
  1372. return calloc (1, size);
  1373. }
  1374. void* juce_Realloc (void* const block, const int size)
  1375. {
  1376. return realloc (block, size);
  1377. }
  1378. void juce_Free (void* const block)
  1379. {
  1380. free (block);
  1381. }
  1382. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1383. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1384. {
  1385. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1386. }
  1387. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1388. {
  1389. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1390. }
  1391. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1392. {
  1393. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1394. }
  1395. void juce_DebugFree (void* const block)
  1396. {
  1397. _free_dbg (block, _NORMAL_BLOCK);
  1398. }
  1399. #endif
  1400. #endif
  1401. END_JUCE_NAMESPACE
  1402. /*** End of inlined file: juce_SystemStats.cpp ***/
  1403. /*** Start of inlined file: juce_Time.cpp ***/
  1404. #if JUCE_MSVC
  1405. #pragma warning (push)
  1406. #pragma warning (disable: 4514)
  1407. #endif
  1408. #ifndef JUCE_WINDOWS
  1409. #include <sys/time.h>
  1410. #else
  1411. #include <ctime>
  1412. #endif
  1413. #include <sys/timeb.h>
  1414. #if JUCE_MSVC
  1415. #pragma warning (pop)
  1416. #ifdef _INC_TIME_INL
  1417. #define USE_NEW_SECURE_TIME_FNS
  1418. #endif
  1419. #endif
  1420. BEGIN_JUCE_NAMESPACE
  1421. namespace TimeHelpers
  1422. {
  1423. static struct tm millisToLocal (const int64 millis) throw()
  1424. {
  1425. struct tm result;
  1426. const int64 seconds = millis / 1000;
  1427. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1428. {
  1429. // use extended maths for dates beyond 1970 to 2037..
  1430. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1431. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1432. const int days = (int) (jdm / literal64bit (86400));
  1433. const int a = 32044 + days;
  1434. const int b = (4 * a + 3) / 146097;
  1435. const int c = a - (b * 146097) / 4;
  1436. const int d = (4 * c + 3) / 1461;
  1437. const int e = c - (d * 1461) / 4;
  1438. const int m = (5 * e + 2) / 153;
  1439. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1440. result.tm_mon = m + 2 - 12 * (m / 10);
  1441. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1442. result.tm_wday = (days + 1) % 7;
  1443. result.tm_yday = -1;
  1444. int t = (int) (jdm % literal64bit (86400));
  1445. result.tm_hour = t / 3600;
  1446. t %= 3600;
  1447. result.tm_min = t / 60;
  1448. result.tm_sec = t % 60;
  1449. result.tm_isdst = -1;
  1450. }
  1451. else
  1452. {
  1453. time_t now = static_cast <time_t> (seconds);
  1454. #if JUCE_WINDOWS
  1455. #ifdef USE_NEW_SECURE_TIME_FNS
  1456. if (now >= 0 && now <= 0x793406fff)
  1457. localtime_s (&result, &now);
  1458. else
  1459. zeromem (&result, sizeof (result));
  1460. #else
  1461. result = *localtime (&now);
  1462. #endif
  1463. #else
  1464. // more thread-safe
  1465. localtime_r (&now, &result);
  1466. #endif
  1467. }
  1468. return result;
  1469. }
  1470. static int extendedModulo (const int64 value, const int modulo) throw()
  1471. {
  1472. return (int) (value >= 0 ? (value % modulo)
  1473. : (value - ((value / modulo) + 1) * modulo));
  1474. }
  1475. static uint32 lastMSCounterValue = 0;
  1476. }
  1477. Time::Time() throw()
  1478. : millisSinceEpoch (0)
  1479. {
  1480. }
  1481. Time::Time (const Time& other) throw()
  1482. : millisSinceEpoch (other.millisSinceEpoch)
  1483. {
  1484. }
  1485. Time::Time (const int64 ms) throw()
  1486. : millisSinceEpoch (ms)
  1487. {
  1488. }
  1489. Time::Time (const int year,
  1490. const int month,
  1491. const int day,
  1492. const int hours,
  1493. const int minutes,
  1494. const int seconds,
  1495. const int milliseconds,
  1496. const bool useLocalTime) throw()
  1497. {
  1498. jassert (year > 100); // year must be a 4-digit version
  1499. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1500. {
  1501. // use extended maths for dates beyond 1970 to 2037..
  1502. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1503. : 0;
  1504. const int a = (13 - month) / 12;
  1505. const int y = year + 4800 - a;
  1506. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1507. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1508. - 32045;
  1509. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1510. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1511. + milliseconds;
  1512. }
  1513. else
  1514. {
  1515. struct tm t;
  1516. t.tm_year = year - 1900;
  1517. t.tm_mon = month;
  1518. t.tm_mday = day;
  1519. t.tm_hour = hours;
  1520. t.tm_min = minutes;
  1521. t.tm_sec = seconds;
  1522. t.tm_isdst = -1;
  1523. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1524. if (millisSinceEpoch < 0)
  1525. millisSinceEpoch = 0;
  1526. else
  1527. millisSinceEpoch += milliseconds;
  1528. }
  1529. }
  1530. Time::~Time() throw()
  1531. {
  1532. }
  1533. Time& Time::operator= (const Time& other) throw()
  1534. {
  1535. millisSinceEpoch = other.millisSinceEpoch;
  1536. return *this;
  1537. }
  1538. int64 Time::currentTimeMillis() throw()
  1539. {
  1540. static uint32 lastCounterResult = 0xffffffff;
  1541. static int64 correction = 0;
  1542. const uint32 now = getMillisecondCounter();
  1543. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1544. if (now < lastCounterResult)
  1545. {
  1546. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1547. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1548. {
  1549. // get the time once using normal library calls, and store the difference needed to
  1550. // turn the millisecond counter into a real time.
  1551. #if JUCE_WINDOWS
  1552. struct _timeb t;
  1553. #ifdef USE_NEW_SECURE_TIME_FNS
  1554. _ftime_s (&t);
  1555. #else
  1556. _ftime (&t);
  1557. #endif
  1558. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1559. #else
  1560. struct timeval tv;
  1561. struct timezone tz;
  1562. gettimeofday (&tv, &tz);
  1563. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1564. #endif
  1565. }
  1566. }
  1567. lastCounterResult = now;
  1568. return correction + now;
  1569. }
  1570. uint32 juce_millisecondsSinceStartup() throw();
  1571. uint32 Time::getMillisecondCounter() throw()
  1572. {
  1573. const uint32 now = juce_millisecondsSinceStartup();
  1574. if (now < TimeHelpers::lastMSCounterValue)
  1575. {
  1576. // in multi-threaded apps this might be called concurrently, so
  1577. // make sure that our last counter value only increases and doesn't
  1578. // go backwards..
  1579. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1580. TimeHelpers::lastMSCounterValue = now;
  1581. }
  1582. else
  1583. {
  1584. TimeHelpers::lastMSCounterValue = now;
  1585. }
  1586. return now;
  1587. }
  1588. uint32 Time::getApproximateMillisecondCounter() throw()
  1589. {
  1590. jassert (TimeHelpers::lastMSCounterValue != 0);
  1591. return TimeHelpers::lastMSCounterValue;
  1592. }
  1593. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1594. {
  1595. for (;;)
  1596. {
  1597. const uint32 now = getMillisecondCounter();
  1598. if (now >= targetTime)
  1599. break;
  1600. const int toWait = targetTime - now;
  1601. if (toWait > 2)
  1602. {
  1603. Thread::sleep (jmin (20, toWait >> 1));
  1604. }
  1605. else
  1606. {
  1607. // xxx should consider using mutex_pause on the mac as it apparently
  1608. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1609. for (int i = 10; --i >= 0;)
  1610. Thread::yield();
  1611. }
  1612. }
  1613. }
  1614. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1615. {
  1616. return ticks / (double) getHighResolutionTicksPerSecond();
  1617. }
  1618. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1619. {
  1620. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1621. }
  1622. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1623. {
  1624. return Time (currentTimeMillis());
  1625. }
  1626. const String Time::toString (const bool includeDate,
  1627. const bool includeTime,
  1628. const bool includeSeconds,
  1629. const bool use24HourClock) const throw()
  1630. {
  1631. String result;
  1632. if (includeDate)
  1633. {
  1634. result << getDayOfMonth() << ' '
  1635. << getMonthName (true) << ' '
  1636. << getYear();
  1637. if (includeTime)
  1638. result << ' ';
  1639. }
  1640. if (includeTime)
  1641. {
  1642. const int mins = getMinutes();
  1643. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1644. << (mins < 10 ? ":0" : ":") << mins;
  1645. if (includeSeconds)
  1646. {
  1647. const int secs = getSeconds();
  1648. result << (secs < 10 ? ":0" : ":") << secs;
  1649. }
  1650. if (! use24HourClock)
  1651. result << (isAfternoon() ? "pm" : "am");
  1652. }
  1653. return result.trimEnd();
  1654. }
  1655. const String Time::formatted (const String& format) const
  1656. {
  1657. String buffer;
  1658. int bufferSize = 128;
  1659. buffer.preallocateStorage (bufferSize);
  1660. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1661. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1662. {
  1663. bufferSize += 128;
  1664. buffer.preallocateStorage (bufferSize);
  1665. }
  1666. return buffer;
  1667. }
  1668. int Time::getYear() const throw()
  1669. {
  1670. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1671. }
  1672. int Time::getMonth() const throw()
  1673. {
  1674. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1675. }
  1676. int Time::getDayOfMonth() const throw()
  1677. {
  1678. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1679. }
  1680. int Time::getDayOfWeek() const throw()
  1681. {
  1682. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1683. }
  1684. int Time::getHours() const throw()
  1685. {
  1686. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1687. }
  1688. int Time::getHoursInAmPmFormat() const throw()
  1689. {
  1690. const int hours = getHours();
  1691. if (hours == 0)
  1692. return 12;
  1693. else if (hours <= 12)
  1694. return hours;
  1695. else
  1696. return hours - 12;
  1697. }
  1698. bool Time::isAfternoon() const throw()
  1699. {
  1700. return getHours() >= 12;
  1701. }
  1702. int Time::getMinutes() const throw()
  1703. {
  1704. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1705. }
  1706. int Time::getSeconds() const throw()
  1707. {
  1708. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1709. }
  1710. int Time::getMilliseconds() const throw()
  1711. {
  1712. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1713. }
  1714. bool Time::isDaylightSavingTime() const throw()
  1715. {
  1716. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1717. }
  1718. const String Time::getTimeZone() const throw()
  1719. {
  1720. String zone[2];
  1721. #if JUCE_WINDOWS
  1722. _tzset();
  1723. #ifdef USE_NEW_SECURE_TIME_FNS
  1724. {
  1725. char name [128];
  1726. size_t length;
  1727. for (int i = 0; i < 2; ++i)
  1728. {
  1729. zeromem (name, sizeof (name));
  1730. _get_tzname (&length, name, 127, i);
  1731. zone[i] = name;
  1732. }
  1733. }
  1734. #else
  1735. const char** const zonePtr = (const char**) _tzname;
  1736. zone[0] = zonePtr[0];
  1737. zone[1] = zonePtr[1];
  1738. #endif
  1739. #else
  1740. tzset();
  1741. const char** const zonePtr = (const char**) tzname;
  1742. zone[0] = zonePtr[0];
  1743. zone[1] = zonePtr[1];
  1744. #endif
  1745. if (isDaylightSavingTime())
  1746. {
  1747. zone[0] = zone[1];
  1748. if (zone[0].length() > 3
  1749. && zone[0].containsIgnoreCase ("daylight")
  1750. && zone[0].contains ("GMT"))
  1751. zone[0] = "BST";
  1752. }
  1753. return zone[0].substring (0, 3);
  1754. }
  1755. const String Time::getMonthName (const bool threeLetterVersion) const
  1756. {
  1757. return getMonthName (getMonth(), threeLetterVersion);
  1758. }
  1759. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1760. {
  1761. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1762. }
  1763. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1764. {
  1765. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1766. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1767. monthNumber %= 12;
  1768. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1769. : longMonthNames [monthNumber]);
  1770. }
  1771. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1772. {
  1773. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1774. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1775. day %= 7;
  1776. return TRANS (threeLetterVersion ? shortDayNames [day]
  1777. : longDayNames [day]);
  1778. }
  1779. END_JUCE_NAMESPACE
  1780. /*** End of inlined file: juce_Time.cpp ***/
  1781. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1782. BEGIN_JUCE_NAMESPACE
  1783. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1784. #endif
  1785. #if JUCE_WINDOWS
  1786. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1787. #endif
  1788. #if JUCE_DEBUG
  1789. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1790. #endif
  1791. #if JUCE_DEBUG
  1792. namespace SimpleUnitTests
  1793. {
  1794. template <typename Type>
  1795. class AtomicTester
  1796. {
  1797. public:
  1798. AtomicTester() {}
  1799. static void testInteger()
  1800. {
  1801. Atomic<Type> a, b;
  1802. a.set ((Type) 10);
  1803. a += (Type) 15;
  1804. a.memoryBarrier();
  1805. a -= (Type) 5;
  1806. ++a; ++a; --a;
  1807. a.memoryBarrier();
  1808. testFloat();
  1809. }
  1810. static void testFloat()
  1811. {
  1812. Atomic<Type> a, b;
  1813. a = (Type) 21;
  1814. a.memoryBarrier();
  1815. /* These are some simple test cases to check the atomics - let me know
  1816. if any of these assertions fail on your system!
  1817. */
  1818. jassert (a.get() == (Type) 21);
  1819. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1820. jassert (a.get() == (Type) 21);
  1821. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1822. jassert (a.get() == (Type) 101);
  1823. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1824. jassert (a.get() == (Type) 101);
  1825. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1826. jassert (a.get() == (Type) 200);
  1827. jassert (a.exchange ((Type) 300) == (Type) 200);
  1828. jassert (a.get() == (Type) 300);
  1829. b = a;
  1830. jassert (b.get() == a.get());
  1831. }
  1832. };
  1833. static void runBasicTests()
  1834. {
  1835. // Some simple test code, to keep an eye on things and make sure these functions
  1836. // work ok on all platforms. Let me know if any of these assertions fail on your system!
  1837. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1838. static_jassert (sizeof (int8) == 1);
  1839. static_jassert (sizeof (uint8) == 1);
  1840. static_jassert (sizeof (int16) == 2);
  1841. static_jassert (sizeof (uint16) == 2);
  1842. static_jassert (sizeof (int32) == 4);
  1843. static_jassert (sizeof (uint32) == 4);
  1844. static_jassert (sizeof (int64) == 8);
  1845. static_jassert (sizeof (uint64) == 8);
  1846. char a1[7];
  1847. jassert (numElementsInArray(a1) == 7);
  1848. int a2[3];
  1849. jassert (numElementsInArray(a2) == 3);
  1850. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1851. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1852. jassert (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1853. // Some quick stream tests..
  1854. int randomInt = Random::getSystemRandom().nextInt();
  1855. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1856. double randomDouble = Random::getSystemRandom().nextDouble();
  1857. String randomString;
  1858. for (int i = 50; --i >= 0;)
  1859. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1860. MemoryOutputStream mo;
  1861. mo.writeInt (randomInt);
  1862. mo.writeIntBigEndian (randomInt);
  1863. mo.writeCompressedInt (randomInt);
  1864. mo.writeString (randomString);
  1865. mo.writeInt64 (randomInt64);
  1866. mo.writeInt64BigEndian (randomInt64);
  1867. mo.writeDouble (randomDouble);
  1868. mo.writeDoubleBigEndian (randomDouble);
  1869. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1870. jassert (mi.readInt() == randomInt);
  1871. jassert (mi.readIntBigEndian() == randomInt);
  1872. jassert (mi.readCompressedInt() == randomInt);
  1873. jassert (mi.readString() == randomString);
  1874. jassert (mi.readInt64() == randomInt64);
  1875. jassert (mi.readInt64BigEndian() == randomInt64);
  1876. jassert (mi.readDouble() == randomDouble);
  1877. jassert (mi.readDoubleBigEndian() == randomDouble);
  1878. AtomicTester <int>::testInteger();
  1879. AtomicTester <unsigned int>::testInteger();
  1880. AtomicTester <int32>::testInteger();
  1881. AtomicTester <uint32>::testInteger();
  1882. AtomicTester <long>::testInteger();
  1883. AtomicTester <void*>::testInteger();
  1884. AtomicTester <int*>::testInteger();
  1885. AtomicTester <float>::testFloat();
  1886. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1887. AtomicTester <int64>::testInteger();
  1888. AtomicTester <uint64>::testInteger();
  1889. AtomicTester <double>::testFloat();
  1890. #endif
  1891. }
  1892. }
  1893. #endif
  1894. static bool juceInitialisedNonGUI = false;
  1895. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1896. {
  1897. if (! juceInitialisedNonGUI)
  1898. {
  1899. juceInitialisedNonGUI = true;
  1900. JUCE_AUTORELEASEPOOL
  1901. #if JUCE_DEBUG
  1902. SimpleUnitTests::runBasicTests();
  1903. #endif
  1904. DBG (SystemStats::getJUCEVersion());
  1905. SystemStats::initialiseStats();
  1906. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1907. }
  1908. }
  1909. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1910. {
  1911. if (juceInitialisedNonGUI)
  1912. {
  1913. juceInitialisedNonGUI = false;
  1914. JUCE_AUTORELEASEPOOL
  1915. LocalisedStrings::setCurrentMappings (0);
  1916. Thread::stopAllThreads (3000);
  1917. #if JUCE_WINDOWS
  1918. juce_shutdownWin32Sockets();
  1919. #endif
  1920. #if JUCE_DEBUG
  1921. juce_CheckForDanglingStreams();
  1922. #endif
  1923. }
  1924. }
  1925. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1926. void juce_setCurrentThreadName (const String& name);
  1927. static bool juceInitialisedGUI = false;
  1928. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1929. {
  1930. if (! juceInitialisedGUI)
  1931. {
  1932. juceInitialisedGUI = true;
  1933. JUCE_AUTORELEASEPOOL
  1934. initialiseJuce_NonGUI();
  1935. MessageManager::getInstance();
  1936. LookAndFeel::setDefaultLookAndFeel (0);
  1937. juce_setCurrentThreadName ("Juce Message Thread");
  1938. #if JUCE_DEBUG
  1939. // This section is just for catching people who mess up their project settings and
  1940. // turn RTTI off..
  1941. try
  1942. {
  1943. TextButton tb (String::empty);
  1944. Component* c = &tb;
  1945. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1946. c = dynamic_cast <Button*> (c);
  1947. }
  1948. catch (...)
  1949. {
  1950. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1951. jassertfalse;
  1952. }
  1953. #endif
  1954. }
  1955. }
  1956. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1957. {
  1958. if (juceInitialisedGUI)
  1959. {
  1960. juceInitialisedGUI = false;
  1961. JUCE_AUTORELEASEPOOL
  1962. DeletedAtShutdown::deleteAll();
  1963. LookAndFeel::clearDefaultLookAndFeel();
  1964. delete MessageManager::getInstance();
  1965. shutdownJuce_NonGUI();
  1966. }
  1967. }
  1968. #endif
  1969. END_JUCE_NAMESPACE
  1970. /*** End of inlined file: juce_Initialisation.cpp ***/
  1971. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1972. BEGIN_JUCE_NAMESPACE
  1973. BigInteger::BigInteger()
  1974. : numValues (4),
  1975. highestBit (-1),
  1976. negative (false)
  1977. {
  1978. values.calloc (numValues + 1);
  1979. }
  1980. BigInteger::BigInteger (const int value)
  1981. : numValues (4),
  1982. highestBit (31),
  1983. negative (value < 0)
  1984. {
  1985. values.calloc (numValues + 1);
  1986. values[0] = abs (value);
  1987. highestBit = getHighestBit();
  1988. }
  1989. BigInteger::BigInteger (int64 value)
  1990. : numValues (4),
  1991. highestBit (63),
  1992. negative (value < 0)
  1993. {
  1994. values.calloc (numValues + 1);
  1995. if (value < 0)
  1996. value = -value;
  1997. values[0] = (unsigned int) value;
  1998. values[1] = (unsigned int) (value >> 32);
  1999. highestBit = getHighestBit();
  2000. }
  2001. BigInteger::BigInteger (const unsigned int value)
  2002. : numValues (4),
  2003. highestBit (31),
  2004. negative (false)
  2005. {
  2006. values.calloc (numValues + 1);
  2007. values[0] = value;
  2008. highestBit = getHighestBit();
  2009. }
  2010. BigInteger::BigInteger (const BigInteger& other)
  2011. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2012. highestBit (other.getHighestBit()),
  2013. negative (other.negative)
  2014. {
  2015. values.malloc (numValues + 1);
  2016. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2017. }
  2018. BigInteger::~BigInteger()
  2019. {
  2020. }
  2021. void BigInteger::swapWith (BigInteger& other) throw()
  2022. {
  2023. values.swapWith (other.values);
  2024. swapVariables (numValues, other.numValues);
  2025. swapVariables (highestBit, other.highestBit);
  2026. swapVariables (negative, other.negative);
  2027. }
  2028. BigInteger& BigInteger::operator= (const BigInteger& other)
  2029. {
  2030. if (this != &other)
  2031. {
  2032. highestBit = other.getHighestBit();
  2033. numValues = jmax (4, (highestBit >> 5) + 1);
  2034. negative = other.negative;
  2035. values.malloc (numValues + 1);
  2036. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2037. }
  2038. return *this;
  2039. }
  2040. void BigInteger::ensureSize (const int numVals)
  2041. {
  2042. if (numVals + 2 >= numValues)
  2043. {
  2044. int oldSize = numValues;
  2045. numValues = ((numVals + 2) * 3) / 2;
  2046. values.realloc (numValues + 1);
  2047. while (oldSize < numValues)
  2048. values [oldSize++] = 0;
  2049. }
  2050. }
  2051. bool BigInteger::operator[] (const int bit) const throw()
  2052. {
  2053. return bit <= highestBit && bit >= 0
  2054. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2055. }
  2056. int BigInteger::toInteger() const throw()
  2057. {
  2058. const int n = (int) (values[0] & 0x7fffffff);
  2059. return negative ? -n : n;
  2060. }
  2061. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2062. {
  2063. BigInteger r;
  2064. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2065. r.ensureSize (numBits >> 5);
  2066. r.highestBit = numBits;
  2067. int i = 0;
  2068. while (numBits > 0)
  2069. {
  2070. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2071. numBits -= 32;
  2072. startBit += 32;
  2073. }
  2074. r.highestBit = r.getHighestBit();
  2075. return r;
  2076. }
  2077. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2078. {
  2079. if (numBits > 32)
  2080. {
  2081. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2082. numBits = 32;
  2083. }
  2084. numBits = jmin (numBits, highestBit + 1 - startBit);
  2085. if (numBits <= 0)
  2086. return 0;
  2087. const int pos = startBit >> 5;
  2088. const int offset = startBit & 31;
  2089. const int endSpace = 32 - numBits;
  2090. uint32 n = ((uint32) values [pos]) >> offset;
  2091. if (offset > endSpace)
  2092. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2093. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2094. }
  2095. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2096. {
  2097. if (numBits > 32)
  2098. {
  2099. jassertfalse;
  2100. numBits = 32;
  2101. }
  2102. for (int i = 0; i < numBits; ++i)
  2103. {
  2104. setBit (startBit + i, (valueToSet & 1) != 0);
  2105. valueToSet >>= 1;
  2106. }
  2107. }
  2108. void BigInteger::clear()
  2109. {
  2110. if (numValues > 16)
  2111. {
  2112. numValues = 4;
  2113. values.calloc (numValues + 1);
  2114. }
  2115. else
  2116. {
  2117. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2118. }
  2119. highestBit = -1;
  2120. negative = false;
  2121. }
  2122. void BigInteger::setBit (const int bit)
  2123. {
  2124. if (bit >= 0)
  2125. {
  2126. if (bit > highestBit)
  2127. {
  2128. ensureSize (bit >> 5);
  2129. highestBit = bit;
  2130. }
  2131. values [bit >> 5] |= (1 << (bit & 31));
  2132. }
  2133. }
  2134. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2135. {
  2136. if (shouldBeSet)
  2137. setBit (bit);
  2138. else
  2139. clearBit (bit);
  2140. }
  2141. void BigInteger::clearBit (const int bit) throw()
  2142. {
  2143. if (bit >= 0 && bit <= highestBit)
  2144. values [bit >> 5] &= ~(1 << (bit & 31));
  2145. }
  2146. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2147. {
  2148. while (--numBits >= 0)
  2149. setBit (startBit++, shouldBeSet);
  2150. }
  2151. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2152. {
  2153. if (bit >= 0)
  2154. shiftBits (1, bit);
  2155. setBit (bit, shouldBeSet);
  2156. }
  2157. bool BigInteger::isZero() const throw()
  2158. {
  2159. return getHighestBit() < 0;
  2160. }
  2161. bool BigInteger::isOne() const throw()
  2162. {
  2163. return getHighestBit() == 0 && ! negative;
  2164. }
  2165. bool BigInteger::isNegative() const throw()
  2166. {
  2167. return negative && ! isZero();
  2168. }
  2169. void BigInteger::setNegative (const bool neg) throw()
  2170. {
  2171. negative = neg;
  2172. }
  2173. void BigInteger::negate() throw()
  2174. {
  2175. negative = (! negative) && ! isZero();
  2176. }
  2177. int BigInteger::countNumberOfSetBits() const throw()
  2178. {
  2179. int total = 0;
  2180. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2181. {
  2182. unsigned int n = values[i];
  2183. if (n == 0xffffffff)
  2184. {
  2185. total += 32;
  2186. }
  2187. else
  2188. {
  2189. while (n != 0)
  2190. {
  2191. total += (n & 1);
  2192. n >>= 1;
  2193. }
  2194. }
  2195. }
  2196. return total;
  2197. }
  2198. int BigInteger::getHighestBit() const throw()
  2199. {
  2200. for (int i = highestBit + 1; --i >= 0;)
  2201. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2202. return i;
  2203. return -1;
  2204. }
  2205. int BigInteger::findNextSetBit (int i) const throw()
  2206. {
  2207. for (; i <= highestBit; ++i)
  2208. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2209. return i;
  2210. return -1;
  2211. }
  2212. int BigInteger::findNextClearBit (int i) const throw()
  2213. {
  2214. for (; i <= highestBit; ++i)
  2215. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2216. break;
  2217. return i;
  2218. }
  2219. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2220. {
  2221. if (other.isNegative())
  2222. return operator-= (-other);
  2223. if (isNegative())
  2224. {
  2225. if (compareAbsolute (other) < 0)
  2226. {
  2227. BigInteger temp (*this);
  2228. temp.negate();
  2229. *this = other;
  2230. operator-= (temp);
  2231. }
  2232. else
  2233. {
  2234. negate();
  2235. operator-= (other);
  2236. negate();
  2237. }
  2238. }
  2239. else
  2240. {
  2241. if (other.highestBit > highestBit)
  2242. highestBit = other.highestBit;
  2243. ++highestBit;
  2244. const int numInts = (highestBit >> 5) + 1;
  2245. ensureSize (numInts);
  2246. int64 remainder = 0;
  2247. for (int i = 0; i <= numInts; ++i)
  2248. {
  2249. if (i < numValues)
  2250. remainder += values[i];
  2251. if (i < other.numValues)
  2252. remainder += other.values[i];
  2253. values[i] = (unsigned int) remainder;
  2254. remainder >>= 32;
  2255. }
  2256. jassert (remainder == 0);
  2257. highestBit = getHighestBit();
  2258. }
  2259. return *this;
  2260. }
  2261. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2262. {
  2263. if (other.isNegative())
  2264. return operator+= (-other);
  2265. if (! isNegative())
  2266. {
  2267. if (compareAbsolute (other) < 0)
  2268. {
  2269. BigInteger temp (other);
  2270. swapWith (temp);
  2271. operator-= (temp);
  2272. negate();
  2273. return *this;
  2274. }
  2275. }
  2276. else
  2277. {
  2278. negate();
  2279. operator+= (other);
  2280. negate();
  2281. return *this;
  2282. }
  2283. const int numInts = (highestBit >> 5) + 1;
  2284. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2285. int64 amountToSubtract = 0;
  2286. for (int i = 0; i <= numInts; ++i)
  2287. {
  2288. if (i <= maxOtherInts)
  2289. amountToSubtract += (int64) other.values[i];
  2290. if (values[i] >= amountToSubtract)
  2291. {
  2292. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2293. amountToSubtract = 0;
  2294. }
  2295. else
  2296. {
  2297. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2298. values[i] = (unsigned int) n;
  2299. amountToSubtract = 1;
  2300. }
  2301. }
  2302. return *this;
  2303. }
  2304. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2305. {
  2306. BigInteger total;
  2307. highestBit = getHighestBit();
  2308. const bool wasNegative = isNegative();
  2309. setNegative (false);
  2310. for (int i = 0; i <= highestBit; ++i)
  2311. {
  2312. if (operator[](i))
  2313. {
  2314. BigInteger n (other);
  2315. n.setNegative (false);
  2316. n <<= i;
  2317. total += n;
  2318. }
  2319. }
  2320. total.setNegative (wasNegative ^ other.isNegative());
  2321. swapWith (total);
  2322. return *this;
  2323. }
  2324. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2325. {
  2326. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2327. const int divHB = divisor.getHighestBit();
  2328. const int ourHB = getHighestBit();
  2329. if (divHB < 0 || ourHB < 0)
  2330. {
  2331. // division by zero
  2332. remainder.clear();
  2333. clear();
  2334. }
  2335. else
  2336. {
  2337. const bool wasNegative = isNegative();
  2338. swapWith (remainder);
  2339. remainder.setNegative (false);
  2340. clear();
  2341. BigInteger temp (divisor);
  2342. temp.setNegative (false);
  2343. int leftShift = ourHB - divHB;
  2344. temp <<= leftShift;
  2345. while (leftShift >= 0)
  2346. {
  2347. if (remainder.compareAbsolute (temp) >= 0)
  2348. {
  2349. remainder -= temp;
  2350. setBit (leftShift);
  2351. }
  2352. if (--leftShift >= 0)
  2353. temp >>= 1;
  2354. }
  2355. negative = wasNegative ^ divisor.isNegative();
  2356. remainder.setNegative (wasNegative);
  2357. }
  2358. }
  2359. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2360. {
  2361. BigInteger remainder;
  2362. divideBy (other, remainder);
  2363. return *this;
  2364. }
  2365. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2366. {
  2367. // this operation doesn't take into account negative values..
  2368. jassert (isNegative() == other.isNegative());
  2369. if (other.highestBit >= 0)
  2370. {
  2371. ensureSize (other.highestBit >> 5);
  2372. int n = (other.highestBit >> 5) + 1;
  2373. while (--n >= 0)
  2374. values[n] |= other.values[n];
  2375. if (other.highestBit > highestBit)
  2376. highestBit = other.highestBit;
  2377. highestBit = getHighestBit();
  2378. }
  2379. return *this;
  2380. }
  2381. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2382. {
  2383. // this operation doesn't take into account negative values..
  2384. jassert (isNegative() == other.isNegative());
  2385. int n = numValues;
  2386. while (n > other.numValues)
  2387. values[--n] = 0;
  2388. while (--n >= 0)
  2389. values[n] &= other.values[n];
  2390. if (other.highestBit < highestBit)
  2391. highestBit = other.highestBit;
  2392. highestBit = getHighestBit();
  2393. return *this;
  2394. }
  2395. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2396. {
  2397. // this operation will only work with the absolute values
  2398. jassert (isNegative() == other.isNegative());
  2399. if (other.highestBit >= 0)
  2400. {
  2401. ensureSize (other.highestBit >> 5);
  2402. int n = (other.highestBit >> 5) + 1;
  2403. while (--n >= 0)
  2404. values[n] ^= other.values[n];
  2405. if (other.highestBit > highestBit)
  2406. highestBit = other.highestBit;
  2407. highestBit = getHighestBit();
  2408. }
  2409. return *this;
  2410. }
  2411. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2412. {
  2413. BigInteger remainder;
  2414. divideBy (divisor, remainder);
  2415. swapWith (remainder);
  2416. return *this;
  2417. }
  2418. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2419. {
  2420. shiftBits (numBitsToShift, 0);
  2421. return *this;
  2422. }
  2423. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2424. {
  2425. return operator<<= (-numBitsToShift);
  2426. }
  2427. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2428. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2429. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2430. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2431. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2432. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2433. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2434. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2435. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2436. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2437. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2438. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2439. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2440. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2441. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2442. int BigInteger::compare (const BigInteger& other) const throw()
  2443. {
  2444. if (isNegative() == other.isNegative())
  2445. {
  2446. const int absComp = compareAbsolute (other);
  2447. return isNegative() ? -absComp : absComp;
  2448. }
  2449. else
  2450. {
  2451. return isNegative() ? -1 : 1;
  2452. }
  2453. }
  2454. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2455. {
  2456. const int h1 = getHighestBit();
  2457. const int h2 = other.getHighestBit();
  2458. if (h1 > h2)
  2459. return 1;
  2460. else if (h1 < h2)
  2461. return -1;
  2462. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2463. if (values[i] != other.values[i])
  2464. return (values[i] > other.values[i]) ? 1 : -1;
  2465. return 0;
  2466. }
  2467. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2468. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2469. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2470. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2471. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2472. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2473. void BigInteger::shiftBits (int bits, const int startBit)
  2474. {
  2475. if (highestBit < 0)
  2476. return;
  2477. if (startBit > 0)
  2478. {
  2479. if (bits < 0)
  2480. {
  2481. // right shift
  2482. for (int i = startBit; i <= highestBit; ++i)
  2483. setBit (i, operator[] (i - bits));
  2484. highestBit = getHighestBit();
  2485. }
  2486. else if (bits > 0)
  2487. {
  2488. // left shift
  2489. for (int i = highestBit + 1; --i >= startBit;)
  2490. setBit (i + bits, operator[] (i));
  2491. while (--bits >= 0)
  2492. clearBit (bits + startBit);
  2493. }
  2494. }
  2495. else
  2496. {
  2497. if (bits < 0)
  2498. {
  2499. // right shift
  2500. bits = -bits;
  2501. if (bits > highestBit)
  2502. {
  2503. clear();
  2504. }
  2505. else
  2506. {
  2507. const int wordsToMove = bits >> 5;
  2508. int top = 1 + (highestBit >> 5) - wordsToMove;
  2509. highestBit -= bits;
  2510. if (wordsToMove > 0)
  2511. {
  2512. int i;
  2513. for (i = 0; i < top; ++i)
  2514. values [i] = values [i + wordsToMove];
  2515. for (i = 0; i < wordsToMove; ++i)
  2516. values [top + i] = 0;
  2517. bits &= 31;
  2518. }
  2519. if (bits != 0)
  2520. {
  2521. const int invBits = 32 - bits;
  2522. --top;
  2523. for (int i = 0; i < top; ++i)
  2524. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2525. values[top] = (values[top] >> bits);
  2526. }
  2527. highestBit = getHighestBit();
  2528. }
  2529. }
  2530. else if (bits > 0)
  2531. {
  2532. // left shift
  2533. ensureSize (((highestBit + bits) >> 5) + 1);
  2534. const int wordsToMove = bits >> 5;
  2535. int top = 1 + (highestBit >> 5);
  2536. highestBit += bits;
  2537. if (wordsToMove > 0)
  2538. {
  2539. int i;
  2540. for (i = top; --i >= 0;)
  2541. values [i + wordsToMove] = values [i];
  2542. for (i = 0; i < wordsToMove; ++i)
  2543. values [i] = 0;
  2544. bits &= 31;
  2545. }
  2546. if (bits != 0)
  2547. {
  2548. const int invBits = 32 - bits;
  2549. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2550. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2551. values [wordsToMove] = values [wordsToMove] << bits;
  2552. }
  2553. highestBit = getHighestBit();
  2554. }
  2555. }
  2556. }
  2557. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2558. {
  2559. while (! m->isZero())
  2560. {
  2561. if (n->compareAbsolute (*m) > 0)
  2562. swapVariables (m, n);
  2563. *m -= *n;
  2564. }
  2565. return *n;
  2566. }
  2567. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2568. {
  2569. BigInteger m (*this);
  2570. while (! n.isZero())
  2571. {
  2572. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2573. return simpleGCD (&m, &n);
  2574. BigInteger temp1 (m), temp2;
  2575. temp1.divideBy (n, temp2);
  2576. m = n;
  2577. n = temp2;
  2578. }
  2579. return m;
  2580. }
  2581. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2582. {
  2583. BigInteger exp (exponent);
  2584. exp %= modulus;
  2585. BigInteger value (1);
  2586. swapWith (value);
  2587. value %= modulus;
  2588. while (! exp.isZero())
  2589. {
  2590. if (exp [0])
  2591. {
  2592. operator*= (value);
  2593. operator%= (modulus);
  2594. }
  2595. value *= value;
  2596. value %= modulus;
  2597. exp >>= 1;
  2598. }
  2599. }
  2600. void BigInteger::inverseModulo (const BigInteger& modulus)
  2601. {
  2602. if (modulus.isOne() || modulus.isNegative())
  2603. {
  2604. clear();
  2605. return;
  2606. }
  2607. if (isNegative() || compareAbsolute (modulus) >= 0)
  2608. operator%= (modulus);
  2609. if (isOne())
  2610. return;
  2611. if (! (*this)[0])
  2612. {
  2613. // not invertible
  2614. clear();
  2615. return;
  2616. }
  2617. BigInteger a1 (modulus);
  2618. BigInteger a2 (*this);
  2619. BigInteger b1 (modulus);
  2620. BigInteger b2 (1);
  2621. while (! a2.isOne())
  2622. {
  2623. BigInteger temp1, temp2, multiplier (a1);
  2624. multiplier.divideBy (a2, temp1);
  2625. temp1 = a2;
  2626. temp1 *= multiplier;
  2627. temp2 = a1;
  2628. temp2 -= temp1;
  2629. a1 = a2;
  2630. a2 = temp2;
  2631. temp1 = b2;
  2632. temp1 *= multiplier;
  2633. temp2 = b1;
  2634. temp2 -= temp1;
  2635. b1 = b2;
  2636. b2 = temp2;
  2637. }
  2638. while (b2.isNegative())
  2639. b2 += modulus;
  2640. b2 %= modulus;
  2641. swapWith (b2);
  2642. }
  2643. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2644. {
  2645. return stream << value.toString (10);
  2646. }
  2647. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2648. {
  2649. String s;
  2650. BigInteger v (*this);
  2651. if (base == 2 || base == 8 || base == 16)
  2652. {
  2653. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2654. static const char* const hexDigits = "0123456789abcdef";
  2655. for (;;)
  2656. {
  2657. const int remainder = v.getBitRangeAsInt (0, bits);
  2658. v >>= bits;
  2659. if (remainder == 0 && v.isZero())
  2660. break;
  2661. s = String::charToString (hexDigits [remainder]) + s;
  2662. }
  2663. }
  2664. else if (base == 10)
  2665. {
  2666. const BigInteger ten (10);
  2667. BigInteger remainder;
  2668. for (;;)
  2669. {
  2670. v.divideBy (ten, remainder);
  2671. if (remainder.isZero() && v.isZero())
  2672. break;
  2673. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2674. }
  2675. }
  2676. else
  2677. {
  2678. jassertfalse; // can't do the specified base!
  2679. return String::empty;
  2680. }
  2681. s = s.paddedLeft ('0', minimumNumCharacters);
  2682. return isNegative() ? "-" + s : s;
  2683. }
  2684. void BigInteger::parseString (const String& text, const int base)
  2685. {
  2686. clear();
  2687. const juce_wchar* t = text;
  2688. if (base == 2 || base == 8 || base == 16)
  2689. {
  2690. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2691. for (;;)
  2692. {
  2693. const juce_wchar c = *t++;
  2694. const int digit = CharacterFunctions::getHexDigitValue (c);
  2695. if (((unsigned int) digit) < (unsigned int) base)
  2696. {
  2697. operator<<= (bits);
  2698. operator+= (digit);
  2699. }
  2700. else if (c == 0)
  2701. {
  2702. break;
  2703. }
  2704. }
  2705. }
  2706. else if (base == 10)
  2707. {
  2708. const BigInteger ten ((unsigned int) 10);
  2709. for (;;)
  2710. {
  2711. const juce_wchar c = *t++;
  2712. if (c >= '0' && c <= '9')
  2713. {
  2714. operator*= (ten);
  2715. operator+= ((int) (c - '0'));
  2716. }
  2717. else if (c == 0)
  2718. {
  2719. break;
  2720. }
  2721. }
  2722. }
  2723. setNegative (text.trimStart().startsWithChar ('-'));
  2724. }
  2725. const MemoryBlock BigInteger::toMemoryBlock() const
  2726. {
  2727. const int numBytes = (getHighestBit() + 8) >> 3;
  2728. MemoryBlock mb ((size_t) numBytes);
  2729. for (int i = 0; i < numBytes; ++i)
  2730. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2731. return mb;
  2732. }
  2733. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2734. {
  2735. clear();
  2736. for (int i = (int) data.getSize(); --i >= 0;)
  2737. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2738. }
  2739. END_JUCE_NAMESPACE
  2740. /*** End of inlined file: juce_BigInteger.cpp ***/
  2741. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2742. BEGIN_JUCE_NAMESPACE
  2743. MemoryBlock::MemoryBlock() throw()
  2744. : size (0)
  2745. {
  2746. }
  2747. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2748. {
  2749. if (initialSize > 0)
  2750. {
  2751. size = initialSize;
  2752. data.allocate (initialSize, initialiseToZero);
  2753. }
  2754. else
  2755. {
  2756. size = 0;
  2757. }
  2758. }
  2759. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2760. : size (other.size)
  2761. {
  2762. if (size > 0)
  2763. {
  2764. jassert (other.data != 0);
  2765. data.malloc (size);
  2766. memcpy (data, other.data, size);
  2767. }
  2768. }
  2769. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2770. : size (jmax ((size_t) 0, sizeInBytes))
  2771. {
  2772. jassert (sizeInBytes >= 0);
  2773. if (size > 0)
  2774. {
  2775. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2776. data.malloc (size);
  2777. if (dataToInitialiseFrom != 0)
  2778. memcpy (data, dataToInitialiseFrom, size);
  2779. }
  2780. }
  2781. MemoryBlock::~MemoryBlock() throw()
  2782. {
  2783. jassert (size >= 0); // should never happen
  2784. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2785. }
  2786. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2787. {
  2788. if (this != &other)
  2789. {
  2790. setSize (other.size, false);
  2791. memcpy (data, other.data, size);
  2792. }
  2793. return *this;
  2794. }
  2795. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2796. {
  2797. return matches (other.data, other.size);
  2798. }
  2799. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2800. {
  2801. return ! operator== (other);
  2802. }
  2803. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2804. {
  2805. return size == dataSize
  2806. && memcmp (data, dataToCompare, size) == 0;
  2807. }
  2808. // this will resize the block to this size
  2809. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2810. {
  2811. if (size != newSize)
  2812. {
  2813. if (newSize <= 0)
  2814. {
  2815. data.free();
  2816. size = 0;
  2817. }
  2818. else
  2819. {
  2820. if (data != 0)
  2821. {
  2822. data.realloc (newSize);
  2823. if (initialiseToZero && (newSize > size))
  2824. zeromem (data + size, newSize - size);
  2825. }
  2826. else
  2827. {
  2828. data.allocate (newSize, initialiseToZero);
  2829. }
  2830. size = newSize;
  2831. }
  2832. }
  2833. }
  2834. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2835. {
  2836. if (size < minimumSize)
  2837. setSize (minimumSize, initialiseToZero);
  2838. }
  2839. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2840. {
  2841. swapVariables (size, other.size);
  2842. data.swapWith (other.data);
  2843. }
  2844. void MemoryBlock::fillWith (const uint8 value) throw()
  2845. {
  2846. memset (data, (int) value, size);
  2847. }
  2848. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2849. {
  2850. if (numBytes > 0)
  2851. {
  2852. const size_t oldSize = size;
  2853. setSize (size + numBytes);
  2854. memcpy (data + oldSize, srcData, numBytes);
  2855. }
  2856. }
  2857. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2858. {
  2859. const char* d = static_cast<const char*> (src);
  2860. if (offset < 0)
  2861. {
  2862. d -= offset;
  2863. num -= offset;
  2864. offset = 0;
  2865. }
  2866. if (offset + num > size)
  2867. num = size - offset;
  2868. if (num > 0)
  2869. memcpy (data + offset, d, num);
  2870. }
  2871. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2872. {
  2873. char* d = static_cast<char*> (dst);
  2874. if (offset < 0)
  2875. {
  2876. zeromem (d, -offset);
  2877. d -= offset;
  2878. num += offset;
  2879. offset = 0;
  2880. }
  2881. if (offset + num > size)
  2882. {
  2883. const size_t newNum = size - offset;
  2884. zeromem (d + newNum, num - newNum);
  2885. num = newNum;
  2886. }
  2887. if (num > 0)
  2888. memcpy (d, data + offset, num);
  2889. }
  2890. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2891. {
  2892. if (startByte < 0)
  2893. {
  2894. numBytesToRemove += startByte;
  2895. startByte = 0;
  2896. }
  2897. if (startByte + numBytesToRemove >= size)
  2898. {
  2899. setSize (startByte);
  2900. }
  2901. else if (numBytesToRemove > 0)
  2902. {
  2903. memmove (data + startByte,
  2904. data + startByte + numBytesToRemove,
  2905. size - (startByte + numBytesToRemove));
  2906. setSize (size - numBytesToRemove);
  2907. }
  2908. }
  2909. const String MemoryBlock::toString() const
  2910. {
  2911. return String (static_cast <const char*> (getData()), size);
  2912. }
  2913. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2914. {
  2915. int res = 0;
  2916. size_t byte = bitRangeStart >> 3;
  2917. int offsetInByte = (int) bitRangeStart & 7;
  2918. size_t bitsSoFar = 0;
  2919. while (numBits > 0 && (size_t) byte < size)
  2920. {
  2921. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2922. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2923. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2924. bitsSoFar += bitsThisTime;
  2925. numBits -= bitsThisTime;
  2926. ++byte;
  2927. offsetInByte = 0;
  2928. }
  2929. return res;
  2930. }
  2931. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2932. {
  2933. size_t byte = bitRangeStart >> 3;
  2934. int offsetInByte = (int) bitRangeStart & 7;
  2935. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2936. while (numBits > 0 && (size_t) byte < size)
  2937. {
  2938. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2939. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2940. const unsigned int tempBits = bitsToSet << offsetInByte;
  2941. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2942. ++byte;
  2943. numBits -= bitsThisTime;
  2944. bitsToSet >>= bitsThisTime;
  2945. mask >>= bitsThisTime;
  2946. offsetInByte = 0;
  2947. }
  2948. }
  2949. void MemoryBlock::loadFromHexString (const String& hex)
  2950. {
  2951. ensureSize (hex.length() >> 1);
  2952. char* dest = data;
  2953. int i = 0;
  2954. for (;;)
  2955. {
  2956. int byte = 0;
  2957. for (int loop = 2; --loop >= 0;)
  2958. {
  2959. byte <<= 4;
  2960. for (;;)
  2961. {
  2962. const juce_wchar c = hex [i++];
  2963. if (c >= '0' && c <= '9')
  2964. {
  2965. byte |= c - '0';
  2966. break;
  2967. }
  2968. else if (c >= 'a' && c <= 'z')
  2969. {
  2970. byte |= c - ('a' - 10);
  2971. break;
  2972. }
  2973. else if (c >= 'A' && c <= 'Z')
  2974. {
  2975. byte |= c - ('A' - 10);
  2976. break;
  2977. }
  2978. else if (c == 0)
  2979. {
  2980. setSize (static_cast <size_t> (dest - data));
  2981. return;
  2982. }
  2983. }
  2984. }
  2985. *dest++ = (char) byte;
  2986. }
  2987. }
  2988. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2989. const String MemoryBlock::toBase64Encoding() const
  2990. {
  2991. const size_t numChars = ((size << 3) + 5) / 6;
  2992. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2993. const int initialLen = destString.length();
  2994. destString.preallocateStorage (initialLen + 2 + numChars);
  2995. juce_wchar* d = destString;
  2996. d += initialLen;
  2997. *d++ = '.';
  2998. for (size_t i = 0; i < numChars; ++i)
  2999. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3000. *d++ = 0;
  3001. return destString;
  3002. }
  3003. bool MemoryBlock::fromBase64Encoding (const String& s)
  3004. {
  3005. const int startPos = s.indexOfChar ('.') + 1;
  3006. if (startPos <= 0)
  3007. return false;
  3008. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3009. setSize (numBytesNeeded, true);
  3010. const int numChars = s.length() - startPos;
  3011. const juce_wchar* srcChars = s;
  3012. srcChars += startPos;
  3013. int pos = 0;
  3014. for (int i = 0; i < numChars; ++i)
  3015. {
  3016. const char c = (char) srcChars[i];
  3017. for (int j = 0; j < 64; ++j)
  3018. {
  3019. if (encodingTable[j] == c)
  3020. {
  3021. setBitRange (pos, 6, j);
  3022. pos += 6;
  3023. break;
  3024. }
  3025. }
  3026. }
  3027. return true;
  3028. }
  3029. END_JUCE_NAMESPACE
  3030. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3031. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3032. BEGIN_JUCE_NAMESPACE
  3033. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3034. : properties (ignoreCaseOfKeyNames),
  3035. fallbackProperties (0),
  3036. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3037. {
  3038. }
  3039. PropertySet::PropertySet (const PropertySet& other)
  3040. : properties (other.properties),
  3041. fallbackProperties (other.fallbackProperties),
  3042. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3043. {
  3044. }
  3045. PropertySet& PropertySet::operator= (const PropertySet& other)
  3046. {
  3047. properties = other.properties;
  3048. fallbackProperties = other.fallbackProperties;
  3049. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3050. propertyChanged();
  3051. return *this;
  3052. }
  3053. PropertySet::~PropertySet()
  3054. {
  3055. }
  3056. void PropertySet::clear()
  3057. {
  3058. const ScopedLock sl (lock);
  3059. if (properties.size() > 0)
  3060. {
  3061. properties.clear();
  3062. propertyChanged();
  3063. }
  3064. }
  3065. const String PropertySet::getValue (const String& keyName,
  3066. const String& defaultValue) const throw()
  3067. {
  3068. const ScopedLock sl (lock);
  3069. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3070. if (index >= 0)
  3071. return properties.getAllValues() [index];
  3072. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3073. : defaultValue;
  3074. }
  3075. int PropertySet::getIntValue (const String& keyName,
  3076. const int defaultValue) const throw()
  3077. {
  3078. const ScopedLock sl (lock);
  3079. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3080. if (index >= 0)
  3081. return properties.getAllValues() [index].getIntValue();
  3082. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3083. : defaultValue;
  3084. }
  3085. double PropertySet::getDoubleValue (const String& keyName,
  3086. const double defaultValue) const throw()
  3087. {
  3088. const ScopedLock sl (lock);
  3089. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3090. if (index >= 0)
  3091. return properties.getAllValues()[index].getDoubleValue();
  3092. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3093. : defaultValue;
  3094. }
  3095. bool PropertySet::getBoolValue (const String& keyName,
  3096. const bool defaultValue) const throw()
  3097. {
  3098. const ScopedLock sl (lock);
  3099. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3100. if (index >= 0)
  3101. return properties.getAllValues() [index].getIntValue() != 0;
  3102. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3103. : defaultValue;
  3104. }
  3105. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3106. {
  3107. XmlDocument doc (getValue (keyName));
  3108. return doc.getDocumentElement();
  3109. }
  3110. void PropertySet::setValue (const String& keyName, const var& v)
  3111. {
  3112. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3113. if (keyName.isNotEmpty())
  3114. {
  3115. const String value (v.toString());
  3116. const ScopedLock sl (lock);
  3117. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3118. if (index < 0 || properties.getAllValues() [index] != value)
  3119. {
  3120. properties.set (keyName, value);
  3121. propertyChanged();
  3122. }
  3123. }
  3124. }
  3125. void PropertySet::removeValue (const String& keyName)
  3126. {
  3127. if (keyName.isNotEmpty())
  3128. {
  3129. const ScopedLock sl (lock);
  3130. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3131. if (index >= 0)
  3132. {
  3133. properties.remove (keyName);
  3134. propertyChanged();
  3135. }
  3136. }
  3137. }
  3138. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3139. {
  3140. setValue (keyName, xml == 0 ? var::null
  3141. : var (xml->createDocument (String::empty, true)));
  3142. }
  3143. bool PropertySet::containsKey (const String& keyName) const throw()
  3144. {
  3145. const ScopedLock sl (lock);
  3146. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3147. }
  3148. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3149. {
  3150. const ScopedLock sl (lock);
  3151. fallbackProperties = fallbackProperties_;
  3152. }
  3153. XmlElement* PropertySet::createXml (const String& nodeName) const
  3154. {
  3155. const ScopedLock sl (lock);
  3156. XmlElement* const xml = new XmlElement (nodeName);
  3157. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3158. {
  3159. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3160. e->setAttribute ("name", properties.getAllKeys()[i]);
  3161. e->setAttribute ("val", properties.getAllValues()[i]);
  3162. }
  3163. return xml;
  3164. }
  3165. void PropertySet::restoreFromXml (const XmlElement& xml)
  3166. {
  3167. const ScopedLock sl (lock);
  3168. clear();
  3169. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3170. {
  3171. if (e->hasAttribute ("name")
  3172. && e->hasAttribute ("val"))
  3173. {
  3174. properties.set (e->getStringAttribute ("name"),
  3175. e->getStringAttribute ("val"));
  3176. }
  3177. }
  3178. if (properties.size() > 0)
  3179. propertyChanged();
  3180. }
  3181. void PropertySet::propertyChanged()
  3182. {
  3183. }
  3184. END_JUCE_NAMESPACE
  3185. /*** End of inlined file: juce_PropertySet.cpp ***/
  3186. /*** Start of inlined file: juce_Identifier.cpp ***/
  3187. BEGIN_JUCE_NAMESPACE
  3188. StringPool& Identifier::getPool()
  3189. {
  3190. static StringPool pool;
  3191. return pool;
  3192. }
  3193. Identifier::Identifier() throw()
  3194. : name (0)
  3195. {
  3196. }
  3197. Identifier::Identifier (const Identifier& other) throw()
  3198. : name (other.name)
  3199. {
  3200. }
  3201. Identifier& Identifier::operator= (const Identifier& other) throw()
  3202. {
  3203. name = other.name;
  3204. return *this;
  3205. }
  3206. Identifier::Identifier (const String& name_)
  3207. : name (Identifier::getPool().getPooledString (name_))
  3208. {
  3209. /* An Identifier string must be suitable for use as a script variable or XML
  3210. attribute, so it can only contain this limited set of characters.. */
  3211. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3212. }
  3213. Identifier::Identifier (const char* const name_)
  3214. : name (Identifier::getPool().getPooledString (name_))
  3215. {
  3216. /* An Identifier string must be suitable for use as a script variable or XML
  3217. attribute, so it can only contain this limited set of characters.. */
  3218. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3219. }
  3220. Identifier::~Identifier()
  3221. {
  3222. }
  3223. END_JUCE_NAMESPACE
  3224. /*** End of inlined file: juce_Identifier.cpp ***/
  3225. /*** Start of inlined file: juce_Variant.cpp ***/
  3226. BEGIN_JUCE_NAMESPACE
  3227. class var::VariantType
  3228. {
  3229. public:
  3230. VariantType() {}
  3231. virtual ~VariantType() {}
  3232. virtual int toInt (const ValueUnion&) const { return 0; }
  3233. virtual double toDouble (const ValueUnion&) const { return 0; }
  3234. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3235. virtual bool toBool (const ValueUnion&) const { return false; }
  3236. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3237. virtual bool isVoid() const throw() { return false; }
  3238. virtual bool isInt() const throw() { return false; }
  3239. virtual bool isBool() const throw() { return false; }
  3240. virtual bool isDouble() const throw() { return false; }
  3241. virtual bool isString() const throw() { return false; }
  3242. virtual bool isObject() const throw() { return false; }
  3243. virtual bool isMethod() const throw() { return false; }
  3244. virtual void cleanUp (ValueUnion&) const throw() {}
  3245. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3246. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3247. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3248. };
  3249. class var::VariantType_Void : public var::VariantType
  3250. {
  3251. public:
  3252. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3253. bool isVoid() const throw() { return true; }
  3254. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3255. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3256. };
  3257. class var::VariantType_Int : public var::VariantType
  3258. {
  3259. public:
  3260. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3261. int toInt (const ValueUnion& data) const { return data.intValue; };
  3262. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3263. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3264. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3265. bool isInt() const throw() { return true; }
  3266. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3267. {
  3268. return otherType.toInt (otherData) == data.intValue;
  3269. }
  3270. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3271. {
  3272. output.writeCompressedInt (5);
  3273. output.writeByte (1);
  3274. output.writeInt (data.intValue);
  3275. }
  3276. };
  3277. class var::VariantType_Double : public var::VariantType
  3278. {
  3279. public:
  3280. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3281. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3282. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3283. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3284. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3285. bool isDouble() const throw() { return true; }
  3286. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3287. {
  3288. return otherType.toDouble (otherData) == data.doubleValue;
  3289. }
  3290. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3291. {
  3292. output.writeCompressedInt (9);
  3293. output.writeByte (4);
  3294. output.writeDouble (data.doubleValue);
  3295. }
  3296. };
  3297. class var::VariantType_Bool : public var::VariantType
  3298. {
  3299. public:
  3300. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3301. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3302. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3303. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3304. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3305. bool isBool() const throw() { return true; }
  3306. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3307. {
  3308. return otherType.toBool (otherData) == data.boolValue;
  3309. }
  3310. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3311. {
  3312. output.writeCompressedInt (1);
  3313. output.writeByte (data.boolValue ? 2 : 3);
  3314. }
  3315. };
  3316. class var::VariantType_String : public var::VariantType
  3317. {
  3318. public:
  3319. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3320. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3321. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3322. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3323. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3324. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3325. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3326. || data.stringValue->trim().equalsIgnoreCase ("true")
  3327. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3328. bool isString() const throw() { return true; }
  3329. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3330. {
  3331. return otherType.toString (otherData) == *data.stringValue;
  3332. }
  3333. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3334. {
  3335. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3336. output.writeCompressedInt (len + 1);
  3337. output.writeByte (5);
  3338. HeapBlock<char> temp (len);
  3339. data.stringValue->copyToUTF8 (temp, len);
  3340. output.write (temp, len);
  3341. }
  3342. };
  3343. class var::VariantType_Object : public var::VariantType
  3344. {
  3345. public:
  3346. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3347. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3348. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3349. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3350. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3351. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3352. bool isObject() const throw() { return true; }
  3353. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3354. {
  3355. return otherType.toObject (otherData) == data.objectValue;
  3356. }
  3357. void writeToStream (const ValueUnion&, OutputStream& output) const
  3358. {
  3359. jassertfalse; // Can't write an object to a stream!
  3360. output.writeCompressedInt (0);
  3361. }
  3362. };
  3363. class var::VariantType_Method : public var::VariantType
  3364. {
  3365. public:
  3366. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3367. const String toString (const ValueUnion&) const { return "Method"; }
  3368. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3369. bool isMethod() const throw() { return true; }
  3370. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3371. {
  3372. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3373. }
  3374. void writeToStream (const ValueUnion&, OutputStream& output) const
  3375. {
  3376. jassertfalse; // Can't write a method to a stream!
  3377. output.writeCompressedInt (0);
  3378. }
  3379. };
  3380. var::var() throw()
  3381. : type (VariantType_Void::getInstance())
  3382. {
  3383. }
  3384. var::~var() throw()
  3385. {
  3386. type->cleanUp (value);
  3387. }
  3388. const var var::null;
  3389. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3390. {
  3391. type->createCopy (value, valueToCopy.value);
  3392. }
  3393. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3394. {
  3395. value.intValue = value_;
  3396. }
  3397. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3398. {
  3399. value.boolValue = value_;
  3400. }
  3401. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3402. {
  3403. value.doubleValue = value_;
  3404. }
  3405. var::var (const String& value_) : type (VariantType_String::getInstance())
  3406. {
  3407. value.stringValue = new String (value_);
  3408. }
  3409. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3410. {
  3411. value.stringValue = new String (value_);
  3412. }
  3413. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3414. {
  3415. value.stringValue = new String (value_);
  3416. }
  3417. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3418. {
  3419. value.objectValue = object;
  3420. if (object != 0)
  3421. object->incReferenceCount();
  3422. }
  3423. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3424. {
  3425. value.methodValue = method_;
  3426. }
  3427. bool var::isVoid() const throw() { return type->isVoid(); }
  3428. bool var::isInt() const throw() { return type->isInt(); }
  3429. bool var::isBool() const throw() { return type->isBool(); }
  3430. bool var::isDouble() const throw() { return type->isDouble(); }
  3431. bool var::isString() const throw() { return type->isString(); }
  3432. bool var::isObject() const throw() { return type->isObject(); }
  3433. bool var::isMethod() const throw() { return type->isMethod(); }
  3434. var::operator int() const { return type->toInt (value); }
  3435. var::operator bool() const { return type->toBool (value); }
  3436. var::operator float() const { return (float) type->toDouble (value); }
  3437. var::operator double() const { return type->toDouble (value); }
  3438. const String var::toString() const { return type->toString (value); }
  3439. var::operator const String() const { return type->toString (value); }
  3440. DynamicObject* var::getObject() const { return type->toObject (value); }
  3441. void var::swapWith (var& other) throw()
  3442. {
  3443. swapVariables (type, other.type);
  3444. swapVariables (value, other.value);
  3445. }
  3446. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3447. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3448. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3449. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3450. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3451. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3452. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3453. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3454. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3455. bool var::equals (const var& other) const throw()
  3456. {
  3457. return type->equals (value, other.value, *other.type);
  3458. }
  3459. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3460. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3461. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3462. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3463. void var::writeToStream (OutputStream& output) const
  3464. {
  3465. type->writeToStream (value, output);
  3466. }
  3467. const var var::readFromStream (InputStream& input)
  3468. {
  3469. const int numBytes = input.readCompressedInt();
  3470. if (numBytes > 0)
  3471. {
  3472. switch (input.readByte())
  3473. {
  3474. case 1: return var (input.readInt());
  3475. case 2: return var (true);
  3476. case 3: return var (false);
  3477. case 4: return var (input.readDouble());
  3478. case 5:
  3479. {
  3480. MemoryOutputStream mo;
  3481. mo.writeFromInputStream (input, numBytes - 1);
  3482. return var (mo.toUTF8());
  3483. }
  3484. default: input.skipNextBytes (numBytes - 1); break;
  3485. }
  3486. }
  3487. return var::null;
  3488. }
  3489. const var var::operator[] (const Identifier& propertyName) const
  3490. {
  3491. DynamicObject* const o = getObject();
  3492. return o != 0 ? o->getProperty (propertyName) : var::null;
  3493. }
  3494. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3495. {
  3496. DynamicObject* const o = getObject();
  3497. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3498. }
  3499. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3500. {
  3501. if (isMethod())
  3502. {
  3503. DynamicObject* const target = targetObject.getObject();
  3504. if (target != 0)
  3505. return (target->*(value.methodValue)) (arguments, numArguments);
  3506. }
  3507. return var::null;
  3508. }
  3509. const var var::call (const Identifier& method) const
  3510. {
  3511. return invoke (method, 0, 0);
  3512. }
  3513. const var var::call (const Identifier& method, const var& arg1) const
  3514. {
  3515. return invoke (method, &arg1, 1);
  3516. }
  3517. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3518. {
  3519. var args[] = { arg1, arg2 };
  3520. return invoke (method, args, 2);
  3521. }
  3522. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3523. {
  3524. var args[] = { arg1, arg2, arg3 };
  3525. return invoke (method, args, 3);
  3526. }
  3527. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3528. {
  3529. var args[] = { arg1, arg2, arg3, arg4 };
  3530. return invoke (method, args, 4);
  3531. }
  3532. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3533. {
  3534. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3535. return invoke (method, args, 5);
  3536. }
  3537. END_JUCE_NAMESPACE
  3538. /*** End of inlined file: juce_Variant.cpp ***/
  3539. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3540. BEGIN_JUCE_NAMESPACE
  3541. NamedValueSet::NamedValue::NamedValue() throw()
  3542. {
  3543. }
  3544. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3545. : name (name_), value (value_)
  3546. {
  3547. }
  3548. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3549. {
  3550. return name == other.name && value == other.value;
  3551. }
  3552. NamedValueSet::NamedValueSet() throw()
  3553. {
  3554. }
  3555. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3556. : values (other.values)
  3557. {
  3558. }
  3559. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3560. {
  3561. values = other.values;
  3562. return *this;
  3563. }
  3564. NamedValueSet::~NamedValueSet()
  3565. {
  3566. }
  3567. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3568. {
  3569. return values == other.values;
  3570. }
  3571. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3572. {
  3573. return ! operator== (other);
  3574. }
  3575. int NamedValueSet::size() const throw()
  3576. {
  3577. return values.size();
  3578. }
  3579. const var& NamedValueSet::operator[] (const Identifier& name) const
  3580. {
  3581. for (int i = values.size(); --i >= 0;)
  3582. {
  3583. const NamedValue& v = values.getReference(i);
  3584. if (v.name == name)
  3585. return v.value;
  3586. }
  3587. return var::null;
  3588. }
  3589. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3590. {
  3591. const var* v = getItem (name);
  3592. return v != 0 ? *v : defaultReturnValue;
  3593. }
  3594. var* NamedValueSet::getItem (const Identifier& name) const
  3595. {
  3596. for (int i = values.size(); --i >= 0;)
  3597. {
  3598. NamedValue& v = values.getReference(i);
  3599. if (v.name == name)
  3600. return &(v.value);
  3601. }
  3602. return 0;
  3603. }
  3604. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3605. {
  3606. for (int i = values.size(); --i >= 0;)
  3607. {
  3608. NamedValue& v = values.getReference(i);
  3609. if (v.name == name)
  3610. {
  3611. if (v.value == newValue)
  3612. return false;
  3613. v.value = newValue;
  3614. return true;
  3615. }
  3616. }
  3617. values.add (NamedValue (name, newValue));
  3618. return true;
  3619. }
  3620. bool NamedValueSet::contains (const Identifier& name) const
  3621. {
  3622. return getItem (name) != 0;
  3623. }
  3624. bool NamedValueSet::remove (const Identifier& name)
  3625. {
  3626. for (int i = values.size(); --i >= 0;)
  3627. {
  3628. if (values.getReference(i).name == name)
  3629. {
  3630. values.remove (i);
  3631. return true;
  3632. }
  3633. }
  3634. return false;
  3635. }
  3636. const Identifier NamedValueSet::getName (const int index) const
  3637. {
  3638. jassert (((unsigned int) index) < (unsigned int) values.size());
  3639. return values [index].name;
  3640. }
  3641. const var NamedValueSet::getValueAt (const int index) const
  3642. {
  3643. jassert (((unsigned int) index) < (unsigned int) values.size());
  3644. return values [index].value;
  3645. }
  3646. void NamedValueSet::clear()
  3647. {
  3648. values.clear();
  3649. }
  3650. END_JUCE_NAMESPACE
  3651. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3652. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3653. BEGIN_JUCE_NAMESPACE
  3654. DynamicObject::DynamicObject()
  3655. {
  3656. }
  3657. DynamicObject::~DynamicObject()
  3658. {
  3659. }
  3660. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3661. {
  3662. var* const v = properties.getItem (propertyName);
  3663. return v != 0 && ! v->isMethod();
  3664. }
  3665. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3666. {
  3667. return properties [propertyName];
  3668. }
  3669. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3670. {
  3671. properties.set (propertyName, newValue);
  3672. }
  3673. void DynamicObject::removeProperty (const Identifier& propertyName)
  3674. {
  3675. properties.remove (propertyName);
  3676. }
  3677. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3678. {
  3679. return getProperty (methodName).isMethod();
  3680. }
  3681. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3682. const var* parameters,
  3683. int numParameters)
  3684. {
  3685. return properties [methodName].invoke (var (this), parameters, numParameters);
  3686. }
  3687. void DynamicObject::setMethod (const Identifier& name,
  3688. var::MethodFunction methodFunction)
  3689. {
  3690. properties.set (name, var (methodFunction));
  3691. }
  3692. void DynamicObject::clear()
  3693. {
  3694. properties.clear();
  3695. }
  3696. END_JUCE_NAMESPACE
  3697. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3698. /*** Start of inlined file: juce_Expression.cpp ***/
  3699. BEGIN_JUCE_NAMESPACE
  3700. class Expression::Helpers
  3701. {
  3702. public:
  3703. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3704. class Constant : public Term
  3705. {
  3706. public:
  3707. Constant (const double value_, bool isResolutionTarget_)
  3708. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3709. Type getType() const throw() { return constantType; }
  3710. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3711. double evaluate (const EvaluationContext&, int) const { return value; }
  3712. int getNumInputs() const { return 0; }
  3713. Term* getInput (int) const { return 0; }
  3714. const TermPtr negated()
  3715. {
  3716. return new Constant (-value, isResolutionTarget);
  3717. }
  3718. const String toString() const
  3719. {
  3720. if (isResolutionTarget)
  3721. return "@" + String (value);
  3722. return String (value);
  3723. }
  3724. double value;
  3725. bool isResolutionTarget;
  3726. };
  3727. class Symbol : public Term
  3728. {
  3729. public:
  3730. explicit Symbol (const String& symbol_)
  3731. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3732. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3733. {}
  3734. Symbol (const String& symbol_, const String& member_)
  3735. : mainSymbol (symbol_),
  3736. member (member_)
  3737. {}
  3738. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3739. {
  3740. if (++recursionDepth > 256)
  3741. throw EvaluationError ("Recursive symbol references");
  3742. try
  3743. {
  3744. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3745. }
  3746. catch (...)
  3747. {}
  3748. return 0;
  3749. }
  3750. Type getType() const throw() { return symbolType; }
  3751. Term* clone() const { return new Symbol (mainSymbol, member); }
  3752. int getNumInputs() const { return 0; }
  3753. Term* getInput (int) const { return 0; }
  3754. const String getFunctionName() const { return toString(); }
  3755. const String toString() const
  3756. {
  3757. return member.isEmpty() ? mainSymbol
  3758. : mainSymbol + "." + member;
  3759. }
  3760. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3761. {
  3762. if (s == mainSymbol)
  3763. return true;
  3764. if (++recursionDepth > 256)
  3765. throw EvaluationError ("Recursive symbol references");
  3766. try
  3767. {
  3768. return c.getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3769. }
  3770. catch (EvaluationError&)
  3771. {
  3772. return false;
  3773. }
  3774. }
  3775. String mainSymbol, member;
  3776. };
  3777. class Function : public Term
  3778. {
  3779. public:
  3780. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3781. : functionName (functionName_), parameters (parameters_)
  3782. {}
  3783. Term* clone() const { return new Function (functionName, parameters); }
  3784. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3785. {
  3786. HeapBlock <double> params (parameters.size());
  3787. for (int i = 0; i < parameters.size(); ++i)
  3788. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3789. return c.evaluateFunction (functionName, params, parameters.size());
  3790. }
  3791. Type getType() const throw() { return functionType; }
  3792. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3793. int getNumInputs() const { return parameters.size(); }
  3794. Term* getInput (int i) const { return parameters [i]; }
  3795. const String getFunctionName() const { return functionName; }
  3796. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3797. {
  3798. for (int i = 0; i < parameters.size(); ++i)
  3799. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3800. return true;
  3801. return false;
  3802. }
  3803. const String toString() const
  3804. {
  3805. if (parameters.size() == 0)
  3806. return functionName + "()";
  3807. String s (functionName + " (");
  3808. for (int i = 0; i < parameters.size(); ++i)
  3809. {
  3810. s << parameters.getUnchecked(i)->toString();
  3811. if (i < parameters.size() - 1)
  3812. s << ", ";
  3813. }
  3814. s << ')';
  3815. return s;
  3816. }
  3817. const String functionName;
  3818. ReferenceCountedArray<Term> parameters;
  3819. };
  3820. class Negate : public Term
  3821. {
  3822. public:
  3823. Negate (const TermPtr& input_) : input (input_)
  3824. {
  3825. jassert (input_ != 0);
  3826. }
  3827. Type getType() const throw() { return operatorType; }
  3828. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3829. int getNumInputs() const { return 1; }
  3830. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3831. Term* clone() const { return new Negate (input->clone()); }
  3832. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3833. const String getFunctionName() const { return "-"; }
  3834. const TermPtr negated()
  3835. {
  3836. return input;
  3837. }
  3838. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3839. {
  3840. jassert (input_ == input);
  3841. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3842. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3843. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3844. }
  3845. const String toString() const
  3846. {
  3847. if (input->getOperatorPrecedence() > 0)
  3848. return "-(" + input->toString() + ")";
  3849. else
  3850. return "-" + input->toString();
  3851. }
  3852. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3853. {
  3854. return input->referencesSymbol (s, c, recursionDepth);
  3855. }
  3856. private:
  3857. const TermPtr input;
  3858. };
  3859. class BinaryTerm : public Term
  3860. {
  3861. public:
  3862. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3863. {
  3864. jassert (left_ != 0 && right_ != 0);
  3865. }
  3866. int getInputIndexFor (const Term* possibleInput) const
  3867. {
  3868. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3869. }
  3870. Type getType() const throw() { return operatorType; }
  3871. int getNumInputs() const { return 2; }
  3872. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3873. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3874. {
  3875. return left->referencesSymbol (s, c, recursionDepth)
  3876. || right->referencesSymbol (s, c, recursionDepth);
  3877. }
  3878. const String toString() const
  3879. {
  3880. String s;
  3881. const int ourPrecendence = getOperatorPrecedence();
  3882. if (left->getOperatorPrecedence() > ourPrecendence)
  3883. s << '(' << left->toString() << ')';
  3884. else
  3885. s = left->toString();
  3886. s << ' ' << getFunctionName() << ' ';
  3887. if (right->getOperatorPrecedence() >= ourPrecendence)
  3888. s << '(' << right->toString() << ')';
  3889. else
  3890. s << right->toString();
  3891. return s;
  3892. }
  3893. protected:
  3894. const TermPtr left, right;
  3895. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3896. {
  3897. jassert (input == left || input == right);
  3898. if (input != left && input != right)
  3899. return 0;
  3900. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3901. if (dest == 0)
  3902. return new Constant (overallTarget, false);
  3903. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3904. }
  3905. };
  3906. class Add : public BinaryTerm
  3907. {
  3908. public:
  3909. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3910. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3911. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3912. int getOperatorPrecedence() const { return 2; }
  3913. const String getFunctionName() const { return "+"; }
  3914. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3915. {
  3916. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3917. if (newDest == 0)
  3918. return 0;
  3919. return new Subtract (newDest, (input == left ? right : left)->clone());
  3920. }
  3921. };
  3922. class Subtract : public BinaryTerm
  3923. {
  3924. public:
  3925. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3926. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3927. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3928. int getOperatorPrecedence() const { return 2; }
  3929. const String getFunctionName() const { return "-"; }
  3930. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3931. {
  3932. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3933. if (newDest == 0)
  3934. return 0;
  3935. if (input == left)
  3936. return new Add (newDest, right->clone());
  3937. else
  3938. return new Subtract (left->clone(), newDest);
  3939. }
  3940. };
  3941. class Multiply : public BinaryTerm
  3942. {
  3943. public:
  3944. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3945. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  3946. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  3947. const String getFunctionName() const { return "*"; }
  3948. int getOperatorPrecedence() const { return 1; }
  3949. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3950. {
  3951. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3952. if (newDest == 0)
  3953. return 0;
  3954. return new Divide (newDest, (input == left ? right : left)->clone());
  3955. }
  3956. };
  3957. class Divide : public BinaryTerm
  3958. {
  3959. public:
  3960. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3961. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  3962. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  3963. const String getFunctionName() const { return "/"; }
  3964. int getOperatorPrecedence() const { return 1; }
  3965. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3966. {
  3967. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3968. if (newDest == 0)
  3969. return 0;
  3970. if (input == left)
  3971. return new Multiply (newDest, right->clone());
  3972. else
  3973. return new Divide (left->clone(), newDest);
  3974. }
  3975. };
  3976. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  3977. {
  3978. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  3979. if (inputIndex >= 0)
  3980. return topLevel;
  3981. for (int i = topLevel->getNumInputs(); --i >= 0;)
  3982. {
  3983. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  3984. if (t != 0)
  3985. return t;
  3986. }
  3987. return 0;
  3988. }
  3989. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  3990. {
  3991. Constant* c = dynamic_cast<Constant*> (term);
  3992. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  3993. return c;
  3994. if (dynamic_cast<Function*> (term) != 0)
  3995. return 0;
  3996. int i;
  3997. const int numIns = term->getNumInputs();
  3998. for (i = 0; i < numIns; ++i)
  3999. {
  4000. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4001. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4002. return c;
  4003. }
  4004. for (i = 0; i < numIns; ++i)
  4005. {
  4006. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4007. if (c != 0)
  4008. return c;
  4009. }
  4010. return 0;
  4011. }
  4012. static bool containsAnySymbols (const Term* const t)
  4013. {
  4014. if (dynamic_cast <const Symbol*> (t) != 0)
  4015. return true;
  4016. for (int i = t->getNumInputs(); --i >= 0;)
  4017. if (containsAnySymbols (t->getInput (i)))
  4018. return true;
  4019. return false;
  4020. }
  4021. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4022. {
  4023. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4024. if (sym != 0 && sym->mainSymbol == oldName)
  4025. {
  4026. sym->mainSymbol = newName;
  4027. return true;
  4028. }
  4029. bool anyChanged = false;
  4030. for (int i = t->getNumInputs(); --i >= 0;)
  4031. if (renameSymbol (t->getInput (i), oldName, newName))
  4032. anyChanged = true;
  4033. return anyChanged;
  4034. }
  4035. class Parser
  4036. {
  4037. public:
  4038. Parser (const String& stringToParse, int& textIndex_)
  4039. : textString (stringToParse), textIndex (textIndex_)
  4040. {
  4041. text = textString;
  4042. }
  4043. const TermPtr readExpression()
  4044. {
  4045. TermPtr lhs (readMultiplyOrDivideExpression());
  4046. char opType;
  4047. while (lhs != 0 && readOperator ("+-", &opType))
  4048. {
  4049. TermPtr rhs (readMultiplyOrDivideExpression());
  4050. if (rhs == 0)
  4051. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4052. if (opType == '+')
  4053. lhs = new Add (lhs, rhs);
  4054. else
  4055. lhs = new Subtract (lhs, rhs);
  4056. }
  4057. return lhs;
  4058. }
  4059. private:
  4060. const String textString;
  4061. const juce_wchar* text;
  4062. int& textIndex;
  4063. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4064. {
  4065. return c >= '0' && c <= '9';
  4066. }
  4067. void skipWhitespace (int& i)
  4068. {
  4069. while (CharacterFunctions::isWhitespace (text [i]))
  4070. ++i;
  4071. }
  4072. bool readChar (const juce_wchar required)
  4073. {
  4074. if (text[textIndex] == required)
  4075. {
  4076. ++textIndex;
  4077. return true;
  4078. }
  4079. return false;
  4080. }
  4081. bool readOperator (const char* ops, char* const opType = 0)
  4082. {
  4083. skipWhitespace (textIndex);
  4084. while (*ops != 0)
  4085. {
  4086. if (readChar (*ops))
  4087. {
  4088. if (opType != 0)
  4089. *opType = *ops;
  4090. return true;
  4091. }
  4092. ++ops;
  4093. }
  4094. return false;
  4095. }
  4096. bool readIdentifier (String& identifier)
  4097. {
  4098. skipWhitespace (textIndex);
  4099. int i = textIndex;
  4100. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4101. {
  4102. ++i;
  4103. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4104. ++i;
  4105. }
  4106. if (i > textIndex)
  4107. {
  4108. identifier = String (text + textIndex, i - textIndex);
  4109. textIndex = i;
  4110. return true;
  4111. }
  4112. return false;
  4113. }
  4114. Term* readNumber()
  4115. {
  4116. skipWhitespace (textIndex);
  4117. int i = textIndex;
  4118. const bool isResolutionTarget = (text[i] == '@');
  4119. if (isResolutionTarget)
  4120. {
  4121. ++i;
  4122. skipWhitespace (i);
  4123. textIndex = i;
  4124. }
  4125. if (text[i] == '-')
  4126. {
  4127. ++i;
  4128. skipWhitespace (i);
  4129. }
  4130. int numDigits = 0;
  4131. while (isDecimalDigit (text[i]))
  4132. {
  4133. ++i;
  4134. ++numDigits;
  4135. }
  4136. const bool hasPoint = (text[i] == '.');
  4137. if (hasPoint)
  4138. {
  4139. ++i;
  4140. while (isDecimalDigit (text[i]))
  4141. {
  4142. ++i;
  4143. ++numDigits;
  4144. }
  4145. }
  4146. if (numDigits == 0)
  4147. return 0;
  4148. juce_wchar c = text[i];
  4149. const bool hasExponent = (c == 'e' || c == 'E');
  4150. if (hasExponent)
  4151. {
  4152. ++i;
  4153. c = text[i];
  4154. if (c == '+' || c == '-')
  4155. ++i;
  4156. int numExpDigits = 0;
  4157. while (isDecimalDigit (text[i]))
  4158. {
  4159. ++i;
  4160. ++numExpDigits;
  4161. }
  4162. if (numExpDigits == 0)
  4163. return 0;
  4164. }
  4165. const int start = textIndex;
  4166. textIndex = i;
  4167. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4168. }
  4169. const TermPtr readMultiplyOrDivideExpression()
  4170. {
  4171. TermPtr lhs (readUnaryExpression());
  4172. char opType;
  4173. while (lhs != 0 && readOperator ("*/", &opType))
  4174. {
  4175. TermPtr rhs (readUnaryExpression());
  4176. if (rhs == 0)
  4177. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4178. if (opType == '*')
  4179. lhs = new Multiply (lhs, rhs);
  4180. else
  4181. lhs = new Divide (lhs, rhs);
  4182. }
  4183. return lhs;
  4184. }
  4185. const TermPtr readUnaryExpression()
  4186. {
  4187. char opType;
  4188. if (readOperator ("+-", &opType))
  4189. {
  4190. TermPtr term (readUnaryExpression());
  4191. if (term == 0)
  4192. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4193. if (opType == '-')
  4194. term = term->negated();
  4195. return term;
  4196. }
  4197. return readPrimaryExpression();
  4198. }
  4199. const TermPtr readPrimaryExpression()
  4200. {
  4201. TermPtr e (readParenthesisedExpression());
  4202. if (e != 0)
  4203. return e;
  4204. e = readNumber();
  4205. if (e != 0)
  4206. return e;
  4207. String identifier;
  4208. if (readIdentifier (identifier))
  4209. {
  4210. if (readOperator ("(")) // method call...
  4211. {
  4212. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4213. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4214. TermPtr param (readExpression());
  4215. if (param == 0)
  4216. {
  4217. if (readOperator (")"))
  4218. return func.release();
  4219. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4220. }
  4221. f->parameters.add (param);
  4222. while (readOperator (","))
  4223. {
  4224. param = readExpression();
  4225. if (param == 0)
  4226. throw ParseError ("Expected expression after \",\"");
  4227. f->parameters.add (param);
  4228. }
  4229. if (readOperator (")"))
  4230. return func.release();
  4231. throw ParseError ("Expected \")\"");
  4232. }
  4233. else // just a symbol..
  4234. {
  4235. return new Symbol (identifier);
  4236. }
  4237. }
  4238. return 0;
  4239. }
  4240. const TermPtr readParenthesisedExpression()
  4241. {
  4242. if (! readOperator ("("))
  4243. return 0;
  4244. const TermPtr e (readExpression());
  4245. if (e == 0 || ! readOperator (")"))
  4246. return 0;
  4247. return e;
  4248. }
  4249. Parser (const Parser&);
  4250. Parser& operator= (const Parser&);
  4251. };
  4252. };
  4253. Expression::Expression()
  4254. : term (new Expression::Helpers::Constant (0, false))
  4255. {
  4256. }
  4257. Expression::~Expression()
  4258. {
  4259. }
  4260. Expression::Expression (Term* const term_)
  4261. : term (term_)
  4262. {
  4263. jassert (term != 0);
  4264. }
  4265. Expression::Expression (const double constant)
  4266. : term (new Expression::Helpers::Constant (constant, false))
  4267. {
  4268. }
  4269. Expression::Expression (const Expression& other)
  4270. : term (other.term)
  4271. {
  4272. }
  4273. Expression& Expression::operator= (const Expression& other)
  4274. {
  4275. term = other.term;
  4276. return *this;
  4277. }
  4278. Expression::Expression (const String& stringToParse)
  4279. {
  4280. int i = 0;
  4281. Helpers::Parser parser (stringToParse, i);
  4282. term = parser.readExpression();
  4283. if (term == 0)
  4284. term = new Helpers::Constant (0, false);
  4285. }
  4286. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4287. {
  4288. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4289. const Helpers::TermPtr term (parser.readExpression());
  4290. if (term != 0)
  4291. return Expression (term);
  4292. return Expression();
  4293. }
  4294. double Expression::evaluate() const
  4295. {
  4296. return evaluate (Expression::EvaluationContext());
  4297. }
  4298. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4299. {
  4300. return term->evaluate (context, 0);
  4301. }
  4302. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4303. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4304. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4305. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4306. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4307. const String Expression::toString() const
  4308. {
  4309. return term->toString();
  4310. }
  4311. const Expression Expression::symbol (const String& symbol)
  4312. {
  4313. return Expression (new Helpers::Symbol (symbol));
  4314. }
  4315. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4316. {
  4317. ReferenceCountedArray<Term> params;
  4318. for (int i = 0; i < parameters.size(); ++i)
  4319. params.add (parameters.getReference(i).term);
  4320. return Expression (new Helpers::Function (functionName, params));
  4321. }
  4322. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4323. const Expression::EvaluationContext& context) const
  4324. {
  4325. ScopedPointer<Term> newTerm (term->clone());
  4326. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4327. if (termToAdjust == 0)
  4328. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4329. if (termToAdjust == 0)
  4330. {
  4331. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4332. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4333. }
  4334. jassert (termToAdjust != 0);
  4335. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4336. if (parent == 0)
  4337. {
  4338. termToAdjust->value = targetValue;
  4339. }
  4340. else
  4341. {
  4342. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4343. if (reverseTerm == 0)
  4344. return Expression (targetValue);
  4345. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4346. }
  4347. return Expression (newTerm.release());
  4348. }
  4349. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4350. {
  4351. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4352. Expression newExpression (term->clone());
  4353. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4354. return newExpression;
  4355. }
  4356. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext& context) const
  4357. {
  4358. return term->referencesSymbol (symbol, context, 0);
  4359. }
  4360. bool Expression::usesAnySymbols() const
  4361. {
  4362. return Helpers::containsAnySymbols (term);
  4363. }
  4364. Expression::Type Expression::getType() const throw()
  4365. {
  4366. return term->getType();
  4367. }
  4368. const String Expression::getSymbol() const
  4369. {
  4370. return term->getSymbolName();
  4371. }
  4372. const String Expression::getFunction() const
  4373. {
  4374. return term->getFunctionName();
  4375. }
  4376. const String Expression::getOperator() const
  4377. {
  4378. return term->getFunctionName();
  4379. }
  4380. int Expression::getNumInputs() const
  4381. {
  4382. return term->getNumInputs();
  4383. }
  4384. const Expression Expression::getInput (int index) const
  4385. {
  4386. return Expression (term->getInput (index));
  4387. }
  4388. int Expression::Term::getOperatorPrecedence() const
  4389. {
  4390. return 0;
  4391. }
  4392. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext&, int) const
  4393. {
  4394. return false;
  4395. }
  4396. int Expression::Term::getInputIndexFor (const Term*) const
  4397. {
  4398. return -1;
  4399. }
  4400. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4401. {
  4402. jassertfalse;
  4403. return 0;
  4404. }
  4405. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4406. {
  4407. return new Helpers::Negate (this);
  4408. }
  4409. const String Expression::Term::getSymbolName() const
  4410. {
  4411. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4412. return String::empty;
  4413. }
  4414. const String Expression::Term::getFunctionName() const
  4415. {
  4416. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4417. return String::empty;
  4418. }
  4419. Expression::ParseError::ParseError (const String& message)
  4420. : description (message)
  4421. {
  4422. DBG ("Expression::ParseError: " + message);
  4423. }
  4424. Expression::EvaluationError::EvaluationError (const String& message)
  4425. : description (message)
  4426. {
  4427. DBG ("Expression::EvaluationError: " + message);
  4428. }
  4429. Expression::EvaluationContext::EvaluationContext() {}
  4430. Expression::EvaluationContext::~EvaluationContext() {}
  4431. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4432. {
  4433. throw EvaluationError ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")));
  4434. }
  4435. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4436. {
  4437. if (numParams > 0)
  4438. {
  4439. if (functionName == "min")
  4440. {
  4441. double v = parameters[0];
  4442. for (int i = 1; i < numParams; ++i)
  4443. v = jmin (v, parameters[i]);
  4444. return v;
  4445. }
  4446. else if (functionName == "max")
  4447. {
  4448. double v = parameters[0];
  4449. for (int i = 1; i < numParams; ++i)
  4450. v = jmax (v, parameters[i]);
  4451. return v;
  4452. }
  4453. else if (numParams == 1)
  4454. {
  4455. if (functionName == "sin")
  4456. return sin (parameters[0]);
  4457. else if (functionName == "cos")
  4458. return cos (parameters[0]);
  4459. else if (functionName == "tan")
  4460. return tan (parameters[0]);
  4461. else if (functionName == "abs")
  4462. return std::abs (parameters[0]);
  4463. }
  4464. }
  4465. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4466. }
  4467. END_JUCE_NAMESPACE
  4468. /*** End of inlined file: juce_Expression.cpp ***/
  4469. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4470. BEGIN_JUCE_NAMESPACE
  4471. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4472. {
  4473. jassert (keyData != 0);
  4474. jassert (keyBytes > 0);
  4475. static const uint32 initialPValues [18] =
  4476. {
  4477. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4478. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4479. 0x9216d5d9, 0x8979fb1b
  4480. };
  4481. static const uint32 initialSValues [4 * 256] =
  4482. {
  4483. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4484. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4485. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4486. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4487. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4488. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4489. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4490. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4491. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4492. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4493. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4494. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4495. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4496. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4497. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4498. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4499. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4500. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4501. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4502. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4503. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4504. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4505. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4506. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4507. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4508. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4509. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4510. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4511. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4512. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4513. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4514. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4515. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4516. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4517. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4518. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4519. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4520. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4521. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4522. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4523. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4524. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4525. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4526. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4527. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4528. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4529. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4530. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4531. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4532. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4533. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4534. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4535. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4536. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4537. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4538. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4539. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4540. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4541. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4542. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4543. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4544. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4545. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4546. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4547. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4548. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4549. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4550. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4551. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4552. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4553. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4554. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4555. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4556. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4557. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4558. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4559. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4560. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4561. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4562. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4563. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4564. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4565. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4566. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4567. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4568. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4569. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4570. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4571. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4572. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4573. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4574. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4575. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4576. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4577. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4578. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4579. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4580. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4581. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4582. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4583. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4584. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4585. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4586. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4587. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4588. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4589. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4590. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4591. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4592. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4593. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4594. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4595. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4596. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4597. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4598. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4599. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4600. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4601. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4602. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4603. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4604. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4605. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4606. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4607. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4608. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4609. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4610. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4611. };
  4612. memcpy (p, initialPValues, sizeof (p));
  4613. int i, j = 0;
  4614. for (i = 4; --i >= 0;)
  4615. {
  4616. s[i].malloc (256);
  4617. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4618. }
  4619. for (i = 0; i < 18; ++i)
  4620. {
  4621. uint32 d = 0;
  4622. for (int k = 0; k < 4; ++k)
  4623. {
  4624. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4625. if (++j >= keyBytes)
  4626. j = 0;
  4627. }
  4628. p[i] = initialPValues[i] ^ d;
  4629. }
  4630. uint32 l = 0, r = 0;
  4631. for (i = 0; i < 18; i += 2)
  4632. {
  4633. encrypt (l, r);
  4634. p[i] = l;
  4635. p[i + 1] = r;
  4636. }
  4637. for (i = 0; i < 4; ++i)
  4638. {
  4639. for (j = 0; j < 256; j += 2)
  4640. {
  4641. encrypt (l, r);
  4642. s[i][j] = l;
  4643. s[i][j + 1] = r;
  4644. }
  4645. }
  4646. }
  4647. BlowFish::BlowFish (const BlowFish& other)
  4648. {
  4649. for (int i = 4; --i >= 0;)
  4650. s[i].malloc (256);
  4651. operator= (other);
  4652. }
  4653. BlowFish& BlowFish::operator= (const BlowFish& other)
  4654. {
  4655. memcpy (p, other.p, sizeof (p));
  4656. for (int i = 4; --i >= 0;)
  4657. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4658. return *this;
  4659. }
  4660. BlowFish::~BlowFish()
  4661. {
  4662. }
  4663. uint32 BlowFish::F (const uint32 x) const throw()
  4664. {
  4665. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4666. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4667. }
  4668. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4669. {
  4670. uint32 l = data1;
  4671. uint32 r = data2;
  4672. for (int i = 0; i < 16; ++i)
  4673. {
  4674. l ^= p[i];
  4675. r ^= F(l);
  4676. swapVariables (l, r);
  4677. }
  4678. data1 = r ^ p[17];
  4679. data2 = l ^ p[16];
  4680. }
  4681. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4682. {
  4683. uint32 l = data1;
  4684. uint32 r = data2;
  4685. for (int i = 17; i > 1; --i)
  4686. {
  4687. l ^= p[i];
  4688. r ^= F(l);
  4689. swapVariables (l, r);
  4690. }
  4691. data1 = r ^ p[0];
  4692. data2 = l ^ p[1];
  4693. }
  4694. END_JUCE_NAMESPACE
  4695. /*** End of inlined file: juce_BlowFish.cpp ***/
  4696. /*** Start of inlined file: juce_MD5.cpp ***/
  4697. BEGIN_JUCE_NAMESPACE
  4698. MD5::MD5()
  4699. {
  4700. zerostruct (result);
  4701. }
  4702. MD5::MD5 (const MD5& other)
  4703. {
  4704. memcpy (result, other.result, sizeof (result));
  4705. }
  4706. MD5& MD5::operator= (const MD5& other)
  4707. {
  4708. memcpy (result, other.result, sizeof (result));
  4709. return *this;
  4710. }
  4711. MD5::MD5 (const MemoryBlock& data)
  4712. {
  4713. ProcessContext context;
  4714. context.processBlock (data.getData(), data.getSize());
  4715. context.finish (result);
  4716. }
  4717. MD5::MD5 (const void* data, const size_t numBytes)
  4718. {
  4719. ProcessContext context;
  4720. context.processBlock (data, numBytes);
  4721. context.finish (result);
  4722. }
  4723. MD5::MD5 (const String& text)
  4724. {
  4725. ProcessContext context;
  4726. const int len = text.length();
  4727. const juce_wchar* const t = text;
  4728. for (int i = 0; i < len; ++i)
  4729. {
  4730. // force the string into integer-sized unicode characters, to try to make it
  4731. // get the same results on all platforms + compilers.
  4732. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4733. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4734. }
  4735. context.finish (result);
  4736. }
  4737. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4738. {
  4739. ProcessContext context;
  4740. if (numBytesToRead < 0)
  4741. numBytesToRead = std::numeric_limits<int64>::max();
  4742. while (numBytesToRead > 0)
  4743. {
  4744. uint8 tempBuffer [512];
  4745. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4746. if (bytesRead <= 0)
  4747. break;
  4748. numBytesToRead -= bytesRead;
  4749. context.processBlock (tempBuffer, bytesRead);
  4750. }
  4751. context.finish (result);
  4752. }
  4753. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4754. {
  4755. processStream (input, numBytesToRead);
  4756. }
  4757. MD5::MD5 (const File& file)
  4758. {
  4759. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4760. if (fin != 0)
  4761. processStream (*fin, -1);
  4762. else
  4763. zerostruct (result);
  4764. }
  4765. MD5::~MD5()
  4766. {
  4767. }
  4768. namespace MD5Functions
  4769. {
  4770. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4771. {
  4772. for (int i = 0; i < (numBytes >> 2); ++i)
  4773. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4774. }
  4775. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4776. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4777. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4778. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4779. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4780. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4781. {
  4782. a += F (b, c, d) + x + ac;
  4783. a = rotateLeft (a, s) + b;
  4784. }
  4785. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4786. {
  4787. a += G (b, c, d) + x + ac;
  4788. a = rotateLeft (a, s) + b;
  4789. }
  4790. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4791. {
  4792. a += H (b, c, d) + x + ac;
  4793. a = rotateLeft (a, s) + b;
  4794. }
  4795. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4796. {
  4797. a += I (b, c, d) + x + ac;
  4798. a = rotateLeft (a, s) + b;
  4799. }
  4800. }
  4801. MD5::ProcessContext::ProcessContext()
  4802. {
  4803. state[0] = 0x67452301;
  4804. state[1] = 0xefcdab89;
  4805. state[2] = 0x98badcfe;
  4806. state[3] = 0x10325476;
  4807. count[0] = 0;
  4808. count[1] = 0;
  4809. }
  4810. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4811. {
  4812. int bufferPos = ((count[0] >> 3) & 0x3F);
  4813. count[0] += (uint32) (dataSize << 3);
  4814. if (count[0] < ((uint32) dataSize << 3))
  4815. count[1]++;
  4816. count[1] += (uint32) (dataSize >> 29);
  4817. const size_t spaceLeft = 64 - bufferPos;
  4818. size_t i = 0;
  4819. if (dataSize >= spaceLeft)
  4820. {
  4821. memcpy (buffer + bufferPos, data, spaceLeft);
  4822. transform (buffer);
  4823. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4824. transform (static_cast <const char*> (data) + i);
  4825. bufferPos = 0;
  4826. }
  4827. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4828. }
  4829. void MD5::ProcessContext::finish (void* const result)
  4830. {
  4831. unsigned char encodedLength[8];
  4832. MD5Functions::encode (encodedLength, count, 8);
  4833. // Pad out to 56 mod 64.
  4834. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4835. const int paddingLength = (index < 56) ? (56 - index)
  4836. : (120 - index);
  4837. uint8 paddingBuffer [64];
  4838. zeromem (paddingBuffer, paddingLength);
  4839. paddingBuffer [0] = 0x80;
  4840. processBlock (paddingBuffer, paddingLength);
  4841. processBlock (encodedLength, 8);
  4842. MD5Functions::encode (result, state, 16);
  4843. zerostruct (buffer);
  4844. }
  4845. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4846. {
  4847. using namespace MD5Functions;
  4848. uint32 a = state[0];
  4849. uint32 b = state[1];
  4850. uint32 c = state[2];
  4851. uint32 d = state[3];
  4852. uint32 x[16];
  4853. encode (x, bufferToTransform, 64);
  4854. enum Constants
  4855. {
  4856. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4857. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4858. };
  4859. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4860. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4861. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4862. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4863. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4864. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4865. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4866. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4867. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4868. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4869. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4870. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4871. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4872. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4873. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4874. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4875. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4876. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4877. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4878. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4879. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4880. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4881. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4882. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4883. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4884. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4885. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4886. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4887. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4888. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4889. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4890. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4891. state[0] += a;
  4892. state[1] += b;
  4893. state[2] += c;
  4894. state[3] += d;
  4895. zerostruct (x);
  4896. }
  4897. const MemoryBlock MD5::getRawChecksumData() const
  4898. {
  4899. return MemoryBlock (result, sizeof (result));
  4900. }
  4901. const String MD5::toHexString() const
  4902. {
  4903. return String::toHexString (result, sizeof (result), 0);
  4904. }
  4905. bool MD5::operator== (const MD5& other) const
  4906. {
  4907. return memcmp (result, other.result, sizeof (result)) == 0;
  4908. }
  4909. bool MD5::operator!= (const MD5& other) const
  4910. {
  4911. return ! operator== (other);
  4912. }
  4913. END_JUCE_NAMESPACE
  4914. /*** End of inlined file: juce_MD5.cpp ***/
  4915. /*** Start of inlined file: juce_Primes.cpp ***/
  4916. BEGIN_JUCE_NAMESPACE
  4917. namespace PrimesHelpers
  4918. {
  4919. static void createSmallSieve (const int numBits, BigInteger& result)
  4920. {
  4921. result.setBit (numBits);
  4922. result.clearBit (numBits); // to enlarge the array
  4923. result.setBit (0);
  4924. int n = 2;
  4925. do
  4926. {
  4927. for (int i = n + n; i < numBits; i += n)
  4928. result.setBit (i);
  4929. n = result.findNextClearBit (n + 1);
  4930. }
  4931. while (n <= (numBits >> 1));
  4932. }
  4933. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4934. const BigInteger& smallSieve, const int smallSieveSize)
  4935. {
  4936. jassert (! base[0]); // must be even!
  4937. result.setBit (numBits);
  4938. result.clearBit (numBits); // to enlarge the array
  4939. int index = smallSieve.findNextClearBit (0);
  4940. do
  4941. {
  4942. const int prime = (index << 1) + 1;
  4943. BigInteger r (base), remainder;
  4944. r.divideBy (prime, remainder);
  4945. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4946. if (r.isZero())
  4947. i += prime;
  4948. if ((i & 1) == 0)
  4949. i += prime;
  4950. i = (i - 1) >> 1;
  4951. while (i < numBits)
  4952. {
  4953. result.setBit (i);
  4954. i += prime;
  4955. }
  4956. index = smallSieve.findNextClearBit (index + 1);
  4957. }
  4958. while (index < smallSieveSize);
  4959. }
  4960. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4961. const int numBits, BigInteger& result, const int certainty)
  4962. {
  4963. for (int i = 0; i < numBits; ++i)
  4964. {
  4965. if (! sieve[i])
  4966. {
  4967. result = base + (unsigned int) ((i << 1) + 1);
  4968. if (Primes::isProbablyPrime (result, certainty))
  4969. return true;
  4970. }
  4971. }
  4972. return false;
  4973. }
  4974. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4975. {
  4976. const BigInteger one (1), two (2);
  4977. const BigInteger nMinusOne (n - one);
  4978. BigInteger d (nMinusOne);
  4979. const int s = d.findNextSetBit (0);
  4980. d >>= s;
  4981. BigInteger smallPrimes;
  4982. int numBitsInSmallPrimes = 0;
  4983. for (;;)
  4984. {
  4985. numBitsInSmallPrimes += 256;
  4986. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4987. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4988. if (numPrimesFound > iterations + 1)
  4989. break;
  4990. }
  4991. int smallPrime = 2;
  4992. while (--iterations >= 0)
  4993. {
  4994. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4995. BigInteger r (smallPrime);
  4996. r.exponentModulo (d, n);
  4997. if (r != one && r != nMinusOne)
  4998. {
  4999. for (int j = 0; j < s; ++j)
  5000. {
  5001. r.exponentModulo (two, n);
  5002. if (r == nMinusOne)
  5003. break;
  5004. }
  5005. if (r != nMinusOne)
  5006. return false;
  5007. }
  5008. }
  5009. return true;
  5010. }
  5011. }
  5012. const BigInteger Primes::createProbablePrime (const int bitLength,
  5013. const int certainty,
  5014. const int* randomSeeds,
  5015. int numRandomSeeds)
  5016. {
  5017. using namespace PrimesHelpers;
  5018. int defaultSeeds [16];
  5019. if (numRandomSeeds <= 0)
  5020. {
  5021. randomSeeds = defaultSeeds;
  5022. numRandomSeeds = numElementsInArray (defaultSeeds);
  5023. Random r (0);
  5024. for (int j = 10; --j >= 0;)
  5025. {
  5026. r.setSeedRandomly();
  5027. for (int i = numRandomSeeds; --i >= 0;)
  5028. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5029. }
  5030. }
  5031. BigInteger smallSieve;
  5032. const int smallSieveSize = 15000;
  5033. createSmallSieve (smallSieveSize, smallSieve);
  5034. BigInteger p;
  5035. for (int i = numRandomSeeds; --i >= 0;)
  5036. {
  5037. BigInteger p2;
  5038. Random r (randomSeeds[i]);
  5039. r.fillBitsRandomly (p2, 0, bitLength);
  5040. p ^= p2;
  5041. }
  5042. p.setBit (bitLength - 1);
  5043. p.clearBit (0);
  5044. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5045. while (p.getHighestBit() < bitLength)
  5046. {
  5047. p += 2 * searchLen;
  5048. BigInteger sieve;
  5049. bigSieve (p, searchLen, sieve,
  5050. smallSieve, smallSieveSize);
  5051. BigInteger candidate;
  5052. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5053. return candidate;
  5054. }
  5055. jassertfalse;
  5056. return BigInteger();
  5057. }
  5058. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5059. {
  5060. using namespace PrimesHelpers;
  5061. if (! number[0])
  5062. return false;
  5063. if (number.getHighestBit() <= 10)
  5064. {
  5065. const int num = number.getBitRangeAsInt (0, 10);
  5066. for (int i = num / 2; --i > 1;)
  5067. if (num % i == 0)
  5068. return false;
  5069. return true;
  5070. }
  5071. else
  5072. {
  5073. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5074. return false;
  5075. return passesMillerRabin (number, certainty);
  5076. }
  5077. }
  5078. END_JUCE_NAMESPACE
  5079. /*** End of inlined file: juce_Primes.cpp ***/
  5080. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5081. BEGIN_JUCE_NAMESPACE
  5082. RSAKey::RSAKey()
  5083. {
  5084. }
  5085. RSAKey::RSAKey (const String& s)
  5086. {
  5087. if (s.containsChar (','))
  5088. {
  5089. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5090. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5091. }
  5092. else
  5093. {
  5094. // the string needs to be two hex numbers, comma-separated..
  5095. jassertfalse;
  5096. }
  5097. }
  5098. RSAKey::~RSAKey()
  5099. {
  5100. }
  5101. bool RSAKey::operator== (const RSAKey& other) const throw()
  5102. {
  5103. return part1 == other.part1 && part2 == other.part2;
  5104. }
  5105. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5106. {
  5107. return ! operator== (other);
  5108. }
  5109. const String RSAKey::toString() const
  5110. {
  5111. return part1.toString (16) + "," + part2.toString (16);
  5112. }
  5113. bool RSAKey::applyToValue (BigInteger& value) const
  5114. {
  5115. if (part1.isZero() || part2.isZero() || value <= 0)
  5116. {
  5117. jassertfalse; // using an uninitialised key
  5118. value.clear();
  5119. return false;
  5120. }
  5121. BigInteger result;
  5122. while (! value.isZero())
  5123. {
  5124. result *= part2;
  5125. BigInteger remainder;
  5126. value.divideBy (part2, remainder);
  5127. remainder.exponentModulo (part1, part2);
  5128. result += remainder;
  5129. }
  5130. value.swapWith (result);
  5131. return true;
  5132. }
  5133. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5134. {
  5135. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5136. // are fast to divide + multiply
  5137. for (int i = 2; i <= 65536; i *= 2)
  5138. {
  5139. const BigInteger e (1 + i);
  5140. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5141. return e;
  5142. }
  5143. BigInteger e (4);
  5144. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5145. ++e;
  5146. return e;
  5147. }
  5148. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5149. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5150. {
  5151. jassert (numBits > 16); // not much point using less than this..
  5152. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5153. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5154. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5155. const BigInteger n (p * q);
  5156. const BigInteger m (--p * --q);
  5157. const BigInteger e (findBestCommonDivisor (p, q));
  5158. BigInteger d (e);
  5159. d.inverseModulo (m);
  5160. publicKey.part1 = e;
  5161. publicKey.part2 = n;
  5162. privateKey.part1 = d;
  5163. privateKey.part2 = n;
  5164. }
  5165. END_JUCE_NAMESPACE
  5166. /*** End of inlined file: juce_RSAKey.cpp ***/
  5167. /*** Start of inlined file: juce_InputStream.cpp ***/
  5168. BEGIN_JUCE_NAMESPACE
  5169. char InputStream::readByte()
  5170. {
  5171. char temp = 0;
  5172. read (&temp, 1);
  5173. return temp;
  5174. }
  5175. bool InputStream::readBool()
  5176. {
  5177. return readByte() != 0;
  5178. }
  5179. short InputStream::readShort()
  5180. {
  5181. char temp[2];
  5182. if (read (temp, 2) == 2)
  5183. return (short) ByteOrder::littleEndianShort (temp);
  5184. return 0;
  5185. }
  5186. short InputStream::readShortBigEndian()
  5187. {
  5188. char temp[2];
  5189. if (read (temp, 2) == 2)
  5190. return (short) ByteOrder::bigEndianShort (temp);
  5191. return 0;
  5192. }
  5193. int InputStream::readInt()
  5194. {
  5195. char temp[4];
  5196. if (read (temp, 4) == 4)
  5197. return (int) ByteOrder::littleEndianInt (temp);
  5198. return 0;
  5199. }
  5200. int InputStream::readIntBigEndian()
  5201. {
  5202. char temp[4];
  5203. if (read (temp, 4) == 4)
  5204. return (int) ByteOrder::bigEndianInt (temp);
  5205. return 0;
  5206. }
  5207. int InputStream::readCompressedInt()
  5208. {
  5209. const unsigned char sizeByte = readByte();
  5210. if (sizeByte == 0)
  5211. return 0;
  5212. const int numBytes = (sizeByte & 0x7f);
  5213. if (numBytes > 4)
  5214. {
  5215. jassertfalse; // trying to read corrupt data - this method must only be used
  5216. // to read data that was written by OutputStream::writeCompressedInt()
  5217. return 0;
  5218. }
  5219. char bytes[4] = { 0, 0, 0, 0 };
  5220. if (read (bytes, numBytes) != numBytes)
  5221. return 0;
  5222. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5223. return (sizeByte >> 7) ? -num : num;
  5224. }
  5225. int64 InputStream::readInt64()
  5226. {
  5227. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5228. if (read (n.asBytes, 8) == 8)
  5229. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5230. return 0;
  5231. }
  5232. int64 InputStream::readInt64BigEndian()
  5233. {
  5234. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5235. if (read (n.asBytes, 8) == 8)
  5236. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5237. return 0;
  5238. }
  5239. float InputStream::readFloat()
  5240. {
  5241. // the union below relies on these types being the same size...
  5242. static_jassert (sizeof (int32) == sizeof (float));
  5243. union { int32 asInt; float asFloat; } n;
  5244. n.asInt = (int32) readInt();
  5245. return n.asFloat;
  5246. }
  5247. float InputStream::readFloatBigEndian()
  5248. {
  5249. union { int32 asInt; float asFloat; } n;
  5250. n.asInt = (int32) readIntBigEndian();
  5251. return n.asFloat;
  5252. }
  5253. double InputStream::readDouble()
  5254. {
  5255. union { int64 asInt; double asDouble; } n;
  5256. n.asInt = readInt64();
  5257. return n.asDouble;
  5258. }
  5259. double InputStream::readDoubleBigEndian()
  5260. {
  5261. union { int64 asInt; double asDouble; } n;
  5262. n.asInt = readInt64BigEndian();
  5263. return n.asDouble;
  5264. }
  5265. const String InputStream::readString()
  5266. {
  5267. MemoryBlock buffer (256);
  5268. char* data = static_cast<char*> (buffer.getData());
  5269. size_t i = 0;
  5270. while ((data[i] = readByte()) != 0)
  5271. {
  5272. if (++i >= buffer.getSize())
  5273. {
  5274. buffer.setSize (buffer.getSize() + 512);
  5275. data = static_cast<char*> (buffer.getData());
  5276. }
  5277. }
  5278. return String::fromUTF8 (data, (int) i);
  5279. }
  5280. const String InputStream::readNextLine()
  5281. {
  5282. MemoryBlock buffer (256);
  5283. char* data = static_cast<char*> (buffer.getData());
  5284. size_t i = 0;
  5285. while ((data[i] = readByte()) != 0)
  5286. {
  5287. if (data[i] == '\n')
  5288. break;
  5289. if (data[i] == '\r')
  5290. {
  5291. const int64 lastPos = getPosition();
  5292. if (readByte() != '\n')
  5293. setPosition (lastPos);
  5294. break;
  5295. }
  5296. if (++i >= buffer.getSize())
  5297. {
  5298. buffer.setSize (buffer.getSize() + 512);
  5299. data = static_cast<char*> (buffer.getData());
  5300. }
  5301. }
  5302. return String::fromUTF8 (data, (int) i);
  5303. }
  5304. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5305. {
  5306. MemoryOutputStream mo (block, true);
  5307. return mo.writeFromInputStream (*this, numBytes);
  5308. }
  5309. const String InputStream::readEntireStreamAsString()
  5310. {
  5311. MemoryOutputStream mo;
  5312. mo.writeFromInputStream (*this, -1);
  5313. return mo.toString();
  5314. }
  5315. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5316. {
  5317. if (numBytesToSkip > 0)
  5318. {
  5319. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5320. HeapBlock<char> temp (skipBufferSize);
  5321. while (numBytesToSkip > 0 && ! isExhausted())
  5322. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5323. }
  5324. }
  5325. END_JUCE_NAMESPACE
  5326. /*** End of inlined file: juce_InputStream.cpp ***/
  5327. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5328. BEGIN_JUCE_NAMESPACE
  5329. #if JUCE_DEBUG
  5330. static Array<void*, CriticalSection> activeStreams;
  5331. void juce_CheckForDanglingStreams()
  5332. {
  5333. /*
  5334. It's always a bad idea to leak any object, but if you're leaking output
  5335. streams, then there's a good chance that you're failing to flush a file
  5336. to disk properly, which could result in corrupted data and other similar
  5337. nastiness..
  5338. */
  5339. jassert (activeStreams.size() == 0);
  5340. };
  5341. #endif
  5342. OutputStream::OutputStream()
  5343. {
  5344. #if JUCE_DEBUG
  5345. activeStreams.add (this);
  5346. #endif
  5347. }
  5348. OutputStream::~OutputStream()
  5349. {
  5350. #if JUCE_DEBUG
  5351. activeStreams.removeValue (this);
  5352. #endif
  5353. }
  5354. void OutputStream::writeBool (const bool b)
  5355. {
  5356. writeByte (b ? (char) 1
  5357. : (char) 0);
  5358. }
  5359. void OutputStream::writeByte (char byte)
  5360. {
  5361. write (&byte, 1);
  5362. }
  5363. void OutputStream::writeShort (short value)
  5364. {
  5365. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5366. write (&v, 2);
  5367. }
  5368. void OutputStream::writeShortBigEndian (short value)
  5369. {
  5370. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5371. write (&v, 2);
  5372. }
  5373. void OutputStream::writeInt (int value)
  5374. {
  5375. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5376. write (&v, 4);
  5377. }
  5378. void OutputStream::writeIntBigEndian (int value)
  5379. {
  5380. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5381. write (&v, 4);
  5382. }
  5383. void OutputStream::writeCompressedInt (int value)
  5384. {
  5385. unsigned int un = (value < 0) ? (unsigned int) -value
  5386. : (unsigned int) value;
  5387. uint8 data[5];
  5388. int num = 0;
  5389. while (un > 0)
  5390. {
  5391. data[++num] = (uint8) un;
  5392. un >>= 8;
  5393. }
  5394. data[0] = (uint8) num;
  5395. if (value < 0)
  5396. data[0] |= 0x80;
  5397. write (data, num + 1);
  5398. }
  5399. void OutputStream::writeInt64 (int64 value)
  5400. {
  5401. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5402. write (&v, 8);
  5403. }
  5404. void OutputStream::writeInt64BigEndian (int64 value)
  5405. {
  5406. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5407. write (&v, 8);
  5408. }
  5409. void OutputStream::writeFloat (float value)
  5410. {
  5411. union { int asInt; float asFloat; } n;
  5412. n.asFloat = value;
  5413. writeInt (n.asInt);
  5414. }
  5415. void OutputStream::writeFloatBigEndian (float value)
  5416. {
  5417. union { int asInt; float asFloat; } n;
  5418. n.asFloat = value;
  5419. writeIntBigEndian (n.asInt);
  5420. }
  5421. void OutputStream::writeDouble (double value)
  5422. {
  5423. union { int64 asInt; double asDouble; } n;
  5424. n.asDouble = value;
  5425. writeInt64 (n.asInt);
  5426. }
  5427. void OutputStream::writeDoubleBigEndian (double value)
  5428. {
  5429. union { int64 asInt; double asDouble; } n;
  5430. n.asDouble = value;
  5431. writeInt64BigEndian (n.asInt);
  5432. }
  5433. void OutputStream::writeString (const String& text)
  5434. {
  5435. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5436. // if lots of large, persistent strings were to be written to streams).
  5437. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5438. HeapBlock<char> temp (numBytes);
  5439. text.copyToUTF8 (temp, numBytes);
  5440. write (temp, numBytes);
  5441. }
  5442. void OutputStream::writeText (const String& text, const bool asUnicode,
  5443. const bool writeUnicodeHeaderBytes)
  5444. {
  5445. if (asUnicode)
  5446. {
  5447. if (writeUnicodeHeaderBytes)
  5448. write ("\x0ff\x0fe", 2);
  5449. const juce_wchar* src = text;
  5450. bool lastCharWasReturn = false;
  5451. while (*src != 0)
  5452. {
  5453. if (*src == L'\n' && ! lastCharWasReturn)
  5454. writeShort ((short) L'\r');
  5455. lastCharWasReturn = (*src == L'\r');
  5456. writeShort ((short) *src++);
  5457. }
  5458. }
  5459. else
  5460. {
  5461. const char* src = text.toUTF8();
  5462. const char* t = src;
  5463. for (;;)
  5464. {
  5465. if (*t == '\n')
  5466. {
  5467. if (t > src)
  5468. write (src, (int) (t - src));
  5469. write ("\r\n", 2);
  5470. src = t + 1;
  5471. }
  5472. else if (*t == '\r')
  5473. {
  5474. if (t[1] == '\n')
  5475. ++t;
  5476. }
  5477. else if (*t == 0)
  5478. {
  5479. if (t > src)
  5480. write (src, (int) (t - src));
  5481. break;
  5482. }
  5483. ++t;
  5484. }
  5485. }
  5486. }
  5487. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5488. {
  5489. if (numBytesToWrite < 0)
  5490. numBytesToWrite = std::numeric_limits<int64>::max();
  5491. int numWritten = 0;
  5492. while (numBytesToWrite > 0 && ! source.isExhausted())
  5493. {
  5494. char buffer [8192];
  5495. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5496. if (num <= 0)
  5497. break;
  5498. write (buffer, num);
  5499. numBytesToWrite -= num;
  5500. numWritten += num;
  5501. }
  5502. return numWritten;
  5503. }
  5504. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5505. {
  5506. return stream << String (number);
  5507. }
  5508. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5509. {
  5510. return stream << String (number);
  5511. }
  5512. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5513. {
  5514. stream.writeByte (character);
  5515. return stream;
  5516. }
  5517. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5518. {
  5519. stream.write (text, (int) strlen (text));
  5520. return stream;
  5521. }
  5522. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5523. {
  5524. stream.write (data.getData(), (int) data.getSize());
  5525. return stream;
  5526. }
  5527. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5528. {
  5529. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5530. if (in != 0)
  5531. stream.writeFromInputStream (*in, -1);
  5532. return stream;
  5533. }
  5534. END_JUCE_NAMESPACE
  5535. /*** End of inlined file: juce_OutputStream.cpp ***/
  5536. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5537. BEGIN_JUCE_NAMESPACE
  5538. DirectoryIterator::DirectoryIterator (const File& directory,
  5539. bool isRecursive_,
  5540. const String& wildCard_,
  5541. const int whatToLookFor_)
  5542. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5543. wildCard (wildCard_),
  5544. path (File::addTrailingSeparator (directory.getFullPathName())),
  5545. index (-1),
  5546. totalNumFiles (-1),
  5547. whatToLookFor (whatToLookFor_),
  5548. isRecursive (isRecursive_)
  5549. {
  5550. // you have to specify the type of files you're looking for!
  5551. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5552. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5553. }
  5554. DirectoryIterator::~DirectoryIterator()
  5555. {
  5556. }
  5557. bool DirectoryIterator::next()
  5558. {
  5559. return next (0, 0, 0, 0, 0, 0);
  5560. }
  5561. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5562. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5563. {
  5564. if (subIterator != 0)
  5565. {
  5566. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5567. return true;
  5568. subIterator = 0;
  5569. }
  5570. String filename;
  5571. bool isDirectory, isHidden;
  5572. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5573. {
  5574. ++index;
  5575. if (! filename.containsOnly ("."))
  5576. {
  5577. const File fileFound (path + filename, 0);
  5578. bool matches = false;
  5579. if (isDirectory)
  5580. {
  5581. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5582. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5583. matches = (whatToLookFor & File::findDirectories) != 0;
  5584. }
  5585. else
  5586. {
  5587. matches = (whatToLookFor & File::findFiles) != 0;
  5588. }
  5589. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5590. if (matches && isRecursive)
  5591. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5592. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5593. matches = ! isHidden;
  5594. if (matches)
  5595. {
  5596. currentFile = fileFound;
  5597. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5598. if (isDirResult != 0) *isDirResult = isDirectory;
  5599. return true;
  5600. }
  5601. else if (subIterator != 0)
  5602. {
  5603. return next();
  5604. }
  5605. }
  5606. }
  5607. return false;
  5608. }
  5609. const File DirectoryIterator::getFile() const
  5610. {
  5611. if (subIterator != 0)
  5612. return subIterator->getFile();
  5613. return currentFile;
  5614. }
  5615. float DirectoryIterator::getEstimatedProgress() const
  5616. {
  5617. if (totalNumFiles < 0)
  5618. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5619. if (totalNumFiles <= 0)
  5620. return 0.0f;
  5621. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5622. : (float) index;
  5623. return detailedIndex / totalNumFiles;
  5624. }
  5625. END_JUCE_NAMESPACE
  5626. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5627. /*** Start of inlined file: juce_File.cpp ***/
  5628. #if ! JUCE_WINDOWS
  5629. #include <pwd.h>
  5630. #endif
  5631. BEGIN_JUCE_NAMESPACE
  5632. File::File (const String& fullPathName)
  5633. : fullPath (parseAbsolutePath (fullPathName))
  5634. {
  5635. }
  5636. File::File (const String& path, int)
  5637. : fullPath (path)
  5638. {
  5639. }
  5640. const File File::createFileWithoutCheckingPath (const String& path)
  5641. {
  5642. return File (path, 0);
  5643. }
  5644. File::File (const File& other)
  5645. : fullPath (other.fullPath)
  5646. {
  5647. }
  5648. File& File::operator= (const String& newPath)
  5649. {
  5650. fullPath = parseAbsolutePath (newPath);
  5651. return *this;
  5652. }
  5653. File& File::operator= (const File& other)
  5654. {
  5655. fullPath = other.fullPath;
  5656. return *this;
  5657. }
  5658. const File File::nonexistent;
  5659. const String File::parseAbsolutePath (const String& p)
  5660. {
  5661. if (p.isEmpty())
  5662. return String::empty;
  5663. #if JUCE_WINDOWS
  5664. // Windows..
  5665. String path (p.replaceCharacter ('/', '\\'));
  5666. if (path.startsWithChar (File::separator))
  5667. {
  5668. if (path[1] != File::separator)
  5669. {
  5670. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5671. If you're trying to parse a string that may be either a relative path or an absolute path,
  5672. you MUST provide a context against which the partial path can be evaluated - you can do
  5673. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5674. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5675. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5676. */
  5677. jassertfalse;
  5678. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5679. }
  5680. }
  5681. else if (! path.containsChar (':'))
  5682. {
  5683. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5684. If you're trying to parse a string that may be either a relative path or an absolute path,
  5685. you MUST provide a context against which the partial path can be evaluated - you can do
  5686. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5687. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5688. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5689. */
  5690. jassertfalse;
  5691. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5692. }
  5693. #else
  5694. // Mac or Linux..
  5695. String path (p.replaceCharacter ('\\', '/'));
  5696. if (path.startsWithChar ('~'))
  5697. {
  5698. if (path[1] == File::separator || path[1] == 0)
  5699. {
  5700. // expand a name of the form "~/abc"
  5701. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5702. + path.substring (1);
  5703. }
  5704. else
  5705. {
  5706. // expand a name of type "~dave/abc"
  5707. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5708. struct passwd* const pw = getpwnam (userName.toUTF8());
  5709. if (pw != 0)
  5710. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5711. }
  5712. }
  5713. else if (! path.startsWithChar (File::separator))
  5714. {
  5715. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5716. If you're trying to parse a string that may be either a relative path or an absolute path,
  5717. you MUST provide a context against which the partial path can be evaluated - you can do
  5718. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5719. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5720. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5721. */
  5722. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5723. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5724. }
  5725. #endif
  5726. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5727. path = path.dropLastCharacters (1);
  5728. return path;
  5729. }
  5730. const String File::addTrailingSeparator (const String& path)
  5731. {
  5732. return path.endsWithChar (File::separator) ? path
  5733. : path + File::separator;
  5734. }
  5735. #if JUCE_LINUX
  5736. #define NAMES_ARE_CASE_SENSITIVE 1
  5737. #endif
  5738. bool File::areFileNamesCaseSensitive()
  5739. {
  5740. #if NAMES_ARE_CASE_SENSITIVE
  5741. return true;
  5742. #else
  5743. return false;
  5744. #endif
  5745. }
  5746. bool File::operator== (const File& other) const
  5747. {
  5748. #if NAMES_ARE_CASE_SENSITIVE
  5749. return fullPath == other.fullPath;
  5750. #else
  5751. return fullPath.equalsIgnoreCase (other.fullPath);
  5752. #endif
  5753. }
  5754. bool File::operator!= (const File& other) const
  5755. {
  5756. return ! operator== (other);
  5757. }
  5758. bool File::operator< (const File& other) const
  5759. {
  5760. #if NAMES_ARE_CASE_SENSITIVE
  5761. return fullPath < other.fullPath;
  5762. #else
  5763. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5764. #endif
  5765. }
  5766. bool File::operator> (const File& other) const
  5767. {
  5768. #if NAMES_ARE_CASE_SENSITIVE
  5769. return fullPath > other.fullPath;
  5770. #else
  5771. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5772. #endif
  5773. }
  5774. bool File::setReadOnly (const bool shouldBeReadOnly,
  5775. const bool applyRecursively) const
  5776. {
  5777. bool worked = true;
  5778. if (applyRecursively && isDirectory())
  5779. {
  5780. Array <File> subFiles;
  5781. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5782. for (int i = subFiles.size(); --i >= 0;)
  5783. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5784. }
  5785. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5786. }
  5787. bool File::deleteRecursively() const
  5788. {
  5789. bool worked = true;
  5790. if (isDirectory())
  5791. {
  5792. Array<File> subFiles;
  5793. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5794. for (int i = subFiles.size(); --i >= 0;)
  5795. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5796. }
  5797. return deleteFile() && worked;
  5798. }
  5799. bool File::moveFileTo (const File& newFile) const
  5800. {
  5801. if (newFile.fullPath == fullPath)
  5802. return true;
  5803. #if ! NAMES_ARE_CASE_SENSITIVE
  5804. if (*this != newFile)
  5805. #endif
  5806. if (! newFile.deleteFile())
  5807. return false;
  5808. return moveInternal (newFile);
  5809. }
  5810. bool File::copyFileTo (const File& newFile) const
  5811. {
  5812. return (*this == newFile)
  5813. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5814. }
  5815. bool File::copyDirectoryTo (const File& newDirectory) const
  5816. {
  5817. if (isDirectory() && newDirectory.createDirectory())
  5818. {
  5819. Array<File> subFiles;
  5820. findChildFiles (subFiles, File::findFiles, false);
  5821. int i;
  5822. for (i = 0; i < subFiles.size(); ++i)
  5823. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5824. return false;
  5825. subFiles.clear();
  5826. findChildFiles (subFiles, File::findDirectories, false);
  5827. for (i = 0; i < subFiles.size(); ++i)
  5828. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5829. return false;
  5830. return true;
  5831. }
  5832. return false;
  5833. }
  5834. const String File::getPathUpToLastSlash() const
  5835. {
  5836. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5837. if (lastSlash > 0)
  5838. return fullPath.substring (0, lastSlash);
  5839. else if (lastSlash == 0)
  5840. return separatorString;
  5841. else
  5842. return fullPath;
  5843. }
  5844. const File File::getParentDirectory() const
  5845. {
  5846. return File (getPathUpToLastSlash(), (int) 0);
  5847. }
  5848. const String File::getFileName() const
  5849. {
  5850. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5851. }
  5852. int File::hashCode() const
  5853. {
  5854. return fullPath.hashCode();
  5855. }
  5856. int64 File::hashCode64() const
  5857. {
  5858. return fullPath.hashCode64();
  5859. }
  5860. const String File::getFileNameWithoutExtension() const
  5861. {
  5862. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5863. const int lastDot = fullPath.lastIndexOfChar ('.');
  5864. if (lastDot > lastSlash)
  5865. return fullPath.substring (lastSlash, lastDot);
  5866. else
  5867. return fullPath.substring (lastSlash);
  5868. }
  5869. bool File::isAChildOf (const File& potentialParent) const
  5870. {
  5871. if (potentialParent == File::nonexistent)
  5872. return false;
  5873. const String ourPath (getPathUpToLastSlash());
  5874. #if NAMES_ARE_CASE_SENSITIVE
  5875. if (potentialParent.fullPath == ourPath)
  5876. #else
  5877. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5878. #endif
  5879. {
  5880. return true;
  5881. }
  5882. else if (potentialParent.fullPath.length() >= ourPath.length())
  5883. {
  5884. return false;
  5885. }
  5886. else
  5887. {
  5888. return getParentDirectory().isAChildOf (potentialParent);
  5889. }
  5890. }
  5891. bool File::isAbsolutePath (const String& path)
  5892. {
  5893. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5894. #if JUCE_WINDOWS
  5895. || (path.isNotEmpty() && path[1] == ':');
  5896. #else
  5897. || path.startsWithChar ('~');
  5898. #endif
  5899. }
  5900. const File File::getChildFile (String relativePath) const
  5901. {
  5902. if (isAbsolutePath (relativePath))
  5903. {
  5904. // the path is really absolute..
  5905. return File (relativePath);
  5906. }
  5907. else
  5908. {
  5909. // it's relative, so remove any ../ or ./ bits at the start.
  5910. String path (fullPath);
  5911. if (relativePath[0] == '.')
  5912. {
  5913. #if JUCE_WINDOWS
  5914. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5915. #else
  5916. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5917. #endif
  5918. while (relativePath[0] == '.')
  5919. {
  5920. if (relativePath[1] == '.')
  5921. {
  5922. if (relativePath [2] == 0 || relativePath[2] == separator)
  5923. {
  5924. const int lastSlash = path.lastIndexOfChar (separator);
  5925. if (lastSlash >= 0)
  5926. path = path.substring (0, lastSlash);
  5927. relativePath = relativePath.substring (3);
  5928. }
  5929. else
  5930. {
  5931. break;
  5932. }
  5933. }
  5934. else if (relativePath[1] == separator)
  5935. {
  5936. relativePath = relativePath.substring (2);
  5937. }
  5938. else
  5939. {
  5940. break;
  5941. }
  5942. }
  5943. }
  5944. return File (addTrailingSeparator (path) + relativePath);
  5945. }
  5946. }
  5947. const File File::getSiblingFile (const String& fileName) const
  5948. {
  5949. return getParentDirectory().getChildFile (fileName);
  5950. }
  5951. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5952. {
  5953. if (bytes == 1)
  5954. {
  5955. return "1 byte";
  5956. }
  5957. else if (bytes < 1024)
  5958. {
  5959. return String ((int) bytes) + " bytes";
  5960. }
  5961. else if (bytes < 1024 * 1024)
  5962. {
  5963. return String (bytes / 1024.0, 1) + " KB";
  5964. }
  5965. else if (bytes < 1024 * 1024 * 1024)
  5966. {
  5967. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5968. }
  5969. else
  5970. {
  5971. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5972. }
  5973. }
  5974. bool File::create() const
  5975. {
  5976. if (exists())
  5977. return true;
  5978. {
  5979. const File parentDir (getParentDirectory());
  5980. if (parentDir == *this || ! parentDir.createDirectory())
  5981. return false;
  5982. FileOutputStream fo (*this, 8);
  5983. }
  5984. return exists();
  5985. }
  5986. bool File::createDirectory() const
  5987. {
  5988. if (! isDirectory())
  5989. {
  5990. const File parentDir (getParentDirectory());
  5991. if (parentDir == *this || ! parentDir.createDirectory())
  5992. return false;
  5993. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5994. return isDirectory();
  5995. }
  5996. return true;
  5997. }
  5998. const Time File::getCreationTime() const
  5999. {
  6000. int64 m, a, c;
  6001. getFileTimesInternal (m, a, c);
  6002. return Time (c);
  6003. }
  6004. const Time File::getLastModificationTime() const
  6005. {
  6006. int64 m, a, c;
  6007. getFileTimesInternal (m, a, c);
  6008. return Time (m);
  6009. }
  6010. const Time File::getLastAccessTime() const
  6011. {
  6012. int64 m, a, c;
  6013. getFileTimesInternal (m, a, c);
  6014. return Time (a);
  6015. }
  6016. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6017. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6018. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6019. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6020. {
  6021. if (! existsAsFile())
  6022. return false;
  6023. FileInputStream in (*this);
  6024. return getSize() == in.readIntoMemoryBlock (destBlock);
  6025. }
  6026. const String File::loadFileAsString() const
  6027. {
  6028. if (! existsAsFile())
  6029. return String::empty;
  6030. FileInputStream in (*this);
  6031. return in.readEntireStreamAsString();
  6032. }
  6033. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  6034. {
  6035. return (whatToLookFor & (isDir ? findDirectories
  6036. : findFiles)) != 0
  6037. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  6038. }
  6039. int File::findChildFiles (Array<File>& results,
  6040. const int whatToLookFor,
  6041. const bool searchRecursively,
  6042. const String& wildCardPattern) const
  6043. {
  6044. // you have to specify the type of files you're looking for!
  6045. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  6046. int total = 0;
  6047. if (isDirectory())
  6048. {
  6049. // find child files or directories in this directory first..
  6050. String path (addTrailingSeparator (fullPath)), filename;
  6051. bool itemIsDirectory, itemIsHidden;
  6052. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  6053. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  6054. {
  6055. if (! filename.containsOnly ("."))
  6056. {
  6057. const File fileFound (path + filename, 0);
  6058. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  6059. {
  6060. results.add (fileFound);
  6061. ++total;
  6062. }
  6063. if (searchRecursively && itemIsDirectory
  6064. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  6065. {
  6066. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  6067. }
  6068. }
  6069. }
  6070. }
  6071. return total;
  6072. }
  6073. int File::getNumberOfChildFiles (const int whatToLookFor,
  6074. const String& wildCardPattern) const
  6075. {
  6076. // you have to specify the type of files you're looking for!
  6077. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  6078. int count = 0;
  6079. if (isDirectory())
  6080. {
  6081. String filename;
  6082. bool itemIsDirectory, itemIsHidden;
  6083. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  6084. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  6085. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  6086. && ! filename.containsOnly ("."))
  6087. ++count;
  6088. }
  6089. else
  6090. {
  6091. // trying to search for files inside a non-directory?
  6092. jassertfalse;
  6093. }
  6094. return count;
  6095. }
  6096. bool File::containsSubDirectories() const
  6097. {
  6098. if (isDirectory())
  6099. {
  6100. String filename;
  6101. bool itemIsDirectory;
  6102. DirectoryIterator::NativeIterator i (*this, "*");
  6103. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  6104. if (itemIsDirectory)
  6105. return true;
  6106. }
  6107. return false;
  6108. }
  6109. const File File::getNonexistentChildFile (const String& prefix_,
  6110. const String& suffix,
  6111. bool putNumbersInBrackets) const
  6112. {
  6113. File f (getChildFile (prefix_ + suffix));
  6114. if (f.exists())
  6115. {
  6116. int num = 2;
  6117. String prefix (prefix_);
  6118. // remove any bracketed numbers that may already be on the end..
  6119. if (prefix.trim().endsWithChar (')'))
  6120. {
  6121. putNumbersInBrackets = true;
  6122. const int openBracks = prefix.lastIndexOfChar ('(');
  6123. const int closeBracks = prefix.lastIndexOfChar (')');
  6124. if (openBracks > 0
  6125. && closeBracks > openBracks
  6126. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6127. {
  6128. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6129. prefix = prefix.substring (0, openBracks);
  6130. }
  6131. }
  6132. // also use brackets if it ends in a digit.
  6133. putNumbersInBrackets = putNumbersInBrackets
  6134. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6135. do
  6136. {
  6137. if (putNumbersInBrackets)
  6138. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6139. else
  6140. f = getChildFile (prefix + String (num++) + suffix);
  6141. } while (f.exists());
  6142. }
  6143. return f;
  6144. }
  6145. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6146. {
  6147. if (exists())
  6148. {
  6149. return getParentDirectory()
  6150. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6151. getFileExtension(),
  6152. putNumbersInBrackets);
  6153. }
  6154. else
  6155. {
  6156. return *this;
  6157. }
  6158. }
  6159. const String File::getFileExtension() const
  6160. {
  6161. String ext;
  6162. if (! isDirectory())
  6163. {
  6164. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6165. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6166. ext = fullPath.substring (indexOfDot);
  6167. }
  6168. return ext;
  6169. }
  6170. bool File::hasFileExtension (const String& possibleSuffix) const
  6171. {
  6172. if (possibleSuffix.isEmpty())
  6173. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6174. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6175. if (semicolon >= 0)
  6176. {
  6177. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6178. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6179. }
  6180. else
  6181. {
  6182. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6183. {
  6184. if (possibleSuffix.startsWithChar ('.'))
  6185. return true;
  6186. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6187. if (dotPos >= 0)
  6188. return fullPath [dotPos] == '.';
  6189. }
  6190. }
  6191. return false;
  6192. }
  6193. const File File::withFileExtension (const String& newExtension) const
  6194. {
  6195. if (fullPath.isEmpty())
  6196. return File::nonexistent;
  6197. String filePart (getFileName());
  6198. int i = filePart.lastIndexOfChar ('.');
  6199. if (i >= 0)
  6200. filePart = filePart.substring (0, i);
  6201. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6202. filePart << '.';
  6203. return getSiblingFile (filePart + newExtension);
  6204. }
  6205. bool File::startAsProcess (const String& parameters) const
  6206. {
  6207. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6208. }
  6209. FileInputStream* File::createInputStream() const
  6210. {
  6211. if (existsAsFile())
  6212. return new FileInputStream (*this);
  6213. return 0;
  6214. }
  6215. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6216. {
  6217. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6218. if (out->failedToOpen())
  6219. return 0;
  6220. return out.release();
  6221. }
  6222. bool File::appendData (const void* const dataToAppend,
  6223. const int numberOfBytes) const
  6224. {
  6225. if (numberOfBytes > 0)
  6226. {
  6227. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6228. if (out == 0)
  6229. return false;
  6230. out->write (dataToAppend, numberOfBytes);
  6231. }
  6232. return true;
  6233. }
  6234. bool File::replaceWithData (const void* const dataToWrite,
  6235. const int numberOfBytes) const
  6236. {
  6237. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6238. if (numberOfBytes <= 0)
  6239. return deleteFile();
  6240. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6241. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6242. return tempFile.overwriteTargetFileWithTemporary();
  6243. }
  6244. bool File::appendText (const String& text,
  6245. const bool asUnicode,
  6246. const bool writeUnicodeHeaderBytes) const
  6247. {
  6248. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6249. if (out != 0)
  6250. {
  6251. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6252. return true;
  6253. }
  6254. return false;
  6255. }
  6256. bool File::replaceWithText (const String& textToWrite,
  6257. const bool asUnicode,
  6258. const bool writeUnicodeHeaderBytes) const
  6259. {
  6260. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6261. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6262. return tempFile.overwriteTargetFileWithTemporary();
  6263. }
  6264. bool File::hasIdenticalContentTo (const File& other) const
  6265. {
  6266. if (other == *this)
  6267. return true;
  6268. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6269. {
  6270. FileInputStream in1 (*this), in2 (other);
  6271. const int bufferSize = 4096;
  6272. HeapBlock <char> buffer1, buffer2;
  6273. buffer1.malloc (bufferSize);
  6274. buffer2.malloc (bufferSize);
  6275. for (;;)
  6276. {
  6277. const int num1 = in1.read (buffer1, bufferSize);
  6278. const int num2 = in2.read (buffer2, bufferSize);
  6279. if (num1 != num2)
  6280. break;
  6281. if (num1 <= 0)
  6282. return true;
  6283. if (memcmp (buffer1, buffer2, num1) != 0)
  6284. break;
  6285. }
  6286. }
  6287. return false;
  6288. }
  6289. const String File::createLegalPathName (const String& original)
  6290. {
  6291. String s (original);
  6292. String start;
  6293. if (s[1] == ':')
  6294. {
  6295. start = s.substring (0, 2);
  6296. s = s.substring (2);
  6297. }
  6298. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6299. .substring (0, 1024);
  6300. }
  6301. const String File::createLegalFileName (const String& original)
  6302. {
  6303. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6304. const int maxLength = 128; // only the length of the filename, not the whole path
  6305. const int len = s.length();
  6306. if (len > maxLength)
  6307. {
  6308. const int lastDot = s.lastIndexOfChar ('.');
  6309. if (lastDot > jmax (0, len - 12))
  6310. {
  6311. s = s.substring (0, maxLength - (len - lastDot))
  6312. + s.substring (lastDot);
  6313. }
  6314. else
  6315. {
  6316. s = s.substring (0, maxLength);
  6317. }
  6318. }
  6319. return s;
  6320. }
  6321. const String File::getRelativePathFrom (const File& dir) const
  6322. {
  6323. String thisPath (fullPath);
  6324. {
  6325. int len = thisPath.length();
  6326. while (--len >= 0 && thisPath [len] == File::separator)
  6327. thisPath [len] = 0;
  6328. }
  6329. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6330. : dir.fullPath));
  6331. const int len = jmin (thisPath.length(), dirPath.length());
  6332. int commonBitLength = 0;
  6333. for (int i = 0; i < len; ++i)
  6334. {
  6335. #if NAMES_ARE_CASE_SENSITIVE
  6336. if (thisPath[i] != dirPath[i])
  6337. #else
  6338. if (CharacterFunctions::toLowerCase (thisPath[i])
  6339. != CharacterFunctions::toLowerCase (dirPath[i]))
  6340. #endif
  6341. {
  6342. break;
  6343. }
  6344. ++commonBitLength;
  6345. }
  6346. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6347. --commonBitLength;
  6348. // if the only common bit is the root, then just return the full path..
  6349. if (commonBitLength <= 0
  6350. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6351. return fullPath;
  6352. thisPath = thisPath.substring (commonBitLength);
  6353. dirPath = dirPath.substring (commonBitLength);
  6354. while (dirPath.isNotEmpty())
  6355. {
  6356. #if JUCE_WINDOWS
  6357. thisPath = "..\\" + thisPath;
  6358. #else
  6359. thisPath = "../" + thisPath;
  6360. #endif
  6361. const int sep = dirPath.indexOfChar (separator);
  6362. if (sep >= 0)
  6363. dirPath = dirPath.substring (sep + 1);
  6364. else
  6365. dirPath = String::empty;
  6366. }
  6367. return thisPath;
  6368. }
  6369. const File File::createTempFile (const String& fileNameEnding)
  6370. {
  6371. const File tempFile (getSpecialLocation (tempDirectory)
  6372. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6373. .withFileExtension (fileNameEnding));
  6374. if (tempFile.exists())
  6375. return createTempFile (fileNameEnding);
  6376. else
  6377. return tempFile;
  6378. }
  6379. END_JUCE_NAMESPACE
  6380. /*** End of inlined file: juce_File.cpp ***/
  6381. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6382. BEGIN_JUCE_NAMESPACE
  6383. int64 juce_fileSetPosition (void* handle, int64 pos);
  6384. FileInputStream::FileInputStream (const File& f)
  6385. : file (f),
  6386. fileHandle (0),
  6387. currentPosition (0),
  6388. totalSize (0),
  6389. needToSeek (true)
  6390. {
  6391. openHandle();
  6392. }
  6393. FileInputStream::~FileInputStream()
  6394. {
  6395. closeHandle();
  6396. }
  6397. int64 FileInputStream::getTotalLength()
  6398. {
  6399. return totalSize;
  6400. }
  6401. int FileInputStream::read (void* buffer, int bytesToRead)
  6402. {
  6403. int num = 0;
  6404. if (needToSeek)
  6405. {
  6406. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6407. return 0;
  6408. needToSeek = false;
  6409. }
  6410. num = readInternal (buffer, bytesToRead);
  6411. currentPosition += num;
  6412. return num;
  6413. }
  6414. bool FileInputStream::isExhausted()
  6415. {
  6416. return currentPosition >= totalSize;
  6417. }
  6418. int64 FileInputStream::getPosition()
  6419. {
  6420. return currentPosition;
  6421. }
  6422. bool FileInputStream::setPosition (int64 pos)
  6423. {
  6424. pos = jlimit ((int64) 0, totalSize, pos);
  6425. needToSeek |= (currentPosition != pos);
  6426. currentPosition = pos;
  6427. return true;
  6428. }
  6429. END_JUCE_NAMESPACE
  6430. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6431. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6432. BEGIN_JUCE_NAMESPACE
  6433. int64 juce_fileSetPosition (void* handle, int64 pos);
  6434. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6435. : file (f),
  6436. fileHandle (0),
  6437. currentPosition (0),
  6438. bufferSize (bufferSize_),
  6439. bytesInBuffer (0),
  6440. buffer (jmax (bufferSize_, 16))
  6441. {
  6442. openHandle();
  6443. }
  6444. FileOutputStream::~FileOutputStream()
  6445. {
  6446. flush();
  6447. closeHandle();
  6448. }
  6449. int64 FileOutputStream::getPosition()
  6450. {
  6451. return currentPosition;
  6452. }
  6453. bool FileOutputStream::setPosition (int64 newPosition)
  6454. {
  6455. if (newPosition != currentPosition)
  6456. {
  6457. flush();
  6458. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6459. }
  6460. return newPosition == currentPosition;
  6461. }
  6462. void FileOutputStream::flush()
  6463. {
  6464. if (bytesInBuffer > 0)
  6465. {
  6466. writeInternal (buffer, bytesInBuffer);
  6467. bytesInBuffer = 0;
  6468. }
  6469. flushInternal();
  6470. }
  6471. bool FileOutputStream::write (const void* const src, const int numBytes)
  6472. {
  6473. if (bytesInBuffer + numBytes < bufferSize)
  6474. {
  6475. memcpy (buffer + bytesInBuffer, src, numBytes);
  6476. bytesInBuffer += numBytes;
  6477. currentPosition += numBytes;
  6478. }
  6479. else
  6480. {
  6481. if (bytesInBuffer > 0)
  6482. {
  6483. // flush the reservoir
  6484. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6485. bytesInBuffer = 0;
  6486. if (! wroteOk)
  6487. return false;
  6488. }
  6489. if (numBytes < bufferSize)
  6490. {
  6491. memcpy (buffer + bytesInBuffer, src, numBytes);
  6492. bytesInBuffer += numBytes;
  6493. currentPosition += numBytes;
  6494. }
  6495. else
  6496. {
  6497. const int bytesWritten = writeInternal (src, numBytes);
  6498. if (bytesWritten < 0)
  6499. return false;
  6500. currentPosition += bytesWritten;
  6501. return bytesWritten == numBytes;
  6502. }
  6503. }
  6504. return true;
  6505. }
  6506. END_JUCE_NAMESPACE
  6507. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6508. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6509. BEGIN_JUCE_NAMESPACE
  6510. FileSearchPath::FileSearchPath()
  6511. {
  6512. }
  6513. FileSearchPath::FileSearchPath (const String& path)
  6514. {
  6515. init (path);
  6516. }
  6517. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6518. : directories (other.directories)
  6519. {
  6520. }
  6521. FileSearchPath::~FileSearchPath()
  6522. {
  6523. }
  6524. FileSearchPath& FileSearchPath::operator= (const String& path)
  6525. {
  6526. init (path);
  6527. return *this;
  6528. }
  6529. void FileSearchPath::init (const String& path)
  6530. {
  6531. directories.clear();
  6532. directories.addTokens (path, ";", "\"");
  6533. directories.trim();
  6534. directories.removeEmptyStrings();
  6535. for (int i = directories.size(); --i >= 0;)
  6536. directories.set (i, directories[i].unquoted());
  6537. }
  6538. int FileSearchPath::getNumPaths() const
  6539. {
  6540. return directories.size();
  6541. }
  6542. const File FileSearchPath::operator[] (const int index) const
  6543. {
  6544. return File (directories [index]);
  6545. }
  6546. const String FileSearchPath::toString() const
  6547. {
  6548. StringArray directories2 (directories);
  6549. for (int i = directories2.size(); --i >= 0;)
  6550. if (directories2[i].containsChar (';'))
  6551. directories2.set (i, directories2[i].quoted());
  6552. return directories2.joinIntoString (";");
  6553. }
  6554. void FileSearchPath::add (const File& dir, const int insertIndex)
  6555. {
  6556. directories.insert (insertIndex, dir.getFullPathName());
  6557. }
  6558. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6559. {
  6560. for (int i = 0; i < directories.size(); ++i)
  6561. if (File (directories[i]) == dir)
  6562. return;
  6563. add (dir);
  6564. }
  6565. void FileSearchPath::remove (const int index)
  6566. {
  6567. directories.remove (index);
  6568. }
  6569. void FileSearchPath::addPath (const FileSearchPath& other)
  6570. {
  6571. for (int i = 0; i < other.getNumPaths(); ++i)
  6572. addIfNotAlreadyThere (other[i]);
  6573. }
  6574. void FileSearchPath::removeRedundantPaths()
  6575. {
  6576. for (int i = directories.size(); --i >= 0;)
  6577. {
  6578. const File d1 (directories[i]);
  6579. for (int j = directories.size(); --j >= 0;)
  6580. {
  6581. const File d2 (directories[j]);
  6582. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6583. {
  6584. directories.remove (i);
  6585. break;
  6586. }
  6587. }
  6588. }
  6589. }
  6590. void FileSearchPath::removeNonExistentPaths()
  6591. {
  6592. for (int i = directories.size(); --i >= 0;)
  6593. if (! File (directories[i]).isDirectory())
  6594. directories.remove (i);
  6595. }
  6596. int FileSearchPath::findChildFiles (Array<File>& results,
  6597. const int whatToLookFor,
  6598. const bool searchRecursively,
  6599. const String& wildCardPattern) const
  6600. {
  6601. int total = 0;
  6602. for (int i = 0; i < directories.size(); ++i)
  6603. total += operator[] (i).findChildFiles (results,
  6604. whatToLookFor,
  6605. searchRecursively,
  6606. wildCardPattern);
  6607. return total;
  6608. }
  6609. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6610. const bool checkRecursively) const
  6611. {
  6612. for (int i = directories.size(); --i >= 0;)
  6613. {
  6614. const File d (directories[i]);
  6615. if (checkRecursively)
  6616. {
  6617. if (fileToCheck.isAChildOf (d))
  6618. return true;
  6619. }
  6620. else
  6621. {
  6622. if (fileToCheck.getParentDirectory() == d)
  6623. return true;
  6624. }
  6625. }
  6626. return false;
  6627. }
  6628. END_JUCE_NAMESPACE
  6629. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6630. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6631. BEGIN_JUCE_NAMESPACE
  6632. NamedPipe::NamedPipe()
  6633. : internal (0)
  6634. {
  6635. }
  6636. NamedPipe::~NamedPipe()
  6637. {
  6638. close();
  6639. }
  6640. bool NamedPipe::openExisting (const String& pipeName)
  6641. {
  6642. currentPipeName = pipeName;
  6643. return openInternal (pipeName, false);
  6644. }
  6645. bool NamedPipe::createNewPipe (const String& pipeName)
  6646. {
  6647. currentPipeName = pipeName;
  6648. return openInternal (pipeName, true);
  6649. }
  6650. bool NamedPipe::isOpen() const
  6651. {
  6652. return internal != 0;
  6653. }
  6654. const String NamedPipe::getName() const
  6655. {
  6656. return currentPipeName;
  6657. }
  6658. // other methods for this class are implemented in the platform-specific files
  6659. END_JUCE_NAMESPACE
  6660. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6661. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6662. BEGIN_JUCE_NAMESPACE
  6663. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6664. {
  6665. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6666. "temp_" + String (Random::getSystemRandom().nextInt()),
  6667. suffix,
  6668. optionFlags);
  6669. }
  6670. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6671. : targetFile (targetFile_)
  6672. {
  6673. // If you use this constructor, you need to give it a valid target file!
  6674. jassert (targetFile != File::nonexistent);
  6675. createTempFile (targetFile.getParentDirectory(),
  6676. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6677. targetFile.getFileExtension(),
  6678. optionFlags);
  6679. }
  6680. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6681. const String& suffix, const int optionFlags)
  6682. {
  6683. if ((optionFlags & useHiddenFile) != 0)
  6684. name = "." + name;
  6685. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6686. }
  6687. TemporaryFile::~TemporaryFile()
  6688. {
  6689. if (! deleteTemporaryFile())
  6690. {
  6691. /* Failed to delete our temporary file! The most likely reason for this would be
  6692. that you've not closed an output stream that was being used to write to file.
  6693. If you find that something beyond your control is changing permissions on
  6694. your temporary files and preventing them from being deleted, you may want to
  6695. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6696. handle them appropriately.
  6697. */
  6698. jassertfalse;
  6699. }
  6700. }
  6701. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6702. {
  6703. // This method only works if you created this object with the constructor
  6704. // that takes a target file!
  6705. jassert (targetFile != File::nonexistent);
  6706. if (temporaryFile.exists())
  6707. {
  6708. // Have a few attempts at overwriting the file before giving up..
  6709. for (int i = 5; --i >= 0;)
  6710. {
  6711. if (temporaryFile.moveFileTo (targetFile))
  6712. return true;
  6713. Thread::sleep (100);
  6714. }
  6715. }
  6716. else
  6717. {
  6718. // There's no temporary file to use. If your write failed, you should
  6719. // probably check, and not bother calling this method.
  6720. jassertfalse;
  6721. }
  6722. return false;
  6723. }
  6724. bool TemporaryFile::deleteTemporaryFile() const
  6725. {
  6726. // Have a few attempts at deleting the file before giving up..
  6727. for (int i = 5; --i >= 0;)
  6728. {
  6729. if (temporaryFile.deleteFile())
  6730. return true;
  6731. Thread::sleep (50);
  6732. }
  6733. return false;
  6734. }
  6735. END_JUCE_NAMESPACE
  6736. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6737. /*** Start of inlined file: juce_Socket.cpp ***/
  6738. #if JUCE_WINDOWS
  6739. #include <winsock2.h>
  6740. #if JUCE_MSVC
  6741. #pragma warning (push)
  6742. #pragma warning (disable : 4127 4389 4018)
  6743. #endif
  6744. #else
  6745. #if JUCE_LINUX
  6746. #include <sys/types.h>
  6747. #include <sys/socket.h>
  6748. #include <sys/errno.h>
  6749. #include <unistd.h>
  6750. #include <netinet/in.h>
  6751. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6752. #include <CoreServices/CoreServices.h>
  6753. #endif
  6754. #include <fcntl.h>
  6755. #include <netdb.h>
  6756. #include <arpa/inet.h>
  6757. #include <netinet/tcp.h>
  6758. #endif
  6759. BEGIN_JUCE_NAMESPACE
  6760. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6761. typedef socklen_t juce_socklen_t;
  6762. #else
  6763. typedef int juce_socklen_t;
  6764. #endif
  6765. #if JUCE_WINDOWS
  6766. namespace SocketHelpers
  6767. {
  6768. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6769. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6770. }
  6771. static void initWin32Sockets()
  6772. {
  6773. static CriticalSection lock;
  6774. const ScopedLock sl (lock);
  6775. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6776. {
  6777. WSADATA wsaData;
  6778. const WORD wVersionRequested = MAKEWORD (1, 1);
  6779. WSAStartup (wVersionRequested, &wsaData);
  6780. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6781. }
  6782. }
  6783. void juce_shutdownWin32Sockets()
  6784. {
  6785. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6786. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6787. }
  6788. #endif
  6789. namespace SocketHelpers
  6790. {
  6791. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6792. {
  6793. const int sndBufSize = 65536;
  6794. const int rcvBufSize = 65536;
  6795. const int one = 1;
  6796. return handle > 0
  6797. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6798. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6799. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6800. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6801. }
  6802. static bool bindSocketToPort (const int handle, const int port) throw()
  6803. {
  6804. if (handle <= 0 || port <= 0)
  6805. return false;
  6806. struct sockaddr_in servTmpAddr;
  6807. zerostruct (servTmpAddr);
  6808. servTmpAddr.sin_family = PF_INET;
  6809. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6810. servTmpAddr.sin_port = htons ((uint16) port);
  6811. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6812. }
  6813. static int readSocket (const int handle,
  6814. void* const destBuffer, const int maxBytesToRead,
  6815. bool volatile& connected,
  6816. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6817. {
  6818. int bytesRead = 0;
  6819. while (bytesRead < maxBytesToRead)
  6820. {
  6821. int bytesThisTime;
  6822. #if JUCE_WINDOWS
  6823. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6824. #else
  6825. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6826. && errno == EINTR
  6827. && connected)
  6828. {
  6829. }
  6830. #endif
  6831. if (bytesThisTime <= 0 || ! connected)
  6832. {
  6833. if (bytesRead == 0)
  6834. bytesRead = -1;
  6835. break;
  6836. }
  6837. bytesRead += bytesThisTime;
  6838. if (! blockUntilSpecifiedAmountHasArrived)
  6839. break;
  6840. }
  6841. return bytesRead;
  6842. }
  6843. static int waitForReadiness (const int handle, const bool forReading,
  6844. const int timeoutMsecs) throw()
  6845. {
  6846. struct timeval timeout;
  6847. struct timeval* timeoutp;
  6848. if (timeoutMsecs >= 0)
  6849. {
  6850. timeout.tv_sec = timeoutMsecs / 1000;
  6851. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6852. timeoutp = &timeout;
  6853. }
  6854. else
  6855. {
  6856. timeoutp = 0;
  6857. }
  6858. fd_set rset, wset;
  6859. FD_ZERO (&rset);
  6860. FD_SET (handle, &rset);
  6861. FD_ZERO (&wset);
  6862. FD_SET (handle, &wset);
  6863. fd_set* const prset = forReading ? &rset : 0;
  6864. fd_set* const pwset = forReading ? 0 : &wset;
  6865. #if JUCE_WINDOWS
  6866. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6867. return -1;
  6868. #else
  6869. {
  6870. int result;
  6871. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6872. && errno == EINTR)
  6873. {
  6874. }
  6875. if (result < 0)
  6876. return -1;
  6877. }
  6878. #endif
  6879. {
  6880. int opt;
  6881. juce_socklen_t len = sizeof (opt);
  6882. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6883. || opt != 0)
  6884. return -1;
  6885. }
  6886. if ((forReading && FD_ISSET (handle, &rset))
  6887. || ((! forReading) && FD_ISSET (handle, &wset)))
  6888. return 1;
  6889. return 0;
  6890. }
  6891. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6892. {
  6893. #if JUCE_WINDOWS
  6894. u_long nonBlocking = shouldBlock ? 0 : 1;
  6895. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6896. return false;
  6897. #else
  6898. int socketFlags = fcntl (handle, F_GETFL, 0);
  6899. if (socketFlags == -1)
  6900. return false;
  6901. if (shouldBlock)
  6902. socketFlags &= ~O_NONBLOCK;
  6903. else
  6904. socketFlags |= O_NONBLOCK;
  6905. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6906. return false;
  6907. #endif
  6908. return true;
  6909. }
  6910. static bool connectSocket (int volatile& handle,
  6911. const bool isDatagram,
  6912. void** serverAddress,
  6913. const String& hostName,
  6914. const int portNumber,
  6915. const int timeOutMillisecs) throw()
  6916. {
  6917. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6918. if (hostEnt == 0)
  6919. return false;
  6920. struct in_addr targetAddress;
  6921. memcpy (&targetAddress.s_addr,
  6922. *(hostEnt->h_addr_list),
  6923. sizeof (targetAddress.s_addr));
  6924. struct sockaddr_in servTmpAddr;
  6925. zerostruct (servTmpAddr);
  6926. servTmpAddr.sin_family = PF_INET;
  6927. servTmpAddr.sin_addr = targetAddress;
  6928. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6929. if (handle < 0)
  6930. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6931. if (handle < 0)
  6932. return false;
  6933. if (isDatagram)
  6934. {
  6935. *serverAddress = new struct sockaddr_in();
  6936. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6937. return true;
  6938. }
  6939. setSocketBlockingState (handle, false);
  6940. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6941. if (result < 0)
  6942. {
  6943. #if JUCE_WINDOWS
  6944. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6945. #else
  6946. if (errno == EINPROGRESS)
  6947. #endif
  6948. {
  6949. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6950. {
  6951. setSocketBlockingState (handle, true);
  6952. return false;
  6953. }
  6954. }
  6955. }
  6956. setSocketBlockingState (handle, true);
  6957. resetSocketOptions (handle, false, false);
  6958. return true;
  6959. }
  6960. }
  6961. StreamingSocket::StreamingSocket()
  6962. : portNumber (0),
  6963. handle (-1),
  6964. connected (false),
  6965. isListener (false)
  6966. {
  6967. #if JUCE_WINDOWS
  6968. initWin32Sockets();
  6969. #endif
  6970. }
  6971. StreamingSocket::StreamingSocket (const String& hostName_,
  6972. const int portNumber_,
  6973. const int handle_)
  6974. : hostName (hostName_),
  6975. portNumber (portNumber_),
  6976. handle (handle_),
  6977. connected (true),
  6978. isListener (false)
  6979. {
  6980. #if JUCE_WINDOWS
  6981. initWin32Sockets();
  6982. #endif
  6983. SocketHelpers::resetSocketOptions (handle_, false, false);
  6984. }
  6985. StreamingSocket::~StreamingSocket()
  6986. {
  6987. close();
  6988. }
  6989. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6990. {
  6991. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6992. : -1;
  6993. }
  6994. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6995. {
  6996. if (isListener || ! connected)
  6997. return -1;
  6998. #if JUCE_WINDOWS
  6999. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7000. #else
  7001. int result;
  7002. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7003. && errno == EINTR)
  7004. {
  7005. }
  7006. return result;
  7007. #endif
  7008. }
  7009. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7010. const int timeoutMsecs) const
  7011. {
  7012. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7013. : -1;
  7014. }
  7015. bool StreamingSocket::bindToPort (const int port)
  7016. {
  7017. return SocketHelpers::bindSocketToPort (handle, port);
  7018. }
  7019. bool StreamingSocket::connect (const String& remoteHostName,
  7020. const int remotePortNumber,
  7021. const int timeOutMillisecs)
  7022. {
  7023. if (isListener)
  7024. {
  7025. jassertfalse; // a listener socket can't connect to another one!
  7026. return false;
  7027. }
  7028. if (connected)
  7029. close();
  7030. hostName = remoteHostName;
  7031. portNumber = remotePortNumber;
  7032. isListener = false;
  7033. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7034. remotePortNumber, timeOutMillisecs);
  7035. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7036. {
  7037. close();
  7038. return false;
  7039. }
  7040. return true;
  7041. }
  7042. void StreamingSocket::close()
  7043. {
  7044. #if JUCE_WINDOWS
  7045. if (handle != SOCKET_ERROR || connected)
  7046. closesocket (handle);
  7047. connected = false;
  7048. #else
  7049. if (connected)
  7050. {
  7051. connected = false;
  7052. if (isListener)
  7053. {
  7054. // need to do this to interrupt the accept() function..
  7055. StreamingSocket temp;
  7056. temp.connect ("localhost", portNumber, 1000);
  7057. }
  7058. }
  7059. if (handle != -1)
  7060. ::close (handle);
  7061. #endif
  7062. hostName = String::empty;
  7063. portNumber = 0;
  7064. handle = -1;
  7065. isListener = false;
  7066. }
  7067. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7068. {
  7069. if (connected)
  7070. close();
  7071. hostName = "listener";
  7072. portNumber = newPortNumber;
  7073. isListener = true;
  7074. struct sockaddr_in servTmpAddr;
  7075. zerostruct (servTmpAddr);
  7076. servTmpAddr.sin_family = PF_INET;
  7077. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7078. if (localHostName.isNotEmpty())
  7079. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7080. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7081. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7082. if (handle < 0)
  7083. return false;
  7084. const int reuse = 1;
  7085. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7086. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7087. || listen (handle, SOMAXCONN) < 0)
  7088. {
  7089. close();
  7090. return false;
  7091. }
  7092. connected = true;
  7093. return true;
  7094. }
  7095. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7096. {
  7097. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7098. // prepare this socket as a listener.
  7099. if (connected && isListener)
  7100. {
  7101. struct sockaddr address;
  7102. juce_socklen_t len = sizeof (sockaddr);
  7103. const int newSocket = (int) accept (handle, &address, &len);
  7104. if (newSocket >= 0 && connected)
  7105. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7106. portNumber, newSocket);
  7107. }
  7108. return 0;
  7109. }
  7110. bool StreamingSocket::isLocal() const throw()
  7111. {
  7112. return hostName == "127.0.0.1";
  7113. }
  7114. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7115. : portNumber (0),
  7116. handle (-1),
  7117. connected (true),
  7118. allowBroadcast (allowBroadcast_),
  7119. serverAddress (0)
  7120. {
  7121. #if JUCE_WINDOWS
  7122. initWin32Sockets();
  7123. #endif
  7124. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7125. bindToPort (localPortNumber);
  7126. }
  7127. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7128. const int handle_, const int localPortNumber)
  7129. : hostName (hostName_),
  7130. portNumber (portNumber_),
  7131. handle (handle_),
  7132. connected (true),
  7133. allowBroadcast (false),
  7134. serverAddress (0)
  7135. {
  7136. #if JUCE_WINDOWS
  7137. initWin32Sockets();
  7138. #endif
  7139. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7140. bindToPort (localPortNumber);
  7141. }
  7142. DatagramSocket::~DatagramSocket()
  7143. {
  7144. close();
  7145. delete static_cast <struct sockaddr_in*> (serverAddress);
  7146. serverAddress = 0;
  7147. }
  7148. void DatagramSocket::close()
  7149. {
  7150. #if JUCE_WINDOWS
  7151. closesocket (handle);
  7152. connected = false;
  7153. #else
  7154. connected = false;
  7155. ::close (handle);
  7156. #endif
  7157. hostName = String::empty;
  7158. portNumber = 0;
  7159. handle = -1;
  7160. }
  7161. bool DatagramSocket::bindToPort (const int port)
  7162. {
  7163. return SocketHelpers::bindSocketToPort (handle, port);
  7164. }
  7165. bool DatagramSocket::connect (const String& remoteHostName,
  7166. const int remotePortNumber,
  7167. const int timeOutMillisecs)
  7168. {
  7169. if (connected)
  7170. close();
  7171. hostName = remoteHostName;
  7172. portNumber = remotePortNumber;
  7173. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7174. remoteHostName, remotePortNumber,
  7175. timeOutMillisecs);
  7176. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7177. {
  7178. close();
  7179. return false;
  7180. }
  7181. return true;
  7182. }
  7183. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7184. {
  7185. struct sockaddr address;
  7186. juce_socklen_t len = sizeof (sockaddr);
  7187. while (waitUntilReady (true, -1) == 1)
  7188. {
  7189. char buf[1];
  7190. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7191. {
  7192. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7193. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7194. -1, -1);
  7195. }
  7196. }
  7197. return 0;
  7198. }
  7199. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7200. const int timeoutMsecs) const
  7201. {
  7202. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7203. : -1;
  7204. }
  7205. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7206. {
  7207. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7208. : -1;
  7209. }
  7210. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7211. {
  7212. // You need to call connect() first to set the server address..
  7213. jassert (serverAddress != 0 && connected);
  7214. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7215. numBytesToWrite, 0,
  7216. (const struct sockaddr*) serverAddress,
  7217. sizeof (struct sockaddr_in))
  7218. : -1;
  7219. }
  7220. bool DatagramSocket::isLocal() const throw()
  7221. {
  7222. return hostName == "127.0.0.1";
  7223. }
  7224. #if JUCE_MSVC
  7225. #pragma warning (pop)
  7226. #endif
  7227. END_JUCE_NAMESPACE
  7228. /*** End of inlined file: juce_Socket.cpp ***/
  7229. /*** Start of inlined file: juce_URL.cpp ***/
  7230. BEGIN_JUCE_NAMESPACE
  7231. URL::URL()
  7232. {
  7233. }
  7234. URL::URL (const String& url_)
  7235. : url (url_)
  7236. {
  7237. int i = url.indexOfChar ('?');
  7238. if (i >= 0)
  7239. {
  7240. do
  7241. {
  7242. const int nextAmp = url.indexOfChar (i + 1, '&');
  7243. const int equalsPos = url.indexOfChar (i + 1, '=');
  7244. if (equalsPos > i + 1)
  7245. {
  7246. if (nextAmp < 0)
  7247. {
  7248. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7249. removeEscapeChars (url.substring (equalsPos + 1)));
  7250. }
  7251. else if (nextAmp > 0 && equalsPos < nextAmp)
  7252. {
  7253. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7254. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7255. }
  7256. }
  7257. i = nextAmp;
  7258. }
  7259. while (i >= 0);
  7260. url = url.upToFirstOccurrenceOf ("?", false, false);
  7261. }
  7262. }
  7263. URL::URL (const URL& other)
  7264. : url (other.url),
  7265. postData (other.postData),
  7266. parameters (other.parameters),
  7267. filesToUpload (other.filesToUpload),
  7268. mimeTypes (other.mimeTypes)
  7269. {
  7270. }
  7271. URL& URL::operator= (const URL& other)
  7272. {
  7273. url = other.url;
  7274. postData = other.postData;
  7275. parameters = other.parameters;
  7276. filesToUpload = other.filesToUpload;
  7277. mimeTypes = other.mimeTypes;
  7278. return *this;
  7279. }
  7280. URL::~URL()
  7281. {
  7282. }
  7283. static const String getMangledParameters (const StringPairArray& parameters)
  7284. {
  7285. String p;
  7286. for (int i = 0; i < parameters.size(); ++i)
  7287. {
  7288. if (i > 0)
  7289. p << '&';
  7290. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7291. << '='
  7292. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7293. }
  7294. return p;
  7295. }
  7296. const String URL::toString (const bool includeGetParameters) const
  7297. {
  7298. if (includeGetParameters && parameters.size() > 0)
  7299. return url + "?" + getMangledParameters (parameters);
  7300. else
  7301. return url;
  7302. }
  7303. bool URL::isWellFormed() const
  7304. {
  7305. //xxx TODO
  7306. return url.isNotEmpty();
  7307. }
  7308. static int findStartOfDomain (const String& url)
  7309. {
  7310. int i = 0;
  7311. while (CharacterFunctions::isLetterOrDigit (url[i])
  7312. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7313. ++i;
  7314. return url[i] == ':' ? i + 1 : 0;
  7315. }
  7316. const String URL::getDomain() const
  7317. {
  7318. int start = findStartOfDomain (url);
  7319. while (url[start] == '/')
  7320. ++start;
  7321. const int end1 = url.indexOfChar (start, '/');
  7322. const int end2 = url.indexOfChar (start, ':');
  7323. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7324. : jmin (end1, end2);
  7325. return url.substring (start, end);
  7326. }
  7327. const String URL::getSubPath() const
  7328. {
  7329. int start = findStartOfDomain (url);
  7330. while (url[start] == '/')
  7331. ++start;
  7332. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7333. return startOfPath <= 0 ? String::empty
  7334. : url.substring (startOfPath);
  7335. }
  7336. const String URL::getScheme() const
  7337. {
  7338. return url.substring (0, findStartOfDomain (url) - 1);
  7339. }
  7340. const URL URL::withNewSubPath (const String& newPath) const
  7341. {
  7342. int start = findStartOfDomain (url);
  7343. while (url[start] == '/')
  7344. ++start;
  7345. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7346. URL u (*this);
  7347. if (startOfPath > 0)
  7348. u.url = url.substring (0, startOfPath);
  7349. if (! u.url.endsWithChar ('/'))
  7350. u.url << '/';
  7351. if (newPath.startsWithChar ('/'))
  7352. u.url << newPath.substring (1);
  7353. else
  7354. u.url << newPath;
  7355. return u;
  7356. }
  7357. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7358. {
  7359. if (possibleURL.startsWithIgnoreCase ("http:")
  7360. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7361. return true;
  7362. if (possibleURL.startsWithIgnoreCase ("file:")
  7363. || possibleURL.containsChar ('@')
  7364. || possibleURL.endsWithChar ('.')
  7365. || (! possibleURL.containsChar ('.')))
  7366. return false;
  7367. if (possibleURL.startsWithIgnoreCase ("www.")
  7368. && possibleURL.substring (5).containsChar ('.'))
  7369. return true;
  7370. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7371. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7372. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7373. return true;
  7374. return false;
  7375. }
  7376. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7377. {
  7378. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7379. return atSign > 0
  7380. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7381. && (! possibleEmailAddress.endsWithChar ('.'));
  7382. }
  7383. void* juce_openInternetFile (const String& url,
  7384. const String& headers,
  7385. const MemoryBlock& optionalPostData,
  7386. const bool isPost,
  7387. URL::OpenStreamProgressCallback* callback,
  7388. void* callbackContext,
  7389. int timeOutMs);
  7390. void juce_closeInternetFile (void* handle);
  7391. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7392. int juce_seekInInternetFile (void* handle, int newPosition);
  7393. int64 juce_getInternetFileContentLength (void* handle);
  7394. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7395. class WebInputStream : public InputStream
  7396. {
  7397. public:
  7398. WebInputStream (const URL& url,
  7399. const bool isPost_,
  7400. URL::OpenStreamProgressCallback* const progressCallback_,
  7401. void* const progressCallbackContext_,
  7402. const String& extraHeaders,
  7403. const int timeOutMs_,
  7404. StringPairArray* const responseHeaders)
  7405. : position (0),
  7406. finished (false),
  7407. isPost (isPost_),
  7408. progressCallback (progressCallback_),
  7409. progressCallbackContext (progressCallbackContext_),
  7410. timeOutMs (timeOutMs_)
  7411. {
  7412. server = url.toString (! isPost);
  7413. if (isPost_)
  7414. createHeadersAndPostData (url);
  7415. headers += extraHeaders;
  7416. if (! headers.endsWithChar ('\n'))
  7417. headers << "\r\n";
  7418. handle = juce_openInternetFile (server, headers, postData, isPost,
  7419. progressCallback_, progressCallbackContext_,
  7420. timeOutMs);
  7421. if (responseHeaders != 0)
  7422. juce_getInternetFileHeaders (handle, *responseHeaders);
  7423. }
  7424. ~WebInputStream()
  7425. {
  7426. juce_closeInternetFile (handle);
  7427. }
  7428. bool isError() const { return handle == 0; }
  7429. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7430. bool isExhausted() { return finished; }
  7431. int64 getPosition() { return position; }
  7432. int read (void* dest, int bytes)
  7433. {
  7434. if (finished || isError())
  7435. {
  7436. return 0;
  7437. }
  7438. else
  7439. {
  7440. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7441. position += bytesRead;
  7442. if (bytesRead == 0)
  7443. finished = true;
  7444. return bytesRead;
  7445. }
  7446. }
  7447. bool setPosition (int64 wantedPos)
  7448. {
  7449. if (wantedPos != position)
  7450. {
  7451. finished = false;
  7452. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7453. if (actualPos == wantedPos)
  7454. {
  7455. position = wantedPos;
  7456. }
  7457. else
  7458. {
  7459. if (wantedPos < position)
  7460. {
  7461. juce_closeInternetFile (handle);
  7462. position = 0;
  7463. finished = false;
  7464. handle = juce_openInternetFile (server, headers, postData, isPost,
  7465. progressCallback, progressCallbackContext,
  7466. timeOutMs);
  7467. }
  7468. skipNextBytes (wantedPos - position);
  7469. }
  7470. }
  7471. return true;
  7472. }
  7473. juce_UseDebuggingNewOperator
  7474. private:
  7475. String server, headers;
  7476. MemoryBlock postData;
  7477. int64 position;
  7478. bool finished;
  7479. const bool isPost;
  7480. void* handle;
  7481. URL::OpenStreamProgressCallback* const progressCallback;
  7482. void* const progressCallbackContext;
  7483. const int timeOutMs;
  7484. void createHeadersAndPostData (const URL& url)
  7485. {
  7486. MemoryOutputStream data (postData, false);
  7487. if (url.getFilesToUpload().size() > 0)
  7488. {
  7489. // need to upload some files, so do it as multi-part...
  7490. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7491. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7492. data << "--" << boundary;
  7493. int i;
  7494. for (i = 0; i < url.getParameters().size(); ++i)
  7495. {
  7496. data << "\r\nContent-Disposition: form-data; name=\""
  7497. << url.getParameters().getAllKeys() [i]
  7498. << "\"\r\n\r\n"
  7499. << url.getParameters().getAllValues() [i]
  7500. << "\r\n--"
  7501. << boundary;
  7502. }
  7503. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7504. {
  7505. const File file (url.getFilesToUpload().getAllValues() [i]);
  7506. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7507. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7508. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7509. const String mimeType (url.getMimeTypesOfUploadFiles()
  7510. .getValue (paramName, String::empty));
  7511. if (mimeType.isNotEmpty())
  7512. data << "Content-Type: " << mimeType << "\r\n";
  7513. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7514. << file << "\r\n--" << boundary;
  7515. }
  7516. data << "--\r\n";
  7517. data.flush();
  7518. }
  7519. else
  7520. {
  7521. data << getMangledParameters (url.getParameters())
  7522. << url.getPostData();
  7523. data.flush();
  7524. // just a short text attachment, so use simple url encoding..
  7525. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7526. + String ((unsigned int) postData.getSize())
  7527. + "\r\n";
  7528. }
  7529. }
  7530. WebInputStream (const WebInputStream&);
  7531. WebInputStream& operator= (const WebInputStream&);
  7532. };
  7533. InputStream* URL::createInputStream (const bool usePostCommand,
  7534. OpenStreamProgressCallback* const progressCallback,
  7535. void* const progressCallbackContext,
  7536. const String& extraHeaders,
  7537. const int timeOutMs,
  7538. StringPairArray* const responseHeaders) const
  7539. {
  7540. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7541. progressCallback, progressCallbackContext,
  7542. extraHeaders, timeOutMs, responseHeaders));
  7543. return wi->isError() ? 0 : wi.release();
  7544. }
  7545. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7546. const bool usePostCommand) const
  7547. {
  7548. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7549. if (in != 0)
  7550. {
  7551. in->readIntoMemoryBlock (destData);
  7552. return true;
  7553. }
  7554. return false;
  7555. }
  7556. const String URL::readEntireTextStream (const bool usePostCommand) const
  7557. {
  7558. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7559. if (in != 0)
  7560. return in->readEntireStreamAsString();
  7561. return String::empty;
  7562. }
  7563. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7564. {
  7565. XmlDocument doc (readEntireTextStream (usePostCommand));
  7566. return doc.getDocumentElement();
  7567. }
  7568. const URL URL::withParameter (const String& parameterName,
  7569. const String& parameterValue) const
  7570. {
  7571. URL u (*this);
  7572. u.parameters.set (parameterName, parameterValue);
  7573. return u;
  7574. }
  7575. const URL URL::withFileToUpload (const String& parameterName,
  7576. const File& fileToUpload,
  7577. const String& mimeType) const
  7578. {
  7579. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7580. URL u (*this);
  7581. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7582. u.mimeTypes.set (parameterName, mimeType);
  7583. return u;
  7584. }
  7585. const URL URL::withPOSTData (const String& postData_) const
  7586. {
  7587. URL u (*this);
  7588. u.postData = postData_;
  7589. return u;
  7590. }
  7591. const StringPairArray& URL::getParameters() const
  7592. {
  7593. return parameters;
  7594. }
  7595. const StringPairArray& URL::getFilesToUpload() const
  7596. {
  7597. return filesToUpload;
  7598. }
  7599. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7600. {
  7601. return mimeTypes;
  7602. }
  7603. const String URL::removeEscapeChars (const String& s)
  7604. {
  7605. String result (s.replaceCharacter ('+', ' '));
  7606. int nextPercent = 0;
  7607. for (;;)
  7608. {
  7609. nextPercent = result.indexOfChar (nextPercent, '%');
  7610. if (nextPercent < 0)
  7611. break;
  7612. int hexDigit1 = 0, hexDigit2 = 0;
  7613. if ((hexDigit1 = CharacterFunctions::getHexDigitValue (result [nextPercent + 1])) >= 0
  7614. && (hexDigit2 = CharacterFunctions::getHexDigitValue (result [nextPercent + 2])) >= 0)
  7615. {
  7616. const juce_wchar replacementChar = (juce_wchar) ((hexDigit1 << 4) + hexDigit2);
  7617. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  7618. }
  7619. ++nextPercent;
  7620. }
  7621. return result;
  7622. }
  7623. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7624. {
  7625. String result;
  7626. result.preallocateStorage (s.length() + 8);
  7627. const char* utf8 = s.toUTF8();
  7628. const char* legalChars = isParameter ? "_-.*!'()"
  7629. : "_-$.*!'(),";
  7630. while (*utf8 != 0)
  7631. {
  7632. const char c = *utf8++;
  7633. if (CharacterFunctions::isLetterOrDigit (c)
  7634. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  7635. {
  7636. result << c;
  7637. }
  7638. else
  7639. {
  7640. const int v = (int) (uint8) c;
  7641. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  7642. }
  7643. }
  7644. return result;
  7645. }
  7646. bool URL::launchInDefaultBrowser() const
  7647. {
  7648. String u (toString (true));
  7649. if (u.containsChar ('@') && ! u.containsChar (':'))
  7650. u = "mailto:" + u;
  7651. return PlatformUtilities::openDocument (u, String::empty);
  7652. }
  7653. END_JUCE_NAMESPACE
  7654. /*** End of inlined file: juce_URL.cpp ***/
  7655. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7656. BEGIN_JUCE_NAMESPACE
  7657. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7658. const int bufferSize_,
  7659. const bool deleteSourceWhenDestroyed)
  7660. : source (source_),
  7661. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7662. bufferSize (jmax (256, bufferSize_)),
  7663. position (source_->getPosition()),
  7664. lastReadPos (0),
  7665. bufferOverlap (128)
  7666. {
  7667. const int sourceSize = (int) source_->getTotalLength();
  7668. if (sourceSize >= 0)
  7669. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7670. bufferStart = position;
  7671. buffer.malloc (bufferSize);
  7672. }
  7673. BufferedInputStream::~BufferedInputStream()
  7674. {
  7675. }
  7676. int64 BufferedInputStream::getTotalLength()
  7677. {
  7678. return source->getTotalLength();
  7679. }
  7680. int64 BufferedInputStream::getPosition()
  7681. {
  7682. return position;
  7683. }
  7684. bool BufferedInputStream::setPosition (int64 newPosition)
  7685. {
  7686. position = jmax ((int64) 0, newPosition);
  7687. return true;
  7688. }
  7689. bool BufferedInputStream::isExhausted()
  7690. {
  7691. return (position >= lastReadPos)
  7692. && source->isExhausted();
  7693. }
  7694. void BufferedInputStream::ensureBuffered()
  7695. {
  7696. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7697. if (position < bufferStart || position >= bufferEndOverlap)
  7698. {
  7699. int bytesRead;
  7700. if (position < lastReadPos
  7701. && position >= bufferEndOverlap
  7702. && position >= bufferStart)
  7703. {
  7704. const int bytesToKeep = (int) (lastReadPos - position);
  7705. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7706. bufferStart = position;
  7707. bytesRead = source->read (buffer + bytesToKeep,
  7708. bufferSize - bytesToKeep);
  7709. lastReadPos += bytesRead;
  7710. bytesRead += bytesToKeep;
  7711. }
  7712. else
  7713. {
  7714. bufferStart = position;
  7715. source->setPosition (bufferStart);
  7716. bytesRead = source->read (buffer, bufferSize);
  7717. lastReadPos = bufferStart + bytesRead;
  7718. }
  7719. while (bytesRead < bufferSize)
  7720. buffer [bytesRead++] = 0;
  7721. }
  7722. }
  7723. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7724. {
  7725. if (position >= bufferStart
  7726. && position + maxBytesToRead <= lastReadPos)
  7727. {
  7728. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7729. position += maxBytesToRead;
  7730. return maxBytesToRead;
  7731. }
  7732. else
  7733. {
  7734. if (position < bufferStart || position >= lastReadPos)
  7735. ensureBuffered();
  7736. int bytesRead = 0;
  7737. while (maxBytesToRead > 0)
  7738. {
  7739. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7740. if (bytesAvailable > 0)
  7741. {
  7742. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7743. maxBytesToRead -= bytesAvailable;
  7744. bytesRead += bytesAvailable;
  7745. position += bytesAvailable;
  7746. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7747. }
  7748. const int64 oldLastReadPos = lastReadPos;
  7749. ensureBuffered();
  7750. if (oldLastReadPos == lastReadPos)
  7751. break; // if ensureBuffered() failed to read any more data, bail out
  7752. if (isExhausted())
  7753. break;
  7754. }
  7755. return bytesRead;
  7756. }
  7757. }
  7758. const String BufferedInputStream::readString()
  7759. {
  7760. if (position >= bufferStart
  7761. && position < lastReadPos)
  7762. {
  7763. const int maxChars = (int) (lastReadPos - position);
  7764. const char* const src = buffer + (int) (position - bufferStart);
  7765. for (int i = 0; i < maxChars; ++i)
  7766. {
  7767. if (src[i] == 0)
  7768. {
  7769. position += i + 1;
  7770. return String::fromUTF8 (src, i);
  7771. }
  7772. }
  7773. }
  7774. return InputStream::readString();
  7775. }
  7776. END_JUCE_NAMESPACE
  7777. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7778. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7779. BEGIN_JUCE_NAMESPACE
  7780. FileInputSource::FileInputSource (const File& file_)
  7781. : file (file_)
  7782. {
  7783. }
  7784. FileInputSource::~FileInputSource()
  7785. {
  7786. }
  7787. InputStream* FileInputSource::createInputStream()
  7788. {
  7789. return file.createInputStream();
  7790. }
  7791. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7792. {
  7793. return file.getSiblingFile (relatedItemPath).createInputStream();
  7794. }
  7795. int64 FileInputSource::hashCode() const
  7796. {
  7797. return file.hashCode();
  7798. }
  7799. END_JUCE_NAMESPACE
  7800. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7801. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7802. BEGIN_JUCE_NAMESPACE
  7803. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7804. const size_t sourceDataSize,
  7805. const bool keepInternalCopy)
  7806. : data (static_cast <const char*> (sourceData)),
  7807. dataSize (sourceDataSize),
  7808. position (0)
  7809. {
  7810. if (keepInternalCopy)
  7811. {
  7812. internalCopy.append (data, sourceDataSize);
  7813. data = static_cast <const char*> (internalCopy.getData());
  7814. }
  7815. }
  7816. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7817. const bool keepInternalCopy)
  7818. : data (static_cast <const char*> (sourceData.getData())),
  7819. dataSize (sourceData.getSize()),
  7820. position (0)
  7821. {
  7822. if (keepInternalCopy)
  7823. {
  7824. internalCopy = sourceData;
  7825. data = static_cast <const char*> (internalCopy.getData());
  7826. }
  7827. }
  7828. MemoryInputStream::~MemoryInputStream()
  7829. {
  7830. }
  7831. int64 MemoryInputStream::getTotalLength()
  7832. {
  7833. return dataSize;
  7834. }
  7835. int MemoryInputStream::read (void* const buffer, const int howMany)
  7836. {
  7837. jassert (howMany >= 0);
  7838. const int num = jmin (howMany, (int) (dataSize - position));
  7839. memcpy (buffer, data + position, num);
  7840. position += num;
  7841. return (int) num;
  7842. }
  7843. bool MemoryInputStream::isExhausted()
  7844. {
  7845. return (position >= dataSize);
  7846. }
  7847. bool MemoryInputStream::setPosition (const int64 pos)
  7848. {
  7849. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7850. return true;
  7851. }
  7852. int64 MemoryInputStream::getPosition()
  7853. {
  7854. return position;
  7855. }
  7856. END_JUCE_NAMESPACE
  7857. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7858. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7859. BEGIN_JUCE_NAMESPACE
  7860. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7861. : data (internalBlock),
  7862. position (0),
  7863. size (0)
  7864. {
  7865. internalBlock.setSize (initialSize, false);
  7866. }
  7867. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7868. const bool appendToExistingBlockContent)
  7869. : data (memoryBlockToWriteTo),
  7870. position (0),
  7871. size (0)
  7872. {
  7873. if (appendToExistingBlockContent)
  7874. position = size = memoryBlockToWriteTo.getSize();
  7875. }
  7876. MemoryOutputStream::~MemoryOutputStream()
  7877. {
  7878. flush();
  7879. }
  7880. void MemoryOutputStream::flush()
  7881. {
  7882. if (&data != &internalBlock)
  7883. data.setSize (size, false);
  7884. }
  7885. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7886. {
  7887. data.ensureSize (bytesToPreallocate + 1);
  7888. }
  7889. void MemoryOutputStream::reset() throw()
  7890. {
  7891. position = 0;
  7892. size = 0;
  7893. }
  7894. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7895. {
  7896. if (howMany > 0)
  7897. {
  7898. const size_t storageNeeded = position + howMany;
  7899. if (storageNeeded >= data.getSize())
  7900. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7901. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7902. position += howMany;
  7903. size = jmax (size, position);
  7904. }
  7905. return true;
  7906. }
  7907. const void* MemoryOutputStream::getData() const throw()
  7908. {
  7909. void* const d = data.getData();
  7910. if (data.getSize() > size)
  7911. static_cast <char*> (d) [size] = 0;
  7912. return d;
  7913. }
  7914. bool MemoryOutputStream::setPosition (int64 newPosition)
  7915. {
  7916. if (newPosition <= (int64) size)
  7917. {
  7918. // ok to seek backwards
  7919. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7920. return true;
  7921. }
  7922. else
  7923. {
  7924. // trying to make it bigger isn't a good thing to do..
  7925. return false;
  7926. }
  7927. }
  7928. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  7929. {
  7930. // before writing from an input, see if we can preallocate to make it more efficient..
  7931. int64 availableData = source.getTotalLength() - source.getPosition();
  7932. if (availableData > 0)
  7933. {
  7934. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  7935. availableData = maxNumBytesToWrite;
  7936. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  7937. }
  7938. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  7939. }
  7940. const String MemoryOutputStream::toUTF8() const
  7941. {
  7942. return String (static_cast <const char*> (getData()), getDataSize());
  7943. }
  7944. const String MemoryOutputStream::toString() const
  7945. {
  7946. return String::createStringFromData (getData(), getDataSize());
  7947. }
  7948. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  7949. {
  7950. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  7951. return stream;
  7952. }
  7953. END_JUCE_NAMESPACE
  7954. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7955. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7956. BEGIN_JUCE_NAMESPACE
  7957. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7958. const int64 startPositionInSourceStream_,
  7959. const int64 lengthOfSourceStream_,
  7960. const bool deleteSourceWhenDestroyed)
  7961. : source (sourceStream),
  7962. startPositionInSourceStream (startPositionInSourceStream_),
  7963. lengthOfSourceStream (lengthOfSourceStream_)
  7964. {
  7965. if (deleteSourceWhenDestroyed)
  7966. sourceToDelete = source;
  7967. setPosition (0);
  7968. }
  7969. SubregionStream::~SubregionStream()
  7970. {
  7971. }
  7972. int64 SubregionStream::getTotalLength()
  7973. {
  7974. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7975. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7976. : srcLen;
  7977. }
  7978. int64 SubregionStream::getPosition()
  7979. {
  7980. return source->getPosition() - startPositionInSourceStream;
  7981. }
  7982. bool SubregionStream::setPosition (int64 newPosition)
  7983. {
  7984. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7985. }
  7986. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7987. {
  7988. if (lengthOfSourceStream < 0)
  7989. {
  7990. return source->read (destBuffer, maxBytesToRead);
  7991. }
  7992. else
  7993. {
  7994. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7995. if (maxBytesToRead <= 0)
  7996. return 0;
  7997. return source->read (destBuffer, maxBytesToRead);
  7998. }
  7999. }
  8000. bool SubregionStream::isExhausted()
  8001. {
  8002. if (lengthOfSourceStream >= 0)
  8003. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8004. else
  8005. return source->isExhausted();
  8006. }
  8007. END_JUCE_NAMESPACE
  8008. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8009. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8010. BEGIN_JUCE_NAMESPACE
  8011. PerformanceCounter::PerformanceCounter (const String& name_,
  8012. int runsPerPrintout,
  8013. const File& loggingFile)
  8014. : name (name_),
  8015. numRuns (0),
  8016. runsPerPrint (runsPerPrintout),
  8017. totalTime (0),
  8018. outputFile (loggingFile)
  8019. {
  8020. if (outputFile != File::nonexistent)
  8021. {
  8022. String s ("**** Counter for \"");
  8023. s << name_ << "\" started at: "
  8024. << Time::getCurrentTime().toString (true, true)
  8025. << "\r\n";
  8026. outputFile.appendText (s, false, false);
  8027. }
  8028. }
  8029. PerformanceCounter::~PerformanceCounter()
  8030. {
  8031. printStatistics();
  8032. }
  8033. void PerformanceCounter::start()
  8034. {
  8035. started = Time::getHighResolutionTicks();
  8036. }
  8037. void PerformanceCounter::stop()
  8038. {
  8039. const int64 now = Time::getHighResolutionTicks();
  8040. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8041. if (++numRuns == runsPerPrint)
  8042. printStatistics();
  8043. }
  8044. void PerformanceCounter::printStatistics()
  8045. {
  8046. if (numRuns > 0)
  8047. {
  8048. String s ("Performance count for \"");
  8049. s << name << "\" - average over " << numRuns << " run(s) = ";
  8050. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8051. if (micros > 10000)
  8052. s << (micros/1000) << " millisecs";
  8053. else
  8054. s << micros << " microsecs";
  8055. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8056. Logger::outputDebugString (s);
  8057. s << "\r\n";
  8058. if (outputFile != File::nonexistent)
  8059. outputFile.appendText (s, false, false);
  8060. numRuns = 0;
  8061. totalTime = 0;
  8062. }
  8063. }
  8064. END_JUCE_NAMESPACE
  8065. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8066. /*** Start of inlined file: juce_Uuid.cpp ***/
  8067. BEGIN_JUCE_NAMESPACE
  8068. Uuid::Uuid()
  8069. {
  8070. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8071. // to make it very very unlikely that two UUIDs will ever be the same..
  8072. static int64 macAddresses[2];
  8073. static bool hasCheckedMacAddresses = false;
  8074. if (! hasCheckedMacAddresses)
  8075. {
  8076. hasCheckedMacAddresses = true;
  8077. SystemStats::getMACAddresses (macAddresses, 2);
  8078. }
  8079. value.asInt64[0] = macAddresses[0];
  8080. value.asInt64[1] = macAddresses[1];
  8081. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8082. // whose seed will carry over between calls to this method.
  8083. Random r (macAddresses[0] ^ macAddresses[1]
  8084. ^ Random::getSystemRandom().nextInt64());
  8085. for (int i = 4; --i >= 0;)
  8086. {
  8087. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8088. value.asInt[i] ^= r.nextInt();
  8089. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8090. }
  8091. }
  8092. Uuid::~Uuid() throw()
  8093. {
  8094. }
  8095. Uuid::Uuid (const Uuid& other)
  8096. : value (other.value)
  8097. {
  8098. }
  8099. Uuid& Uuid::operator= (const Uuid& other)
  8100. {
  8101. value = other.value;
  8102. return *this;
  8103. }
  8104. bool Uuid::operator== (const Uuid& other) const
  8105. {
  8106. return value.asInt64[0] == other.value.asInt64[0]
  8107. && value.asInt64[1] == other.value.asInt64[1];
  8108. }
  8109. bool Uuid::operator!= (const Uuid& other) const
  8110. {
  8111. return ! operator== (other);
  8112. }
  8113. bool Uuid::isNull() const throw()
  8114. {
  8115. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8116. }
  8117. const String Uuid::toString() const
  8118. {
  8119. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8120. }
  8121. Uuid::Uuid (const String& uuidString)
  8122. {
  8123. operator= (uuidString);
  8124. }
  8125. Uuid& Uuid::operator= (const String& uuidString)
  8126. {
  8127. MemoryBlock mb;
  8128. mb.loadFromHexString (uuidString);
  8129. mb.ensureSize (sizeof (value.asBytes), true);
  8130. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8131. return *this;
  8132. }
  8133. Uuid::Uuid (const uint8* const rawData)
  8134. {
  8135. operator= (rawData);
  8136. }
  8137. Uuid& Uuid::operator= (const uint8* const rawData)
  8138. {
  8139. if (rawData != 0)
  8140. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8141. else
  8142. zeromem (value.asBytes, sizeof (value.asBytes));
  8143. return *this;
  8144. }
  8145. END_JUCE_NAMESPACE
  8146. /*** End of inlined file: juce_Uuid.cpp ***/
  8147. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8148. BEGIN_JUCE_NAMESPACE
  8149. class ZipFile::ZipEntryInfo
  8150. {
  8151. public:
  8152. ZipFile::ZipEntry entry;
  8153. int streamOffset;
  8154. int compressedSize;
  8155. bool compressed;
  8156. };
  8157. class ZipFile::ZipInputStream : public InputStream
  8158. {
  8159. public:
  8160. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8161. : file (file_),
  8162. zipEntryInfo (zei),
  8163. pos (0),
  8164. headerSize (0),
  8165. inputStream (0)
  8166. {
  8167. inputStream = file_.inputStream;
  8168. if (file_.inputSource != 0)
  8169. {
  8170. inputStream = file.inputSource->createInputStream();
  8171. }
  8172. else
  8173. {
  8174. #if JUCE_DEBUG
  8175. file_.numOpenStreams++;
  8176. #endif
  8177. }
  8178. char buffer [30];
  8179. if (inputStream != 0
  8180. && inputStream->setPosition (zei.streamOffset)
  8181. && inputStream->read (buffer, 30) == 30
  8182. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8183. {
  8184. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8185. + ByteOrder::littleEndianShort (buffer + 28);
  8186. }
  8187. }
  8188. ~ZipInputStream()
  8189. {
  8190. #if JUCE_DEBUG
  8191. if (inputStream != 0 && inputStream == file.inputStream)
  8192. file.numOpenStreams--;
  8193. #endif
  8194. if (inputStream != file.inputStream)
  8195. delete inputStream;
  8196. }
  8197. int64 getTotalLength()
  8198. {
  8199. return zipEntryInfo.compressedSize;
  8200. }
  8201. int read (void* buffer, int howMany)
  8202. {
  8203. if (headerSize <= 0)
  8204. return 0;
  8205. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8206. if (inputStream == 0)
  8207. return 0;
  8208. int num;
  8209. if (inputStream == file.inputStream)
  8210. {
  8211. const ScopedLock sl (file.lock);
  8212. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8213. num = inputStream->read (buffer, howMany);
  8214. }
  8215. else
  8216. {
  8217. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8218. num = inputStream->read (buffer, howMany);
  8219. }
  8220. pos += num;
  8221. return num;
  8222. }
  8223. bool isExhausted()
  8224. {
  8225. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8226. }
  8227. int64 getPosition()
  8228. {
  8229. return pos;
  8230. }
  8231. bool setPosition (int64 newPos)
  8232. {
  8233. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8234. return true;
  8235. }
  8236. private:
  8237. ZipFile& file;
  8238. ZipEntryInfo zipEntryInfo;
  8239. int64 pos;
  8240. int headerSize;
  8241. InputStream* inputStream;
  8242. ZipInputStream (const ZipInputStream&);
  8243. ZipInputStream& operator= (const ZipInputStream&);
  8244. };
  8245. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8246. : inputStream (source_)
  8247. #if JUCE_DEBUG
  8248. , numOpenStreams (0)
  8249. #endif
  8250. {
  8251. if (deleteStreamWhenDestroyed)
  8252. streamToDelete = inputStream;
  8253. init();
  8254. }
  8255. ZipFile::ZipFile (const File& file)
  8256. : inputStream (0)
  8257. #if JUCE_DEBUG
  8258. , numOpenStreams (0)
  8259. #endif
  8260. {
  8261. inputSource = new FileInputSource (file);
  8262. init();
  8263. }
  8264. ZipFile::ZipFile (InputSource* const inputSource_)
  8265. : inputStream (0),
  8266. inputSource (inputSource_)
  8267. #if JUCE_DEBUG
  8268. , numOpenStreams (0)
  8269. #endif
  8270. {
  8271. init();
  8272. }
  8273. ZipFile::~ZipFile()
  8274. {
  8275. #if JUCE_DEBUG
  8276. entries.clear();
  8277. // If you hit this assertion, it means you've created a stream to read
  8278. // one of the items in the zipfile, but you've forgotten to delete that
  8279. // stream object before deleting the file.. Streams can't be kept open
  8280. // after the file is deleted because they need to share the input
  8281. // stream that the file uses to read itself.
  8282. jassert (numOpenStreams == 0);
  8283. #endif
  8284. }
  8285. int ZipFile::getNumEntries() const throw()
  8286. {
  8287. return entries.size();
  8288. }
  8289. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8290. {
  8291. ZipEntryInfo* const zei = entries [index];
  8292. return zei != 0 ? &(zei->entry) : 0;
  8293. }
  8294. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8295. {
  8296. for (int i = 0; i < entries.size(); ++i)
  8297. if (entries.getUnchecked (i)->entry.filename == fileName)
  8298. return i;
  8299. return -1;
  8300. }
  8301. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8302. {
  8303. return getEntry (getIndexOfFileName (fileName));
  8304. }
  8305. InputStream* ZipFile::createStreamForEntry (const int index)
  8306. {
  8307. ZipEntryInfo* const zei = entries[index];
  8308. InputStream* stream = 0;
  8309. if (zei != 0)
  8310. {
  8311. stream = new ZipInputStream (*this, *zei);
  8312. if (zei->compressed)
  8313. {
  8314. stream = new GZIPDecompressorInputStream (stream, true, true,
  8315. zei->entry.uncompressedSize);
  8316. // (much faster to unzip in big blocks using a buffer..)
  8317. stream = new BufferedInputStream (stream, 32768, true);
  8318. }
  8319. }
  8320. return stream;
  8321. }
  8322. class ZipFile::ZipFilenameComparator
  8323. {
  8324. public:
  8325. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8326. {
  8327. return first->entry.filename.compare (second->entry.filename);
  8328. }
  8329. };
  8330. void ZipFile::sortEntriesByFilename()
  8331. {
  8332. ZipFilenameComparator sorter;
  8333. entries.sort (sorter);
  8334. }
  8335. void ZipFile::init()
  8336. {
  8337. ScopedPointer <InputStream> toDelete;
  8338. InputStream* in = inputStream;
  8339. if (inputSource != 0)
  8340. {
  8341. in = inputSource->createInputStream();
  8342. toDelete = in;
  8343. }
  8344. if (in != 0)
  8345. {
  8346. int numEntries = 0;
  8347. int pos = findEndOfZipEntryTable (in, numEntries);
  8348. if (pos >= 0 && pos < in->getTotalLength())
  8349. {
  8350. const int size = (int) (in->getTotalLength() - pos);
  8351. in->setPosition (pos);
  8352. MemoryBlock headerData;
  8353. if (in->readIntoMemoryBlock (headerData, size) == size)
  8354. {
  8355. pos = 0;
  8356. for (int i = 0; i < numEntries; ++i)
  8357. {
  8358. if (pos + 46 > size)
  8359. break;
  8360. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8361. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8362. if (pos + 46 + fileNameLen > size)
  8363. break;
  8364. ZipEntryInfo* const zei = new ZipEntryInfo();
  8365. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8366. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8367. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8368. const int year = 1980 + (date >> 9);
  8369. const int month = ((date >> 5) & 15) - 1;
  8370. const int day = date & 31;
  8371. const int hours = time >> 11;
  8372. const int minutes = (time >> 5) & 63;
  8373. const int seconds = (time & 31) << 1;
  8374. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8375. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8376. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8377. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8378. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8379. entries.add (zei);
  8380. pos += 46 + fileNameLen
  8381. + ByteOrder::littleEndianShort (buffer + 30)
  8382. + ByteOrder::littleEndianShort (buffer + 32);
  8383. }
  8384. }
  8385. }
  8386. }
  8387. }
  8388. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8389. {
  8390. BufferedInputStream in (input, 8192, false);
  8391. in.setPosition (in.getTotalLength());
  8392. int64 pos = in.getPosition();
  8393. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8394. char buffer [32];
  8395. zeromem (buffer, sizeof (buffer));
  8396. while (pos > lowestPos)
  8397. {
  8398. in.setPosition (pos - 22);
  8399. pos = in.getPosition();
  8400. memcpy (buffer + 22, buffer, 4);
  8401. if (in.read (buffer, 22) != 22)
  8402. return 0;
  8403. for (int i = 0; i < 22; ++i)
  8404. {
  8405. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8406. {
  8407. in.setPosition (pos + i);
  8408. in.read (buffer, 22);
  8409. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8410. return ByteOrder::littleEndianInt (buffer + 16);
  8411. }
  8412. }
  8413. }
  8414. return 0;
  8415. }
  8416. void ZipFile::uncompressTo (const File& targetDirectory,
  8417. const bool shouldOverwriteFiles)
  8418. {
  8419. for (int i = 0; i < entries.size(); ++i)
  8420. {
  8421. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  8422. const File targetFile (targetDirectory.getChildFile (zei.filename));
  8423. if (zei.filename.endsWithChar ('/'))
  8424. {
  8425. targetFile.createDirectory(); // (entry is a directory, not a file)
  8426. }
  8427. else
  8428. {
  8429. ScopedPointer <InputStream> in (createStreamForEntry (i));
  8430. if (in != 0)
  8431. {
  8432. if (shouldOverwriteFiles)
  8433. targetFile.deleteFile();
  8434. if ((! targetFile.exists())
  8435. && targetFile.getParentDirectory().createDirectory())
  8436. {
  8437. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  8438. if (out != 0)
  8439. {
  8440. out->writeFromInputStream (*in, -1);
  8441. out = 0;
  8442. targetFile.setCreationTime (zei.fileTime);
  8443. targetFile.setLastModificationTime (zei.fileTime);
  8444. targetFile.setLastAccessTime (zei.fileTime);
  8445. }
  8446. }
  8447. }
  8448. }
  8449. }
  8450. }
  8451. END_JUCE_NAMESPACE
  8452. /*** End of inlined file: juce_ZipFile.cpp ***/
  8453. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8454. #if JUCE_MSVC
  8455. #pragma warning (push)
  8456. #pragma warning (disable: 4514 4996)
  8457. #endif
  8458. #include <cwctype>
  8459. #include <cctype>
  8460. #include <ctime>
  8461. BEGIN_JUCE_NAMESPACE
  8462. int CharacterFunctions::length (const char* const s) throw()
  8463. {
  8464. return (int) strlen (s);
  8465. }
  8466. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8467. {
  8468. return (int) wcslen (s);
  8469. }
  8470. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8471. {
  8472. strncpy (dest, src, maxChars);
  8473. }
  8474. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8475. {
  8476. wcsncpy (dest, src, maxChars);
  8477. }
  8478. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8479. {
  8480. mbstowcs (dest, src, maxChars);
  8481. }
  8482. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8483. {
  8484. wcstombs (dest, src, maxChars);
  8485. }
  8486. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8487. {
  8488. return (int) wcstombs (0, src, 0);
  8489. }
  8490. void CharacterFunctions::append (char* dest, const char* src) throw()
  8491. {
  8492. strcat (dest, src);
  8493. }
  8494. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8495. {
  8496. wcscat (dest, src);
  8497. }
  8498. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8499. {
  8500. return strcmp (s1, s2);
  8501. }
  8502. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8503. {
  8504. jassert (s1 != 0 && s2 != 0);
  8505. return wcscmp (s1, s2);
  8506. }
  8507. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8508. {
  8509. jassert (s1 != 0 && s2 != 0);
  8510. return strncmp (s1, s2, maxChars);
  8511. }
  8512. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8513. {
  8514. jassert (s1 != 0 && s2 != 0);
  8515. return wcsncmp (s1, s2, maxChars);
  8516. }
  8517. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8518. {
  8519. jassert (s1 != 0 && s2 != 0);
  8520. for (;;)
  8521. {
  8522. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8523. if (diff != 0)
  8524. return diff;
  8525. else if (*s1 == 0)
  8526. break;
  8527. ++s1;
  8528. ++s2;
  8529. }
  8530. return 0;
  8531. }
  8532. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8533. {
  8534. return -compare (s2, s1);
  8535. }
  8536. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8537. {
  8538. jassert (s1 != 0 && s2 != 0);
  8539. #if JUCE_WINDOWS
  8540. return stricmp (s1, s2);
  8541. #else
  8542. return strcasecmp (s1, s2);
  8543. #endif
  8544. }
  8545. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8546. {
  8547. jassert (s1 != 0 && s2 != 0);
  8548. #if JUCE_WINDOWS
  8549. return _wcsicmp (s1, s2);
  8550. #else
  8551. for (;;)
  8552. {
  8553. if (*s1 != *s2)
  8554. {
  8555. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8556. if (diff != 0)
  8557. return diff < 0 ? -1 : 1;
  8558. }
  8559. else if (*s1 == 0)
  8560. break;
  8561. ++s1;
  8562. ++s2;
  8563. }
  8564. return 0;
  8565. #endif
  8566. }
  8567. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8568. {
  8569. jassert (s1 != 0 && s2 != 0);
  8570. for (;;)
  8571. {
  8572. if (*s1 != *s2)
  8573. {
  8574. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8575. if (diff != 0)
  8576. return diff < 0 ? -1 : 1;
  8577. }
  8578. else if (*s1 == 0)
  8579. break;
  8580. ++s1;
  8581. ++s2;
  8582. }
  8583. return 0;
  8584. }
  8585. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8586. {
  8587. jassert (s1 != 0 && s2 != 0);
  8588. #if JUCE_WINDOWS
  8589. return strnicmp (s1, s2, maxChars);
  8590. #else
  8591. return strncasecmp (s1, s2, maxChars);
  8592. #endif
  8593. }
  8594. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8595. {
  8596. jassert (s1 != 0 && s2 != 0);
  8597. #if JUCE_WINDOWS
  8598. return _wcsnicmp (s1, s2, maxChars);
  8599. #else
  8600. while (--maxChars >= 0)
  8601. {
  8602. if (*s1 != *s2)
  8603. {
  8604. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8605. if (diff != 0)
  8606. return diff < 0 ? -1 : 1;
  8607. }
  8608. else if (*s1 == 0)
  8609. break;
  8610. ++s1;
  8611. ++s2;
  8612. }
  8613. return 0;
  8614. #endif
  8615. }
  8616. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8617. {
  8618. return strstr (haystack, needle);
  8619. }
  8620. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8621. {
  8622. return wcsstr (haystack, needle);
  8623. }
  8624. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8625. {
  8626. if (haystack != 0)
  8627. {
  8628. int i = 0;
  8629. if (ignoreCase)
  8630. {
  8631. const char n1 = toLowerCase (needle);
  8632. const char n2 = toUpperCase (needle);
  8633. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8634. {
  8635. while (haystack[i] != 0)
  8636. {
  8637. if (haystack[i] == n1 || haystack[i] == n2)
  8638. return i;
  8639. ++i;
  8640. }
  8641. return -1;
  8642. }
  8643. jassert (n1 == needle);
  8644. }
  8645. while (haystack[i] != 0)
  8646. {
  8647. if (haystack[i] == needle)
  8648. return i;
  8649. ++i;
  8650. }
  8651. }
  8652. return -1;
  8653. }
  8654. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8655. {
  8656. if (haystack != 0)
  8657. {
  8658. int i = 0;
  8659. if (ignoreCase)
  8660. {
  8661. const juce_wchar n1 = toLowerCase (needle);
  8662. const juce_wchar n2 = toUpperCase (needle);
  8663. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8664. {
  8665. while (haystack[i] != 0)
  8666. {
  8667. if (haystack[i] == n1 || haystack[i] == n2)
  8668. return i;
  8669. ++i;
  8670. }
  8671. return -1;
  8672. }
  8673. jassert (n1 == needle);
  8674. }
  8675. while (haystack[i] != 0)
  8676. {
  8677. if (haystack[i] == needle)
  8678. return i;
  8679. ++i;
  8680. }
  8681. }
  8682. return -1;
  8683. }
  8684. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8685. {
  8686. jassert (haystack != 0);
  8687. int i = 0;
  8688. while (haystack[i] != 0)
  8689. {
  8690. if (haystack[i] == needle)
  8691. return i;
  8692. ++i;
  8693. }
  8694. return -1;
  8695. }
  8696. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8697. {
  8698. jassert (haystack != 0);
  8699. int i = 0;
  8700. while (haystack[i] != 0)
  8701. {
  8702. if (haystack[i] == needle)
  8703. return i;
  8704. ++i;
  8705. }
  8706. return -1;
  8707. }
  8708. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8709. {
  8710. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8711. }
  8712. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8713. {
  8714. if (allowedChars == 0)
  8715. return 0;
  8716. int i = 0;
  8717. for (;;)
  8718. {
  8719. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8720. break;
  8721. ++i;
  8722. }
  8723. return i;
  8724. }
  8725. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8726. {
  8727. return (int) strftime (dest, maxChars, format, tm);
  8728. }
  8729. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8730. {
  8731. return (int) wcsftime (dest, maxChars, format, tm);
  8732. }
  8733. int CharacterFunctions::getIntValue (const char* const s) throw()
  8734. {
  8735. return atoi (s);
  8736. }
  8737. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8738. {
  8739. #if JUCE_WINDOWS
  8740. return _wtoi (s);
  8741. #else
  8742. int v = 0;
  8743. while (isWhitespace (*s))
  8744. ++s;
  8745. const bool isNeg = *s == '-';
  8746. if (isNeg)
  8747. ++s;
  8748. for (;;)
  8749. {
  8750. const wchar_t c = *s++;
  8751. if (c >= '0' && c <= '9')
  8752. v = v * 10 + (int) (c - '0');
  8753. else
  8754. break;
  8755. }
  8756. return isNeg ? -v : v;
  8757. #endif
  8758. }
  8759. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8760. {
  8761. #if JUCE_LINUX
  8762. return atoll (s);
  8763. #elif JUCE_WINDOWS
  8764. return _atoi64 (s);
  8765. #else
  8766. int64 v = 0;
  8767. while (isWhitespace (*s))
  8768. ++s;
  8769. const bool isNeg = *s == '-';
  8770. if (isNeg)
  8771. ++s;
  8772. for (;;)
  8773. {
  8774. const char c = *s++;
  8775. if (c >= '0' && c <= '9')
  8776. v = v * 10 + (int64) (c - '0');
  8777. else
  8778. break;
  8779. }
  8780. return isNeg ? -v : v;
  8781. #endif
  8782. }
  8783. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8784. {
  8785. #if JUCE_WINDOWS
  8786. return _wtoi64 (s);
  8787. #else
  8788. int64 v = 0;
  8789. while (isWhitespace (*s))
  8790. ++s;
  8791. const bool isNeg = *s == '-';
  8792. if (isNeg)
  8793. ++s;
  8794. for (;;)
  8795. {
  8796. const juce_wchar c = *s++;
  8797. if (c >= '0' && c <= '9')
  8798. v = v * 10 + (int64) (c - '0');
  8799. else
  8800. break;
  8801. }
  8802. return isNeg ? -v : v;
  8803. #endif
  8804. }
  8805. static double juce_mulexp10 (const double value, int exponent) throw()
  8806. {
  8807. if (exponent == 0)
  8808. return value;
  8809. if (value == 0)
  8810. return 0;
  8811. const bool negative = (exponent < 0);
  8812. if (negative)
  8813. exponent = -exponent;
  8814. double result = 1.0, power = 10.0;
  8815. for (int bit = 1; exponent != 0; bit <<= 1)
  8816. {
  8817. if ((exponent & bit) != 0)
  8818. {
  8819. exponent ^= bit;
  8820. result *= power;
  8821. if (exponent == 0)
  8822. break;
  8823. }
  8824. power *= power;
  8825. }
  8826. return negative ? (value / result) : (value * result);
  8827. }
  8828. template <class CharType>
  8829. double juce_atof (const CharType* const original) throw()
  8830. {
  8831. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8832. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8833. int exponent = 0, decPointIndex = 0, digit = 0;
  8834. int lastDigit = 0, numSignificantDigits = 0;
  8835. bool isNegative = false, digitsFound = false;
  8836. const int maxSignificantDigits = 15 + 2;
  8837. const CharType* s = original;
  8838. while (CharacterFunctions::isWhitespace (*s))
  8839. ++s;
  8840. switch (*s)
  8841. {
  8842. case '-': isNegative = true; // fall-through..
  8843. case '+': ++s;
  8844. }
  8845. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8846. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8847. for (;;)
  8848. {
  8849. if (CharacterFunctions::isDigit (*s))
  8850. {
  8851. lastDigit = digit;
  8852. digit = *s++ - '0';
  8853. digitsFound = true;
  8854. if (decPointIndex != 0)
  8855. exponentAdjustment[1]++;
  8856. if (numSignificantDigits == 0 && digit == 0)
  8857. continue;
  8858. if (++numSignificantDigits > maxSignificantDigits)
  8859. {
  8860. if (digit > 5)
  8861. ++accumulator [decPointIndex];
  8862. else if (digit == 5 && (lastDigit & 1) != 0)
  8863. ++accumulator [decPointIndex];
  8864. if (decPointIndex > 0)
  8865. exponentAdjustment[1]--;
  8866. else
  8867. exponentAdjustment[0]++;
  8868. while (CharacterFunctions::isDigit (*s))
  8869. {
  8870. ++s;
  8871. if (decPointIndex == 0)
  8872. exponentAdjustment[0]++;
  8873. }
  8874. }
  8875. else
  8876. {
  8877. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8878. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8879. {
  8880. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8881. + accumulator [decPointIndex];
  8882. accumulator [decPointIndex] = 0;
  8883. exponentAccumulator [decPointIndex] = 0;
  8884. }
  8885. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8886. exponentAccumulator [decPointIndex]++;
  8887. }
  8888. }
  8889. else if (decPointIndex == 0 && *s == '.')
  8890. {
  8891. ++s;
  8892. decPointIndex = 1;
  8893. if (numSignificantDigits > maxSignificantDigits)
  8894. {
  8895. while (CharacterFunctions::isDigit (*s))
  8896. ++s;
  8897. break;
  8898. }
  8899. }
  8900. else
  8901. {
  8902. break;
  8903. }
  8904. }
  8905. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8906. if (decPointIndex != 0)
  8907. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8908. if ((*s == 'e' || *s == 'E') && digitsFound)
  8909. {
  8910. bool negativeExponent = false;
  8911. switch (*++s)
  8912. {
  8913. case '-': negativeExponent = true; // fall-through..
  8914. case '+': ++s;
  8915. }
  8916. while (CharacterFunctions::isDigit (*s))
  8917. exponent = (exponent * 10) + (*s++ - '0');
  8918. if (negativeExponent)
  8919. exponent = -exponent;
  8920. }
  8921. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8922. if (decPointIndex != 0)
  8923. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8924. return isNegative ? -r : r;
  8925. }
  8926. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8927. {
  8928. return juce_atof <char> (s);
  8929. }
  8930. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8931. {
  8932. return juce_atof <juce_wchar> (s);
  8933. }
  8934. char CharacterFunctions::toUpperCase (const char character) throw()
  8935. {
  8936. return (char) toupper (character);
  8937. }
  8938. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8939. {
  8940. return towupper (character);
  8941. }
  8942. void CharacterFunctions::toUpperCase (char* s) throw()
  8943. {
  8944. #if JUCE_WINDOWS
  8945. strupr (s);
  8946. #else
  8947. while (*s != 0)
  8948. {
  8949. *s = toUpperCase (*s);
  8950. ++s;
  8951. }
  8952. #endif
  8953. }
  8954. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8955. {
  8956. #if JUCE_WINDOWS
  8957. _wcsupr (s);
  8958. #else
  8959. while (*s != 0)
  8960. {
  8961. *s = toUpperCase (*s);
  8962. ++s;
  8963. }
  8964. #endif
  8965. }
  8966. bool CharacterFunctions::isUpperCase (const char character) throw()
  8967. {
  8968. return isupper (character) != 0;
  8969. }
  8970. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8971. {
  8972. #if JUCE_WINDOWS
  8973. return iswupper (character) != 0;
  8974. #else
  8975. return toLowerCase (character) != character;
  8976. #endif
  8977. }
  8978. char CharacterFunctions::toLowerCase (const char character) throw()
  8979. {
  8980. return (char) tolower (character);
  8981. }
  8982. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8983. {
  8984. return towlower (character);
  8985. }
  8986. void CharacterFunctions::toLowerCase (char* s) throw()
  8987. {
  8988. #if JUCE_WINDOWS
  8989. strlwr (s);
  8990. #else
  8991. while (*s != 0)
  8992. {
  8993. *s = toLowerCase (*s);
  8994. ++s;
  8995. }
  8996. #endif
  8997. }
  8998. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8999. {
  9000. #if JUCE_WINDOWS
  9001. _wcslwr (s);
  9002. #else
  9003. while (*s != 0)
  9004. {
  9005. *s = toLowerCase (*s);
  9006. ++s;
  9007. }
  9008. #endif
  9009. }
  9010. bool CharacterFunctions::isLowerCase (const char character) throw()
  9011. {
  9012. return islower (character) != 0;
  9013. }
  9014. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9015. {
  9016. #if JUCE_WINDOWS
  9017. return iswlower (character) != 0;
  9018. #else
  9019. return toUpperCase (character) != character;
  9020. #endif
  9021. }
  9022. bool CharacterFunctions::isWhitespace (const char character) throw()
  9023. {
  9024. return character == ' ' || (character <= 13 && character >= 9);
  9025. }
  9026. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9027. {
  9028. return iswspace (character) != 0;
  9029. }
  9030. bool CharacterFunctions::isDigit (const char character) throw()
  9031. {
  9032. return (character >= '0' && character <= '9');
  9033. }
  9034. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9035. {
  9036. return iswdigit (character) != 0;
  9037. }
  9038. bool CharacterFunctions::isLetter (const char character) throw()
  9039. {
  9040. return (character >= 'a' && character <= 'z')
  9041. || (character >= 'A' && character <= 'Z');
  9042. }
  9043. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9044. {
  9045. return iswalpha (character) != 0;
  9046. }
  9047. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9048. {
  9049. return (character >= 'a' && character <= 'z')
  9050. || (character >= 'A' && character <= 'Z')
  9051. || (character >= '0' && character <= '9');
  9052. }
  9053. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9054. {
  9055. return iswalnum (character) != 0;
  9056. }
  9057. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9058. {
  9059. unsigned int d = digit - '0';
  9060. if (d < (unsigned int) 10)
  9061. return (int) d;
  9062. d += (unsigned int) ('0' - 'a');
  9063. if (d < (unsigned int) 6)
  9064. return (int) d + 10;
  9065. d += (unsigned int) ('a' - 'A');
  9066. if (d < (unsigned int) 6)
  9067. return (int) d + 10;
  9068. return -1;
  9069. }
  9070. #if JUCE_MSVC
  9071. #pragma warning (pop)
  9072. #endif
  9073. END_JUCE_NAMESPACE
  9074. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9075. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9076. BEGIN_JUCE_NAMESPACE
  9077. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9078. {
  9079. loadFromText (fileContents);
  9080. }
  9081. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9082. {
  9083. loadFromText (fileToLoad.loadFileAsString());
  9084. }
  9085. LocalisedStrings::~LocalisedStrings()
  9086. {
  9087. }
  9088. const String LocalisedStrings::translate (const String& text) const
  9089. {
  9090. return translations.getValue (text, text);
  9091. }
  9092. static int findCloseQuote (const String& text, int startPos)
  9093. {
  9094. juce_wchar lastChar = 0;
  9095. for (;;)
  9096. {
  9097. const juce_wchar c = text [startPos];
  9098. if (c == 0 || (c == '"' && lastChar != '\\'))
  9099. break;
  9100. lastChar = c;
  9101. ++startPos;
  9102. }
  9103. return startPos;
  9104. }
  9105. static const String unescapeString (const String& s)
  9106. {
  9107. return s.replace ("\\\"", "\"")
  9108. .replace ("\\\'", "\'")
  9109. .replace ("\\t", "\t")
  9110. .replace ("\\r", "\r")
  9111. .replace ("\\n", "\n");
  9112. }
  9113. void LocalisedStrings::loadFromText (const String& fileContents)
  9114. {
  9115. StringArray lines;
  9116. lines.addLines (fileContents);
  9117. for (int i = 0; i < lines.size(); ++i)
  9118. {
  9119. String line (lines[i].trim());
  9120. if (line.startsWithChar ('"'))
  9121. {
  9122. int closeQuote = findCloseQuote (line, 1);
  9123. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9124. if (originalText.isNotEmpty())
  9125. {
  9126. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9127. closeQuote = findCloseQuote (line, openingQuote + 1);
  9128. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9129. if (newText.isNotEmpty())
  9130. translations.set (originalText, newText);
  9131. }
  9132. }
  9133. else if (line.startsWithIgnoreCase ("language:"))
  9134. {
  9135. languageName = line.substring (9).trim();
  9136. }
  9137. else if (line.startsWithIgnoreCase ("countries:"))
  9138. {
  9139. countryCodes.addTokens (line.substring (10).trim(), true);
  9140. countryCodes.trim();
  9141. countryCodes.removeEmptyStrings();
  9142. }
  9143. }
  9144. }
  9145. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9146. {
  9147. translations.setIgnoresCase (shouldIgnoreCase);
  9148. }
  9149. static CriticalSection currentMappingsLock;
  9150. static LocalisedStrings* currentMappings = 0;
  9151. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9152. {
  9153. const ScopedLock sl (currentMappingsLock);
  9154. delete currentMappings;
  9155. currentMappings = newTranslations;
  9156. }
  9157. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9158. {
  9159. return currentMappings;
  9160. }
  9161. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9162. {
  9163. const ScopedLock sl (currentMappingsLock);
  9164. if (currentMappings != 0)
  9165. return currentMappings->translate (text);
  9166. return text;
  9167. }
  9168. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9169. {
  9170. return translateWithCurrentMappings (String (text));
  9171. }
  9172. END_JUCE_NAMESPACE
  9173. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9174. /*** Start of inlined file: juce_String.cpp ***/
  9175. #if JUCE_MSVC
  9176. #pragma warning (push)
  9177. #pragma warning (disable: 4514)
  9178. #endif
  9179. #include <locale>
  9180. BEGIN_JUCE_NAMESPACE
  9181. #if JUCE_MSVC
  9182. #pragma warning (pop)
  9183. #endif
  9184. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9185. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9186. #endif
  9187. class StringHolder
  9188. {
  9189. public:
  9190. StringHolder()
  9191. : refCount (0x3fffffff), allocatedNumChars (0)
  9192. {
  9193. text[0] = 0;
  9194. }
  9195. static juce_wchar* createUninitialised (const size_t numChars)
  9196. {
  9197. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9198. s->refCount.value = 0;
  9199. s->allocatedNumChars = numChars;
  9200. return &(s->text[0]);
  9201. }
  9202. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9203. {
  9204. juce_wchar* const dest = createUninitialised (numChars);
  9205. copyChars (dest, src, numChars);
  9206. return dest;
  9207. }
  9208. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9209. {
  9210. juce_wchar* const dest = createUninitialised (numChars);
  9211. CharacterFunctions::copy (dest, src, (int) numChars);
  9212. dest [numChars] = 0;
  9213. return dest;
  9214. }
  9215. static inline juce_wchar* getEmpty() throw()
  9216. {
  9217. return &(empty.text[0]);
  9218. }
  9219. static void retain (juce_wchar* const text) throw()
  9220. {
  9221. ++(bufferFromText (text)->refCount);
  9222. }
  9223. static inline void release (StringHolder* const b) throw()
  9224. {
  9225. if (--(b->refCount) == -1 && b != &empty)
  9226. delete[] reinterpret_cast <char*> (b);
  9227. }
  9228. static void release (juce_wchar* const text) throw()
  9229. {
  9230. release (bufferFromText (text));
  9231. }
  9232. static juce_wchar* makeUnique (juce_wchar* const text)
  9233. {
  9234. StringHolder* const b = bufferFromText (text);
  9235. if (b->refCount.get() <= 0)
  9236. return text;
  9237. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9238. release (b);
  9239. return newText;
  9240. }
  9241. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9242. {
  9243. StringHolder* const b = bufferFromText (text);
  9244. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9245. return text;
  9246. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9247. copyChars (newText, text, b->allocatedNumChars);
  9248. release (b);
  9249. return newText;
  9250. }
  9251. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9252. {
  9253. return bufferFromText (text)->allocatedNumChars;
  9254. }
  9255. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9256. {
  9257. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9258. dest [numChars] = 0;
  9259. }
  9260. Atomic<int> refCount;
  9261. size_t allocatedNumChars;
  9262. juce_wchar text[1];
  9263. static StringHolder empty;
  9264. private:
  9265. static inline StringHolder* bufferFromText (void* const text) throw()
  9266. {
  9267. // (Can't use offsetof() here because of warnings about this not being a POD)
  9268. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9269. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9270. }
  9271. };
  9272. StringHolder StringHolder::empty;
  9273. const String String::empty;
  9274. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9275. {
  9276. jassert (t[numChars] == 0); // must have a null terminator
  9277. text = StringHolder::createCopy (t, numChars);
  9278. }
  9279. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9280. {
  9281. if (numExtraChars > 0)
  9282. {
  9283. const int oldLen = length();
  9284. const int newTotalLen = oldLen + numExtraChars;
  9285. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9286. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9287. }
  9288. }
  9289. void String::preallocateStorage (const size_t numChars)
  9290. {
  9291. text = StringHolder::makeUniqueWithSize (text, numChars);
  9292. }
  9293. String::String() throw()
  9294. : text (StringHolder::getEmpty())
  9295. {
  9296. }
  9297. String::~String() throw()
  9298. {
  9299. StringHolder::release (text);
  9300. }
  9301. String::String (const String& other) throw()
  9302. : text (other.text)
  9303. {
  9304. StringHolder::retain (text);
  9305. }
  9306. void String::swapWith (String& other) throw()
  9307. {
  9308. swapVariables (text, other.text);
  9309. }
  9310. String& String::operator= (const String& other) throw()
  9311. {
  9312. juce_wchar* const newText = other.text;
  9313. StringHolder::retain (newText);
  9314. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9315. return *this;
  9316. }
  9317. String::String (const size_t numChars, const int /*dummyVariable*/)
  9318. : text (StringHolder::createUninitialised (numChars))
  9319. {
  9320. }
  9321. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9322. {
  9323. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9324. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9325. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9326. }
  9327. String::String (const char* const t)
  9328. {
  9329. if (t != 0 && *t != 0)
  9330. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9331. else
  9332. text = StringHolder::getEmpty();
  9333. }
  9334. String::String (const juce_wchar* const t)
  9335. {
  9336. if (t != 0 && *t != 0)
  9337. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9338. else
  9339. text = StringHolder::getEmpty();
  9340. }
  9341. String::String (const char* const t, const size_t maxChars)
  9342. {
  9343. int i;
  9344. for (i = 0; (size_t) i < maxChars; ++i)
  9345. if (t[i] == 0)
  9346. break;
  9347. if (i > 0)
  9348. text = StringHolder::createCopy (t, i);
  9349. else
  9350. text = StringHolder::getEmpty();
  9351. }
  9352. String::String (const juce_wchar* const t, const size_t maxChars)
  9353. {
  9354. int i;
  9355. for (i = 0; (size_t) i < maxChars; ++i)
  9356. if (t[i] == 0)
  9357. break;
  9358. if (i > 0)
  9359. text = StringHolder::createCopy (t, i);
  9360. else
  9361. text = StringHolder::getEmpty();
  9362. }
  9363. const String String::charToString (const juce_wchar character)
  9364. {
  9365. String result ((size_t) 1, (int) 0);
  9366. result.text[0] = character;
  9367. result.text[1] = 0;
  9368. return result;
  9369. }
  9370. namespace NumberToStringConverters
  9371. {
  9372. // pass in a pointer to the END of a buffer..
  9373. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9374. {
  9375. *--t = 0;
  9376. int64 v = (n >= 0) ? n : -n;
  9377. do
  9378. {
  9379. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9380. v /= 10;
  9381. } while (v > 0);
  9382. if (n < 0)
  9383. *--t = '-';
  9384. return t;
  9385. }
  9386. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9387. {
  9388. *--t = 0;
  9389. do
  9390. {
  9391. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9392. v /= 10;
  9393. } while (v > 0);
  9394. return t;
  9395. }
  9396. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9397. {
  9398. if (n == (int) 0x80000000) // (would cause an overflow)
  9399. return int64ToString (t, n);
  9400. *--t = 0;
  9401. int v = abs (n);
  9402. do
  9403. {
  9404. *--t = (juce_wchar) ('0' + (v % 10));
  9405. v /= 10;
  9406. } while (v > 0);
  9407. if (n < 0)
  9408. *--t = '-';
  9409. return t;
  9410. }
  9411. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9412. {
  9413. *--t = 0;
  9414. do
  9415. {
  9416. *--t = (juce_wchar) ('0' + (v % 10));
  9417. v /= 10;
  9418. } while (v > 0);
  9419. return t;
  9420. }
  9421. static juce_wchar getDecimalPoint()
  9422. {
  9423. #if JUCE_WINDOWS && _MSC_VER < 1400
  9424. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9425. #else
  9426. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9427. #endif
  9428. return dp;
  9429. }
  9430. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9431. {
  9432. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9433. {
  9434. juce_wchar* const end = buffer + numChars;
  9435. juce_wchar* t = end;
  9436. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9437. *--t = (juce_wchar) 0;
  9438. while (numDecPlaces >= 0 || v > 0)
  9439. {
  9440. if (numDecPlaces == 0)
  9441. *--t = getDecimalPoint();
  9442. *--t = (juce_wchar) ('0' + (v % 10));
  9443. v /= 10;
  9444. --numDecPlaces;
  9445. }
  9446. if (n < 0)
  9447. *--t = '-';
  9448. len = end - t - 1;
  9449. return t;
  9450. }
  9451. else
  9452. {
  9453. #if JUCE_WINDOWS
  9454. #if _MSC_VER <= 1400
  9455. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9456. #else
  9457. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9458. #endif
  9459. #else
  9460. len = swprintf (buffer, numChars, L"%.9g", n);
  9461. #endif
  9462. return buffer;
  9463. }
  9464. }
  9465. }
  9466. String::String (const int number)
  9467. {
  9468. juce_wchar buffer [16];
  9469. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9470. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9471. createInternal (start, end - start - 1);
  9472. }
  9473. String::String (const unsigned int number)
  9474. {
  9475. juce_wchar buffer [16];
  9476. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9477. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9478. createInternal (start, end - start - 1);
  9479. }
  9480. String::String (const short number)
  9481. {
  9482. juce_wchar buffer [16];
  9483. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9484. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9485. createInternal (start, end - start - 1);
  9486. }
  9487. String::String (const unsigned short number)
  9488. {
  9489. juce_wchar buffer [16];
  9490. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9491. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9492. createInternal (start, end - start - 1);
  9493. }
  9494. String::String (const int64 number)
  9495. {
  9496. juce_wchar buffer [32];
  9497. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9498. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9499. createInternal (start, end - start - 1);
  9500. }
  9501. String::String (const uint64 number)
  9502. {
  9503. juce_wchar buffer [32];
  9504. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9505. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9506. createInternal (start, end - start - 1);
  9507. }
  9508. String::String (const float number, const int numberOfDecimalPlaces)
  9509. {
  9510. juce_wchar buffer [48];
  9511. size_t len;
  9512. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9513. createInternal (start, len);
  9514. }
  9515. String::String (const double number, const int numberOfDecimalPlaces)
  9516. {
  9517. juce_wchar buffer [48];
  9518. size_t len;
  9519. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9520. createInternal (start, len);
  9521. }
  9522. int String::length() const throw()
  9523. {
  9524. return CharacterFunctions::length (text);
  9525. }
  9526. int String::hashCode() const throw()
  9527. {
  9528. const juce_wchar* t = text;
  9529. int result = 0;
  9530. while (*t != (juce_wchar) 0)
  9531. result = 31 * result + *t++;
  9532. return result;
  9533. }
  9534. int64 String::hashCode64() const throw()
  9535. {
  9536. const juce_wchar* t = text;
  9537. int64 result = 0;
  9538. while (*t != (juce_wchar) 0)
  9539. result = 101 * result + *t++;
  9540. return result;
  9541. }
  9542. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9543. {
  9544. return string1.compare (string2) == 0;
  9545. }
  9546. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9547. {
  9548. return string1.compare (string2) == 0;
  9549. }
  9550. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9551. {
  9552. return string1.compare (string2) == 0;
  9553. }
  9554. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9555. {
  9556. return string1.compare (string2) != 0;
  9557. }
  9558. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9559. {
  9560. return string1.compare (string2) != 0;
  9561. }
  9562. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9563. {
  9564. return string1.compare (string2) != 0;
  9565. }
  9566. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9567. {
  9568. return string1.compare (string2) > 0;
  9569. }
  9570. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9571. {
  9572. return string1.compare (string2) < 0;
  9573. }
  9574. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9575. {
  9576. return string1.compare (string2) >= 0;
  9577. }
  9578. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9579. {
  9580. return string1.compare (string2) <= 0;
  9581. }
  9582. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9583. {
  9584. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9585. : isEmpty();
  9586. }
  9587. bool String::equalsIgnoreCase (const char* t) const throw()
  9588. {
  9589. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9590. : isEmpty();
  9591. }
  9592. bool String::equalsIgnoreCase (const String& other) const throw()
  9593. {
  9594. return text == other.text
  9595. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9596. }
  9597. int String::compare (const String& other) const throw()
  9598. {
  9599. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9600. }
  9601. int String::compare (const char* other) const throw()
  9602. {
  9603. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9604. }
  9605. int String::compare (const juce_wchar* other) const throw()
  9606. {
  9607. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9608. }
  9609. int String::compareIgnoreCase (const String& other) const throw()
  9610. {
  9611. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9612. }
  9613. int String::compareLexicographically (const String& other) const throw()
  9614. {
  9615. const juce_wchar* s1 = text;
  9616. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9617. ++s1;
  9618. const juce_wchar* s2 = other.text;
  9619. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9620. ++s2;
  9621. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9622. }
  9623. String& String::operator+= (const juce_wchar* const t)
  9624. {
  9625. if (t != 0)
  9626. appendInternal (t, CharacterFunctions::length (t));
  9627. return *this;
  9628. }
  9629. String& String::operator+= (const String& other)
  9630. {
  9631. if (isEmpty())
  9632. operator= (other);
  9633. else
  9634. appendInternal (other.text, other.length());
  9635. return *this;
  9636. }
  9637. String& String::operator+= (const char ch)
  9638. {
  9639. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9640. return operator+= (static_cast <const juce_wchar*> (asString));
  9641. }
  9642. String& String::operator+= (const juce_wchar ch)
  9643. {
  9644. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9645. return operator+= (static_cast <const juce_wchar*> (asString));
  9646. }
  9647. String& String::operator+= (const int number)
  9648. {
  9649. juce_wchar buffer [16];
  9650. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9651. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9652. appendInternal (start, (int) (end - start));
  9653. return *this;
  9654. }
  9655. String& String::operator+= (const unsigned int number)
  9656. {
  9657. juce_wchar buffer [16];
  9658. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9659. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9660. appendInternal (start, (int) (end - start));
  9661. return *this;
  9662. }
  9663. void String::append (const juce_wchar* const other, const int howMany)
  9664. {
  9665. if (howMany > 0)
  9666. {
  9667. int i;
  9668. for (i = 0; i < howMany; ++i)
  9669. if (other[i] == 0)
  9670. break;
  9671. appendInternal (other, i);
  9672. }
  9673. }
  9674. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9675. {
  9676. String s (string1);
  9677. return s += string2;
  9678. }
  9679. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9680. {
  9681. String s (string1);
  9682. return s += string2;
  9683. }
  9684. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9685. {
  9686. return String::charToString (string1) + string2;
  9687. }
  9688. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9689. {
  9690. return String::charToString (string1) + string2;
  9691. }
  9692. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9693. {
  9694. return string1 += string2;
  9695. }
  9696. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9697. {
  9698. return string1 += string2;
  9699. }
  9700. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9701. {
  9702. return string1 += string2;
  9703. }
  9704. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9705. {
  9706. return string1 += string2;
  9707. }
  9708. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9709. {
  9710. return string1 += string2;
  9711. }
  9712. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9713. {
  9714. return string1 += characterToAppend;
  9715. }
  9716. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9717. {
  9718. return string1 += characterToAppend;
  9719. }
  9720. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9721. {
  9722. return string1 += string2;
  9723. }
  9724. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9725. {
  9726. return string1 += string2;
  9727. }
  9728. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9729. {
  9730. return string1 += string2;
  9731. }
  9732. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9733. {
  9734. return string1 += (int) number;
  9735. }
  9736. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9737. {
  9738. return string1 += number;
  9739. }
  9740. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9741. {
  9742. return string1 += number;
  9743. }
  9744. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9745. {
  9746. return string1 += (int) number;
  9747. }
  9748. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9749. {
  9750. return string1 += (unsigned int) number;
  9751. }
  9752. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9753. {
  9754. return string1 += String (number);
  9755. }
  9756. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9757. {
  9758. return string1 += String (number);
  9759. }
  9760. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9761. {
  9762. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9763. // if lots of large, persistent strings were to be written to streams).
  9764. const int numBytes = text.getNumBytesAsUTF8();
  9765. HeapBlock<char> temp (numBytes + 1);
  9766. text.copyToUTF8 (temp, numBytes + 1);
  9767. stream.write (temp, numBytes);
  9768. return stream;
  9769. }
  9770. int String::indexOfChar (const juce_wchar character) const throw()
  9771. {
  9772. const juce_wchar* t = text;
  9773. for (;;)
  9774. {
  9775. if (*t == character)
  9776. return (int) (t - text);
  9777. if (*t++ == 0)
  9778. return -1;
  9779. }
  9780. }
  9781. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9782. {
  9783. for (int i = length(); --i >= 0;)
  9784. if (text[i] == character)
  9785. return i;
  9786. return -1;
  9787. }
  9788. int String::indexOf (const String& t) const throw()
  9789. {
  9790. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9791. return r == 0 ? -1 : (int) (r - text);
  9792. }
  9793. int String::indexOfChar (const int startIndex,
  9794. const juce_wchar character) const throw()
  9795. {
  9796. if (startIndex > 0 && startIndex >= length())
  9797. return -1;
  9798. const juce_wchar* t = text + jmax (0, startIndex);
  9799. for (;;)
  9800. {
  9801. if (*t == character)
  9802. return (int) (t - text);
  9803. if (*t == 0)
  9804. return -1;
  9805. ++t;
  9806. }
  9807. }
  9808. int String::indexOfAnyOf (const String& charactersToLookFor,
  9809. const int startIndex,
  9810. const bool ignoreCase) const throw()
  9811. {
  9812. if (startIndex > 0 && startIndex >= length())
  9813. return -1;
  9814. const juce_wchar* t = text + jmax (0, startIndex);
  9815. while (*t != 0)
  9816. {
  9817. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9818. return (int) (t - text);
  9819. ++t;
  9820. }
  9821. return -1;
  9822. }
  9823. int String::indexOf (const int startIndex, const String& other) const throw()
  9824. {
  9825. if (startIndex > 0 && startIndex >= length())
  9826. return -1;
  9827. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9828. return found == 0 ? -1 : (int) (found - text);
  9829. }
  9830. int String::indexOfIgnoreCase (const String& other) const throw()
  9831. {
  9832. if (other.isNotEmpty())
  9833. {
  9834. const int len = other.length();
  9835. const int end = length() - len;
  9836. for (int i = 0; i <= end; ++i)
  9837. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9838. return i;
  9839. }
  9840. return -1;
  9841. }
  9842. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9843. {
  9844. if (other.isNotEmpty())
  9845. {
  9846. const int len = other.length();
  9847. const int end = length() - len;
  9848. for (int i = jmax (0, startIndex); i <= end; ++i)
  9849. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9850. return i;
  9851. }
  9852. return -1;
  9853. }
  9854. int String::lastIndexOf (const String& other) const throw()
  9855. {
  9856. if (other.isNotEmpty())
  9857. {
  9858. const int len = other.length();
  9859. int i = length() - len;
  9860. if (i >= 0)
  9861. {
  9862. const juce_wchar* n = text + i;
  9863. while (i >= 0)
  9864. {
  9865. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9866. return i;
  9867. --i;
  9868. }
  9869. }
  9870. }
  9871. return -1;
  9872. }
  9873. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9874. {
  9875. if (other.isNotEmpty())
  9876. {
  9877. const int len = other.length();
  9878. int i = length() - len;
  9879. if (i >= 0)
  9880. {
  9881. const juce_wchar* n = text + i;
  9882. while (i >= 0)
  9883. {
  9884. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9885. return i;
  9886. --i;
  9887. }
  9888. }
  9889. }
  9890. return -1;
  9891. }
  9892. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9893. {
  9894. for (int i = length(); --i >= 0;)
  9895. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9896. return i;
  9897. return -1;
  9898. }
  9899. bool String::contains (const String& other) const throw()
  9900. {
  9901. return indexOf (other) >= 0;
  9902. }
  9903. bool String::containsChar (const juce_wchar character) const throw()
  9904. {
  9905. const juce_wchar* t = text;
  9906. for (;;)
  9907. {
  9908. if (*t == 0)
  9909. return false;
  9910. if (*t == character)
  9911. return true;
  9912. ++t;
  9913. }
  9914. }
  9915. bool String::containsIgnoreCase (const String& t) const throw()
  9916. {
  9917. return indexOfIgnoreCase (t) >= 0;
  9918. }
  9919. int String::indexOfWholeWord (const String& word) const throw()
  9920. {
  9921. if (word.isNotEmpty())
  9922. {
  9923. const int wordLen = word.length();
  9924. const int end = length() - wordLen;
  9925. const juce_wchar* t = text;
  9926. for (int i = 0; i <= end; ++i)
  9927. {
  9928. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9929. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9930. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9931. {
  9932. return i;
  9933. }
  9934. ++t;
  9935. }
  9936. }
  9937. return -1;
  9938. }
  9939. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9940. {
  9941. if (word.isNotEmpty())
  9942. {
  9943. const int wordLen = word.length();
  9944. const int end = length() - wordLen;
  9945. const juce_wchar* t = text;
  9946. for (int i = 0; i <= end; ++i)
  9947. {
  9948. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9949. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9950. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9951. {
  9952. return i;
  9953. }
  9954. ++t;
  9955. }
  9956. }
  9957. return -1;
  9958. }
  9959. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9960. {
  9961. return indexOfWholeWord (wordToLookFor) >= 0;
  9962. }
  9963. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9964. {
  9965. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9966. }
  9967. static int indexOfMatch (const juce_wchar* const wildcard,
  9968. const juce_wchar* const test,
  9969. const bool ignoreCase) throw()
  9970. {
  9971. int start = 0;
  9972. while (test [start] != 0)
  9973. {
  9974. int i = 0;
  9975. for (;;)
  9976. {
  9977. const juce_wchar wc = wildcard [i];
  9978. const juce_wchar c = test [i + start];
  9979. if (wc == c
  9980. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9981. || (wc == '?' && c != 0))
  9982. {
  9983. if (wc == 0)
  9984. return start;
  9985. ++i;
  9986. }
  9987. else
  9988. {
  9989. if (wc == '*' && (wildcard [i + 1] == 0
  9990. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9991. {
  9992. return start;
  9993. }
  9994. break;
  9995. }
  9996. }
  9997. ++start;
  9998. }
  9999. return -1;
  10000. }
  10001. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10002. {
  10003. int i = 0;
  10004. for (;;)
  10005. {
  10006. const juce_wchar wc = wildcard.text [i];
  10007. const juce_wchar c = text [i];
  10008. if (wc == c
  10009. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10010. || (wc == '?' && c != 0))
  10011. {
  10012. if (wc == 0)
  10013. return true;
  10014. ++i;
  10015. }
  10016. else
  10017. {
  10018. return wc == '*' && (wildcard [i + 1] == 0
  10019. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10020. }
  10021. }
  10022. }
  10023. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10024. {
  10025. const int len = stringToRepeat.length();
  10026. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10027. juce_wchar* n = result.text;
  10028. *n = 0;
  10029. while (--numberOfTimesToRepeat >= 0)
  10030. {
  10031. StringHolder::copyChars (n, stringToRepeat.text, len);
  10032. n += len;
  10033. }
  10034. return result;
  10035. }
  10036. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10037. {
  10038. jassert (padCharacter != 0);
  10039. const int len = length();
  10040. if (len >= minimumLength || padCharacter == 0)
  10041. return *this;
  10042. String result ((size_t) minimumLength + 1, (int) 0);
  10043. juce_wchar* n = result.text;
  10044. minimumLength -= len;
  10045. while (--minimumLength >= 0)
  10046. *n++ = padCharacter;
  10047. StringHolder::copyChars (n, text, len);
  10048. return result;
  10049. }
  10050. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10051. {
  10052. jassert (padCharacter != 0);
  10053. const int len = length();
  10054. if (len >= minimumLength || padCharacter == 0)
  10055. return *this;
  10056. String result (*this, (size_t) minimumLength);
  10057. juce_wchar* n = result.text + len;
  10058. minimumLength -= len;
  10059. while (--minimumLength >= 0)
  10060. *n++ = padCharacter;
  10061. *n = 0;
  10062. return result;
  10063. }
  10064. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10065. {
  10066. if (index < 0)
  10067. {
  10068. // a negative index to replace from?
  10069. jassertfalse;
  10070. index = 0;
  10071. }
  10072. if (numCharsToReplace < 0)
  10073. {
  10074. // replacing a negative number of characters?
  10075. numCharsToReplace = 0;
  10076. jassertfalse;
  10077. }
  10078. const int len = length();
  10079. if (index + numCharsToReplace > len)
  10080. {
  10081. if (index > len)
  10082. {
  10083. // replacing beyond the end of the string?
  10084. index = len;
  10085. jassertfalse;
  10086. }
  10087. numCharsToReplace = len - index;
  10088. }
  10089. const int newStringLen = stringToInsert.length();
  10090. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10091. if (newTotalLen <= 0)
  10092. return String::empty;
  10093. String result ((size_t) newTotalLen, (int) 0);
  10094. StringHolder::copyChars (result.text, text, index);
  10095. if (newStringLen > 0)
  10096. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10097. const int endStringLen = newTotalLen - (index + newStringLen);
  10098. if (endStringLen > 0)
  10099. StringHolder::copyChars (result.text + (index + newStringLen),
  10100. text + (index + numCharsToReplace),
  10101. endStringLen);
  10102. return result;
  10103. }
  10104. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10105. {
  10106. const int stringToReplaceLen = stringToReplace.length();
  10107. const int stringToInsertLen = stringToInsert.length();
  10108. int i = 0;
  10109. String result (*this);
  10110. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10111. : result.indexOf (i, stringToReplace))) >= 0)
  10112. {
  10113. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10114. i += stringToInsertLen;
  10115. }
  10116. return result;
  10117. }
  10118. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10119. {
  10120. const int index = indexOfChar (charToReplace);
  10121. if (index < 0)
  10122. return *this;
  10123. String result (*this, size_t());
  10124. juce_wchar* t = result.text + index;
  10125. while (*t != 0)
  10126. {
  10127. if (*t == charToReplace)
  10128. *t = charToInsert;
  10129. ++t;
  10130. }
  10131. return result;
  10132. }
  10133. const String String::replaceCharacters (const String& charactersToReplace,
  10134. const String& charactersToInsertInstead) const
  10135. {
  10136. String result (*this, size_t());
  10137. juce_wchar* t = result.text;
  10138. const int len2 = charactersToInsertInstead.length();
  10139. // the two strings passed in are supposed to be the same length!
  10140. jassert (len2 == charactersToReplace.length());
  10141. while (*t != 0)
  10142. {
  10143. const int index = charactersToReplace.indexOfChar (*t);
  10144. if (((unsigned int) index) < (unsigned int) len2)
  10145. *t = charactersToInsertInstead [index];
  10146. ++t;
  10147. }
  10148. return result;
  10149. }
  10150. bool String::startsWith (const String& other) const throw()
  10151. {
  10152. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10153. }
  10154. bool String::startsWithIgnoreCase (const String& other) const throw()
  10155. {
  10156. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10157. }
  10158. bool String::startsWithChar (const juce_wchar character) const throw()
  10159. {
  10160. jassert (character != 0); // strings can't contain a null character!
  10161. return text[0] == character;
  10162. }
  10163. bool String::endsWithChar (const juce_wchar character) const throw()
  10164. {
  10165. jassert (character != 0); // strings can't contain a null character!
  10166. return text[0] != 0
  10167. && text [length() - 1] == character;
  10168. }
  10169. bool String::endsWith (const String& other) const throw()
  10170. {
  10171. const int thisLen = length();
  10172. const int otherLen = other.length();
  10173. return thisLen >= otherLen
  10174. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10175. }
  10176. bool String::endsWithIgnoreCase (const String& other) const throw()
  10177. {
  10178. const int thisLen = length();
  10179. const int otherLen = other.length();
  10180. return thisLen >= otherLen
  10181. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10182. }
  10183. const String String::toUpperCase() const
  10184. {
  10185. String result (*this, size_t());
  10186. CharacterFunctions::toUpperCase (result.text);
  10187. return result;
  10188. }
  10189. const String String::toLowerCase() const
  10190. {
  10191. String result (*this, size_t());
  10192. CharacterFunctions::toLowerCase (result.text);
  10193. return result;
  10194. }
  10195. juce_wchar& String::operator[] (const int index)
  10196. {
  10197. jassert (((unsigned int) index) <= (unsigned int) length());
  10198. text = StringHolder::makeUnique (text);
  10199. return text [index];
  10200. }
  10201. juce_wchar String::getLastCharacter() const throw()
  10202. {
  10203. return isEmpty() ? juce_wchar() : text [length() - 1];
  10204. }
  10205. const String String::substring (int start, int end) const
  10206. {
  10207. if (start < 0)
  10208. start = 0;
  10209. else if (end <= start)
  10210. return empty;
  10211. int len = 0;
  10212. while (len <= end && text [len] != 0)
  10213. ++len;
  10214. if (end >= len)
  10215. {
  10216. if (start == 0)
  10217. return *this;
  10218. end = len;
  10219. }
  10220. return String (text + start, end - start);
  10221. }
  10222. const String String::substring (const int start) const
  10223. {
  10224. if (start <= 0)
  10225. return *this;
  10226. const int len = length();
  10227. if (start >= len)
  10228. return empty;
  10229. return String (text + start, len - start);
  10230. }
  10231. const String String::dropLastCharacters (const int numberToDrop) const
  10232. {
  10233. return String (text, jmax (0, length() - numberToDrop));
  10234. }
  10235. const String String::getLastCharacters (const int numCharacters) const
  10236. {
  10237. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10238. }
  10239. const String String::fromFirstOccurrenceOf (const String& sub,
  10240. const bool includeSubString,
  10241. const bool ignoreCase) const
  10242. {
  10243. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10244. : indexOf (sub);
  10245. if (i < 0)
  10246. return empty;
  10247. return substring (includeSubString ? i : i + sub.length());
  10248. }
  10249. const String String::fromLastOccurrenceOf (const String& sub,
  10250. const bool includeSubString,
  10251. const bool ignoreCase) const
  10252. {
  10253. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10254. : lastIndexOf (sub);
  10255. if (i < 0)
  10256. return *this;
  10257. return substring (includeSubString ? i : i + sub.length());
  10258. }
  10259. const String String::upToFirstOccurrenceOf (const String& sub,
  10260. const bool includeSubString,
  10261. const bool ignoreCase) const
  10262. {
  10263. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10264. : indexOf (sub);
  10265. if (i < 0)
  10266. return *this;
  10267. return substring (0, includeSubString ? i + sub.length() : i);
  10268. }
  10269. const String String::upToLastOccurrenceOf (const String& sub,
  10270. const bool includeSubString,
  10271. const bool ignoreCase) const
  10272. {
  10273. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10274. : lastIndexOf (sub);
  10275. if (i < 0)
  10276. return *this;
  10277. return substring (0, includeSubString ? i + sub.length() : i);
  10278. }
  10279. bool String::isQuotedString() const
  10280. {
  10281. const String trimmed (trimStart());
  10282. return trimmed[0] == '"'
  10283. || trimmed[0] == '\'';
  10284. }
  10285. const String String::unquoted() const
  10286. {
  10287. String s (*this);
  10288. if (s.text[0] == '"' || s.text[0] == '\'')
  10289. s = s.substring (1);
  10290. const int lastCharIndex = s.length() - 1;
  10291. if (lastCharIndex >= 0
  10292. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10293. s [lastCharIndex] = 0;
  10294. return s;
  10295. }
  10296. const String String::quoted (const juce_wchar quoteCharacter) const
  10297. {
  10298. if (isEmpty())
  10299. return charToString (quoteCharacter) + quoteCharacter;
  10300. String t (*this);
  10301. if (! t.startsWithChar (quoteCharacter))
  10302. t = charToString (quoteCharacter) + t;
  10303. if (! t.endsWithChar (quoteCharacter))
  10304. t += quoteCharacter;
  10305. return t;
  10306. }
  10307. const String String::trim() const
  10308. {
  10309. if (isEmpty())
  10310. return empty;
  10311. int start = 0;
  10312. while (CharacterFunctions::isWhitespace (text [start]))
  10313. ++start;
  10314. const int len = length();
  10315. int end = len - 1;
  10316. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10317. --end;
  10318. ++end;
  10319. if (end <= start)
  10320. return empty;
  10321. else if (start > 0 || end < len)
  10322. return String (text + start, end - start);
  10323. return *this;
  10324. }
  10325. const String String::trimStart() const
  10326. {
  10327. if (isEmpty())
  10328. return empty;
  10329. const juce_wchar* t = text;
  10330. while (CharacterFunctions::isWhitespace (*t))
  10331. ++t;
  10332. if (t == text)
  10333. return *this;
  10334. return String (t);
  10335. }
  10336. const String String::trimEnd() const
  10337. {
  10338. if (isEmpty())
  10339. return empty;
  10340. const juce_wchar* endT = text + (length() - 1);
  10341. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10342. --endT;
  10343. return String (text, (int) (++endT - text));
  10344. }
  10345. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10346. {
  10347. const juce_wchar* t = text;
  10348. while (charactersToTrim.containsChar (*t))
  10349. ++t;
  10350. return t == text ? *this : String (t);
  10351. }
  10352. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10353. {
  10354. if (isEmpty())
  10355. return empty;
  10356. const int len = length();
  10357. const juce_wchar* endT = text + (len - 1);
  10358. int numToRemove = 0;
  10359. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10360. {
  10361. ++numToRemove;
  10362. --endT;
  10363. }
  10364. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10365. }
  10366. const String String::retainCharacters (const String& charactersToRetain) const
  10367. {
  10368. if (isEmpty())
  10369. return empty;
  10370. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10371. juce_wchar* dst = result.text;
  10372. const juce_wchar* src = text;
  10373. while (*src != 0)
  10374. {
  10375. if (charactersToRetain.containsChar (*src))
  10376. *dst++ = *src;
  10377. ++src;
  10378. }
  10379. *dst = 0;
  10380. return result;
  10381. }
  10382. const String String::removeCharacters (const String& charactersToRemove) const
  10383. {
  10384. if (isEmpty())
  10385. return empty;
  10386. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10387. juce_wchar* dst = result.text;
  10388. const juce_wchar* src = text;
  10389. while (*src != 0)
  10390. {
  10391. if (! charactersToRemove.containsChar (*src))
  10392. *dst++ = *src;
  10393. ++src;
  10394. }
  10395. *dst = 0;
  10396. return result;
  10397. }
  10398. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10399. {
  10400. int i = 0;
  10401. for (;;)
  10402. {
  10403. if (! permittedCharacters.containsChar (text[i]))
  10404. break;
  10405. ++i;
  10406. }
  10407. return substring (0, i);
  10408. }
  10409. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10410. {
  10411. const juce_wchar* const t = text;
  10412. int i = 0;
  10413. while (t[i] != 0)
  10414. {
  10415. if (charactersToStopAt.containsChar (t[i]))
  10416. return String (text, i);
  10417. ++i;
  10418. }
  10419. return empty;
  10420. }
  10421. bool String::containsOnly (const String& chars) const throw()
  10422. {
  10423. const juce_wchar* t = text;
  10424. while (*t != 0)
  10425. if (! chars.containsChar (*t++))
  10426. return false;
  10427. return true;
  10428. }
  10429. bool String::containsAnyOf (const String& chars) const throw()
  10430. {
  10431. const juce_wchar* t = text;
  10432. while (*t != 0)
  10433. if (chars.containsChar (*t++))
  10434. return true;
  10435. return false;
  10436. }
  10437. bool String::containsNonWhitespaceChars() const throw()
  10438. {
  10439. const juce_wchar* t = text;
  10440. while (*t != 0)
  10441. if (! CharacterFunctions::isWhitespace (*t++))
  10442. return true;
  10443. return false;
  10444. }
  10445. const String String::formatted (const juce_wchar* const pf, ... )
  10446. {
  10447. jassert (pf != 0);
  10448. va_list args;
  10449. va_start (args, pf);
  10450. size_t bufferSize = 256;
  10451. String result (bufferSize, (int) 0);
  10452. result.text[0] = 0;
  10453. for (;;)
  10454. {
  10455. #if JUCE_LINUX && JUCE_64BIT
  10456. va_list tempArgs;
  10457. va_copy (tempArgs, args);
  10458. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10459. va_end (tempArgs);
  10460. #elif JUCE_WINDOWS
  10461. #if JUCE_MSVC
  10462. #pragma warning (push)
  10463. #pragma warning (disable: 4996)
  10464. #endif
  10465. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10466. #if JUCE_MSVC
  10467. #pragma warning (pop)
  10468. #endif
  10469. #else
  10470. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10471. #endif
  10472. if (num > 0)
  10473. return result;
  10474. bufferSize += 256;
  10475. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10476. break; // returns -1 because of an error rather than because it needs more space.
  10477. result.preallocateStorage (bufferSize);
  10478. }
  10479. return empty;
  10480. }
  10481. int String::getIntValue() const throw()
  10482. {
  10483. return CharacterFunctions::getIntValue (text);
  10484. }
  10485. int String::getTrailingIntValue() const throw()
  10486. {
  10487. int n = 0;
  10488. int mult = 1;
  10489. const juce_wchar* t = text + length();
  10490. while (--t >= text)
  10491. {
  10492. const juce_wchar c = *t;
  10493. if (! CharacterFunctions::isDigit (c))
  10494. {
  10495. if (c == '-')
  10496. n = -n;
  10497. break;
  10498. }
  10499. n += mult * (c - '0');
  10500. mult *= 10;
  10501. }
  10502. return n;
  10503. }
  10504. int64 String::getLargeIntValue() const throw()
  10505. {
  10506. return CharacterFunctions::getInt64Value (text);
  10507. }
  10508. float String::getFloatValue() const throw()
  10509. {
  10510. return (float) CharacterFunctions::getDoubleValue (text);
  10511. }
  10512. double String::getDoubleValue() const throw()
  10513. {
  10514. return CharacterFunctions::getDoubleValue (text);
  10515. }
  10516. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10517. const String String::toHexString (const int number)
  10518. {
  10519. juce_wchar buffer[32];
  10520. juce_wchar* const end = buffer + 32;
  10521. juce_wchar* t = end;
  10522. *--t = 0;
  10523. unsigned int v = (unsigned int) number;
  10524. do
  10525. {
  10526. *--t = hexDigits [v & 15];
  10527. v >>= 4;
  10528. } while (v != 0);
  10529. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10530. }
  10531. const String String::toHexString (const int64 number)
  10532. {
  10533. juce_wchar buffer[32];
  10534. juce_wchar* const end = buffer + 32;
  10535. juce_wchar* t = end;
  10536. *--t = 0;
  10537. uint64 v = (uint64) number;
  10538. do
  10539. {
  10540. *--t = hexDigits [(int) (v & 15)];
  10541. v >>= 4;
  10542. } while (v != 0);
  10543. return String (t, (int) (((char*) end) - (char*) t));
  10544. }
  10545. const String String::toHexString (const short number)
  10546. {
  10547. return toHexString ((int) (unsigned short) number);
  10548. }
  10549. const String String::toHexString (const unsigned char* data,
  10550. const int size,
  10551. const int groupSize)
  10552. {
  10553. if (size <= 0)
  10554. return empty;
  10555. int numChars = (size * 2) + 2;
  10556. if (groupSize > 0)
  10557. numChars += size / groupSize;
  10558. String s ((size_t) numChars, (int) 0);
  10559. juce_wchar* d = s.text;
  10560. for (int i = 0; i < size; ++i)
  10561. {
  10562. *d++ = hexDigits [(*data) >> 4];
  10563. *d++ = hexDigits [(*data) & 0xf];
  10564. ++data;
  10565. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10566. *d++ = ' ';
  10567. }
  10568. *d = 0;
  10569. return s;
  10570. }
  10571. int String::getHexValue32() const throw()
  10572. {
  10573. int result = 0;
  10574. const juce_wchar* c = text;
  10575. for (;;)
  10576. {
  10577. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10578. if (hexValue >= 0)
  10579. result = (result << 4) | hexValue;
  10580. else if (*c == 0)
  10581. break;
  10582. ++c;
  10583. }
  10584. return result;
  10585. }
  10586. int64 String::getHexValue64() const throw()
  10587. {
  10588. int64 result = 0;
  10589. const juce_wchar* c = text;
  10590. for (;;)
  10591. {
  10592. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10593. if (hexValue >= 0)
  10594. result = (result << 4) | hexValue;
  10595. else if (*c == 0)
  10596. break;
  10597. ++c;
  10598. }
  10599. return result;
  10600. }
  10601. const String String::createStringFromData (const void* const data_, const int size)
  10602. {
  10603. const char* const data = static_cast <const char*> (data_);
  10604. if (size <= 0 || data == 0)
  10605. {
  10606. return empty;
  10607. }
  10608. else if (size < 2)
  10609. {
  10610. return charToString (data[0]);
  10611. }
  10612. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10613. || (data[0] == (char)-1 && data[1] == (char)-2))
  10614. {
  10615. // assume it's 16-bit unicode
  10616. const bool bigEndian = (data[0] == (char)-2);
  10617. const int numChars = size / 2 - 1;
  10618. String result;
  10619. result.preallocateStorage (numChars + 2);
  10620. const uint16* const src = (const uint16*) (data + 2);
  10621. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10622. if (bigEndian)
  10623. {
  10624. for (int i = 0; i < numChars; ++i)
  10625. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10626. }
  10627. else
  10628. {
  10629. for (int i = 0; i < numChars; ++i)
  10630. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10631. }
  10632. dst [numChars] = 0;
  10633. return result;
  10634. }
  10635. else
  10636. {
  10637. return String::fromUTF8 (data, size);
  10638. }
  10639. }
  10640. const char* String::toUTF8() const
  10641. {
  10642. if (isEmpty())
  10643. {
  10644. return reinterpret_cast <const char*> (text);
  10645. }
  10646. else
  10647. {
  10648. const int currentLen = length() + 1;
  10649. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10650. String* const mutableThis = const_cast <String*> (this);
  10651. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10652. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10653. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10654. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10655. #endif
  10656. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10657. return otherCopy;
  10658. }
  10659. }
  10660. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10661. {
  10662. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10663. int num = 0, index = 0;
  10664. for (;;)
  10665. {
  10666. const uint32 c = (uint32) text [index++];
  10667. if (c >= 0x80)
  10668. {
  10669. int numExtraBytes = 1;
  10670. if (c >= 0x800)
  10671. {
  10672. ++numExtraBytes;
  10673. if (c >= 0x10000)
  10674. {
  10675. ++numExtraBytes;
  10676. if (c >= 0x200000)
  10677. {
  10678. ++numExtraBytes;
  10679. if (c >= 0x4000000)
  10680. ++numExtraBytes;
  10681. }
  10682. }
  10683. }
  10684. if (buffer != 0)
  10685. {
  10686. if (num + numExtraBytes >= maxBufferSizeBytes)
  10687. {
  10688. buffer [num++] = 0;
  10689. break;
  10690. }
  10691. else
  10692. {
  10693. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10694. while (--numExtraBytes >= 0)
  10695. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10696. }
  10697. }
  10698. else
  10699. {
  10700. num += numExtraBytes + 1;
  10701. }
  10702. }
  10703. else
  10704. {
  10705. if (buffer != 0)
  10706. {
  10707. if (num + 1 >= maxBufferSizeBytes)
  10708. {
  10709. buffer [num++] = 0;
  10710. break;
  10711. }
  10712. buffer [num] = (uint8) c;
  10713. }
  10714. ++num;
  10715. }
  10716. if (c == 0)
  10717. break;
  10718. }
  10719. return num;
  10720. }
  10721. int String::getNumBytesAsUTF8() const throw()
  10722. {
  10723. int num = 0;
  10724. const juce_wchar* t = text;
  10725. for (;;)
  10726. {
  10727. const uint32 c = (uint32) *t;
  10728. if (c >= 0x80)
  10729. {
  10730. ++num;
  10731. if (c >= 0x800)
  10732. {
  10733. ++num;
  10734. if (c >= 0x10000)
  10735. {
  10736. ++num;
  10737. if (c >= 0x200000)
  10738. {
  10739. ++num;
  10740. if (c >= 0x4000000)
  10741. ++num;
  10742. }
  10743. }
  10744. }
  10745. }
  10746. else if (c == 0)
  10747. break;
  10748. ++num;
  10749. ++t;
  10750. }
  10751. return num;
  10752. }
  10753. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10754. {
  10755. if (buffer == 0)
  10756. return empty;
  10757. if (bufferSizeBytes < 0)
  10758. bufferSizeBytes = std::numeric_limits<int>::max();
  10759. size_t numBytes;
  10760. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10761. if (buffer [numBytes] == 0)
  10762. break;
  10763. String result ((size_t) numBytes + 1, (int) 0);
  10764. juce_wchar* dest = result.text;
  10765. size_t i = 0;
  10766. while (i < numBytes)
  10767. {
  10768. const char c = buffer [i++];
  10769. if (c < 0)
  10770. {
  10771. unsigned int mask = 0x7f;
  10772. int bit = 0x40;
  10773. int numExtraValues = 0;
  10774. while (bit != 0 && (c & bit) != 0)
  10775. {
  10776. bit >>= 1;
  10777. mask >>= 1;
  10778. ++numExtraValues;
  10779. }
  10780. int n = (mask & (unsigned char) c);
  10781. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10782. {
  10783. const char nextByte = buffer[i];
  10784. if ((nextByte & 0xc0) != 0x80)
  10785. break;
  10786. n <<= 6;
  10787. n |= (nextByte & 0x3f);
  10788. ++i;
  10789. }
  10790. *dest++ = (juce_wchar) n;
  10791. }
  10792. else
  10793. {
  10794. *dest++ = (juce_wchar) c;
  10795. }
  10796. }
  10797. *dest = 0;
  10798. return result;
  10799. }
  10800. const char* String::toCString() const
  10801. {
  10802. if (isEmpty())
  10803. {
  10804. return reinterpret_cast <const char*> (text);
  10805. }
  10806. else
  10807. {
  10808. const int len = length();
  10809. String* const mutableThis = const_cast <String*> (this);
  10810. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10811. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10812. CharacterFunctions::copy (otherCopy, text, len);
  10813. otherCopy [len] = 0;
  10814. return otherCopy;
  10815. }
  10816. }
  10817. #if JUCE_MSVC
  10818. #pragma warning (push)
  10819. #pragma warning (disable: 4514 4996)
  10820. #endif
  10821. int String::getNumBytesAsCString() const throw()
  10822. {
  10823. return (int) wcstombs (0, text, 0);
  10824. }
  10825. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10826. {
  10827. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10828. if (destBuffer != 0 && numBytes >= 0)
  10829. destBuffer [numBytes] = 0;
  10830. return numBytes;
  10831. }
  10832. #if JUCE_MSVC
  10833. #pragma warning (pop)
  10834. #endif
  10835. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10836. {
  10837. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10838. }
  10839. String::Concatenator::Concatenator (String& stringToAppendTo)
  10840. : result (stringToAppendTo),
  10841. nextIndex (stringToAppendTo.length())
  10842. {
  10843. }
  10844. String::Concatenator::~Concatenator()
  10845. {
  10846. }
  10847. void String::Concatenator::append (const String& s)
  10848. {
  10849. const int len = s.length();
  10850. if (len > 0)
  10851. {
  10852. result.preallocateStorage (nextIndex + len);
  10853. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10854. nextIndex += len;
  10855. }
  10856. }
  10857. END_JUCE_NAMESPACE
  10858. /*** End of inlined file: juce_String.cpp ***/
  10859. /*** Start of inlined file: juce_StringArray.cpp ***/
  10860. BEGIN_JUCE_NAMESPACE
  10861. StringArray::StringArray() throw()
  10862. {
  10863. }
  10864. StringArray::StringArray (const StringArray& other)
  10865. : strings (other.strings)
  10866. {
  10867. }
  10868. StringArray::StringArray (const String& firstValue)
  10869. {
  10870. strings.add (firstValue);
  10871. }
  10872. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10873. const int numberOfStrings)
  10874. {
  10875. for (int i = 0; i < numberOfStrings; ++i)
  10876. strings.add (initialStrings [i]);
  10877. }
  10878. StringArray::StringArray (const char* const* const initialStrings,
  10879. const int numberOfStrings)
  10880. {
  10881. for (int i = 0; i < numberOfStrings; ++i)
  10882. strings.add (initialStrings [i]);
  10883. }
  10884. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10885. {
  10886. int i = 0;
  10887. while (initialStrings[i] != 0)
  10888. strings.add (initialStrings [i++]);
  10889. }
  10890. StringArray::StringArray (const char* const* const initialStrings)
  10891. {
  10892. int i = 0;
  10893. while (initialStrings[i] != 0)
  10894. strings.add (initialStrings [i++]);
  10895. }
  10896. StringArray& StringArray::operator= (const StringArray& other)
  10897. {
  10898. strings = other.strings;
  10899. return *this;
  10900. }
  10901. StringArray::~StringArray()
  10902. {
  10903. }
  10904. bool StringArray::operator== (const StringArray& other) const throw()
  10905. {
  10906. if (other.size() != size())
  10907. return false;
  10908. for (int i = size(); --i >= 0;)
  10909. if (other.strings.getReference(i) != strings.getReference(i))
  10910. return false;
  10911. return true;
  10912. }
  10913. bool StringArray::operator!= (const StringArray& other) const throw()
  10914. {
  10915. return ! operator== (other);
  10916. }
  10917. void StringArray::clear()
  10918. {
  10919. strings.clear();
  10920. }
  10921. const String& StringArray::operator[] (const int index) const throw()
  10922. {
  10923. if (((unsigned int) index) < (unsigned int) strings.size())
  10924. return strings.getReference (index);
  10925. return String::empty;
  10926. }
  10927. String& StringArray::getReference (const int index) throw()
  10928. {
  10929. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10930. return strings.getReference (index);
  10931. }
  10932. void StringArray::add (const String& newString)
  10933. {
  10934. strings.add (newString);
  10935. }
  10936. void StringArray::insert (const int index, const String& newString)
  10937. {
  10938. strings.insert (index, newString);
  10939. }
  10940. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10941. {
  10942. if (! contains (newString, ignoreCase))
  10943. add (newString);
  10944. }
  10945. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10946. {
  10947. if (startIndex < 0)
  10948. {
  10949. jassertfalse;
  10950. startIndex = 0;
  10951. }
  10952. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10953. numElementsToAdd = otherArray.size() - startIndex;
  10954. while (--numElementsToAdd >= 0)
  10955. strings.add (otherArray.strings.getReference (startIndex++));
  10956. }
  10957. void StringArray::set (const int index, const String& newString)
  10958. {
  10959. strings.set (index, newString);
  10960. }
  10961. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10962. {
  10963. if (ignoreCase)
  10964. {
  10965. for (int i = size(); --i >= 0;)
  10966. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10967. return true;
  10968. }
  10969. else
  10970. {
  10971. for (int i = size(); --i >= 0;)
  10972. if (stringToLookFor == strings.getReference(i))
  10973. return true;
  10974. }
  10975. return false;
  10976. }
  10977. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10978. {
  10979. if (i < 0)
  10980. i = 0;
  10981. const int numElements = size();
  10982. if (ignoreCase)
  10983. {
  10984. while (i < numElements)
  10985. {
  10986. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10987. return i;
  10988. ++i;
  10989. }
  10990. }
  10991. else
  10992. {
  10993. while (i < numElements)
  10994. {
  10995. if (stringToLookFor == strings.getReference (i))
  10996. return i;
  10997. ++i;
  10998. }
  10999. }
  11000. return -1;
  11001. }
  11002. void StringArray::remove (const int index)
  11003. {
  11004. strings.remove (index);
  11005. }
  11006. void StringArray::removeString (const String& stringToRemove,
  11007. const bool ignoreCase)
  11008. {
  11009. if (ignoreCase)
  11010. {
  11011. for (int i = size(); --i >= 0;)
  11012. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11013. strings.remove (i);
  11014. }
  11015. else
  11016. {
  11017. for (int i = size(); --i >= 0;)
  11018. if (stringToRemove == strings.getReference (i))
  11019. strings.remove (i);
  11020. }
  11021. }
  11022. void StringArray::removeRange (int startIndex, int numberToRemove)
  11023. {
  11024. strings.removeRange (startIndex, numberToRemove);
  11025. }
  11026. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11027. {
  11028. if (removeWhitespaceStrings)
  11029. {
  11030. for (int i = size(); --i >= 0;)
  11031. if (! strings.getReference(i).containsNonWhitespaceChars())
  11032. strings.remove (i);
  11033. }
  11034. else
  11035. {
  11036. for (int i = size(); --i >= 0;)
  11037. if (strings.getReference(i).isEmpty())
  11038. strings.remove (i);
  11039. }
  11040. }
  11041. void StringArray::trim()
  11042. {
  11043. for (int i = size(); --i >= 0;)
  11044. {
  11045. String& s = strings.getReference(i);
  11046. s = s.trim();
  11047. }
  11048. }
  11049. class InternalStringArrayComparator_CaseSensitive
  11050. {
  11051. public:
  11052. static int compareElements (String& first, String& second) { return first.compare (second); }
  11053. };
  11054. class InternalStringArrayComparator_CaseInsensitive
  11055. {
  11056. public:
  11057. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11058. };
  11059. void StringArray::sort (const bool ignoreCase)
  11060. {
  11061. if (ignoreCase)
  11062. {
  11063. InternalStringArrayComparator_CaseInsensitive comp;
  11064. strings.sort (comp);
  11065. }
  11066. else
  11067. {
  11068. InternalStringArrayComparator_CaseSensitive comp;
  11069. strings.sort (comp);
  11070. }
  11071. }
  11072. void StringArray::move (const int currentIndex, int newIndex) throw()
  11073. {
  11074. strings.move (currentIndex, newIndex);
  11075. }
  11076. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11077. {
  11078. const int last = (numberToJoin < 0) ? size()
  11079. : jmin (size(), start + numberToJoin);
  11080. if (start < 0)
  11081. start = 0;
  11082. if (start >= last)
  11083. return String::empty;
  11084. if (start == last - 1)
  11085. return strings.getReference (start);
  11086. const int separatorLen = separator.length();
  11087. int charsNeeded = separatorLen * (last - start - 1);
  11088. for (int i = start; i < last; ++i)
  11089. charsNeeded += strings.getReference(i).length();
  11090. String result;
  11091. result.preallocateStorage (charsNeeded);
  11092. juce_wchar* dest = result;
  11093. while (start < last)
  11094. {
  11095. const String& s = strings.getReference (start);
  11096. const int len = s.length();
  11097. if (len > 0)
  11098. {
  11099. s.copyToUnicode (dest, len);
  11100. dest += len;
  11101. }
  11102. if (++start < last && separatorLen > 0)
  11103. {
  11104. separator.copyToUnicode (dest, separatorLen);
  11105. dest += separatorLen;
  11106. }
  11107. }
  11108. *dest = 0;
  11109. return result;
  11110. }
  11111. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11112. {
  11113. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11114. }
  11115. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11116. {
  11117. int num = 0;
  11118. if (text.isNotEmpty())
  11119. {
  11120. bool insideQuotes = false;
  11121. juce_wchar currentQuoteChar = 0;
  11122. int i = 0;
  11123. int tokenStart = 0;
  11124. for (;;)
  11125. {
  11126. const juce_wchar c = text[i];
  11127. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11128. if (! isBreak)
  11129. {
  11130. if (quoteCharacters.containsChar (c))
  11131. {
  11132. if (insideQuotes)
  11133. {
  11134. // only break out of quotes-mode if we find a matching quote to the
  11135. // one that we opened with..
  11136. if (currentQuoteChar == c)
  11137. insideQuotes = false;
  11138. }
  11139. else
  11140. {
  11141. insideQuotes = true;
  11142. currentQuoteChar = c;
  11143. }
  11144. }
  11145. }
  11146. else
  11147. {
  11148. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11149. ++num;
  11150. tokenStart = i + 1;
  11151. }
  11152. if (c == 0)
  11153. break;
  11154. ++i;
  11155. }
  11156. }
  11157. return num;
  11158. }
  11159. int StringArray::addLines (const String& sourceText)
  11160. {
  11161. int numLines = 0;
  11162. const juce_wchar* text = sourceText;
  11163. while (*text != 0)
  11164. {
  11165. const juce_wchar* const startOfLine = text;
  11166. while (*text != 0)
  11167. {
  11168. if (*text == '\r')
  11169. {
  11170. ++text;
  11171. if (*text == '\n')
  11172. ++text;
  11173. break;
  11174. }
  11175. if (*text == '\n')
  11176. {
  11177. ++text;
  11178. break;
  11179. }
  11180. ++text;
  11181. }
  11182. const juce_wchar* endOfLine = text;
  11183. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11184. --endOfLine;
  11185. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11186. --endOfLine;
  11187. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11188. ++numLines;
  11189. }
  11190. return numLines;
  11191. }
  11192. void StringArray::removeDuplicates (const bool ignoreCase)
  11193. {
  11194. for (int i = 0; i < size() - 1; ++i)
  11195. {
  11196. const String s (strings.getReference(i));
  11197. int nextIndex = i + 1;
  11198. for (;;)
  11199. {
  11200. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11201. if (nextIndex < 0)
  11202. break;
  11203. strings.remove (nextIndex);
  11204. }
  11205. }
  11206. }
  11207. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11208. const bool appendNumberToFirstInstance,
  11209. const juce_wchar* preNumberString,
  11210. const juce_wchar* postNumberString)
  11211. {
  11212. if (preNumberString == 0)
  11213. preNumberString = L" (";
  11214. if (postNumberString == 0)
  11215. postNumberString = L")";
  11216. for (int i = 0; i < size() - 1; ++i)
  11217. {
  11218. String& s = strings.getReference(i);
  11219. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11220. if (nextIndex >= 0)
  11221. {
  11222. const String original (s);
  11223. int number = 0;
  11224. if (appendNumberToFirstInstance)
  11225. s = original + preNumberString + String (++number) + postNumberString;
  11226. else
  11227. ++number;
  11228. while (nextIndex >= 0)
  11229. {
  11230. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11231. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11232. }
  11233. }
  11234. }
  11235. }
  11236. void StringArray::minimiseStorageOverheads()
  11237. {
  11238. strings.minimiseStorageOverheads();
  11239. }
  11240. END_JUCE_NAMESPACE
  11241. /*** End of inlined file: juce_StringArray.cpp ***/
  11242. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11243. BEGIN_JUCE_NAMESPACE
  11244. StringPairArray::StringPairArray (const bool ignoreCase_)
  11245. : ignoreCase (ignoreCase_)
  11246. {
  11247. }
  11248. StringPairArray::StringPairArray (const StringPairArray& other)
  11249. : keys (other.keys),
  11250. values (other.values),
  11251. ignoreCase (other.ignoreCase)
  11252. {
  11253. }
  11254. StringPairArray::~StringPairArray()
  11255. {
  11256. }
  11257. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11258. {
  11259. keys = other.keys;
  11260. values = other.values;
  11261. return *this;
  11262. }
  11263. bool StringPairArray::operator== (const StringPairArray& other) const
  11264. {
  11265. for (int i = keys.size(); --i >= 0;)
  11266. if (other [keys[i]] != values[i])
  11267. return false;
  11268. return true;
  11269. }
  11270. bool StringPairArray::operator!= (const StringPairArray& other) const
  11271. {
  11272. return ! operator== (other);
  11273. }
  11274. const String& StringPairArray::operator[] (const String& key) const
  11275. {
  11276. return values [keys.indexOf (key, ignoreCase)];
  11277. }
  11278. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11279. {
  11280. const int i = keys.indexOf (key, ignoreCase);
  11281. if (i >= 0)
  11282. return values[i];
  11283. return defaultReturnValue;
  11284. }
  11285. void StringPairArray::set (const String& key, const String& value)
  11286. {
  11287. const int i = keys.indexOf (key, ignoreCase);
  11288. if (i >= 0)
  11289. {
  11290. values.set (i, value);
  11291. }
  11292. else
  11293. {
  11294. keys.add (key);
  11295. values.add (value);
  11296. }
  11297. }
  11298. void StringPairArray::addArray (const StringPairArray& other)
  11299. {
  11300. for (int i = 0; i < other.size(); ++i)
  11301. set (other.keys[i], other.values[i]);
  11302. }
  11303. void StringPairArray::clear()
  11304. {
  11305. keys.clear();
  11306. values.clear();
  11307. }
  11308. void StringPairArray::remove (const String& key)
  11309. {
  11310. remove (keys.indexOf (key, ignoreCase));
  11311. }
  11312. void StringPairArray::remove (const int index)
  11313. {
  11314. keys.remove (index);
  11315. values.remove (index);
  11316. }
  11317. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11318. {
  11319. ignoreCase = shouldIgnoreCase;
  11320. }
  11321. const String StringPairArray::getDescription() const
  11322. {
  11323. String s;
  11324. for (int i = 0; i < keys.size(); ++i)
  11325. {
  11326. s << keys[i] << " = " << values[i];
  11327. if (i < keys.size())
  11328. s << ", ";
  11329. }
  11330. return s;
  11331. }
  11332. void StringPairArray::minimiseStorageOverheads()
  11333. {
  11334. keys.minimiseStorageOverheads();
  11335. values.minimiseStorageOverheads();
  11336. }
  11337. END_JUCE_NAMESPACE
  11338. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11339. /*** Start of inlined file: juce_StringPool.cpp ***/
  11340. BEGIN_JUCE_NAMESPACE
  11341. StringPool::StringPool() throw() {}
  11342. StringPool::~StringPool() {}
  11343. template <class StringType>
  11344. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11345. {
  11346. int start = 0;
  11347. int end = strings.size();
  11348. for (;;)
  11349. {
  11350. if (start >= end)
  11351. {
  11352. jassert (start <= end);
  11353. strings.insert (start, newString);
  11354. return strings.getReference (start);
  11355. }
  11356. else
  11357. {
  11358. const String& startString = strings.getReference (start);
  11359. if (startString == newString)
  11360. return startString;
  11361. const int halfway = (start + end) >> 1;
  11362. if (halfway == start)
  11363. {
  11364. if (startString.compare (newString) < 0)
  11365. ++start;
  11366. strings.insert (start, newString);
  11367. return strings.getReference (start);
  11368. }
  11369. const int comp = strings.getReference (halfway).compare (newString);
  11370. if (comp == 0)
  11371. return strings.getReference (halfway);
  11372. else if (comp < 0)
  11373. start = halfway;
  11374. else
  11375. end = halfway;
  11376. }
  11377. }
  11378. }
  11379. const juce_wchar* StringPool::getPooledString (const String& s)
  11380. {
  11381. if (s.isEmpty())
  11382. return String::empty;
  11383. return getPooledStringFromArray (strings, s);
  11384. }
  11385. const juce_wchar* StringPool::getPooledString (const char* const s)
  11386. {
  11387. if (s == 0 || *s == 0)
  11388. return String::empty;
  11389. return getPooledStringFromArray (strings, s);
  11390. }
  11391. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11392. {
  11393. if (s == 0 || *s == 0)
  11394. return String::empty;
  11395. return getPooledStringFromArray (strings, s);
  11396. }
  11397. int StringPool::size() const throw()
  11398. {
  11399. return strings.size();
  11400. }
  11401. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11402. {
  11403. return strings [index];
  11404. }
  11405. END_JUCE_NAMESPACE
  11406. /*** End of inlined file: juce_StringPool.cpp ***/
  11407. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11408. BEGIN_JUCE_NAMESPACE
  11409. XmlDocument::XmlDocument (const String& documentText)
  11410. : originalText (documentText),
  11411. ignoreEmptyTextElements (true)
  11412. {
  11413. }
  11414. XmlDocument::XmlDocument (const File& file)
  11415. : ignoreEmptyTextElements (true)
  11416. {
  11417. inputSource = new FileInputSource (file);
  11418. }
  11419. XmlDocument::~XmlDocument()
  11420. {
  11421. }
  11422. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11423. {
  11424. inputSource = newSource;
  11425. }
  11426. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11427. {
  11428. ignoreEmptyTextElements = shouldBeIgnored;
  11429. }
  11430. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11431. {
  11432. return CharacterFunctions::isLetterOrDigit (c)
  11433. || c == '_' || c == '-' || c == ':' || c == '.';
  11434. }
  11435. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11436. {
  11437. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11438. : isXmlIdentifierCharSlow (c);
  11439. }
  11440. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11441. {
  11442. String textToParse (originalText);
  11443. if (textToParse.isEmpty() && inputSource != 0)
  11444. {
  11445. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11446. if (in != 0)
  11447. {
  11448. MemoryOutputStream data;
  11449. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11450. textToParse = data.toString();
  11451. if (! onlyReadOuterDocumentElement)
  11452. originalText = textToParse;
  11453. }
  11454. }
  11455. input = textToParse;
  11456. lastError = String::empty;
  11457. errorOccurred = false;
  11458. outOfData = false;
  11459. needToLoadDTD = true;
  11460. for (int i = 0; i < 128; ++i)
  11461. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11462. if (textToParse.isEmpty())
  11463. {
  11464. lastError = "not enough input";
  11465. }
  11466. else
  11467. {
  11468. skipHeader();
  11469. if (input != 0)
  11470. {
  11471. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11472. if (! errorOccurred)
  11473. return result.release();
  11474. }
  11475. else
  11476. {
  11477. lastError = "incorrect xml header";
  11478. }
  11479. }
  11480. return 0;
  11481. }
  11482. const String& XmlDocument::getLastParseError() const throw()
  11483. {
  11484. return lastError;
  11485. }
  11486. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11487. {
  11488. lastError = desc;
  11489. errorOccurred = ! carryOn;
  11490. }
  11491. const String XmlDocument::getFileContents (const String& filename) const
  11492. {
  11493. if (inputSource != 0)
  11494. {
  11495. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11496. if (in != 0)
  11497. return in->readEntireStreamAsString();
  11498. }
  11499. return String::empty;
  11500. }
  11501. juce_wchar XmlDocument::readNextChar() throw()
  11502. {
  11503. if (*input != 0)
  11504. {
  11505. return *input++;
  11506. }
  11507. else
  11508. {
  11509. outOfData = true;
  11510. return 0;
  11511. }
  11512. }
  11513. int XmlDocument::findNextTokenLength() throw()
  11514. {
  11515. int len = 0;
  11516. juce_wchar c = *input;
  11517. while (isXmlIdentifierChar (c))
  11518. c = input [++len];
  11519. return len;
  11520. }
  11521. void XmlDocument::skipHeader()
  11522. {
  11523. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11524. if (found != 0)
  11525. {
  11526. input = found;
  11527. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11528. if (input == 0)
  11529. return;
  11530. input += 2;
  11531. }
  11532. skipNextWhiteSpace();
  11533. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11534. if (docType == 0)
  11535. return;
  11536. input = docType + 9;
  11537. int n = 1;
  11538. while (n > 0)
  11539. {
  11540. const juce_wchar c = readNextChar();
  11541. if (outOfData)
  11542. return;
  11543. if (c == '<')
  11544. ++n;
  11545. else if (c == '>')
  11546. --n;
  11547. }
  11548. docType += 9;
  11549. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11550. }
  11551. void XmlDocument::skipNextWhiteSpace()
  11552. {
  11553. for (;;)
  11554. {
  11555. juce_wchar c = *input;
  11556. while (CharacterFunctions::isWhitespace (c))
  11557. c = *++input;
  11558. if (c == 0)
  11559. {
  11560. outOfData = true;
  11561. break;
  11562. }
  11563. else if (c == '<')
  11564. {
  11565. if (input[1] == '!'
  11566. && input[2] == '-'
  11567. && input[3] == '-')
  11568. {
  11569. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  11570. if (closeComment == 0)
  11571. {
  11572. outOfData = true;
  11573. break;
  11574. }
  11575. input = closeComment + 3;
  11576. continue;
  11577. }
  11578. else if (input[1] == '?')
  11579. {
  11580. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  11581. if (closeBracket == 0)
  11582. {
  11583. outOfData = true;
  11584. break;
  11585. }
  11586. input = closeBracket + 2;
  11587. continue;
  11588. }
  11589. }
  11590. break;
  11591. }
  11592. }
  11593. void XmlDocument::readQuotedString (String& result)
  11594. {
  11595. const juce_wchar quote = readNextChar();
  11596. while (! outOfData)
  11597. {
  11598. const juce_wchar c = readNextChar();
  11599. if (c == quote)
  11600. break;
  11601. if (c == '&')
  11602. {
  11603. --input;
  11604. readEntity (result);
  11605. }
  11606. else
  11607. {
  11608. --input;
  11609. const juce_wchar* const start = input;
  11610. for (;;)
  11611. {
  11612. const juce_wchar character = *input;
  11613. if (character == quote)
  11614. {
  11615. result.append (start, (int) (input - start));
  11616. ++input;
  11617. return;
  11618. }
  11619. else if (character == '&')
  11620. {
  11621. result.append (start, (int) (input - start));
  11622. break;
  11623. }
  11624. else if (character == 0)
  11625. {
  11626. outOfData = true;
  11627. setLastError ("unmatched quotes", false);
  11628. break;
  11629. }
  11630. ++input;
  11631. }
  11632. }
  11633. }
  11634. }
  11635. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11636. {
  11637. XmlElement* node = 0;
  11638. skipNextWhiteSpace();
  11639. if (outOfData)
  11640. return 0;
  11641. input = CharacterFunctions::find (input, JUCE_T("<"));
  11642. if (input != 0)
  11643. {
  11644. ++input;
  11645. int tagLen = findNextTokenLength();
  11646. if (tagLen == 0)
  11647. {
  11648. // no tag name - but allow for a gap after the '<' before giving an error
  11649. skipNextWhiteSpace();
  11650. tagLen = findNextTokenLength();
  11651. if (tagLen == 0)
  11652. {
  11653. setLastError ("tag name missing", false);
  11654. return node;
  11655. }
  11656. }
  11657. node = new XmlElement (String (input, tagLen));
  11658. input += tagLen;
  11659. XmlElement::XmlAttributeNode* lastAttribute = 0;
  11660. // look for attributes
  11661. for (;;)
  11662. {
  11663. skipNextWhiteSpace();
  11664. const juce_wchar c = *input;
  11665. // empty tag..
  11666. if (c == '/' && input[1] == '>')
  11667. {
  11668. input += 2;
  11669. break;
  11670. }
  11671. // parse the guts of the element..
  11672. if (c == '>')
  11673. {
  11674. ++input;
  11675. skipNextWhiteSpace();
  11676. if (alsoParseSubElements)
  11677. readChildElements (node);
  11678. break;
  11679. }
  11680. // get an attribute..
  11681. if (isXmlIdentifierChar (c))
  11682. {
  11683. const int attNameLen = findNextTokenLength();
  11684. if (attNameLen > 0)
  11685. {
  11686. const juce_wchar* attNameStart = input;
  11687. input += attNameLen;
  11688. skipNextWhiteSpace();
  11689. if (readNextChar() == '=')
  11690. {
  11691. skipNextWhiteSpace();
  11692. const juce_wchar nextChar = *input;
  11693. if (nextChar == '"' || nextChar == '\'')
  11694. {
  11695. XmlElement::XmlAttributeNode* const newAtt
  11696. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  11697. String::empty);
  11698. readQuotedString (newAtt->value);
  11699. if (lastAttribute == 0)
  11700. node->attributes = newAtt;
  11701. else
  11702. lastAttribute->next = newAtt;
  11703. lastAttribute = newAtt;
  11704. continue;
  11705. }
  11706. }
  11707. }
  11708. }
  11709. else
  11710. {
  11711. if (! outOfData)
  11712. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11713. }
  11714. break;
  11715. }
  11716. }
  11717. return node;
  11718. }
  11719. void XmlDocument::readChildElements (XmlElement* parent)
  11720. {
  11721. XmlElement* lastChildNode = 0;
  11722. for (;;)
  11723. {
  11724. skipNextWhiteSpace();
  11725. if (outOfData)
  11726. {
  11727. setLastError ("unmatched tags", false);
  11728. break;
  11729. }
  11730. if (*input == '<')
  11731. {
  11732. if (input[1] == '/')
  11733. {
  11734. // our close tag..
  11735. input = CharacterFunctions::find (input, JUCE_T(">"));
  11736. ++input;
  11737. break;
  11738. }
  11739. else if (input[1] == '!'
  11740. && input[2] == '['
  11741. && input[3] == 'C'
  11742. && input[4] == 'D'
  11743. && input[5] == 'A'
  11744. && input[6] == 'T'
  11745. && input[7] == 'A'
  11746. && input[8] == '[')
  11747. {
  11748. input += 9;
  11749. const juce_wchar* const inputStart = input;
  11750. int len = 0;
  11751. for (;;)
  11752. {
  11753. if (*input == 0)
  11754. {
  11755. setLastError ("unterminated CDATA section", false);
  11756. outOfData = true;
  11757. break;
  11758. }
  11759. else if (input[0] == ']'
  11760. && input[1] == ']'
  11761. && input[2] == '>')
  11762. {
  11763. input += 3;
  11764. break;
  11765. }
  11766. ++input;
  11767. ++len;
  11768. }
  11769. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  11770. if (lastChildNode != 0)
  11771. lastChildNode->nextElement = e;
  11772. else
  11773. parent->addChildElement (e);
  11774. lastChildNode = e;
  11775. }
  11776. else
  11777. {
  11778. // this is some other element, so parse and add it..
  11779. XmlElement* const n = readNextElement (true);
  11780. if (n != 0)
  11781. {
  11782. if (lastChildNode == 0)
  11783. parent->addChildElement (n);
  11784. else
  11785. lastChildNode->nextElement = n;
  11786. lastChildNode = n;
  11787. }
  11788. else
  11789. {
  11790. return;
  11791. }
  11792. }
  11793. }
  11794. else
  11795. {
  11796. // read character block..
  11797. XmlElement* const e = new XmlElement ((int)0);
  11798. if (lastChildNode != 0)
  11799. lastChildNode->nextElement = e;
  11800. else
  11801. parent->addChildElement (e);
  11802. lastChildNode = e;
  11803. String textElementContent;
  11804. for (;;)
  11805. {
  11806. const juce_wchar c = *input;
  11807. if (c == '<')
  11808. break;
  11809. if (c == 0)
  11810. {
  11811. setLastError ("unmatched tags", false);
  11812. outOfData = true;
  11813. return;
  11814. }
  11815. if (c == '&')
  11816. {
  11817. String entity;
  11818. readEntity (entity);
  11819. if (entity.startsWithChar ('<') && entity [1] != 0)
  11820. {
  11821. const juce_wchar* const oldInput = input;
  11822. const bool oldOutOfData = outOfData;
  11823. input = entity;
  11824. outOfData = false;
  11825. for (;;)
  11826. {
  11827. XmlElement* const n = readNextElement (true);
  11828. if (n == 0)
  11829. break;
  11830. if (lastChildNode == 0)
  11831. parent->addChildElement (n);
  11832. else
  11833. lastChildNode->nextElement = n;
  11834. lastChildNode = n;
  11835. }
  11836. input = oldInput;
  11837. outOfData = oldOutOfData;
  11838. }
  11839. else
  11840. {
  11841. textElementContent += entity;
  11842. }
  11843. }
  11844. else
  11845. {
  11846. const juce_wchar* start = input;
  11847. int len = 0;
  11848. for (;;)
  11849. {
  11850. const juce_wchar nextChar = *input;
  11851. if (nextChar == '<' || nextChar == '&')
  11852. {
  11853. break;
  11854. }
  11855. else if (nextChar == 0)
  11856. {
  11857. setLastError ("unmatched tags", false);
  11858. outOfData = true;
  11859. return;
  11860. }
  11861. ++input;
  11862. ++len;
  11863. }
  11864. textElementContent.append (start, len);
  11865. }
  11866. }
  11867. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11868. : textElementContent.isNotEmpty())
  11869. e->setText (textElementContent);
  11870. }
  11871. }
  11872. }
  11873. void XmlDocument::readEntity (String& result)
  11874. {
  11875. // skip over the ampersand
  11876. ++input;
  11877. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11878. {
  11879. input += 4;
  11880. result += '&';
  11881. }
  11882. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11883. {
  11884. input += 5;
  11885. result += '"';
  11886. }
  11887. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11888. {
  11889. input += 5;
  11890. result += '\'';
  11891. }
  11892. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11893. {
  11894. input += 3;
  11895. result += '<';
  11896. }
  11897. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11898. {
  11899. input += 3;
  11900. result += '>';
  11901. }
  11902. else if (*input == '#')
  11903. {
  11904. int charCode = 0;
  11905. ++input;
  11906. if (*input == 'x' || *input == 'X')
  11907. {
  11908. ++input;
  11909. int numChars = 0;
  11910. while (input[0] != ';')
  11911. {
  11912. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11913. if (hexValue < 0 || ++numChars > 8)
  11914. {
  11915. setLastError ("illegal escape sequence", true);
  11916. break;
  11917. }
  11918. charCode = (charCode << 4) | hexValue;
  11919. ++input;
  11920. }
  11921. ++input;
  11922. }
  11923. else if (input[0] >= '0' && input[0] <= '9')
  11924. {
  11925. int numChars = 0;
  11926. while (input[0] != ';')
  11927. {
  11928. if (++numChars > 12)
  11929. {
  11930. setLastError ("illegal escape sequence", true);
  11931. break;
  11932. }
  11933. charCode = charCode * 10 + (input[0] - '0');
  11934. ++input;
  11935. }
  11936. ++input;
  11937. }
  11938. else
  11939. {
  11940. setLastError ("illegal escape sequence", true);
  11941. result += '&';
  11942. return;
  11943. }
  11944. result << (juce_wchar) charCode;
  11945. }
  11946. else
  11947. {
  11948. const juce_wchar* const entityNameStart = input;
  11949. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11950. if (closingSemiColon == 0)
  11951. {
  11952. outOfData = true;
  11953. result += '&';
  11954. }
  11955. else
  11956. {
  11957. input = closingSemiColon + 1;
  11958. result += expandExternalEntity (String (entityNameStart,
  11959. (int) (closingSemiColon - entityNameStart)));
  11960. }
  11961. }
  11962. }
  11963. const String XmlDocument::expandEntity (const String& ent)
  11964. {
  11965. if (ent.equalsIgnoreCase ("amp"))
  11966. return String::charToString ('&');
  11967. if (ent.equalsIgnoreCase ("quot"))
  11968. return String::charToString ('"');
  11969. if (ent.equalsIgnoreCase ("apos"))
  11970. return String::charToString ('\'');
  11971. if (ent.equalsIgnoreCase ("lt"))
  11972. return String::charToString ('<');
  11973. if (ent.equalsIgnoreCase ("gt"))
  11974. return String::charToString ('>');
  11975. if (ent[0] == '#')
  11976. {
  11977. if (ent[1] == 'x' || ent[1] == 'X')
  11978. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11979. if (ent[1] >= '0' && ent[1] <= '9')
  11980. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11981. setLastError ("illegal escape sequence", false);
  11982. return String::charToString ('&');
  11983. }
  11984. return expandExternalEntity (ent);
  11985. }
  11986. const String XmlDocument::expandExternalEntity (const String& entity)
  11987. {
  11988. if (needToLoadDTD)
  11989. {
  11990. if (dtdText.isNotEmpty())
  11991. {
  11992. dtdText = dtdText.trimCharactersAtEnd (">");
  11993. tokenisedDTD.addTokens (dtdText, true);
  11994. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11995. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11996. {
  11997. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11998. tokenisedDTD.clear();
  11999. tokenisedDTD.addTokens (getFileContents (fn), true);
  12000. }
  12001. else
  12002. {
  12003. tokenisedDTD.clear();
  12004. const int openBracket = dtdText.indexOfChar ('[');
  12005. if (openBracket > 0)
  12006. {
  12007. const int closeBracket = dtdText.lastIndexOfChar (']');
  12008. if (closeBracket > openBracket)
  12009. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12010. closeBracket), true);
  12011. }
  12012. }
  12013. for (int i = tokenisedDTD.size(); --i >= 0;)
  12014. {
  12015. if (tokenisedDTD[i].startsWithChar ('%')
  12016. && tokenisedDTD[i].endsWithChar (';'))
  12017. {
  12018. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12019. StringArray newToks;
  12020. newToks.addTokens (parsed, true);
  12021. tokenisedDTD.remove (i);
  12022. for (int j = newToks.size(); --j >= 0;)
  12023. tokenisedDTD.insert (i, newToks[j]);
  12024. }
  12025. }
  12026. }
  12027. needToLoadDTD = false;
  12028. }
  12029. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12030. {
  12031. if (tokenisedDTD[i] == entity)
  12032. {
  12033. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12034. {
  12035. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12036. // check for sub-entities..
  12037. int ampersand = ent.indexOfChar ('&');
  12038. while (ampersand >= 0)
  12039. {
  12040. const int semiColon = ent.indexOf (i + 1, ";");
  12041. if (semiColon < 0)
  12042. {
  12043. setLastError ("entity without terminating semi-colon", false);
  12044. break;
  12045. }
  12046. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12047. ent = ent.substring (0, ampersand)
  12048. + resolved
  12049. + ent.substring (semiColon + 1);
  12050. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12051. }
  12052. return ent;
  12053. }
  12054. }
  12055. }
  12056. setLastError ("unknown entity", true);
  12057. return entity;
  12058. }
  12059. const String XmlDocument::getParameterEntity (const String& entity)
  12060. {
  12061. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12062. {
  12063. if (tokenisedDTD[i] == entity)
  12064. {
  12065. if (tokenisedDTD [i - 1] == "%"
  12066. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12067. {
  12068. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12069. if (ent.equalsIgnoreCase ("system"))
  12070. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12071. else
  12072. return ent.trim().unquoted();
  12073. }
  12074. }
  12075. }
  12076. return entity;
  12077. }
  12078. END_JUCE_NAMESPACE
  12079. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12080. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12081. BEGIN_JUCE_NAMESPACE
  12082. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12083. : name (other.name),
  12084. value (other.value),
  12085. next (0)
  12086. {
  12087. }
  12088. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12089. : name (name_),
  12090. value (value_),
  12091. next (0)
  12092. {
  12093. }
  12094. XmlElement::XmlElement (const String& tagName_) throw()
  12095. : tagName (tagName_),
  12096. firstChildElement (0),
  12097. nextElement (0),
  12098. attributes (0)
  12099. {
  12100. // the tag name mustn't be empty, or it'll look like a text element!
  12101. jassert (tagName_.containsNonWhitespaceChars())
  12102. // The tag can't contain spaces or other characters that would create invalid XML!
  12103. jassert (! tagName_.containsAnyOf (" <>/&"));
  12104. }
  12105. XmlElement::XmlElement (int /*dummy*/) throw()
  12106. : firstChildElement (0),
  12107. nextElement (0),
  12108. attributes (0)
  12109. {
  12110. }
  12111. XmlElement::XmlElement (const XmlElement& other)
  12112. : tagName (other.tagName),
  12113. firstChildElement (0),
  12114. nextElement (0),
  12115. attributes (0)
  12116. {
  12117. copyChildrenAndAttributesFrom (other);
  12118. }
  12119. XmlElement& XmlElement::operator= (const XmlElement& other)
  12120. {
  12121. if (this != &other)
  12122. {
  12123. removeAllAttributes();
  12124. deleteAllChildElements();
  12125. tagName = other.tagName;
  12126. copyChildrenAndAttributesFrom (other);
  12127. }
  12128. return *this;
  12129. }
  12130. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12131. {
  12132. XmlElement* child = other.firstChildElement;
  12133. XmlElement* lastChild = 0;
  12134. while (child != 0)
  12135. {
  12136. XmlElement* const copiedChild = new XmlElement (*child);
  12137. if (lastChild != 0)
  12138. lastChild->nextElement = copiedChild;
  12139. else
  12140. firstChildElement = copiedChild;
  12141. lastChild = copiedChild;
  12142. child = child->nextElement;
  12143. }
  12144. const XmlAttributeNode* att = other.attributes;
  12145. XmlAttributeNode* lastAtt = 0;
  12146. while (att != 0)
  12147. {
  12148. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12149. if (lastAtt != 0)
  12150. lastAtt->next = newAtt;
  12151. else
  12152. attributes = newAtt;
  12153. lastAtt = newAtt;
  12154. att = att->next;
  12155. }
  12156. }
  12157. XmlElement::~XmlElement() throw()
  12158. {
  12159. XmlElement* child = firstChildElement;
  12160. while (child != 0)
  12161. {
  12162. XmlElement* const nextChild = child->nextElement;
  12163. delete child;
  12164. child = nextChild;
  12165. }
  12166. XmlAttributeNode* att = attributes;
  12167. while (att != 0)
  12168. {
  12169. XmlAttributeNode* const nextAtt = att->next;
  12170. delete att;
  12171. att = nextAtt;
  12172. }
  12173. }
  12174. namespace XmlOutputFunctions
  12175. {
  12176. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12177. {
  12178. if ((character >= 'a' && character <= 'z')
  12179. || (character >= 'A' && character <= 'Z')
  12180. || (character >= '0' && character <= '9'))
  12181. return true;
  12182. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12183. do
  12184. {
  12185. if (((juce_wchar) (uint8) *t) == character)
  12186. return true;
  12187. }
  12188. while (*++t != 0);
  12189. return false;
  12190. }
  12191. static void generateLegalCharConstants()
  12192. {
  12193. uint8 n[32];
  12194. zerostruct (n);
  12195. for (int i = 0; i < 256; ++i)
  12196. if (isLegalXmlCharSlow (i))
  12197. n[i >> 3] |= (1 << (i & 7));
  12198. String s;
  12199. for (int i = 0; i < 32; ++i)
  12200. s << (int) n[i] << ", ";
  12201. DBG (s);
  12202. }*/
  12203. static bool isLegalXmlChar (const uint32 c) throw()
  12204. {
  12205. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12206. return c < sizeof (legalChars) * 8
  12207. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12208. }
  12209. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12210. {
  12211. const juce_wchar* t = text;
  12212. for (;;)
  12213. {
  12214. const juce_wchar character = *t++;
  12215. if (character == 0)
  12216. {
  12217. break;
  12218. }
  12219. else if (isLegalXmlChar ((uint32) character))
  12220. {
  12221. outputStream << (char) character;
  12222. }
  12223. else
  12224. {
  12225. switch (character)
  12226. {
  12227. case '&': outputStream << "&amp;"; break;
  12228. case '"': outputStream << "&quot;"; break;
  12229. case '>': outputStream << "&gt;"; break;
  12230. case '<': outputStream << "&lt;"; break;
  12231. case '\n':
  12232. if (changeNewLines)
  12233. outputStream << "&#10;";
  12234. else
  12235. outputStream << (char) character;
  12236. break;
  12237. case '\r':
  12238. if (changeNewLines)
  12239. outputStream << "&#13;";
  12240. else
  12241. outputStream << (char) character;
  12242. break;
  12243. default:
  12244. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12245. break;
  12246. }
  12247. }
  12248. }
  12249. }
  12250. static void writeSpaces (OutputStream& out, int numSpaces)
  12251. {
  12252. if (numSpaces > 0)
  12253. {
  12254. const char* const blanks = " ";
  12255. const int blankSize = (int) sizeof (blanks) - 1;
  12256. while (numSpaces > blankSize)
  12257. {
  12258. out.write (blanks, blankSize);
  12259. numSpaces -= blankSize;
  12260. }
  12261. out.write (blanks, numSpaces);
  12262. }
  12263. }
  12264. }
  12265. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12266. const int indentationLevel,
  12267. const int lineWrapLength) const
  12268. {
  12269. using namespace XmlOutputFunctions;
  12270. writeSpaces (outputStream, indentationLevel);
  12271. if (! isTextElement())
  12272. {
  12273. outputStream.writeByte ('<');
  12274. outputStream << tagName;
  12275. const int attIndent = indentationLevel + tagName.length() + 1;
  12276. int lineLen = 0;
  12277. const XmlAttributeNode* att = attributes;
  12278. while (att != 0)
  12279. {
  12280. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12281. {
  12282. outputStream.write ("\r\n", 2);
  12283. writeSpaces (outputStream, attIndent);
  12284. lineLen = 0;
  12285. }
  12286. const int64 startPos = outputStream.getPosition();
  12287. outputStream.writeByte (' ');
  12288. outputStream << att->name;
  12289. outputStream.write ("=\"", 2);
  12290. escapeIllegalXmlChars (outputStream, att->value, true);
  12291. outputStream.writeByte ('"');
  12292. lineLen += (int) (outputStream.getPosition() - startPos);
  12293. att = att->next;
  12294. }
  12295. if (firstChildElement != 0)
  12296. {
  12297. XmlElement* child = firstChildElement;
  12298. if (child->nextElement == 0 && child->isTextElement())
  12299. {
  12300. outputStream.writeByte ('>');
  12301. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12302. }
  12303. else
  12304. {
  12305. if (indentationLevel >= 0)
  12306. outputStream.write (">\r\n", 3);
  12307. else
  12308. outputStream.writeByte ('>');
  12309. bool lastWasTextNode = false;
  12310. while (child != 0)
  12311. {
  12312. if (child->isTextElement())
  12313. {
  12314. if ((! lastWasTextNode) && (indentationLevel >= 0))
  12315. writeSpaces (outputStream, indentationLevel + 2);
  12316. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12317. lastWasTextNode = true;
  12318. }
  12319. else
  12320. {
  12321. if (indentationLevel >= 0)
  12322. {
  12323. if (lastWasTextNode)
  12324. outputStream.write ("\r\n", 2);
  12325. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  12326. }
  12327. else
  12328. {
  12329. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  12330. }
  12331. lastWasTextNode = false;
  12332. }
  12333. child = child->nextElement;
  12334. }
  12335. if (indentationLevel >= 0)
  12336. {
  12337. if (lastWasTextNode)
  12338. outputStream.write ("\r\n", 2);
  12339. writeSpaces (outputStream, indentationLevel);
  12340. }
  12341. }
  12342. outputStream.write ("</", 2);
  12343. outputStream << tagName;
  12344. if (indentationLevel >= 0)
  12345. outputStream.write (">\r\n", 3);
  12346. else
  12347. outputStream.writeByte ('>');
  12348. }
  12349. else
  12350. {
  12351. if (indentationLevel >= 0)
  12352. outputStream.write ("/>\r\n", 4);
  12353. else
  12354. outputStream.write ("/>", 2);
  12355. }
  12356. }
  12357. else
  12358. {
  12359. if (indentationLevel >= 0)
  12360. writeSpaces (outputStream, indentationLevel + 2);
  12361. escapeIllegalXmlChars (outputStream, getText(), false);
  12362. }
  12363. }
  12364. const String XmlElement::createDocument (const String& dtdToUse,
  12365. const bool allOnOneLine,
  12366. const bool includeXmlHeader,
  12367. const String& encodingType,
  12368. const int lineWrapLength) const
  12369. {
  12370. MemoryOutputStream mem (2048);
  12371. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12372. return mem.toUTF8();
  12373. }
  12374. void XmlElement::writeToStream (OutputStream& output,
  12375. const String& dtdToUse,
  12376. const bool allOnOneLine,
  12377. const bool includeXmlHeader,
  12378. const String& encodingType,
  12379. const int lineWrapLength) const
  12380. {
  12381. if (includeXmlHeader)
  12382. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  12383. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  12384. if (dtdToUse.isNotEmpty())
  12385. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  12386. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12387. }
  12388. bool XmlElement::writeToFile (const File& file,
  12389. const String& dtdToUse,
  12390. const String& encodingType,
  12391. const int lineWrapLength) const
  12392. {
  12393. if (file.hasWriteAccess())
  12394. {
  12395. TemporaryFile tempFile (file);
  12396. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12397. if (out != 0)
  12398. {
  12399. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12400. out = 0;
  12401. return tempFile.overwriteTargetFileWithTemporary();
  12402. }
  12403. }
  12404. return false;
  12405. }
  12406. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12407. {
  12408. #if JUCE_DEBUG
  12409. // if debugging, check that the case is actually the same, because
  12410. // valid xml is case-sensitive, and although this lets it pass, it's
  12411. // better not to..
  12412. if (tagName.equalsIgnoreCase (tagNameWanted))
  12413. {
  12414. jassert (tagName == tagNameWanted);
  12415. return true;
  12416. }
  12417. else
  12418. {
  12419. return false;
  12420. }
  12421. #else
  12422. return tagName.equalsIgnoreCase (tagNameWanted);
  12423. #endif
  12424. }
  12425. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12426. {
  12427. XmlElement* e = nextElement;
  12428. while (e != 0 && ! e->hasTagName (requiredTagName))
  12429. e = e->nextElement;
  12430. return e;
  12431. }
  12432. int XmlElement::getNumAttributes() const throw()
  12433. {
  12434. const XmlAttributeNode* att = attributes;
  12435. int count = 0;
  12436. while (att != 0)
  12437. {
  12438. att = att->next;
  12439. ++count;
  12440. }
  12441. return count;
  12442. }
  12443. const String& XmlElement::getAttributeName (const int index) const throw()
  12444. {
  12445. const XmlAttributeNode* att = attributes;
  12446. int count = 0;
  12447. while (att != 0)
  12448. {
  12449. if (count == index)
  12450. return att->name;
  12451. att = att->next;
  12452. ++count;
  12453. }
  12454. return String::empty;
  12455. }
  12456. const String& XmlElement::getAttributeValue (const int index) const throw()
  12457. {
  12458. const XmlAttributeNode* att = attributes;
  12459. int count = 0;
  12460. while (att != 0)
  12461. {
  12462. if (count == index)
  12463. return att->value;
  12464. att = att->next;
  12465. ++count;
  12466. }
  12467. return String::empty;
  12468. }
  12469. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12470. {
  12471. const XmlAttributeNode* att = attributes;
  12472. while (att != 0)
  12473. {
  12474. if (att->name.equalsIgnoreCase (attributeName))
  12475. return true;
  12476. att = att->next;
  12477. }
  12478. return false;
  12479. }
  12480. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12481. {
  12482. const XmlAttributeNode* att = attributes;
  12483. while (att != 0)
  12484. {
  12485. if (att->name.equalsIgnoreCase (attributeName))
  12486. return att->value;
  12487. att = att->next;
  12488. }
  12489. return String::empty;
  12490. }
  12491. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12492. {
  12493. const XmlAttributeNode* att = attributes;
  12494. while (att != 0)
  12495. {
  12496. if (att->name.equalsIgnoreCase (attributeName))
  12497. return att->value;
  12498. att = att->next;
  12499. }
  12500. return defaultReturnValue;
  12501. }
  12502. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12503. {
  12504. const XmlAttributeNode* att = attributes;
  12505. while (att != 0)
  12506. {
  12507. if (att->name.equalsIgnoreCase (attributeName))
  12508. return att->value.getIntValue();
  12509. att = att->next;
  12510. }
  12511. return defaultReturnValue;
  12512. }
  12513. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12514. {
  12515. const XmlAttributeNode* att = attributes;
  12516. while (att != 0)
  12517. {
  12518. if (att->name.equalsIgnoreCase (attributeName))
  12519. return att->value.getDoubleValue();
  12520. att = att->next;
  12521. }
  12522. return defaultReturnValue;
  12523. }
  12524. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12525. {
  12526. const XmlAttributeNode* att = attributes;
  12527. while (att != 0)
  12528. {
  12529. if (att->name.equalsIgnoreCase (attributeName))
  12530. {
  12531. juce_wchar firstChar = att->value[0];
  12532. if (CharacterFunctions::isWhitespace (firstChar))
  12533. firstChar = att->value.trimStart() [0];
  12534. return firstChar == '1'
  12535. || firstChar == 't'
  12536. || firstChar == 'y'
  12537. || firstChar == 'T'
  12538. || firstChar == 'Y';
  12539. }
  12540. att = att->next;
  12541. }
  12542. return defaultReturnValue;
  12543. }
  12544. bool XmlElement::compareAttribute (const String& attributeName,
  12545. const String& stringToCompareAgainst,
  12546. const bool ignoreCase) const throw()
  12547. {
  12548. const XmlAttributeNode* att = attributes;
  12549. while (att != 0)
  12550. {
  12551. if (att->name.equalsIgnoreCase (attributeName))
  12552. {
  12553. if (ignoreCase)
  12554. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12555. else
  12556. return att->value == stringToCompareAgainst;
  12557. }
  12558. att = att->next;
  12559. }
  12560. return false;
  12561. }
  12562. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12563. {
  12564. #if JUCE_DEBUG
  12565. // check the identifier being passed in is legal..
  12566. const juce_wchar* t = attributeName;
  12567. while (*t != 0)
  12568. {
  12569. jassert (CharacterFunctions::isLetterOrDigit (*t)
  12570. || *t == '_'
  12571. || *t == '-'
  12572. || *t == ':');
  12573. ++t;
  12574. }
  12575. #endif
  12576. if (attributes == 0)
  12577. {
  12578. attributes = new XmlAttributeNode (attributeName, value);
  12579. }
  12580. else
  12581. {
  12582. XmlAttributeNode* att = attributes;
  12583. for (;;)
  12584. {
  12585. if (att->name.equalsIgnoreCase (attributeName))
  12586. {
  12587. att->value = value;
  12588. break;
  12589. }
  12590. else if (att->next == 0)
  12591. {
  12592. att->next = new XmlAttributeNode (attributeName, value);
  12593. break;
  12594. }
  12595. att = att->next;
  12596. }
  12597. }
  12598. }
  12599. void XmlElement::setAttribute (const String& attributeName, const int number)
  12600. {
  12601. setAttribute (attributeName, String (number));
  12602. }
  12603. void XmlElement::setAttribute (const String& attributeName, const double number)
  12604. {
  12605. setAttribute (attributeName, String (number));
  12606. }
  12607. void XmlElement::removeAttribute (const String& attributeName) throw()
  12608. {
  12609. XmlAttributeNode* att = attributes;
  12610. XmlAttributeNode* lastAtt = 0;
  12611. while (att != 0)
  12612. {
  12613. if (att->name.equalsIgnoreCase (attributeName))
  12614. {
  12615. if (lastAtt == 0)
  12616. attributes = att->next;
  12617. else
  12618. lastAtt->next = att->next;
  12619. delete att;
  12620. break;
  12621. }
  12622. lastAtt = att;
  12623. att = att->next;
  12624. }
  12625. }
  12626. void XmlElement::removeAllAttributes() throw()
  12627. {
  12628. while (attributes != 0)
  12629. {
  12630. XmlAttributeNode* const nextAtt = attributes->next;
  12631. delete attributes;
  12632. attributes = nextAtt;
  12633. }
  12634. }
  12635. int XmlElement::getNumChildElements() const throw()
  12636. {
  12637. int count = 0;
  12638. const XmlElement* child = firstChildElement;
  12639. while (child != 0)
  12640. {
  12641. ++count;
  12642. child = child->nextElement;
  12643. }
  12644. return count;
  12645. }
  12646. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12647. {
  12648. int count = 0;
  12649. XmlElement* child = firstChildElement;
  12650. while (child != 0 && count < index)
  12651. {
  12652. child = child->nextElement;
  12653. ++count;
  12654. }
  12655. return child;
  12656. }
  12657. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12658. {
  12659. XmlElement* child = firstChildElement;
  12660. while (child != 0)
  12661. {
  12662. if (child->hasTagName (childName))
  12663. break;
  12664. child = child->nextElement;
  12665. }
  12666. return child;
  12667. }
  12668. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12669. {
  12670. if (newNode != 0)
  12671. {
  12672. if (firstChildElement == 0)
  12673. {
  12674. firstChildElement = newNode;
  12675. }
  12676. else
  12677. {
  12678. XmlElement* child = firstChildElement;
  12679. while (child->nextElement != 0)
  12680. child = child->nextElement;
  12681. child->nextElement = newNode;
  12682. // if this is non-zero, then something's probably
  12683. // gone wrong..
  12684. jassert (newNode->nextElement == 0);
  12685. }
  12686. }
  12687. }
  12688. void XmlElement::insertChildElement (XmlElement* const newNode,
  12689. int indexToInsertAt) throw()
  12690. {
  12691. if (newNode != 0)
  12692. {
  12693. removeChildElement (newNode, false);
  12694. if (indexToInsertAt == 0)
  12695. {
  12696. newNode->nextElement = firstChildElement;
  12697. firstChildElement = newNode;
  12698. }
  12699. else
  12700. {
  12701. if (firstChildElement == 0)
  12702. {
  12703. firstChildElement = newNode;
  12704. }
  12705. else
  12706. {
  12707. if (indexToInsertAt < 0)
  12708. indexToInsertAt = std::numeric_limits<int>::max();
  12709. XmlElement* child = firstChildElement;
  12710. while (child->nextElement != 0 && --indexToInsertAt > 0)
  12711. child = child->nextElement;
  12712. newNode->nextElement = child->nextElement;
  12713. child->nextElement = newNode;
  12714. }
  12715. }
  12716. }
  12717. }
  12718. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12719. {
  12720. XmlElement* const newElement = new XmlElement (childTagName);
  12721. addChildElement (newElement);
  12722. return newElement;
  12723. }
  12724. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12725. XmlElement* const newNode) throw()
  12726. {
  12727. if (newNode != 0)
  12728. {
  12729. XmlElement* child = firstChildElement;
  12730. XmlElement* previousNode = 0;
  12731. while (child != 0)
  12732. {
  12733. if (child == currentChildElement)
  12734. {
  12735. if (child != newNode)
  12736. {
  12737. if (previousNode == 0)
  12738. firstChildElement = newNode;
  12739. else
  12740. previousNode->nextElement = newNode;
  12741. newNode->nextElement = child->nextElement;
  12742. delete child;
  12743. }
  12744. return true;
  12745. }
  12746. previousNode = child;
  12747. child = child->nextElement;
  12748. }
  12749. }
  12750. return false;
  12751. }
  12752. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12753. const bool shouldDeleteTheChild) throw()
  12754. {
  12755. if (childToRemove != 0)
  12756. {
  12757. if (firstChildElement == childToRemove)
  12758. {
  12759. firstChildElement = childToRemove->nextElement;
  12760. childToRemove->nextElement = 0;
  12761. }
  12762. else
  12763. {
  12764. XmlElement* child = firstChildElement;
  12765. XmlElement* last = 0;
  12766. while (child != 0)
  12767. {
  12768. if (child == childToRemove)
  12769. {
  12770. if (last == 0)
  12771. firstChildElement = child->nextElement;
  12772. else
  12773. last->nextElement = child->nextElement;
  12774. childToRemove->nextElement = 0;
  12775. break;
  12776. }
  12777. last = child;
  12778. child = child->nextElement;
  12779. }
  12780. }
  12781. if (shouldDeleteTheChild)
  12782. delete childToRemove;
  12783. }
  12784. }
  12785. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12786. const bool ignoreOrderOfAttributes) const throw()
  12787. {
  12788. if (this != other)
  12789. {
  12790. if (other == 0 || tagName != other->tagName)
  12791. {
  12792. return false;
  12793. }
  12794. if (ignoreOrderOfAttributes)
  12795. {
  12796. int totalAtts = 0;
  12797. const XmlAttributeNode* att = attributes;
  12798. while (att != 0)
  12799. {
  12800. if (! other->compareAttribute (att->name, att->value))
  12801. return false;
  12802. att = att->next;
  12803. ++totalAtts;
  12804. }
  12805. if (totalAtts != other->getNumAttributes())
  12806. return false;
  12807. }
  12808. else
  12809. {
  12810. const XmlAttributeNode* thisAtt = attributes;
  12811. const XmlAttributeNode* otherAtt = other->attributes;
  12812. for (;;)
  12813. {
  12814. if (thisAtt == 0 || otherAtt == 0)
  12815. {
  12816. if (thisAtt == otherAtt) // both 0, so it's a match
  12817. break;
  12818. return false;
  12819. }
  12820. if (thisAtt->name != otherAtt->name
  12821. || thisAtt->value != otherAtt->value)
  12822. {
  12823. return false;
  12824. }
  12825. thisAtt = thisAtt->next;
  12826. otherAtt = otherAtt->next;
  12827. }
  12828. }
  12829. const XmlElement* thisChild = firstChildElement;
  12830. const XmlElement* otherChild = other->firstChildElement;
  12831. for (;;)
  12832. {
  12833. if (thisChild == 0 || otherChild == 0)
  12834. {
  12835. if (thisChild == otherChild) // both 0, so it's a match
  12836. break;
  12837. return false;
  12838. }
  12839. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12840. return false;
  12841. thisChild = thisChild->nextElement;
  12842. otherChild = otherChild->nextElement;
  12843. }
  12844. }
  12845. return true;
  12846. }
  12847. void XmlElement::deleteAllChildElements() throw()
  12848. {
  12849. while (firstChildElement != 0)
  12850. {
  12851. XmlElement* const nextChild = firstChildElement->nextElement;
  12852. delete firstChildElement;
  12853. firstChildElement = nextChild;
  12854. }
  12855. }
  12856. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12857. {
  12858. XmlElement* child = firstChildElement;
  12859. while (child != 0)
  12860. {
  12861. if (child->hasTagName (name))
  12862. {
  12863. XmlElement* const nextChild = child->nextElement;
  12864. removeChildElement (child, true);
  12865. child = nextChild;
  12866. }
  12867. else
  12868. {
  12869. child = child->nextElement;
  12870. }
  12871. }
  12872. }
  12873. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12874. {
  12875. const XmlElement* child = firstChildElement;
  12876. while (child != 0)
  12877. {
  12878. if (child == possibleChild)
  12879. return true;
  12880. child = child->nextElement;
  12881. }
  12882. return false;
  12883. }
  12884. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12885. {
  12886. if (this == elementToLookFor || elementToLookFor == 0)
  12887. return 0;
  12888. XmlElement* child = firstChildElement;
  12889. while (child != 0)
  12890. {
  12891. if (elementToLookFor == child)
  12892. return this;
  12893. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12894. if (found != 0)
  12895. return found;
  12896. child = child->nextElement;
  12897. }
  12898. return 0;
  12899. }
  12900. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12901. {
  12902. XmlElement* e = firstChildElement;
  12903. while (e != 0)
  12904. {
  12905. *elems++ = e;
  12906. e = e->nextElement;
  12907. }
  12908. }
  12909. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12910. {
  12911. XmlElement* e = firstChildElement = elems[0];
  12912. for (int i = 1; i < num; ++i)
  12913. {
  12914. e->nextElement = elems[i];
  12915. e = e->nextElement;
  12916. }
  12917. e->nextElement = 0;
  12918. }
  12919. bool XmlElement::isTextElement() const throw()
  12920. {
  12921. return tagName.isEmpty();
  12922. }
  12923. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12924. const String& XmlElement::getText() const throw()
  12925. {
  12926. jassert (isTextElement()); // you're trying to get the text from an element that
  12927. // isn't actually a text element.. If this contains text sub-nodes, you
  12928. // probably want to use getAllSubText instead.
  12929. return getStringAttribute (juce_xmltextContentAttributeName);
  12930. }
  12931. void XmlElement::setText (const String& newText)
  12932. {
  12933. if (isTextElement())
  12934. setAttribute (juce_xmltextContentAttributeName, newText);
  12935. else
  12936. jassertfalse; // you can only change the text in a text element, not a normal one.
  12937. }
  12938. const String XmlElement::getAllSubText() const
  12939. {
  12940. String result;
  12941. String::Concatenator concatenator (result);
  12942. const XmlElement* child = firstChildElement;
  12943. while (child != 0)
  12944. {
  12945. if (child->isTextElement())
  12946. concatenator.append (child->getText());
  12947. child = child->nextElement;
  12948. }
  12949. return result;
  12950. }
  12951. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12952. const String& defaultReturnValue) const
  12953. {
  12954. const XmlElement* const child = getChildByName (childTagName);
  12955. if (child != 0)
  12956. return child->getAllSubText();
  12957. return defaultReturnValue;
  12958. }
  12959. XmlElement* XmlElement::createTextElement (const String& text)
  12960. {
  12961. XmlElement* const e = new XmlElement ((int) 0);
  12962. e->setAttribute (juce_xmltextContentAttributeName, text);
  12963. return e;
  12964. }
  12965. void XmlElement::addTextElement (const String& text)
  12966. {
  12967. addChildElement (createTextElement (text));
  12968. }
  12969. void XmlElement::deleteAllTextElements() throw()
  12970. {
  12971. XmlElement* child = firstChildElement;
  12972. while (child != 0)
  12973. {
  12974. XmlElement* const next = child->nextElement;
  12975. if (child->isTextElement())
  12976. removeChildElement (child, true);
  12977. child = next;
  12978. }
  12979. }
  12980. END_JUCE_NAMESPACE
  12981. /*** End of inlined file: juce_XmlElement.cpp ***/
  12982. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12983. BEGIN_JUCE_NAMESPACE
  12984. ReadWriteLock::ReadWriteLock() throw()
  12985. : numWaitingWriters (0),
  12986. numWriters (0),
  12987. writerThreadId (0)
  12988. {
  12989. }
  12990. ReadWriteLock::~ReadWriteLock() throw()
  12991. {
  12992. jassert (readerThreads.size() == 0);
  12993. jassert (numWriters == 0);
  12994. }
  12995. void ReadWriteLock::enterRead() const throw()
  12996. {
  12997. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12998. const ScopedLock sl (accessLock);
  12999. for (;;)
  13000. {
  13001. jassert (readerThreads.size() % 2 == 0);
  13002. int i;
  13003. for (i = 0; i < readerThreads.size(); i += 2)
  13004. if (readerThreads.getUnchecked(i) == threadId)
  13005. break;
  13006. if (i < readerThreads.size()
  13007. || numWriters + numWaitingWriters == 0
  13008. || (threadId == writerThreadId && numWriters > 0))
  13009. {
  13010. if (i < readerThreads.size())
  13011. {
  13012. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13013. }
  13014. else
  13015. {
  13016. readerThreads.add (threadId);
  13017. readerThreads.add ((Thread::ThreadID) 1);
  13018. }
  13019. return;
  13020. }
  13021. const ScopedUnlock ul (accessLock);
  13022. waitEvent.wait (100);
  13023. }
  13024. }
  13025. void ReadWriteLock::exitRead() const throw()
  13026. {
  13027. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13028. const ScopedLock sl (accessLock);
  13029. for (int i = 0; i < readerThreads.size(); i += 2)
  13030. {
  13031. if (readerThreads.getUnchecked(i) == threadId)
  13032. {
  13033. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13034. if (newCount == 0)
  13035. {
  13036. readerThreads.removeRange (i, 2);
  13037. waitEvent.signal();
  13038. }
  13039. else
  13040. {
  13041. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13042. }
  13043. return;
  13044. }
  13045. }
  13046. jassertfalse; // unlocking a lock that wasn't locked..
  13047. }
  13048. void ReadWriteLock::enterWrite() const throw()
  13049. {
  13050. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13051. const ScopedLock sl (accessLock);
  13052. for (;;)
  13053. {
  13054. if (readerThreads.size() + numWriters == 0
  13055. || threadId == writerThreadId
  13056. || (readerThreads.size() == 2
  13057. && readerThreads.getUnchecked(0) == threadId))
  13058. {
  13059. writerThreadId = threadId;
  13060. ++numWriters;
  13061. break;
  13062. }
  13063. ++numWaitingWriters;
  13064. accessLock.exit();
  13065. waitEvent.wait (100);
  13066. accessLock.enter();
  13067. --numWaitingWriters;
  13068. }
  13069. }
  13070. bool ReadWriteLock::tryEnterWrite() const throw()
  13071. {
  13072. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13073. const ScopedLock sl (accessLock);
  13074. if (readerThreads.size() + numWriters == 0
  13075. || threadId == writerThreadId
  13076. || (readerThreads.size() == 2
  13077. && readerThreads.getUnchecked(0) == threadId))
  13078. {
  13079. writerThreadId = threadId;
  13080. ++numWriters;
  13081. return true;
  13082. }
  13083. return false;
  13084. }
  13085. void ReadWriteLock::exitWrite() const throw()
  13086. {
  13087. const ScopedLock sl (accessLock);
  13088. // check this thread actually had the lock..
  13089. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13090. if (--numWriters == 0)
  13091. {
  13092. writerThreadId = 0;
  13093. waitEvent.signal();
  13094. }
  13095. }
  13096. END_JUCE_NAMESPACE
  13097. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13098. /*** Start of inlined file: juce_Thread.cpp ***/
  13099. BEGIN_JUCE_NAMESPACE
  13100. // these functions are implemented in the platform-specific code.
  13101. void* juce_createThread (void* userData);
  13102. void juce_killThread (void* handle);
  13103. bool juce_setThreadPriority (void* handle, int priority);
  13104. void juce_setCurrentThreadName (const String& name);
  13105. #if JUCE_WINDOWS
  13106. void juce_CloseThreadHandle (void* handle);
  13107. #endif
  13108. void Thread::threadEntryPoint (Thread* const thread)
  13109. {
  13110. {
  13111. const ScopedLock sl (runningThreadsLock);
  13112. runningThreads.add (thread);
  13113. }
  13114. JUCE_TRY
  13115. {
  13116. thread->threadId_ = Thread::getCurrentThreadId();
  13117. if (thread->threadName_.isNotEmpty())
  13118. juce_setCurrentThreadName (thread->threadName_);
  13119. if (thread->startSuspensionEvent_.wait (10000))
  13120. {
  13121. if (thread->affinityMask_ != 0)
  13122. setCurrentThreadAffinityMask (thread->affinityMask_);
  13123. thread->run();
  13124. }
  13125. }
  13126. JUCE_CATCH_ALL_ASSERT
  13127. {
  13128. const ScopedLock sl (runningThreadsLock);
  13129. jassert (runningThreads.contains (thread));
  13130. runningThreads.removeValue (thread);
  13131. }
  13132. #if JUCE_WINDOWS
  13133. juce_CloseThreadHandle (thread->threadHandle_);
  13134. #endif
  13135. thread->threadHandle_ = 0;
  13136. thread->threadId_ = 0;
  13137. }
  13138. // used to wrap the incoming call from the platform-specific code
  13139. void JUCE_API juce_threadEntryPoint (void* userData)
  13140. {
  13141. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13142. }
  13143. Thread::Thread (const String& threadName)
  13144. : threadName_ (threadName),
  13145. threadHandle_ (0),
  13146. threadPriority_ (5),
  13147. threadId_ (0),
  13148. affinityMask_ (0),
  13149. threadShouldExit_ (false)
  13150. {
  13151. }
  13152. Thread::~Thread()
  13153. {
  13154. stopThread (100);
  13155. }
  13156. void Thread::startThread()
  13157. {
  13158. const ScopedLock sl (startStopLock);
  13159. threadShouldExit_ = false;
  13160. if (threadHandle_ == 0)
  13161. {
  13162. threadHandle_ = juce_createThread (this);
  13163. juce_setThreadPriority (threadHandle_, threadPriority_);
  13164. startSuspensionEvent_.signal();
  13165. }
  13166. }
  13167. void Thread::startThread (const int priority)
  13168. {
  13169. const ScopedLock sl (startStopLock);
  13170. if (threadHandle_ == 0)
  13171. {
  13172. threadPriority_ = priority;
  13173. startThread();
  13174. }
  13175. else
  13176. {
  13177. setPriority (priority);
  13178. }
  13179. }
  13180. bool Thread::isThreadRunning() const
  13181. {
  13182. return threadHandle_ != 0;
  13183. }
  13184. void Thread::signalThreadShouldExit()
  13185. {
  13186. threadShouldExit_ = true;
  13187. }
  13188. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13189. {
  13190. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13191. jassert (getThreadId() != getCurrentThreadId());
  13192. const int sleepMsPerIteration = 5;
  13193. int count = timeOutMilliseconds / sleepMsPerIteration;
  13194. while (isThreadRunning())
  13195. {
  13196. if (timeOutMilliseconds > 0 && --count < 0)
  13197. return false;
  13198. sleep (sleepMsPerIteration);
  13199. }
  13200. return true;
  13201. }
  13202. void Thread::stopThread (const int timeOutMilliseconds)
  13203. {
  13204. // agh! You can't stop the thread that's calling this method! How on earth
  13205. // would that work??
  13206. jassert (getCurrentThreadId() != getThreadId());
  13207. const ScopedLock sl (startStopLock);
  13208. if (isThreadRunning())
  13209. {
  13210. signalThreadShouldExit();
  13211. notify();
  13212. if (timeOutMilliseconds != 0)
  13213. waitForThreadToExit (timeOutMilliseconds);
  13214. if (isThreadRunning())
  13215. {
  13216. // very bad karma if this point is reached, as
  13217. // there are bound to be locks and events left in
  13218. // silly states when a thread is killed by force..
  13219. jassertfalse;
  13220. Logger::writeToLog ("!! killing thread by force !!");
  13221. juce_killThread (threadHandle_);
  13222. threadHandle_ = 0;
  13223. threadId_ = 0;
  13224. const ScopedLock sl2 (runningThreadsLock);
  13225. runningThreads.removeValue (this);
  13226. }
  13227. }
  13228. }
  13229. bool Thread::setPriority (const int priority)
  13230. {
  13231. const ScopedLock sl (startStopLock);
  13232. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13233. if (worked)
  13234. threadPriority_ = priority;
  13235. return worked;
  13236. }
  13237. bool Thread::setCurrentThreadPriority (const int priority)
  13238. {
  13239. return juce_setThreadPriority (0, priority);
  13240. }
  13241. void Thread::setAffinityMask (const uint32 affinityMask)
  13242. {
  13243. affinityMask_ = affinityMask;
  13244. }
  13245. bool Thread::wait (const int timeOutMilliseconds) const
  13246. {
  13247. return defaultEvent_.wait (timeOutMilliseconds);
  13248. }
  13249. void Thread::notify() const
  13250. {
  13251. defaultEvent_.signal();
  13252. }
  13253. int Thread::getNumRunningThreads()
  13254. {
  13255. return runningThreads.size();
  13256. }
  13257. Thread* Thread::getCurrentThread()
  13258. {
  13259. const ThreadID thisId = getCurrentThreadId();
  13260. const ScopedLock sl (runningThreadsLock);
  13261. for (int i = runningThreads.size(); --i >= 0;)
  13262. {
  13263. Thread* const t = runningThreads.getUnchecked(i);
  13264. if (t->threadId_ == thisId)
  13265. return t;
  13266. }
  13267. return 0;
  13268. }
  13269. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13270. {
  13271. {
  13272. const ScopedLock sl (runningThreadsLock);
  13273. for (int i = runningThreads.size(); --i >= 0;)
  13274. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13275. }
  13276. for (;;)
  13277. {
  13278. Thread* firstThread;
  13279. {
  13280. const ScopedLock sl (runningThreadsLock);
  13281. firstThread = runningThreads.getFirst();
  13282. }
  13283. if (firstThread == 0)
  13284. break;
  13285. firstThread->stopThread (timeOutMilliseconds);
  13286. }
  13287. }
  13288. Array<Thread*> Thread::runningThreads;
  13289. CriticalSection Thread::runningThreadsLock;
  13290. END_JUCE_NAMESPACE
  13291. /*** End of inlined file: juce_Thread.cpp ***/
  13292. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13293. BEGIN_JUCE_NAMESPACE
  13294. ThreadPoolJob::ThreadPoolJob (const String& name)
  13295. : jobName (name),
  13296. pool (0),
  13297. shouldStop (false),
  13298. isActive (false),
  13299. shouldBeDeleted (false)
  13300. {
  13301. }
  13302. ThreadPoolJob::~ThreadPoolJob()
  13303. {
  13304. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13305. // to remove it first!
  13306. jassert (pool == 0 || ! pool->contains (this));
  13307. }
  13308. const String ThreadPoolJob::getJobName() const
  13309. {
  13310. return jobName;
  13311. }
  13312. void ThreadPoolJob::setJobName (const String& newName)
  13313. {
  13314. jobName = newName;
  13315. }
  13316. void ThreadPoolJob::signalJobShouldExit()
  13317. {
  13318. shouldStop = true;
  13319. }
  13320. class ThreadPool::ThreadPoolThread : public Thread
  13321. {
  13322. public:
  13323. ThreadPoolThread (ThreadPool& pool_)
  13324. : Thread ("Pool"),
  13325. pool (pool_),
  13326. busy (false)
  13327. {
  13328. }
  13329. ~ThreadPoolThread()
  13330. {
  13331. }
  13332. void run()
  13333. {
  13334. while (! threadShouldExit())
  13335. {
  13336. if (! pool.runNextJob())
  13337. wait (500);
  13338. }
  13339. }
  13340. private:
  13341. ThreadPool& pool;
  13342. bool volatile busy;
  13343. ThreadPoolThread (const ThreadPoolThread&);
  13344. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13345. };
  13346. ThreadPool::ThreadPool (const int numThreads,
  13347. const bool startThreadsOnlyWhenNeeded,
  13348. const int stopThreadsWhenNotUsedTimeoutMs)
  13349. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13350. priority (5)
  13351. {
  13352. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13353. for (int i = jmax (1, numThreads); --i >= 0;)
  13354. threads.add (new ThreadPoolThread (*this));
  13355. if (! startThreadsOnlyWhenNeeded)
  13356. for (int i = threads.size(); --i >= 0;)
  13357. threads.getUnchecked(i)->startThread (priority);
  13358. }
  13359. ThreadPool::~ThreadPool()
  13360. {
  13361. removeAllJobs (true, 4000);
  13362. int i;
  13363. for (i = threads.size(); --i >= 0;)
  13364. threads.getUnchecked(i)->signalThreadShouldExit();
  13365. for (i = threads.size(); --i >= 0;)
  13366. threads.getUnchecked(i)->stopThread (500);
  13367. }
  13368. void ThreadPool::addJob (ThreadPoolJob* const job)
  13369. {
  13370. jassert (job != 0);
  13371. jassert (job->pool == 0);
  13372. if (job->pool == 0)
  13373. {
  13374. job->pool = this;
  13375. job->shouldStop = false;
  13376. job->isActive = false;
  13377. {
  13378. const ScopedLock sl (lock);
  13379. jobs.add (job);
  13380. int numRunning = 0;
  13381. for (int i = threads.size(); --i >= 0;)
  13382. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13383. ++numRunning;
  13384. if (numRunning < threads.size())
  13385. {
  13386. bool startedOne = false;
  13387. int n = 1000;
  13388. while (--n >= 0 && ! startedOne)
  13389. {
  13390. for (int i = threads.size(); --i >= 0;)
  13391. {
  13392. if (! threads.getUnchecked(i)->isThreadRunning())
  13393. {
  13394. threads.getUnchecked(i)->startThread (priority);
  13395. startedOne = true;
  13396. break;
  13397. }
  13398. }
  13399. if (! startedOne)
  13400. Thread::sleep (2);
  13401. }
  13402. }
  13403. }
  13404. for (int i = threads.size(); --i >= 0;)
  13405. threads.getUnchecked(i)->notify();
  13406. }
  13407. }
  13408. int ThreadPool::getNumJobs() const
  13409. {
  13410. return jobs.size();
  13411. }
  13412. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13413. {
  13414. const ScopedLock sl (lock);
  13415. return jobs [index];
  13416. }
  13417. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13418. {
  13419. const ScopedLock sl (lock);
  13420. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13421. }
  13422. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13423. {
  13424. const ScopedLock sl (lock);
  13425. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13426. }
  13427. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13428. const int timeOutMs) const
  13429. {
  13430. if (job != 0)
  13431. {
  13432. const uint32 start = Time::getMillisecondCounter();
  13433. while (contains (job))
  13434. {
  13435. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13436. return false;
  13437. jobFinishedSignal.wait (2);
  13438. }
  13439. }
  13440. return true;
  13441. }
  13442. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13443. const bool interruptIfRunning,
  13444. const int timeOutMs)
  13445. {
  13446. bool dontWait = true;
  13447. if (job != 0)
  13448. {
  13449. const ScopedLock sl (lock);
  13450. if (jobs.contains (job))
  13451. {
  13452. if (job->isActive)
  13453. {
  13454. if (interruptIfRunning)
  13455. job->signalJobShouldExit();
  13456. dontWait = false;
  13457. }
  13458. else
  13459. {
  13460. jobs.removeValue (job);
  13461. job->pool = 0;
  13462. }
  13463. }
  13464. }
  13465. return dontWait || waitForJobToFinish (job, timeOutMs);
  13466. }
  13467. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13468. const int timeOutMs,
  13469. const bool deleteInactiveJobs,
  13470. ThreadPool::JobSelector* selectedJobsToRemove)
  13471. {
  13472. Array <ThreadPoolJob*> jobsToWaitFor;
  13473. {
  13474. const ScopedLock sl (lock);
  13475. for (int i = jobs.size(); --i >= 0;)
  13476. {
  13477. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13478. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13479. {
  13480. if (job->isActive)
  13481. {
  13482. jobsToWaitFor.add (job);
  13483. if (interruptRunningJobs)
  13484. job->signalJobShouldExit();
  13485. }
  13486. else
  13487. {
  13488. jobs.remove (i);
  13489. if (deleteInactiveJobs)
  13490. delete job;
  13491. else
  13492. job->pool = 0;
  13493. }
  13494. }
  13495. }
  13496. }
  13497. const uint32 start = Time::getMillisecondCounter();
  13498. for (;;)
  13499. {
  13500. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13501. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13502. jobsToWaitFor.remove (i);
  13503. if (jobsToWaitFor.size() == 0)
  13504. break;
  13505. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13506. return false;
  13507. jobFinishedSignal.wait (20);
  13508. }
  13509. return true;
  13510. }
  13511. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13512. {
  13513. StringArray s;
  13514. const ScopedLock sl (lock);
  13515. for (int i = 0; i < jobs.size(); ++i)
  13516. {
  13517. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13518. if (job->isActive || ! onlyReturnActiveJobs)
  13519. s.add (job->getJobName());
  13520. }
  13521. return s;
  13522. }
  13523. bool ThreadPool::setThreadPriorities (const int newPriority)
  13524. {
  13525. bool ok = true;
  13526. if (priority != newPriority)
  13527. {
  13528. priority = newPriority;
  13529. for (int i = threads.size(); --i >= 0;)
  13530. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13531. ok = false;
  13532. }
  13533. return ok;
  13534. }
  13535. bool ThreadPool::runNextJob()
  13536. {
  13537. ThreadPoolJob* job = 0;
  13538. {
  13539. const ScopedLock sl (lock);
  13540. for (int i = 0; i < jobs.size(); ++i)
  13541. {
  13542. job = jobs[i];
  13543. if (job != 0 && ! (job->isActive || job->shouldStop))
  13544. break;
  13545. job = 0;
  13546. }
  13547. if (job != 0)
  13548. job->isActive = true;
  13549. }
  13550. if (job != 0)
  13551. {
  13552. JUCE_TRY
  13553. {
  13554. ThreadPoolJob::JobStatus result = job->runJob();
  13555. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13556. const ScopedLock sl (lock);
  13557. if (jobs.contains (job))
  13558. {
  13559. job->isActive = false;
  13560. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13561. {
  13562. job->pool = 0;
  13563. job->shouldStop = true;
  13564. jobs.removeValue (job);
  13565. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13566. delete job;
  13567. jobFinishedSignal.signal();
  13568. }
  13569. else
  13570. {
  13571. // move the job to the end of the queue if it wants another go
  13572. jobs.move (jobs.indexOf (job), -1);
  13573. }
  13574. }
  13575. }
  13576. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13577. catch (...)
  13578. {
  13579. const ScopedLock sl (lock);
  13580. jobs.removeValue (job);
  13581. }
  13582. #endif
  13583. }
  13584. else
  13585. {
  13586. if (threadStopTimeout > 0
  13587. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13588. {
  13589. const ScopedLock sl (lock);
  13590. if (jobs.size() == 0)
  13591. for (int i = threads.size(); --i >= 0;)
  13592. threads.getUnchecked(i)->signalThreadShouldExit();
  13593. }
  13594. else
  13595. {
  13596. return false;
  13597. }
  13598. }
  13599. return true;
  13600. }
  13601. END_JUCE_NAMESPACE
  13602. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13603. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13604. BEGIN_JUCE_NAMESPACE
  13605. TimeSliceThread::TimeSliceThread (const String& threadName)
  13606. : Thread (threadName),
  13607. index (0),
  13608. clientBeingCalled (0),
  13609. clientsChanged (false)
  13610. {
  13611. }
  13612. TimeSliceThread::~TimeSliceThread()
  13613. {
  13614. stopThread (2000);
  13615. }
  13616. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13617. {
  13618. const ScopedLock sl (listLock);
  13619. clients.addIfNotAlreadyThere (client);
  13620. clientsChanged = true;
  13621. notify();
  13622. }
  13623. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13624. {
  13625. const ScopedLock sl1 (listLock);
  13626. clientsChanged = true;
  13627. // if there's a chance we're in the middle of calling this client, we need to
  13628. // also lock the outer lock..
  13629. if (clientBeingCalled == client)
  13630. {
  13631. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13632. const ScopedLock sl2 (callbackLock);
  13633. const ScopedLock sl3 (listLock);
  13634. clients.removeValue (client);
  13635. }
  13636. else
  13637. {
  13638. clients.removeValue (client);
  13639. }
  13640. }
  13641. int TimeSliceThread::getNumClients() const
  13642. {
  13643. return clients.size();
  13644. }
  13645. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13646. {
  13647. const ScopedLock sl (listLock);
  13648. return clients [i];
  13649. }
  13650. void TimeSliceThread::run()
  13651. {
  13652. int numCallsSinceBusy = 0;
  13653. while (! threadShouldExit())
  13654. {
  13655. int timeToWait = 500;
  13656. {
  13657. const ScopedLock sl (callbackLock);
  13658. {
  13659. const ScopedLock sl2 (listLock);
  13660. if (clients.size() > 0)
  13661. {
  13662. index = (index + 1) % clients.size();
  13663. clientBeingCalled = clients [index];
  13664. }
  13665. else
  13666. {
  13667. index = 0;
  13668. clientBeingCalled = 0;
  13669. }
  13670. if (clientsChanged)
  13671. {
  13672. clientsChanged = false;
  13673. numCallsSinceBusy = 0;
  13674. }
  13675. }
  13676. if (clientBeingCalled != 0)
  13677. {
  13678. if (clientBeingCalled->useTimeSlice())
  13679. numCallsSinceBusy = 0;
  13680. else
  13681. ++numCallsSinceBusy;
  13682. if (numCallsSinceBusy >= clients.size())
  13683. timeToWait = 500;
  13684. else if (index == 0)
  13685. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13686. else
  13687. timeToWait = 0;
  13688. }
  13689. }
  13690. if (timeToWait > 0)
  13691. wait (timeToWait);
  13692. }
  13693. }
  13694. END_JUCE_NAMESPACE
  13695. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13696. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13697. BEGIN_JUCE_NAMESPACE
  13698. DeletedAtShutdown::DeletedAtShutdown()
  13699. {
  13700. const ScopedLock sl (getLock());
  13701. getObjects().add (this);
  13702. }
  13703. DeletedAtShutdown::~DeletedAtShutdown()
  13704. {
  13705. const ScopedLock sl (getLock());
  13706. getObjects().removeValue (this);
  13707. }
  13708. void DeletedAtShutdown::deleteAll()
  13709. {
  13710. // make a local copy of the array, so it can't get into a loop if something
  13711. // creates another DeletedAtShutdown object during its destructor.
  13712. Array <DeletedAtShutdown*> localCopy;
  13713. {
  13714. const ScopedLock sl (getLock());
  13715. localCopy = getObjects();
  13716. }
  13717. for (int i = localCopy.size(); --i >= 0;)
  13718. {
  13719. JUCE_TRY
  13720. {
  13721. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13722. // double-check that it's not already been deleted during another object's destructor.
  13723. {
  13724. const ScopedLock sl (getLock());
  13725. if (! getObjects().contains (deletee))
  13726. deletee = 0;
  13727. }
  13728. delete deletee;
  13729. }
  13730. JUCE_CATCH_EXCEPTION
  13731. }
  13732. // if no objects got re-created during shutdown, this should have been emptied by their
  13733. // destructors
  13734. jassert (getObjects().size() == 0);
  13735. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13736. }
  13737. CriticalSection& DeletedAtShutdown::getLock()
  13738. {
  13739. static CriticalSection lock;
  13740. return lock;
  13741. }
  13742. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13743. {
  13744. static Array <DeletedAtShutdown*> objects;
  13745. return objects;
  13746. }
  13747. END_JUCE_NAMESPACE
  13748. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13749. #endif
  13750. #if JUCE_BUILD_MISC
  13751. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13752. BEGIN_JUCE_NAMESPACE
  13753. class ValueTree::SetPropertyAction : public UndoableAction
  13754. {
  13755. public:
  13756. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13757. const var& newValue_, const var& oldValue_,
  13758. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13759. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13760. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13761. {
  13762. }
  13763. ~SetPropertyAction() {}
  13764. bool perform()
  13765. {
  13766. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13767. if (isDeletingProperty)
  13768. target->removeProperty (name, 0);
  13769. else
  13770. target->setProperty (name, newValue, 0);
  13771. return true;
  13772. }
  13773. bool undo()
  13774. {
  13775. if (isAddingNewProperty)
  13776. target->removeProperty (name, 0);
  13777. else
  13778. target->setProperty (name, oldValue, 0);
  13779. return true;
  13780. }
  13781. int getSizeInUnits()
  13782. {
  13783. return (int) sizeof (*this); //xxx should be more accurate
  13784. }
  13785. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13786. {
  13787. if (! (isAddingNewProperty || isDeletingProperty))
  13788. {
  13789. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13790. if (next != 0 && next->target == target && next->name == name
  13791. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13792. {
  13793. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13794. }
  13795. }
  13796. return 0;
  13797. }
  13798. private:
  13799. const SharedObjectPtr target;
  13800. const Identifier name;
  13801. const var newValue;
  13802. var oldValue;
  13803. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13804. SetPropertyAction (const SetPropertyAction&);
  13805. SetPropertyAction& operator= (const SetPropertyAction&);
  13806. };
  13807. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13808. {
  13809. public:
  13810. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13811. const SharedObjectPtr& newChild_)
  13812. : target (target_),
  13813. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13814. childIndex (childIndex_),
  13815. isDeleting (newChild_ == 0)
  13816. {
  13817. jassert (child != 0);
  13818. }
  13819. ~AddOrRemoveChildAction() {}
  13820. bool perform()
  13821. {
  13822. if (isDeleting)
  13823. target->removeChild (childIndex, 0);
  13824. else
  13825. target->addChild (child, childIndex, 0);
  13826. return true;
  13827. }
  13828. bool undo()
  13829. {
  13830. if (isDeleting)
  13831. {
  13832. target->addChild (child, childIndex, 0);
  13833. }
  13834. else
  13835. {
  13836. // If you hit this, it seems that your object's state is getting confused - probably
  13837. // because you've interleaved some undoable and non-undoable operations?
  13838. jassert (childIndex < target->children.size());
  13839. target->removeChild (childIndex, 0);
  13840. }
  13841. return true;
  13842. }
  13843. int getSizeInUnits()
  13844. {
  13845. return (int) sizeof (*this); //xxx should be more accurate
  13846. }
  13847. private:
  13848. const SharedObjectPtr target, child;
  13849. const int childIndex;
  13850. const bool isDeleting;
  13851. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13852. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13853. };
  13854. class ValueTree::MoveChildAction : public UndoableAction
  13855. {
  13856. public:
  13857. MoveChildAction (const SharedObjectPtr& parent_,
  13858. const int startIndex_, const int endIndex_)
  13859. : parent (parent_),
  13860. startIndex (startIndex_),
  13861. endIndex (endIndex_)
  13862. {
  13863. }
  13864. ~MoveChildAction() {}
  13865. bool perform()
  13866. {
  13867. parent->moveChild (startIndex, endIndex, 0);
  13868. return true;
  13869. }
  13870. bool undo()
  13871. {
  13872. parent->moveChild (endIndex, startIndex, 0);
  13873. return true;
  13874. }
  13875. int getSizeInUnits()
  13876. {
  13877. return (int) sizeof (*this); //xxx should be more accurate
  13878. }
  13879. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13880. {
  13881. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13882. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13883. return new MoveChildAction (parent, startIndex, next->endIndex);
  13884. return 0;
  13885. }
  13886. private:
  13887. const SharedObjectPtr parent;
  13888. const int startIndex, endIndex;
  13889. MoveChildAction (const MoveChildAction&);
  13890. MoveChildAction& operator= (const MoveChildAction&);
  13891. };
  13892. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13893. : type (type_), parent (0)
  13894. {
  13895. }
  13896. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13897. : type (other.type), properties (other.properties), parent (0)
  13898. {
  13899. for (int i = 0; i < other.children.size(); ++i)
  13900. {
  13901. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13902. child->parent = this;
  13903. children.add (child);
  13904. }
  13905. }
  13906. ValueTree::SharedObject::~SharedObject()
  13907. {
  13908. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13909. for (int i = children.size(); --i >= 0;)
  13910. {
  13911. const SharedObjectPtr c (children.getUnchecked(i));
  13912. c->parent = 0;
  13913. children.remove (i);
  13914. c->sendParentChangeMessage();
  13915. }
  13916. }
  13917. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13918. {
  13919. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13920. {
  13921. ValueTree* const v = valueTreesWithListeners[i];
  13922. if (v != 0)
  13923. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13924. }
  13925. }
  13926. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13927. {
  13928. ValueTree tree (this);
  13929. ValueTree::SharedObject* t = this;
  13930. while (t != 0)
  13931. {
  13932. t->sendPropertyChangeMessage (tree, property);
  13933. t = t->parent;
  13934. }
  13935. }
  13936. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13937. {
  13938. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13939. {
  13940. ValueTree* const v = valueTreesWithListeners[i];
  13941. if (v != 0)
  13942. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13943. }
  13944. }
  13945. void ValueTree::SharedObject::sendChildChangeMessage()
  13946. {
  13947. ValueTree tree (this);
  13948. ValueTree::SharedObject* t = this;
  13949. while (t != 0)
  13950. {
  13951. t->sendChildChangeMessage (tree);
  13952. t = t->parent;
  13953. }
  13954. }
  13955. void ValueTree::SharedObject::sendParentChangeMessage()
  13956. {
  13957. ValueTree tree (this);
  13958. int i;
  13959. for (i = children.size(); --i >= 0;)
  13960. {
  13961. SharedObject* const t = children[i];
  13962. if (t != 0)
  13963. t->sendParentChangeMessage();
  13964. }
  13965. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13966. {
  13967. ValueTree* const v = valueTreesWithListeners[i];
  13968. if (v != 0)
  13969. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13970. }
  13971. }
  13972. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13973. {
  13974. return properties [name];
  13975. }
  13976. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13977. {
  13978. return properties.getWithDefault (name, defaultReturnValue);
  13979. }
  13980. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13981. {
  13982. if (undoManager == 0)
  13983. {
  13984. if (properties.set (name, newValue))
  13985. sendPropertyChangeMessage (name);
  13986. }
  13987. else
  13988. {
  13989. var* const existingValue = properties.getItem (name);
  13990. if (existingValue != 0)
  13991. {
  13992. if (*existingValue != newValue)
  13993. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13994. }
  13995. else
  13996. {
  13997. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13998. }
  13999. }
  14000. }
  14001. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14002. {
  14003. return properties.contains (name);
  14004. }
  14005. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14006. {
  14007. if (undoManager == 0)
  14008. {
  14009. if (properties.remove (name))
  14010. sendPropertyChangeMessage (name);
  14011. }
  14012. else
  14013. {
  14014. if (properties.contains (name))
  14015. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14016. }
  14017. }
  14018. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14019. {
  14020. if (undoManager == 0)
  14021. {
  14022. while (properties.size() > 0)
  14023. {
  14024. const Identifier name (properties.getName (properties.size() - 1));
  14025. properties.remove (name);
  14026. sendPropertyChangeMessage (name);
  14027. }
  14028. }
  14029. else
  14030. {
  14031. for (int i = properties.size(); --i >= 0;)
  14032. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14033. }
  14034. }
  14035. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14036. {
  14037. for (int i = 0; i < children.size(); ++i)
  14038. if (children.getUnchecked(i)->type == typeToMatch)
  14039. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14040. return ValueTree::invalid;
  14041. }
  14042. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14043. {
  14044. for (int i = 0; i < children.size(); ++i)
  14045. if (children.getUnchecked(i)->type == typeToMatch)
  14046. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14047. SharedObject* const newObject = new SharedObject (typeToMatch);
  14048. addChild (newObject, -1, undoManager);
  14049. return ValueTree (newObject);
  14050. }
  14051. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14052. {
  14053. for (int i = 0; i < children.size(); ++i)
  14054. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14055. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14056. return ValueTree::invalid;
  14057. }
  14058. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14059. {
  14060. const SharedObject* p = parent;
  14061. while (p != 0)
  14062. {
  14063. if (p == possibleParent)
  14064. return true;
  14065. p = p->parent;
  14066. }
  14067. return false;
  14068. }
  14069. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14070. {
  14071. return children.indexOf (child.object);
  14072. }
  14073. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14074. {
  14075. if (child != 0 && child->parent != this)
  14076. {
  14077. if (child != this && ! isAChildOf (child))
  14078. {
  14079. // You should always make sure that a child is removed from its previous parent before
  14080. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14081. // undomanager should be used when removing it from its current parent..
  14082. jassert (child->parent == 0);
  14083. if (child->parent != 0)
  14084. {
  14085. jassert (child->parent->children.indexOf (child) >= 0);
  14086. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14087. }
  14088. if (undoManager == 0)
  14089. {
  14090. children.insert (index, child);
  14091. child->parent = this;
  14092. sendChildChangeMessage();
  14093. child->sendParentChangeMessage();
  14094. }
  14095. else
  14096. {
  14097. if (index < 0)
  14098. index = children.size();
  14099. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14100. }
  14101. }
  14102. else
  14103. {
  14104. // You're attempting to create a recursive loop! A node
  14105. // can't be a child of one of its own children!
  14106. jassertfalse;
  14107. }
  14108. }
  14109. }
  14110. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14111. {
  14112. const SharedObjectPtr child (children [childIndex]);
  14113. if (child != 0)
  14114. {
  14115. if (undoManager == 0)
  14116. {
  14117. children.remove (childIndex);
  14118. child->parent = 0;
  14119. sendChildChangeMessage();
  14120. child->sendParentChangeMessage();
  14121. }
  14122. else
  14123. {
  14124. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14125. }
  14126. }
  14127. }
  14128. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14129. {
  14130. while (children.size() > 0)
  14131. removeChild (children.size() - 1, undoManager);
  14132. }
  14133. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14134. {
  14135. // The source index must be a valid index!
  14136. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14137. if (currentIndex != newIndex
  14138. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14139. {
  14140. if (undoManager == 0)
  14141. {
  14142. children.move (currentIndex, newIndex);
  14143. sendChildChangeMessage();
  14144. }
  14145. else
  14146. {
  14147. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14148. newIndex = children.size() - 1;
  14149. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14150. }
  14151. }
  14152. }
  14153. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14154. {
  14155. if (type != other.type
  14156. || properties.size() != other.properties.size()
  14157. || children.size() != other.children.size()
  14158. || properties != other.properties)
  14159. return false;
  14160. for (int i = 0; i < children.size(); ++i)
  14161. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14162. return false;
  14163. return true;
  14164. }
  14165. ValueTree::ValueTree() throw()
  14166. : object (0)
  14167. {
  14168. }
  14169. const ValueTree ValueTree::invalid;
  14170. ValueTree::ValueTree (const Identifier& type_)
  14171. : object (new ValueTree::SharedObject (type_))
  14172. {
  14173. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14174. }
  14175. ValueTree::ValueTree (SharedObject* const object_)
  14176. : object (object_)
  14177. {
  14178. }
  14179. ValueTree::ValueTree (const ValueTree& other)
  14180. : object (other.object)
  14181. {
  14182. }
  14183. ValueTree& ValueTree::operator= (const ValueTree& other)
  14184. {
  14185. if (listeners.size() > 0)
  14186. {
  14187. if (object != 0)
  14188. object->valueTreesWithListeners.removeValue (this);
  14189. if (other.object != 0)
  14190. other.object->valueTreesWithListeners.add (this);
  14191. }
  14192. object = other.object;
  14193. return *this;
  14194. }
  14195. ValueTree::~ValueTree()
  14196. {
  14197. if (listeners.size() > 0 && object != 0)
  14198. object->valueTreesWithListeners.removeValue (this);
  14199. }
  14200. bool ValueTree::operator== (const ValueTree& other) const throw()
  14201. {
  14202. return object == other.object;
  14203. }
  14204. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14205. {
  14206. return object != other.object;
  14207. }
  14208. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14209. {
  14210. return object == other.object
  14211. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14212. }
  14213. ValueTree ValueTree::createCopy() const
  14214. {
  14215. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14216. }
  14217. bool ValueTree::hasType (const Identifier& typeName) const
  14218. {
  14219. return object != 0 && object->type == typeName;
  14220. }
  14221. const Identifier ValueTree::getType() const
  14222. {
  14223. return object != 0 ? object->type : Identifier();
  14224. }
  14225. ValueTree ValueTree::getParent() const
  14226. {
  14227. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14228. }
  14229. ValueTree ValueTree::getSibling (const int delta) const
  14230. {
  14231. if (object == 0 || object->parent == 0)
  14232. return invalid;
  14233. const int index = object->parent->indexOf (*this) + delta;
  14234. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14235. }
  14236. const var& ValueTree::operator[] (const Identifier& name) const
  14237. {
  14238. return object == 0 ? var::null : object->getProperty (name);
  14239. }
  14240. const var& ValueTree::getProperty (const Identifier& name) const
  14241. {
  14242. return object == 0 ? var::null : object->getProperty (name);
  14243. }
  14244. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14245. {
  14246. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14247. }
  14248. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14249. {
  14250. jassert (name.toString().isNotEmpty());
  14251. if (object != 0 && name.toString().isNotEmpty())
  14252. object->setProperty (name, newValue, undoManager);
  14253. }
  14254. bool ValueTree::hasProperty (const Identifier& name) const
  14255. {
  14256. return object != 0 && object->hasProperty (name);
  14257. }
  14258. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14259. {
  14260. if (object != 0)
  14261. object->removeProperty (name, undoManager);
  14262. }
  14263. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14264. {
  14265. if (object != 0)
  14266. object->removeAllProperties (undoManager);
  14267. }
  14268. int ValueTree::getNumProperties() const
  14269. {
  14270. return object == 0 ? 0 : object->properties.size();
  14271. }
  14272. const Identifier ValueTree::getPropertyName (const int index) const
  14273. {
  14274. return object == 0 ? Identifier()
  14275. : object->properties.getName (index);
  14276. }
  14277. class ValueTreePropertyValueSource : public Value::ValueSource,
  14278. public ValueTree::Listener
  14279. {
  14280. public:
  14281. ValueTreePropertyValueSource (const ValueTree& tree_,
  14282. const Identifier& property_,
  14283. UndoManager* const undoManager_)
  14284. : tree (tree_),
  14285. property (property_),
  14286. undoManager (undoManager_)
  14287. {
  14288. tree.addListener (this);
  14289. }
  14290. ~ValueTreePropertyValueSource()
  14291. {
  14292. tree.removeListener (this);
  14293. }
  14294. const var getValue() const
  14295. {
  14296. return tree [property];
  14297. }
  14298. void setValue (const var& newValue)
  14299. {
  14300. tree.setProperty (property, newValue, undoManager);
  14301. }
  14302. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14303. {
  14304. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14305. sendChangeMessage (false);
  14306. }
  14307. void valueTreeChildrenChanged (ValueTree&) {}
  14308. void valueTreeParentChanged (ValueTree&) {}
  14309. private:
  14310. ValueTree tree;
  14311. const Identifier property;
  14312. UndoManager* const undoManager;
  14313. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14314. };
  14315. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14316. {
  14317. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14318. }
  14319. int ValueTree::getNumChildren() const
  14320. {
  14321. return object == 0 ? 0 : object->children.size();
  14322. }
  14323. ValueTree ValueTree::getChild (int index) const
  14324. {
  14325. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14326. }
  14327. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14328. {
  14329. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14330. }
  14331. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14332. {
  14333. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14334. }
  14335. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14336. {
  14337. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14338. }
  14339. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14340. {
  14341. return object != 0 && object->isAChildOf (possibleParent.object);
  14342. }
  14343. int ValueTree::indexOf (const ValueTree& child) const
  14344. {
  14345. return object != 0 ? object->indexOf (child) : -1;
  14346. }
  14347. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14348. {
  14349. if (object != 0)
  14350. object->addChild (child.object, index, undoManager);
  14351. }
  14352. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14353. {
  14354. if (object != 0)
  14355. object->removeChild (childIndex, undoManager);
  14356. }
  14357. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14358. {
  14359. if (object != 0)
  14360. object->removeChild (object->children.indexOf (child.object), undoManager);
  14361. }
  14362. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14363. {
  14364. if (object != 0)
  14365. object->removeAllChildren (undoManager);
  14366. }
  14367. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14368. {
  14369. if (object != 0)
  14370. object->moveChild (currentIndex, newIndex, undoManager);
  14371. }
  14372. void ValueTree::addListener (Listener* listener)
  14373. {
  14374. if (listener != 0)
  14375. {
  14376. if (listeners.size() == 0 && object != 0)
  14377. object->valueTreesWithListeners.add (this);
  14378. listeners.add (listener);
  14379. }
  14380. }
  14381. void ValueTree::removeListener (Listener* listener)
  14382. {
  14383. listeners.remove (listener);
  14384. if (listeners.size() == 0 && object != 0)
  14385. object->valueTreesWithListeners.removeValue (this);
  14386. }
  14387. XmlElement* ValueTree::SharedObject::createXml() const
  14388. {
  14389. XmlElement* xml = new XmlElement (type.toString());
  14390. int i;
  14391. for (i = 0; i < properties.size(); ++i)
  14392. {
  14393. Identifier name (properties.getName(i));
  14394. const var& v = properties [name];
  14395. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14396. xml->setAttribute (name.toString(), v.toString());
  14397. }
  14398. for (i = 0; i < children.size(); ++i)
  14399. xml->addChildElement (children.getUnchecked(i)->createXml());
  14400. return xml;
  14401. }
  14402. XmlElement* ValueTree::createXml() const
  14403. {
  14404. return object != 0 ? object->createXml() : 0;
  14405. }
  14406. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14407. {
  14408. ValueTree v (xml.getTagName());
  14409. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14410. for (int i = 0; i < numAtts; ++i)
  14411. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14412. forEachXmlChildElement (xml, e)
  14413. {
  14414. v.addChild (fromXml (*e), -1, 0);
  14415. }
  14416. return v;
  14417. }
  14418. void ValueTree::writeToStream (OutputStream& output)
  14419. {
  14420. output.writeString (getType().toString());
  14421. const int numProps = getNumProperties();
  14422. output.writeCompressedInt (numProps);
  14423. int i;
  14424. for (i = 0; i < numProps; ++i)
  14425. {
  14426. const Identifier name (getPropertyName(i));
  14427. output.writeString (name.toString());
  14428. getProperty(name).writeToStream (output);
  14429. }
  14430. const int numChildren = getNumChildren();
  14431. output.writeCompressedInt (numChildren);
  14432. for (i = 0; i < numChildren; ++i)
  14433. getChild (i).writeToStream (output);
  14434. }
  14435. ValueTree ValueTree::readFromStream (InputStream& input)
  14436. {
  14437. const String type (input.readString());
  14438. if (type.isEmpty())
  14439. return ValueTree::invalid;
  14440. ValueTree v (type);
  14441. const int numProps = input.readCompressedInt();
  14442. if (numProps < 0)
  14443. {
  14444. jassertfalse; // trying to read corrupted data!
  14445. return v;
  14446. }
  14447. int i;
  14448. for (i = 0; i < numProps; ++i)
  14449. {
  14450. const String name (input.readString());
  14451. jassert (name.isNotEmpty());
  14452. const var value (var::readFromStream (input));
  14453. v.setProperty (name, value, 0);
  14454. }
  14455. const int numChildren = input.readCompressedInt();
  14456. for (i = 0; i < numChildren; ++i)
  14457. v.addChild (readFromStream (input), -1, 0);
  14458. return v;
  14459. }
  14460. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14461. {
  14462. MemoryInputStream in (data, numBytes, false);
  14463. return readFromStream (in);
  14464. }
  14465. END_JUCE_NAMESPACE
  14466. /*** End of inlined file: juce_ValueTree.cpp ***/
  14467. /*** Start of inlined file: juce_Value.cpp ***/
  14468. BEGIN_JUCE_NAMESPACE
  14469. Value::ValueSource::ValueSource()
  14470. {
  14471. }
  14472. Value::ValueSource::~ValueSource()
  14473. {
  14474. }
  14475. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14476. {
  14477. if (synchronous)
  14478. {
  14479. for (int i = valuesWithListeners.size(); --i >= 0;)
  14480. {
  14481. Value* const v = valuesWithListeners[i];
  14482. if (v != 0)
  14483. v->callListeners();
  14484. }
  14485. }
  14486. else
  14487. {
  14488. triggerAsyncUpdate();
  14489. }
  14490. }
  14491. void Value::ValueSource::handleAsyncUpdate()
  14492. {
  14493. sendChangeMessage (true);
  14494. }
  14495. class SimpleValueSource : public Value::ValueSource
  14496. {
  14497. public:
  14498. SimpleValueSource()
  14499. {
  14500. }
  14501. SimpleValueSource (const var& initialValue)
  14502. : value (initialValue)
  14503. {
  14504. }
  14505. ~SimpleValueSource()
  14506. {
  14507. }
  14508. const var getValue() const
  14509. {
  14510. return value;
  14511. }
  14512. void setValue (const var& newValue)
  14513. {
  14514. if (newValue != value)
  14515. {
  14516. value = newValue;
  14517. sendChangeMessage (false);
  14518. }
  14519. }
  14520. private:
  14521. var value;
  14522. SimpleValueSource (const SimpleValueSource&);
  14523. SimpleValueSource& operator= (const SimpleValueSource&);
  14524. };
  14525. Value::Value()
  14526. : value (new SimpleValueSource())
  14527. {
  14528. }
  14529. Value::Value (ValueSource* const value_)
  14530. : value (value_)
  14531. {
  14532. jassert (value_ != 0);
  14533. }
  14534. Value::Value (const var& initialValue)
  14535. : value (new SimpleValueSource (initialValue))
  14536. {
  14537. }
  14538. Value::Value (const Value& other)
  14539. : value (other.value)
  14540. {
  14541. }
  14542. Value& Value::operator= (const Value& other)
  14543. {
  14544. value = other.value;
  14545. return *this;
  14546. }
  14547. Value::~Value()
  14548. {
  14549. if (listeners.size() > 0)
  14550. value->valuesWithListeners.removeValue (this);
  14551. }
  14552. const var Value::getValue() const
  14553. {
  14554. return value->getValue();
  14555. }
  14556. Value::operator const var() const
  14557. {
  14558. return getValue();
  14559. }
  14560. void Value::setValue (const var& newValue)
  14561. {
  14562. value->setValue (newValue);
  14563. }
  14564. const String Value::toString() const
  14565. {
  14566. return value->getValue().toString();
  14567. }
  14568. Value& Value::operator= (const var& newValue)
  14569. {
  14570. value->setValue (newValue);
  14571. return *this;
  14572. }
  14573. void Value::referTo (const Value& valueToReferTo)
  14574. {
  14575. if (valueToReferTo.value != value)
  14576. {
  14577. if (listeners.size() > 0)
  14578. {
  14579. value->valuesWithListeners.removeValue (this);
  14580. valueToReferTo.value->valuesWithListeners.add (this);
  14581. }
  14582. value = valueToReferTo.value;
  14583. callListeners();
  14584. }
  14585. }
  14586. bool Value::refersToSameSourceAs (const Value& other) const
  14587. {
  14588. return value == other.value;
  14589. }
  14590. bool Value::operator== (const Value& other) const
  14591. {
  14592. return value == other.value || value->getValue() == other.getValue();
  14593. }
  14594. bool Value::operator!= (const Value& other) const
  14595. {
  14596. return value != other.value && value->getValue() != other.getValue();
  14597. }
  14598. void Value::addListener (Listener* const listener)
  14599. {
  14600. if (listener != 0)
  14601. {
  14602. if (listeners.size() == 0)
  14603. value->valuesWithListeners.add (this);
  14604. listeners.add (listener);
  14605. }
  14606. }
  14607. void Value::removeListener (Listener* const listener)
  14608. {
  14609. listeners.remove (listener);
  14610. if (listeners.size() == 0)
  14611. value->valuesWithListeners.removeValue (this);
  14612. }
  14613. void Value::callListeners()
  14614. {
  14615. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14616. listeners.call (&Value::Listener::valueChanged, v);
  14617. }
  14618. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14619. {
  14620. return stream << value.toString();
  14621. }
  14622. END_JUCE_NAMESPACE
  14623. /*** End of inlined file: juce_Value.cpp ***/
  14624. /*** Start of inlined file: juce_Application.cpp ***/
  14625. BEGIN_JUCE_NAMESPACE
  14626. #if JUCE_MAC
  14627. extern void juce_initialiseMacMainMenu();
  14628. #endif
  14629. JUCEApplication::JUCEApplication()
  14630. : appReturnValue (0),
  14631. stillInitialising (true)
  14632. {
  14633. jassert (isStandaloneApp() && appInstance == 0);
  14634. appInstance = this;
  14635. }
  14636. JUCEApplication::~JUCEApplication()
  14637. {
  14638. if (appLock != 0)
  14639. {
  14640. appLock->exit();
  14641. appLock = 0;
  14642. }
  14643. jassert (appInstance == this);
  14644. appInstance = 0;
  14645. }
  14646. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14647. JUCEApplication* JUCEApplication::appInstance = 0;
  14648. bool JUCEApplication::moreThanOneInstanceAllowed()
  14649. {
  14650. return true;
  14651. }
  14652. void JUCEApplication::anotherInstanceStarted (const String&)
  14653. {
  14654. }
  14655. void JUCEApplication::systemRequestedQuit()
  14656. {
  14657. quit();
  14658. }
  14659. void JUCEApplication::quit()
  14660. {
  14661. MessageManager::getInstance()->stopDispatchLoop();
  14662. }
  14663. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14664. {
  14665. appReturnValue = newReturnValue;
  14666. }
  14667. void JUCEApplication::actionListenerCallback (const String& message)
  14668. {
  14669. if (message.startsWith (getApplicationName() + "/"))
  14670. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14671. }
  14672. void JUCEApplication::unhandledException (const std::exception*,
  14673. const String&,
  14674. const int)
  14675. {
  14676. jassertfalse;
  14677. }
  14678. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14679. const char* const sourceFile,
  14680. const int lineNumber)
  14681. {
  14682. if (appInstance != 0)
  14683. appInstance->unhandledException (e, sourceFile, lineNumber);
  14684. }
  14685. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14686. {
  14687. return 0;
  14688. }
  14689. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14690. {
  14691. commands.add (StandardApplicationCommandIDs::quit);
  14692. }
  14693. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14694. {
  14695. if (commandID == StandardApplicationCommandIDs::quit)
  14696. {
  14697. result.setInfo (TRANS("Quit"),
  14698. TRANS("Quits the application"),
  14699. "Application",
  14700. 0);
  14701. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14702. }
  14703. }
  14704. bool JUCEApplication::perform (const InvocationInfo& info)
  14705. {
  14706. if (info.commandID == StandardApplicationCommandIDs::quit)
  14707. {
  14708. systemRequestedQuit();
  14709. return true;
  14710. }
  14711. return false;
  14712. }
  14713. bool JUCEApplication::initialiseApp (const String& commandLine)
  14714. {
  14715. commandLineParameters = commandLine.trim();
  14716. #if ! JUCE_IOS
  14717. jassert (appLock == 0); // initialiseApp must only be called once!
  14718. if (! moreThanOneInstanceAllowed())
  14719. {
  14720. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14721. if (! appLock->enter(0))
  14722. {
  14723. appLock = 0;
  14724. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14725. DBG ("Another instance is running - quitting...");
  14726. return false;
  14727. }
  14728. }
  14729. #endif
  14730. // let the app do its setting-up..
  14731. initialise (commandLineParameters);
  14732. #if JUCE_MAC
  14733. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14734. #endif
  14735. // register for broadcast new app messages
  14736. MessageManager::getInstance()->registerBroadcastListener (this);
  14737. stillInitialising = false;
  14738. return true;
  14739. }
  14740. int JUCEApplication::shutdownApp()
  14741. {
  14742. jassert (appInstance == this);
  14743. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14744. JUCE_TRY
  14745. {
  14746. // give the app a chance to clean up..
  14747. shutdown();
  14748. }
  14749. JUCE_CATCH_EXCEPTION
  14750. return getApplicationReturnValue();
  14751. }
  14752. int JUCEApplication::main (const String& commandLine)
  14753. {
  14754. ScopedJuceInitialiser_GUI libraryInitialiser;
  14755. jassert (createInstance != 0);
  14756. const ScopedPointer<JUCEApplication> app (createInstance());
  14757. if (! app->initialiseApp (commandLine))
  14758. return 0;
  14759. JUCE_TRY
  14760. {
  14761. // loop until a quit message is received..
  14762. MessageManager::getInstance()->runDispatchLoop();
  14763. }
  14764. JUCE_CATCH_EXCEPTION
  14765. return app->shutdownApp();
  14766. }
  14767. #if JUCE_IOS
  14768. extern int juce_iOSMain (int argc, const char* argv[]);
  14769. #endif
  14770. #if ! JUCE_WINDOWS
  14771. extern const char* juce_Argv0;
  14772. #endif
  14773. int JUCEApplication::main (int argc, const char* argv[])
  14774. {
  14775. JUCE_AUTORELEASEPOOL
  14776. #if ! JUCE_WINDOWS
  14777. jassert (createInstance != 0);
  14778. juce_Argv0 = argv[0];
  14779. #endif
  14780. #if JUCE_IOS
  14781. return juce_iOSMain (argc, argv);
  14782. #else
  14783. String cmd;
  14784. for (int i = 1; i < argc; ++i)
  14785. cmd << argv[i] << ' ';
  14786. return JUCEApplication::main (cmd);
  14787. #endif
  14788. }
  14789. END_JUCE_NAMESPACE
  14790. /*** End of inlined file: juce_Application.cpp ***/
  14791. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14792. BEGIN_JUCE_NAMESPACE
  14793. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14794. : commandID (commandID_),
  14795. flags (0)
  14796. {
  14797. }
  14798. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14799. const String& description_,
  14800. const String& categoryName_,
  14801. const int flags_) throw()
  14802. {
  14803. shortName = shortName_;
  14804. description = description_;
  14805. categoryName = categoryName_;
  14806. flags = flags_;
  14807. }
  14808. void ApplicationCommandInfo::setActive (const bool b) throw()
  14809. {
  14810. if (b)
  14811. flags &= ~isDisabled;
  14812. else
  14813. flags |= isDisabled;
  14814. }
  14815. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14816. {
  14817. if (b)
  14818. flags |= isTicked;
  14819. else
  14820. flags &= ~isTicked;
  14821. }
  14822. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14823. {
  14824. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14825. }
  14826. END_JUCE_NAMESPACE
  14827. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14828. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14829. BEGIN_JUCE_NAMESPACE
  14830. ApplicationCommandManager::ApplicationCommandManager()
  14831. : firstTarget (0)
  14832. {
  14833. keyMappings = new KeyPressMappingSet (this);
  14834. Desktop::getInstance().addFocusChangeListener (this);
  14835. }
  14836. ApplicationCommandManager::~ApplicationCommandManager()
  14837. {
  14838. Desktop::getInstance().removeFocusChangeListener (this);
  14839. keyMappings = 0;
  14840. }
  14841. void ApplicationCommandManager::clearCommands()
  14842. {
  14843. commands.clear();
  14844. keyMappings->clearAllKeyPresses();
  14845. triggerAsyncUpdate();
  14846. }
  14847. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14848. {
  14849. // zero isn't a valid command ID!
  14850. jassert (newCommand.commandID != 0);
  14851. // the name isn't optional!
  14852. jassert (newCommand.shortName.isNotEmpty());
  14853. if (getCommandForID (newCommand.commandID) == 0)
  14854. {
  14855. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14856. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14857. commands.add (newInfo);
  14858. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14859. triggerAsyncUpdate();
  14860. }
  14861. else
  14862. {
  14863. // trying to re-register the same command with different parameters?
  14864. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14865. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14866. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14867. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14868. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14869. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14870. }
  14871. }
  14872. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14873. {
  14874. if (target != 0)
  14875. {
  14876. Array <CommandID> commandIDs;
  14877. target->getAllCommands (commandIDs);
  14878. for (int i = 0; i < commandIDs.size(); ++i)
  14879. {
  14880. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14881. target->getCommandInfo (info.commandID, info);
  14882. registerCommand (info);
  14883. }
  14884. }
  14885. }
  14886. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14887. {
  14888. for (int i = commands.size(); --i >= 0;)
  14889. {
  14890. if (commands.getUnchecked (i)->commandID == commandID)
  14891. {
  14892. commands.remove (i);
  14893. triggerAsyncUpdate();
  14894. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14895. for (int j = keys.size(); --j >= 0;)
  14896. keyMappings->removeKeyPress (keys.getReference (j));
  14897. }
  14898. }
  14899. }
  14900. void ApplicationCommandManager::commandStatusChanged()
  14901. {
  14902. triggerAsyncUpdate();
  14903. }
  14904. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14905. {
  14906. for (int i = commands.size(); --i >= 0;)
  14907. if (commands.getUnchecked(i)->commandID == commandID)
  14908. return commands.getUnchecked(i);
  14909. return 0;
  14910. }
  14911. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14912. {
  14913. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14914. return (ci != 0) ? ci->shortName : String::empty;
  14915. }
  14916. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14917. {
  14918. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14919. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14920. : String::empty;
  14921. }
  14922. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14923. {
  14924. StringArray s;
  14925. for (int i = 0; i < commands.size(); ++i)
  14926. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14927. return s;
  14928. }
  14929. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14930. {
  14931. Array <CommandID> results;
  14932. for (int i = 0; i < commands.size(); ++i)
  14933. if (commands.getUnchecked(i)->categoryName == categoryName)
  14934. results.add (commands.getUnchecked(i)->commandID);
  14935. return results;
  14936. }
  14937. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14938. {
  14939. ApplicationCommandTarget::InvocationInfo info (commandID);
  14940. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14941. return invoke (info, asynchronously);
  14942. }
  14943. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14944. {
  14945. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14946. // manager first..
  14947. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14948. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14949. if (target == 0)
  14950. return false;
  14951. ApplicationCommandInfo commandInfo (0);
  14952. target->getCommandInfo (info_.commandID, commandInfo);
  14953. ApplicationCommandTarget::InvocationInfo info (info_);
  14954. info.commandFlags = commandInfo.flags;
  14955. sendListenerInvokeCallback (info);
  14956. const bool ok = target->invoke (info, asynchronously);
  14957. commandStatusChanged();
  14958. return ok;
  14959. }
  14960. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14961. {
  14962. return firstTarget != 0 ? firstTarget
  14963. : findDefaultComponentTarget();
  14964. }
  14965. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14966. {
  14967. firstTarget = newTarget;
  14968. }
  14969. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14970. ApplicationCommandInfo& upToDateInfo)
  14971. {
  14972. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14973. if (target == 0)
  14974. target = JUCEApplication::getInstance();
  14975. if (target != 0)
  14976. target = target->getTargetForCommand (commandID);
  14977. if (target != 0)
  14978. target->getCommandInfo (commandID, upToDateInfo);
  14979. return target;
  14980. }
  14981. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14982. {
  14983. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14984. if (target == 0 && c != 0)
  14985. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14986. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14987. return target;
  14988. }
  14989. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14990. {
  14991. Component* c = Component::getCurrentlyFocusedComponent();
  14992. if (c == 0)
  14993. {
  14994. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14995. if (activeWindow != 0)
  14996. {
  14997. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14998. if (c == 0)
  14999. c = activeWindow;
  15000. }
  15001. }
  15002. if (c == 0 && Process::isForegroundProcess())
  15003. {
  15004. // getting a bit desperate now - try all desktop comps..
  15005. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15006. {
  15007. ApplicationCommandTarget* const target
  15008. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15009. ->getPeer()->getLastFocusedSubcomponent());
  15010. if (target != 0)
  15011. return target;
  15012. }
  15013. }
  15014. if (c != 0)
  15015. {
  15016. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15017. // if we're focused on a ResizableWindow, chances are that it's the content
  15018. // component that really should get the event. And if not, the event will
  15019. // still be passed up to the top level window anyway, so let's send it to the
  15020. // content comp.
  15021. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15022. c = resizableWindow->getContentComponent();
  15023. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15024. if (target != 0)
  15025. return target;
  15026. }
  15027. return JUCEApplication::getInstance();
  15028. }
  15029. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  15030. {
  15031. listeners.add (listener);
  15032. }
  15033. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  15034. {
  15035. listeners.remove (listener);
  15036. }
  15037. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15038. {
  15039. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15040. }
  15041. void ApplicationCommandManager::handleAsyncUpdate()
  15042. {
  15043. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15044. }
  15045. void ApplicationCommandManager::globalFocusChanged (Component*)
  15046. {
  15047. commandStatusChanged();
  15048. }
  15049. END_JUCE_NAMESPACE
  15050. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15051. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15052. BEGIN_JUCE_NAMESPACE
  15053. ApplicationCommandTarget::ApplicationCommandTarget()
  15054. {
  15055. }
  15056. ApplicationCommandTarget::~ApplicationCommandTarget()
  15057. {
  15058. messageInvoker = 0;
  15059. }
  15060. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15061. {
  15062. if (isCommandActive (info.commandID))
  15063. {
  15064. if (async)
  15065. {
  15066. if (messageInvoker == 0)
  15067. messageInvoker = new CommandTargetMessageInvoker (this);
  15068. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15069. return true;
  15070. }
  15071. else
  15072. {
  15073. const bool success = perform (info);
  15074. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15075. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15076. // returns the command's info.
  15077. return success;
  15078. }
  15079. }
  15080. return false;
  15081. }
  15082. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15083. {
  15084. Component* c = dynamic_cast <Component*> (this);
  15085. if (c != 0)
  15086. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15087. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15088. return 0;
  15089. }
  15090. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15091. {
  15092. ApplicationCommandTarget* target = this;
  15093. int depth = 0;
  15094. while (target != 0)
  15095. {
  15096. Array <CommandID> commandIDs;
  15097. target->getAllCommands (commandIDs);
  15098. if (commandIDs.contains (commandID))
  15099. return target;
  15100. target = target->getNextCommandTarget();
  15101. ++depth;
  15102. jassert (depth < 100); // could be a recursive command chain??
  15103. jassert (target != this); // definitely a recursive command chain!
  15104. if (depth > 100 || target == this)
  15105. break;
  15106. }
  15107. if (target == 0)
  15108. {
  15109. target = JUCEApplication::getInstance();
  15110. if (target != 0)
  15111. {
  15112. Array <CommandID> commandIDs;
  15113. target->getAllCommands (commandIDs);
  15114. if (commandIDs.contains (commandID))
  15115. return target;
  15116. }
  15117. }
  15118. return 0;
  15119. }
  15120. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15121. {
  15122. ApplicationCommandInfo info (commandID);
  15123. info.flags = ApplicationCommandInfo::isDisabled;
  15124. getCommandInfo (commandID, info);
  15125. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15126. }
  15127. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15128. {
  15129. ApplicationCommandTarget* target = this;
  15130. int depth = 0;
  15131. while (target != 0)
  15132. {
  15133. if (target->tryToInvoke (info, async))
  15134. return true;
  15135. target = target->getNextCommandTarget();
  15136. ++depth;
  15137. jassert (depth < 100); // could be a recursive command chain??
  15138. jassert (target != this); // definitely a recursive command chain!
  15139. if (depth > 100 || target == this)
  15140. break;
  15141. }
  15142. if (target == 0)
  15143. {
  15144. target = JUCEApplication::getInstance();
  15145. if (target != 0)
  15146. return target->tryToInvoke (info, async);
  15147. }
  15148. return false;
  15149. }
  15150. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15151. {
  15152. ApplicationCommandTarget::InvocationInfo info (commandID);
  15153. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15154. return invoke (info, asynchronously);
  15155. }
  15156. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  15157. : commandID (commandID_),
  15158. commandFlags (0),
  15159. invocationMethod (direct),
  15160. originatingComponent (0),
  15161. isKeyDown (false),
  15162. millisecsSinceKeyPressed (0)
  15163. {
  15164. }
  15165. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15166. : owner (owner_)
  15167. {
  15168. }
  15169. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15170. {
  15171. }
  15172. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15173. {
  15174. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15175. owner->tryToInvoke (*info, false);
  15176. }
  15177. END_JUCE_NAMESPACE
  15178. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15179. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15180. BEGIN_JUCE_NAMESPACE
  15181. juce_ImplementSingleton (ApplicationProperties)
  15182. ApplicationProperties::ApplicationProperties()
  15183. : msBeforeSaving (3000),
  15184. options (PropertiesFile::storeAsBinary),
  15185. commonSettingsAreReadOnly (0),
  15186. processLock (0)
  15187. {
  15188. }
  15189. ApplicationProperties::~ApplicationProperties()
  15190. {
  15191. closeFiles();
  15192. clearSingletonInstance();
  15193. }
  15194. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15195. const String& fileNameSuffix,
  15196. const String& folderName_,
  15197. const int millisecondsBeforeSaving,
  15198. const int propertiesFileOptions,
  15199. InterProcessLock* processLock_)
  15200. {
  15201. appName = applicationName;
  15202. fileSuffix = fileNameSuffix;
  15203. folderName = folderName_;
  15204. msBeforeSaving = millisecondsBeforeSaving;
  15205. options = propertiesFileOptions;
  15206. processLock = processLock_;
  15207. }
  15208. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15209. const bool testCommonSettings,
  15210. const bool showWarningDialogOnFailure)
  15211. {
  15212. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15213. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15214. if (! (userOk && commonOk))
  15215. {
  15216. if (showWarningDialogOnFailure)
  15217. {
  15218. String filenames;
  15219. if (userProps != 0 && ! userOk)
  15220. filenames << '\n' << userProps->getFile().getFullPathName();
  15221. if (commonProps != 0 && ! commonOk)
  15222. filenames << '\n' << commonProps->getFile().getFullPathName();
  15223. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15224. appName + TRANS(" - Unable to save settings"),
  15225. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15226. + appName + TRANS(" needs to be able to write to the following files:\n")
  15227. + filenames
  15228. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15229. }
  15230. return false;
  15231. }
  15232. return true;
  15233. }
  15234. void ApplicationProperties::openFiles()
  15235. {
  15236. // You need to call setStorageParameters() before trying to get hold of the
  15237. // properties!
  15238. jassert (appName.isNotEmpty());
  15239. if (appName.isNotEmpty())
  15240. {
  15241. if (userProps == 0)
  15242. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15243. false, msBeforeSaving, options, processLock);
  15244. if (commonProps == 0)
  15245. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15246. true, msBeforeSaving, options, processLock);
  15247. userProps->setFallbackPropertySet (commonProps);
  15248. }
  15249. }
  15250. PropertiesFile* ApplicationProperties::getUserSettings()
  15251. {
  15252. if (userProps == 0)
  15253. openFiles();
  15254. return userProps;
  15255. }
  15256. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15257. {
  15258. if (commonProps == 0)
  15259. openFiles();
  15260. if (returnUserPropsIfReadOnly)
  15261. {
  15262. if (commonSettingsAreReadOnly == 0)
  15263. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15264. if (commonSettingsAreReadOnly > 0)
  15265. return userProps;
  15266. }
  15267. return commonProps;
  15268. }
  15269. bool ApplicationProperties::saveIfNeeded()
  15270. {
  15271. return (userProps == 0 || userProps->saveIfNeeded())
  15272. && (commonProps == 0 || commonProps->saveIfNeeded());
  15273. }
  15274. void ApplicationProperties::closeFiles()
  15275. {
  15276. userProps = 0;
  15277. commonProps = 0;
  15278. }
  15279. END_JUCE_NAMESPACE
  15280. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15281. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15282. BEGIN_JUCE_NAMESPACE
  15283. namespace PropertyFileConstants
  15284. {
  15285. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15286. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15287. static const char* const fileTag = "PROPERTIES";
  15288. static const char* const valueTag = "VALUE";
  15289. static const char* const nameAttribute = "name";
  15290. static const char* const valueAttribute = "val";
  15291. }
  15292. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15293. const int options_, InterProcessLock* const processLock_)
  15294. : PropertySet (ignoreCaseOfKeyNames),
  15295. file (f),
  15296. timerInterval (millisecondsBeforeSaving),
  15297. options (options_),
  15298. loadedOk (false),
  15299. needsWriting (false),
  15300. processLock (processLock_)
  15301. {
  15302. // You need to correctly specify just one storage format for the file
  15303. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15304. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15305. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15306. ProcessScopedLock pl (createProcessLock());
  15307. if (pl != 0 && ! pl->isLocked())
  15308. return; // locking failure..
  15309. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15310. if (fileStream != 0)
  15311. {
  15312. int magicNumber = fileStream->readInt();
  15313. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15314. {
  15315. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15316. magicNumber = PropertyFileConstants::magicNumber;
  15317. }
  15318. if (magicNumber == PropertyFileConstants::magicNumber)
  15319. {
  15320. loadedOk = true;
  15321. BufferedInputStream in (fileStream.release(), 2048, true);
  15322. int numValues = in.readInt();
  15323. while (--numValues >= 0 && ! in.isExhausted())
  15324. {
  15325. const String key (in.readString());
  15326. const String value (in.readString());
  15327. jassert (key.isNotEmpty());
  15328. if (key.isNotEmpty())
  15329. getAllProperties().set (key, value);
  15330. }
  15331. }
  15332. else
  15333. {
  15334. // Not a binary props file - let's see if it's XML..
  15335. fileStream = 0;
  15336. XmlDocument parser (f);
  15337. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15338. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15339. {
  15340. doc = parser.getDocumentElement();
  15341. if (doc != 0)
  15342. {
  15343. loadedOk = true;
  15344. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15345. {
  15346. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15347. if (name.isNotEmpty())
  15348. {
  15349. getAllProperties().set (name,
  15350. e->getFirstChildElement() != 0
  15351. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15352. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15353. }
  15354. }
  15355. }
  15356. else
  15357. {
  15358. // must be a pretty broken XML file we're trying to parse here,
  15359. // or a sign that this object needs an InterProcessLock,
  15360. // or just a failure reading the file. This last reason is why
  15361. // we don't jassertfalse here.
  15362. }
  15363. }
  15364. }
  15365. }
  15366. else
  15367. {
  15368. loadedOk = ! f.exists();
  15369. }
  15370. }
  15371. PropertiesFile::~PropertiesFile()
  15372. {
  15373. if (! saveIfNeeded())
  15374. jassertfalse;
  15375. }
  15376. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15377. {
  15378. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15379. }
  15380. bool PropertiesFile::saveIfNeeded()
  15381. {
  15382. const ScopedLock sl (getLock());
  15383. return (! needsWriting) || save();
  15384. }
  15385. bool PropertiesFile::needsToBeSaved() const
  15386. {
  15387. const ScopedLock sl (getLock());
  15388. return needsWriting;
  15389. }
  15390. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15391. {
  15392. const ScopedLock sl (getLock());
  15393. needsWriting = needsToBeSaved_;
  15394. }
  15395. bool PropertiesFile::save()
  15396. {
  15397. const ScopedLock sl (getLock());
  15398. stopTimer();
  15399. if (file == File::nonexistent
  15400. || file.isDirectory()
  15401. || ! file.getParentDirectory().createDirectory())
  15402. return false;
  15403. if ((options & storeAsXML) != 0)
  15404. {
  15405. XmlElement doc (PropertyFileConstants::fileTag);
  15406. for (int i = 0; i < getAllProperties().size(); ++i)
  15407. {
  15408. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15409. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15410. // if the value seems to contain xml, store it as such..
  15411. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  15412. XmlElement* const childElement = xmlContent.getDocumentElement();
  15413. if (childElement != 0)
  15414. e->addChildElement (childElement);
  15415. else
  15416. e->setAttribute (PropertyFileConstants::valueAttribute,
  15417. getAllProperties().getAllValues() [i]);
  15418. }
  15419. ProcessScopedLock pl (createProcessLock());
  15420. if (pl != 0 && ! pl->isLocked())
  15421. return false; // locking failure..
  15422. if (doc.writeToFile (file, String::empty))
  15423. {
  15424. needsWriting = false;
  15425. return true;
  15426. }
  15427. }
  15428. else
  15429. {
  15430. ProcessScopedLock pl (createProcessLock());
  15431. if (pl != 0 && ! pl->isLocked())
  15432. return false; // locking failure..
  15433. TemporaryFile tempFile (file);
  15434. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15435. if (out != 0)
  15436. {
  15437. if ((options & storeAsCompressedBinary) != 0)
  15438. {
  15439. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15440. out->flush();
  15441. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15442. }
  15443. else
  15444. {
  15445. // have you set up the storage option flags correctly?
  15446. jassert ((options & storeAsBinary) != 0);
  15447. out->writeInt (PropertyFileConstants::magicNumber);
  15448. }
  15449. const int numProperties = getAllProperties().size();
  15450. out->writeInt (numProperties);
  15451. for (int i = 0; i < numProperties; ++i)
  15452. {
  15453. out->writeString (getAllProperties().getAllKeys() [i]);
  15454. out->writeString (getAllProperties().getAllValues() [i]);
  15455. }
  15456. out = 0;
  15457. if (tempFile.overwriteTargetFileWithTemporary())
  15458. {
  15459. needsWriting = false;
  15460. return true;
  15461. }
  15462. }
  15463. }
  15464. return false;
  15465. }
  15466. void PropertiesFile::timerCallback()
  15467. {
  15468. saveIfNeeded();
  15469. }
  15470. void PropertiesFile::propertyChanged()
  15471. {
  15472. sendChangeMessage (this);
  15473. needsWriting = true;
  15474. if (timerInterval > 0)
  15475. startTimer (timerInterval);
  15476. else if (timerInterval == 0)
  15477. saveIfNeeded();
  15478. }
  15479. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15480. const String& fileNameSuffix,
  15481. const String& folderName,
  15482. const bool commonToAllUsers)
  15483. {
  15484. // mustn't have illegal characters in this name..
  15485. jassert (applicationName == File::createLegalFileName (applicationName));
  15486. #if JUCE_MAC || JUCE_IOS
  15487. File dir (commonToAllUsers ? "/Library/Preferences"
  15488. : "~/Library/Preferences");
  15489. if (folderName.isNotEmpty())
  15490. dir = dir.getChildFile (folderName);
  15491. #endif
  15492. #ifdef JUCE_LINUX
  15493. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15494. + (folderName.isNotEmpty() ? folderName
  15495. : ("." + applicationName)));
  15496. #endif
  15497. #if JUCE_WINDOWS
  15498. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15499. : File::userApplicationDataDirectory));
  15500. if (dir == File::nonexistent)
  15501. return File::nonexistent;
  15502. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15503. : applicationName);
  15504. #endif
  15505. return dir.getChildFile (applicationName)
  15506. .withFileExtension (fileNameSuffix);
  15507. }
  15508. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15509. const String& fileNameSuffix,
  15510. const String& folderName,
  15511. const bool commonToAllUsers,
  15512. const int millisecondsBeforeSaving,
  15513. const int propertiesFileOptions,
  15514. InterProcessLock* processLock_)
  15515. {
  15516. const File file (getDefaultAppSettingsFile (applicationName,
  15517. fileNameSuffix,
  15518. folderName,
  15519. commonToAllUsers));
  15520. jassert (file != File::nonexistent);
  15521. if (file == File::nonexistent)
  15522. return 0;
  15523. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15524. }
  15525. END_JUCE_NAMESPACE
  15526. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15527. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15528. BEGIN_JUCE_NAMESPACE
  15529. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15530. const String& fileWildcard_,
  15531. const String& openFileDialogTitle_,
  15532. const String& saveFileDialogTitle_)
  15533. : changedSinceSave (false),
  15534. fileExtension (fileExtension_),
  15535. fileWildcard (fileWildcard_),
  15536. openFileDialogTitle (openFileDialogTitle_),
  15537. saveFileDialogTitle (saveFileDialogTitle_)
  15538. {
  15539. }
  15540. FileBasedDocument::~FileBasedDocument()
  15541. {
  15542. }
  15543. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15544. {
  15545. if (changedSinceSave != hasChanged)
  15546. {
  15547. changedSinceSave = hasChanged;
  15548. sendChangeMessage (this);
  15549. }
  15550. }
  15551. void FileBasedDocument::changed()
  15552. {
  15553. changedSinceSave = true;
  15554. sendChangeMessage (this);
  15555. }
  15556. void FileBasedDocument::setFile (const File& newFile)
  15557. {
  15558. if (documentFile != newFile)
  15559. {
  15560. documentFile = newFile;
  15561. changed();
  15562. }
  15563. }
  15564. bool FileBasedDocument::loadFrom (const File& newFile,
  15565. const bool showMessageOnFailure)
  15566. {
  15567. MouseCursor::showWaitCursor();
  15568. const File oldFile (documentFile);
  15569. documentFile = newFile;
  15570. String error;
  15571. if (newFile.existsAsFile())
  15572. {
  15573. error = loadDocument (newFile);
  15574. if (error.isEmpty())
  15575. {
  15576. setChangedFlag (false);
  15577. MouseCursor::hideWaitCursor();
  15578. setLastDocumentOpened (newFile);
  15579. return true;
  15580. }
  15581. }
  15582. else
  15583. {
  15584. error = "The file doesn't exist";
  15585. }
  15586. documentFile = oldFile;
  15587. MouseCursor::hideWaitCursor();
  15588. if (showMessageOnFailure)
  15589. {
  15590. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15591. TRANS("Failed to open file..."),
  15592. TRANS("There was an error while trying to load the file:\n\n")
  15593. + newFile.getFullPathName()
  15594. + "\n\n"
  15595. + error);
  15596. }
  15597. return false;
  15598. }
  15599. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15600. {
  15601. FileChooser fc (openFileDialogTitle,
  15602. getLastDocumentOpened(),
  15603. fileWildcard);
  15604. if (fc.browseForFileToOpen())
  15605. return loadFrom (fc.getResult(), showMessageOnFailure);
  15606. return false;
  15607. }
  15608. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15609. const bool showMessageOnFailure)
  15610. {
  15611. return saveAs (documentFile,
  15612. false,
  15613. askUserForFileIfNotSpecified,
  15614. showMessageOnFailure);
  15615. }
  15616. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15617. const bool warnAboutOverwritingExistingFiles,
  15618. const bool askUserForFileIfNotSpecified,
  15619. const bool showMessageOnFailure)
  15620. {
  15621. if (newFile == File::nonexistent)
  15622. {
  15623. if (askUserForFileIfNotSpecified)
  15624. {
  15625. return saveAsInteractive (true);
  15626. }
  15627. else
  15628. {
  15629. // can't save to an unspecified file
  15630. jassertfalse;
  15631. return failedToWriteToFile;
  15632. }
  15633. }
  15634. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15635. {
  15636. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15637. TRANS("File already exists"),
  15638. TRANS("There's already a file called:\n\n")
  15639. + newFile.getFullPathName()
  15640. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15641. TRANS("overwrite"),
  15642. TRANS("cancel")))
  15643. {
  15644. return userCancelledSave;
  15645. }
  15646. }
  15647. MouseCursor::showWaitCursor();
  15648. const File oldFile (documentFile);
  15649. documentFile = newFile;
  15650. String error (saveDocument (newFile));
  15651. if (error.isEmpty())
  15652. {
  15653. setChangedFlag (false);
  15654. MouseCursor::hideWaitCursor();
  15655. return savedOk;
  15656. }
  15657. documentFile = oldFile;
  15658. MouseCursor::hideWaitCursor();
  15659. if (showMessageOnFailure)
  15660. {
  15661. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15662. TRANS("Error writing to file..."),
  15663. TRANS("An error occurred while trying to save \"")
  15664. + getDocumentTitle()
  15665. + TRANS("\" to the file:\n\n")
  15666. + newFile.getFullPathName()
  15667. + "\n\n"
  15668. + error);
  15669. }
  15670. return failedToWriteToFile;
  15671. }
  15672. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15673. {
  15674. if (! hasChangedSinceSaved())
  15675. return savedOk;
  15676. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15677. TRANS("Closing document..."),
  15678. TRANS("Do you want to save the changes to \"")
  15679. + getDocumentTitle() + "\"?",
  15680. TRANS("save"),
  15681. TRANS("discard changes"),
  15682. TRANS("cancel"));
  15683. if (r == 1)
  15684. {
  15685. // save changes
  15686. return save (true, true);
  15687. }
  15688. else if (r == 2)
  15689. {
  15690. // discard changes
  15691. return savedOk;
  15692. }
  15693. return userCancelledSave;
  15694. }
  15695. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15696. {
  15697. File f;
  15698. if (documentFile.existsAsFile())
  15699. f = documentFile;
  15700. else
  15701. f = getLastDocumentOpened();
  15702. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15703. if (legalFilename.isEmpty())
  15704. legalFilename = "unnamed";
  15705. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15706. f = f.getSiblingFile (legalFilename);
  15707. else
  15708. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15709. f = f.withFileExtension (fileExtension)
  15710. .getNonexistentSibling (true);
  15711. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15712. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15713. {
  15714. File chosen (fc.getResult());
  15715. if (chosen.getFileExtension().isEmpty())
  15716. {
  15717. chosen = chosen.withFileExtension (fileExtension);
  15718. if (chosen.exists())
  15719. {
  15720. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15721. TRANS("File already exists"),
  15722. TRANS("There's already a file called:")
  15723. + "\n\n" + chosen.getFullPathName()
  15724. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15725. TRANS("overwrite"),
  15726. TRANS("cancel")))
  15727. {
  15728. return userCancelledSave;
  15729. }
  15730. }
  15731. }
  15732. setLastDocumentOpened (chosen);
  15733. return saveAs (chosen, false, false, true);
  15734. }
  15735. return userCancelledSave;
  15736. }
  15737. END_JUCE_NAMESPACE
  15738. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15739. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15740. BEGIN_JUCE_NAMESPACE
  15741. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15742. : maxNumberOfItems (10)
  15743. {
  15744. }
  15745. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15746. {
  15747. }
  15748. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15749. {
  15750. maxNumberOfItems = jmax (1, newMaxNumber);
  15751. while (getNumFiles() > maxNumberOfItems)
  15752. files.remove (getNumFiles() - 1);
  15753. }
  15754. int RecentlyOpenedFilesList::getNumFiles() const
  15755. {
  15756. return files.size();
  15757. }
  15758. const File RecentlyOpenedFilesList::getFile (const int index) const
  15759. {
  15760. return File (files [index]);
  15761. }
  15762. void RecentlyOpenedFilesList::clear()
  15763. {
  15764. files.clear();
  15765. }
  15766. void RecentlyOpenedFilesList::addFile (const File& file)
  15767. {
  15768. const String path (file.getFullPathName());
  15769. files.removeString (path, true);
  15770. files.insert (0, path);
  15771. setMaxNumberOfItems (maxNumberOfItems);
  15772. }
  15773. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15774. {
  15775. for (int i = getNumFiles(); --i >= 0;)
  15776. if (! getFile(i).exists())
  15777. files.remove (i);
  15778. }
  15779. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15780. const int baseItemId,
  15781. const bool showFullPaths,
  15782. const bool dontAddNonExistentFiles,
  15783. const File** filesToAvoid)
  15784. {
  15785. int num = 0;
  15786. for (int i = 0; i < getNumFiles(); ++i)
  15787. {
  15788. const File f (getFile(i));
  15789. if ((! dontAddNonExistentFiles) || f.exists())
  15790. {
  15791. bool needsAvoiding = false;
  15792. if (filesToAvoid != 0)
  15793. {
  15794. const File** avoid = filesToAvoid;
  15795. while (*avoid != 0)
  15796. {
  15797. if (f == **avoid)
  15798. {
  15799. needsAvoiding = true;
  15800. break;
  15801. }
  15802. ++avoid;
  15803. }
  15804. }
  15805. if (! needsAvoiding)
  15806. {
  15807. menuToAddTo.addItem (baseItemId + i,
  15808. showFullPaths ? f.getFullPathName()
  15809. : f.getFileName());
  15810. ++num;
  15811. }
  15812. }
  15813. }
  15814. return num;
  15815. }
  15816. const String RecentlyOpenedFilesList::toString() const
  15817. {
  15818. return files.joinIntoString ("\n");
  15819. }
  15820. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15821. {
  15822. clear();
  15823. files.addLines (stringifiedVersion);
  15824. setMaxNumberOfItems (maxNumberOfItems);
  15825. }
  15826. END_JUCE_NAMESPACE
  15827. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15828. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15829. BEGIN_JUCE_NAMESPACE
  15830. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15831. const int minimumTransactions)
  15832. : totalUnitsStored (0),
  15833. nextIndex (0),
  15834. newTransaction (true),
  15835. reentrancyCheck (false)
  15836. {
  15837. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15838. minimumTransactions);
  15839. }
  15840. UndoManager::~UndoManager()
  15841. {
  15842. clearUndoHistory();
  15843. }
  15844. void UndoManager::clearUndoHistory()
  15845. {
  15846. transactions.clear();
  15847. transactionNames.clear();
  15848. totalUnitsStored = 0;
  15849. nextIndex = 0;
  15850. sendChangeMessage (this);
  15851. }
  15852. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15853. {
  15854. return totalUnitsStored;
  15855. }
  15856. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15857. const int minimumTransactions)
  15858. {
  15859. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15860. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15861. }
  15862. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15863. {
  15864. if (command_ != 0)
  15865. {
  15866. ScopedPointer<UndoableAction> command (command_);
  15867. if (actionName.isNotEmpty())
  15868. currentTransactionName = actionName;
  15869. if (reentrancyCheck)
  15870. {
  15871. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15872. // undo() methods, or else these actions won't actually get done.
  15873. return false;
  15874. }
  15875. else if (command->perform())
  15876. {
  15877. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15878. if (commandSet != 0 && ! newTransaction)
  15879. {
  15880. UndoableAction* lastAction = commandSet->getLast();
  15881. if (lastAction != 0)
  15882. {
  15883. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15884. if (coalescedAction != 0)
  15885. {
  15886. command = coalescedAction;
  15887. totalUnitsStored -= lastAction->getSizeInUnits();
  15888. commandSet->removeLast();
  15889. }
  15890. }
  15891. }
  15892. else
  15893. {
  15894. commandSet = new OwnedArray<UndoableAction>();
  15895. transactions.insert (nextIndex, commandSet);
  15896. transactionNames.insert (nextIndex, currentTransactionName);
  15897. ++nextIndex;
  15898. }
  15899. totalUnitsStored += command->getSizeInUnits();
  15900. commandSet->add (command.release());
  15901. newTransaction = false;
  15902. while (nextIndex < transactions.size())
  15903. {
  15904. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15905. for (int i = lastSet->size(); --i >= 0;)
  15906. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15907. transactions.removeLast();
  15908. transactionNames.remove (transactionNames.size() - 1);
  15909. }
  15910. while (nextIndex > 0
  15911. && totalUnitsStored > maxNumUnitsToKeep
  15912. && transactions.size() > minimumTransactionsToKeep)
  15913. {
  15914. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15915. for (int i = firstSet->size(); --i >= 0;)
  15916. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15917. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15918. transactions.remove (0);
  15919. transactionNames.remove (0);
  15920. --nextIndex;
  15921. }
  15922. sendChangeMessage (this);
  15923. return true;
  15924. }
  15925. }
  15926. return false;
  15927. }
  15928. void UndoManager::beginNewTransaction (const String& actionName)
  15929. {
  15930. newTransaction = true;
  15931. currentTransactionName = actionName;
  15932. }
  15933. void UndoManager::setCurrentTransactionName (const String& newName)
  15934. {
  15935. currentTransactionName = newName;
  15936. }
  15937. bool UndoManager::canUndo() const
  15938. {
  15939. return nextIndex > 0;
  15940. }
  15941. bool UndoManager::canRedo() const
  15942. {
  15943. return nextIndex < transactions.size();
  15944. }
  15945. const String UndoManager::getUndoDescription() const
  15946. {
  15947. return transactionNames [nextIndex - 1];
  15948. }
  15949. const String UndoManager::getRedoDescription() const
  15950. {
  15951. return transactionNames [nextIndex];
  15952. }
  15953. bool UndoManager::undo()
  15954. {
  15955. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15956. if (commandSet == 0)
  15957. return false;
  15958. reentrancyCheck = true;
  15959. bool failed = false;
  15960. for (int i = commandSet->size(); --i >= 0;)
  15961. {
  15962. if (! commandSet->getUnchecked(i)->undo())
  15963. {
  15964. jassertfalse;
  15965. failed = true;
  15966. break;
  15967. }
  15968. }
  15969. reentrancyCheck = false;
  15970. if (failed)
  15971. clearUndoHistory();
  15972. else
  15973. --nextIndex;
  15974. beginNewTransaction();
  15975. sendChangeMessage (this);
  15976. return true;
  15977. }
  15978. bool UndoManager::redo()
  15979. {
  15980. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15981. if (commandSet == 0)
  15982. return false;
  15983. reentrancyCheck = true;
  15984. bool failed = false;
  15985. for (int i = 0; i < commandSet->size(); ++i)
  15986. {
  15987. if (! commandSet->getUnchecked(i)->perform())
  15988. {
  15989. jassertfalse;
  15990. failed = true;
  15991. break;
  15992. }
  15993. }
  15994. reentrancyCheck = false;
  15995. if (failed)
  15996. clearUndoHistory();
  15997. else
  15998. ++nextIndex;
  15999. beginNewTransaction();
  16000. sendChangeMessage (this);
  16001. return true;
  16002. }
  16003. bool UndoManager::undoCurrentTransactionOnly()
  16004. {
  16005. return newTransaction ? false : undo();
  16006. }
  16007. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16008. {
  16009. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16010. if (commandSet != 0 && ! newTransaction)
  16011. {
  16012. for (int i = 0; i < commandSet->size(); ++i)
  16013. actionsFound.add (commandSet->getUnchecked(i));
  16014. }
  16015. }
  16016. int UndoManager::getNumActionsInCurrentTransaction() const
  16017. {
  16018. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16019. if (commandSet != 0 && ! newTransaction)
  16020. return commandSet->size();
  16021. return 0;
  16022. }
  16023. END_JUCE_NAMESPACE
  16024. /*** End of inlined file: juce_UndoManager.cpp ***/
  16025. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16026. BEGIN_JUCE_NAMESPACE
  16027. static const char* const aiffFormatName = "AIFF file";
  16028. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16029. class AiffAudioFormatReader : public AudioFormatReader
  16030. {
  16031. public:
  16032. int bytesPerFrame;
  16033. int64 dataChunkStart;
  16034. bool littleEndian;
  16035. AiffAudioFormatReader (InputStream* in)
  16036. : AudioFormatReader (in, TRANS (aiffFormatName))
  16037. {
  16038. if (input->readInt() == chunkName ("FORM"))
  16039. {
  16040. const int len = input->readIntBigEndian();
  16041. const int64 end = input->getPosition() + len;
  16042. const int nextType = input->readInt();
  16043. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16044. {
  16045. bool hasGotVer = false;
  16046. bool hasGotData = false;
  16047. bool hasGotType = false;
  16048. while (input->getPosition() < end)
  16049. {
  16050. const int type = input->readInt();
  16051. const uint32 length = (uint32) input->readIntBigEndian();
  16052. const int64 chunkEnd = input->getPosition() + length;
  16053. if (type == chunkName ("FVER"))
  16054. {
  16055. hasGotVer = true;
  16056. const int ver = input->readIntBigEndian();
  16057. if (ver != 0 && ver != (int)0xa2805140)
  16058. break;
  16059. }
  16060. else if (type == chunkName ("COMM"))
  16061. {
  16062. hasGotType = true;
  16063. numChannels = (unsigned int)input->readShortBigEndian();
  16064. lengthInSamples = input->readIntBigEndian();
  16065. bitsPerSample = input->readShortBigEndian();
  16066. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16067. unsigned char sampleRateBytes[10];
  16068. input->read (sampleRateBytes, 10);
  16069. const int byte0 = sampleRateBytes[0];
  16070. if ((byte0 & 0x80) != 0
  16071. || byte0 <= 0x3F || byte0 > 0x40
  16072. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16073. break;
  16074. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16075. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16076. sampleRate = (int) sampRate;
  16077. if (length <= 18)
  16078. {
  16079. // some types don't have a chunk large enough to include a compression
  16080. // type, so assume it's just big-endian pcm
  16081. littleEndian = false;
  16082. }
  16083. else
  16084. {
  16085. const int compType = input->readInt();
  16086. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16087. {
  16088. littleEndian = false;
  16089. }
  16090. else if (compType == chunkName ("sowt"))
  16091. {
  16092. littleEndian = true;
  16093. }
  16094. else
  16095. {
  16096. sampleRate = 0;
  16097. break;
  16098. }
  16099. }
  16100. }
  16101. else if (type == chunkName ("SSND"))
  16102. {
  16103. hasGotData = true;
  16104. const int offset = input->readIntBigEndian();
  16105. dataChunkStart = input->getPosition() + 4 + offset;
  16106. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16107. }
  16108. else if ((hasGotVer && hasGotData && hasGotType)
  16109. || chunkEnd < input->getPosition()
  16110. || input->isExhausted())
  16111. {
  16112. break;
  16113. }
  16114. input->setPosition (chunkEnd);
  16115. }
  16116. }
  16117. }
  16118. }
  16119. ~AiffAudioFormatReader()
  16120. {
  16121. }
  16122. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16123. int64 startSampleInFile, int numSamples)
  16124. {
  16125. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16126. if (samplesAvailable < numSamples)
  16127. {
  16128. for (int i = numDestChannels; --i >= 0;)
  16129. if (destSamples[i] != 0)
  16130. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16131. numSamples = (int) samplesAvailable;
  16132. }
  16133. if (numSamples <= 0)
  16134. return true;
  16135. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16136. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16137. char tempBuffer [tempBufSize];
  16138. while (numSamples > 0)
  16139. {
  16140. int* left = destSamples[0];
  16141. if (left != 0)
  16142. left += startOffsetInDestBuffer;
  16143. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16144. if (right != 0)
  16145. right += startOffsetInDestBuffer;
  16146. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16147. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16148. if (bytesRead < numThisTime * bytesPerFrame)
  16149. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16150. if (bitsPerSample == 16)
  16151. {
  16152. if (littleEndian)
  16153. {
  16154. const short* src = reinterpret_cast <const short*> (tempBuffer);
  16155. if (numChannels > 1)
  16156. {
  16157. if (left == 0)
  16158. {
  16159. for (int i = numThisTime; --i >= 0;)
  16160. {
  16161. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16162. ++src;
  16163. }
  16164. }
  16165. else if (right == 0)
  16166. {
  16167. for (int i = numThisTime; --i >= 0;)
  16168. {
  16169. ++src;
  16170. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16171. }
  16172. }
  16173. else
  16174. {
  16175. for (int i = numThisTime; --i >= 0;)
  16176. {
  16177. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16178. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16179. }
  16180. }
  16181. }
  16182. else
  16183. {
  16184. for (int i = numThisTime; --i >= 0;)
  16185. {
  16186. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16187. }
  16188. }
  16189. }
  16190. else
  16191. {
  16192. const char* src = tempBuffer;
  16193. if (numChannels > 1)
  16194. {
  16195. if (left == 0)
  16196. {
  16197. for (int i = numThisTime; --i >= 0;)
  16198. {
  16199. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16200. src += 4;
  16201. }
  16202. }
  16203. else if (right == 0)
  16204. {
  16205. for (int i = numThisTime; --i >= 0;)
  16206. {
  16207. src += 2;
  16208. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16209. src += 2;
  16210. }
  16211. }
  16212. else
  16213. {
  16214. for (int i = numThisTime; --i >= 0;)
  16215. {
  16216. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16217. src += 2;
  16218. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16219. src += 2;
  16220. }
  16221. }
  16222. }
  16223. else
  16224. {
  16225. for (int i = numThisTime; --i >= 0;)
  16226. {
  16227. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16228. src += 2;
  16229. }
  16230. }
  16231. }
  16232. }
  16233. else if (bitsPerSample == 24)
  16234. {
  16235. const char* src = (const char*)tempBuffer;
  16236. if (littleEndian)
  16237. {
  16238. if (numChannels > 1)
  16239. {
  16240. if (left == 0)
  16241. {
  16242. for (int i = numThisTime; --i >= 0;)
  16243. {
  16244. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16245. src += 6;
  16246. }
  16247. }
  16248. else if (right == 0)
  16249. {
  16250. for (int i = numThisTime; --i >= 0;)
  16251. {
  16252. src += 3;
  16253. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16254. src += 3;
  16255. }
  16256. }
  16257. else
  16258. {
  16259. for (int i = numThisTime; --i >= 0;)
  16260. {
  16261. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16262. src += 3;
  16263. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16264. src += 3;
  16265. }
  16266. }
  16267. }
  16268. else
  16269. {
  16270. for (int i = numThisTime; --i >= 0;)
  16271. {
  16272. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16273. src += 3;
  16274. }
  16275. }
  16276. }
  16277. else
  16278. {
  16279. if (numChannels > 1)
  16280. {
  16281. if (left == 0)
  16282. {
  16283. for (int i = numThisTime; --i >= 0;)
  16284. {
  16285. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16286. src += 6;
  16287. }
  16288. }
  16289. else if (right == 0)
  16290. {
  16291. for (int i = numThisTime; --i >= 0;)
  16292. {
  16293. src += 3;
  16294. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16295. src += 3;
  16296. }
  16297. }
  16298. else
  16299. {
  16300. for (int i = numThisTime; --i >= 0;)
  16301. {
  16302. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16303. src += 3;
  16304. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16305. src += 3;
  16306. }
  16307. }
  16308. }
  16309. else
  16310. {
  16311. for (int i = numThisTime; --i >= 0;)
  16312. {
  16313. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16314. src += 3;
  16315. }
  16316. }
  16317. }
  16318. }
  16319. else if (bitsPerSample == 32)
  16320. {
  16321. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  16322. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  16323. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  16324. if (littleEndian)
  16325. {
  16326. if (numChannels > 1)
  16327. {
  16328. if (l == 0)
  16329. {
  16330. for (int i = numThisTime; --i >= 0;)
  16331. {
  16332. ++src;
  16333. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16334. }
  16335. }
  16336. else if (r == 0)
  16337. {
  16338. for (int i = numThisTime; --i >= 0;)
  16339. {
  16340. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16341. ++src;
  16342. }
  16343. }
  16344. else
  16345. {
  16346. for (int i = numThisTime; --i >= 0;)
  16347. {
  16348. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16349. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16350. }
  16351. }
  16352. }
  16353. else
  16354. {
  16355. for (int i = numThisTime; --i >= 0;)
  16356. {
  16357. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16358. }
  16359. }
  16360. }
  16361. else
  16362. {
  16363. if (numChannels > 1)
  16364. {
  16365. if (l == 0)
  16366. {
  16367. for (int i = numThisTime; --i >= 0;)
  16368. {
  16369. ++src;
  16370. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16371. }
  16372. }
  16373. else if (r == 0)
  16374. {
  16375. for (int i = numThisTime; --i >= 0;)
  16376. {
  16377. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16378. ++src;
  16379. }
  16380. }
  16381. else
  16382. {
  16383. for (int i = numThisTime; --i >= 0;)
  16384. {
  16385. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16386. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16387. }
  16388. }
  16389. }
  16390. else
  16391. {
  16392. for (int i = numThisTime; --i >= 0;)
  16393. {
  16394. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16395. }
  16396. }
  16397. }
  16398. left = reinterpret_cast <int*> (l);
  16399. right = reinterpret_cast <int*> (r);
  16400. }
  16401. else if (bitsPerSample == 8)
  16402. {
  16403. const char* src = tempBuffer;
  16404. if (numChannels > 1)
  16405. {
  16406. if (left == 0)
  16407. {
  16408. for (int i = numThisTime; --i >= 0;)
  16409. {
  16410. *right++ = ((int) *src++) << 24;
  16411. ++src;
  16412. }
  16413. }
  16414. else if (right == 0)
  16415. {
  16416. for (int i = numThisTime; --i >= 0;)
  16417. {
  16418. ++src;
  16419. *left++ = ((int) *src++) << 24;
  16420. }
  16421. }
  16422. else
  16423. {
  16424. for (int i = numThisTime; --i >= 0;)
  16425. {
  16426. *left++ = ((int) *src++) << 24;
  16427. *right++ = ((int) *src++) << 24;
  16428. }
  16429. }
  16430. }
  16431. else
  16432. {
  16433. for (int i = numThisTime; --i >= 0;)
  16434. {
  16435. *left++ = ((int) *src++) << 24;
  16436. }
  16437. }
  16438. }
  16439. startOffsetInDestBuffer += numThisTime;
  16440. numSamples -= numThisTime;
  16441. }
  16442. if (numSamples > 0)
  16443. {
  16444. for (int i = numDestChannels; --i >= 0;)
  16445. if (destSamples[i] != 0)
  16446. zeromem (destSamples[i] + startOffsetInDestBuffer,
  16447. sizeof (int) * numSamples);
  16448. }
  16449. return true;
  16450. }
  16451. juce_UseDebuggingNewOperator
  16452. private:
  16453. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16454. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16455. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16456. };
  16457. class AiffAudioFormatWriter : public AudioFormatWriter
  16458. {
  16459. MemoryBlock tempBlock;
  16460. uint32 lengthInSamples, bytesWritten;
  16461. int64 headerPosition;
  16462. bool writeFailed;
  16463. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16464. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16465. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16466. void writeHeader()
  16467. {
  16468. const bool couldSeekOk = output->setPosition (headerPosition);
  16469. (void) couldSeekOk;
  16470. // if this fails, you've given it an output stream that can't seek! It needs
  16471. // to be able to seek back to write the header
  16472. jassert (couldSeekOk);
  16473. const int headerLen = 54;
  16474. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16475. audioBytes += (audioBytes & 1);
  16476. output->writeInt (chunkName ("FORM"));
  16477. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16478. output->writeInt (chunkName ("AIFF"));
  16479. output->writeInt (chunkName ("COMM"));
  16480. output->writeIntBigEndian (18);
  16481. output->writeShortBigEndian ((short) numChannels);
  16482. output->writeIntBigEndian (lengthInSamples);
  16483. output->writeShortBigEndian ((short) bitsPerSample);
  16484. uint8 sampleRateBytes[10];
  16485. zeromem (sampleRateBytes, 10);
  16486. if (sampleRate <= 1)
  16487. {
  16488. sampleRateBytes[0] = 0x3f;
  16489. sampleRateBytes[1] = 0xff;
  16490. sampleRateBytes[2] = 0x80;
  16491. }
  16492. else
  16493. {
  16494. int mask = 0x40000000;
  16495. sampleRateBytes[0] = 0x40;
  16496. if (sampleRate >= mask)
  16497. {
  16498. jassertfalse;
  16499. sampleRateBytes[1] = 0x1d;
  16500. }
  16501. else
  16502. {
  16503. int n = (int) sampleRate;
  16504. int i;
  16505. for (i = 0; i <= 32 ; ++i)
  16506. {
  16507. if ((n & mask) != 0)
  16508. break;
  16509. mask >>= 1;
  16510. }
  16511. n = n << (i + 1);
  16512. sampleRateBytes[1] = (uint8) (29 - i);
  16513. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16514. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16515. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16516. sampleRateBytes[5] = (uint8) (n & 0xff);
  16517. }
  16518. }
  16519. output->write (sampleRateBytes, 10);
  16520. output->writeInt (chunkName ("SSND"));
  16521. output->writeIntBigEndian (audioBytes + 8);
  16522. output->writeInt (0);
  16523. output->writeInt (0);
  16524. jassert (output->getPosition() == headerLen);
  16525. }
  16526. public:
  16527. AiffAudioFormatWriter (OutputStream* out,
  16528. const double sampleRate_,
  16529. const unsigned int chans,
  16530. const int bits)
  16531. : AudioFormatWriter (out,
  16532. TRANS (aiffFormatName),
  16533. sampleRate_,
  16534. chans,
  16535. bits),
  16536. lengthInSamples (0),
  16537. bytesWritten (0),
  16538. writeFailed (false)
  16539. {
  16540. headerPosition = out->getPosition();
  16541. writeHeader();
  16542. }
  16543. ~AiffAudioFormatWriter()
  16544. {
  16545. if ((bytesWritten & 1) != 0)
  16546. output->writeByte (0);
  16547. writeHeader();
  16548. }
  16549. bool write (const int** data, int numSamples)
  16550. {
  16551. if (writeFailed)
  16552. return false;
  16553. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16554. tempBlock.ensureSize (bytes, false);
  16555. char* buffer = static_cast <char*> (tempBlock.getData());
  16556. const int* left = data[0];
  16557. const int* right = data[1];
  16558. if (right == 0)
  16559. right = left;
  16560. if (bitsPerSample == 16)
  16561. {
  16562. short* b = reinterpret_cast <short*> (buffer);
  16563. if (numChannels > 1)
  16564. {
  16565. for (int i = numSamples; --i >= 0;)
  16566. {
  16567. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  16568. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  16569. }
  16570. }
  16571. else
  16572. {
  16573. for (int i = numSamples; --i >= 0;)
  16574. {
  16575. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  16576. }
  16577. }
  16578. }
  16579. else if (bitsPerSample == 24)
  16580. {
  16581. char* b = buffer;
  16582. if (numChannels > 1)
  16583. {
  16584. for (int i = numSamples; --i >= 0;)
  16585. {
  16586. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  16587. b += 3;
  16588. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  16589. b += 3;
  16590. }
  16591. }
  16592. else
  16593. {
  16594. for (int i = numSamples; --i >= 0;)
  16595. {
  16596. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  16597. b += 3;
  16598. }
  16599. }
  16600. }
  16601. else if (bitsPerSample == 32)
  16602. {
  16603. uint32* b = reinterpret_cast <uint32*> (buffer);
  16604. if (numChannels > 1)
  16605. {
  16606. for (int i = numSamples; --i >= 0;)
  16607. {
  16608. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  16609. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  16610. }
  16611. }
  16612. else
  16613. {
  16614. for (int i = numSamples; --i >= 0;)
  16615. {
  16616. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  16617. }
  16618. }
  16619. }
  16620. else if (bitsPerSample == 8)
  16621. {
  16622. char* b = buffer;
  16623. if (numChannels > 1)
  16624. {
  16625. for (int i = numSamples; --i >= 0;)
  16626. {
  16627. *b++ = (char) (*left++ >> 24);
  16628. *b++ = (char) (*right++ >> 24);
  16629. }
  16630. }
  16631. else
  16632. {
  16633. for (int i = numSamples; --i >= 0;)
  16634. {
  16635. *b++ = (char) (*left++ >> 24);
  16636. }
  16637. }
  16638. }
  16639. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16640. || ! output->write (buffer, bytes))
  16641. {
  16642. // failed to write to disk, so let's try writing the header.
  16643. // If it's just run out of disk space, then if it does manage
  16644. // to write the header, we'll still have a useable file..
  16645. writeHeader();
  16646. writeFailed = true;
  16647. return false;
  16648. }
  16649. else
  16650. {
  16651. bytesWritten += bytes;
  16652. lengthInSamples += numSamples;
  16653. return true;
  16654. }
  16655. }
  16656. juce_UseDebuggingNewOperator
  16657. };
  16658. AiffAudioFormat::AiffAudioFormat()
  16659. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16660. {
  16661. }
  16662. AiffAudioFormat::~AiffAudioFormat()
  16663. {
  16664. }
  16665. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16666. {
  16667. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16668. return Array <int> (rates);
  16669. }
  16670. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16671. {
  16672. const int depths[] = { 8, 16, 24, 0 };
  16673. return Array <int> (depths);
  16674. }
  16675. bool AiffAudioFormat::canDoStereo()
  16676. {
  16677. return true;
  16678. }
  16679. bool AiffAudioFormat::canDoMono()
  16680. {
  16681. return true;
  16682. }
  16683. #if JUCE_MAC
  16684. bool AiffAudioFormat::canHandleFile (const File& f)
  16685. {
  16686. if (AudioFormat::canHandleFile (f))
  16687. return true;
  16688. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16689. return type == 'AIFF' || type == 'AIFC'
  16690. || type == 'aiff' || type == 'aifc';
  16691. }
  16692. #endif
  16693. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  16694. const bool deleteStreamIfOpeningFails)
  16695. {
  16696. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16697. if (w->sampleRate != 0)
  16698. return w.release();
  16699. if (! deleteStreamIfOpeningFails)
  16700. w->input = 0;
  16701. return 0;
  16702. }
  16703. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16704. double sampleRate,
  16705. unsigned int chans,
  16706. int bitsPerSample,
  16707. const StringPairArray& /*metadataValues*/,
  16708. int /*qualityOptionIndex*/)
  16709. {
  16710. if (getPossibleBitDepths().contains (bitsPerSample))
  16711. {
  16712. return new AiffAudioFormatWriter (out,
  16713. sampleRate,
  16714. chans,
  16715. bitsPerSample);
  16716. }
  16717. return 0;
  16718. }
  16719. END_JUCE_NAMESPACE
  16720. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16721. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16722. BEGIN_JUCE_NAMESPACE
  16723. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16724. const String& formatName_)
  16725. : sampleRate (0),
  16726. bitsPerSample (0),
  16727. lengthInSamples (0),
  16728. numChannels (0),
  16729. usesFloatingPointData (false),
  16730. input (in),
  16731. formatName (formatName_)
  16732. {
  16733. }
  16734. AudioFormatReader::~AudioFormatReader()
  16735. {
  16736. delete input;
  16737. }
  16738. bool AudioFormatReader::read (int** destSamples,
  16739. int numDestChannels,
  16740. int64 startSampleInSource,
  16741. int numSamplesToRead,
  16742. const bool fillLeftoverChannelsWithCopies)
  16743. {
  16744. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16745. int startOffsetInDestBuffer = 0;
  16746. if (startSampleInSource < 0)
  16747. {
  16748. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16749. for (int i = numDestChannels; --i >= 0;)
  16750. if (destSamples[i] != 0)
  16751. zeromem (destSamples[i], sizeof (int) * silence);
  16752. startOffsetInDestBuffer += silence;
  16753. numSamplesToRead -= silence;
  16754. startSampleInSource = 0;
  16755. }
  16756. if (numSamplesToRead <= 0)
  16757. return true;
  16758. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16759. startSampleInSource, numSamplesToRead))
  16760. return false;
  16761. if (numDestChannels > (int) numChannels)
  16762. {
  16763. if (fillLeftoverChannelsWithCopies)
  16764. {
  16765. int* lastFullChannel = destSamples[0];
  16766. for (int i = (int) numChannels; --i > 0;)
  16767. {
  16768. if (destSamples[i] != 0)
  16769. {
  16770. lastFullChannel = destSamples[i];
  16771. break;
  16772. }
  16773. }
  16774. if (lastFullChannel != 0)
  16775. for (int i = numChannels; i < numDestChannels; ++i)
  16776. if (destSamples[i] != 0)
  16777. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16778. }
  16779. else
  16780. {
  16781. for (int i = numChannels; i < numDestChannels; ++i)
  16782. if (destSamples[i] != 0)
  16783. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16784. }
  16785. }
  16786. return true;
  16787. }
  16788. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16789. {
  16790. float mn = buffer[0];
  16791. float mx = mn;
  16792. for (int i = 1; i < num; ++i)
  16793. {
  16794. const float s = buffer[i];
  16795. if (s > mx) mx = s;
  16796. if (s < mn) mn = s;
  16797. }
  16798. maxVal = mx;
  16799. minVal = mn;
  16800. }
  16801. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16802. int64 numSamples,
  16803. float& lowestLeft, float& highestLeft,
  16804. float& lowestRight, float& highestRight)
  16805. {
  16806. if (numSamples <= 0)
  16807. {
  16808. lowestLeft = 0;
  16809. lowestRight = 0;
  16810. highestLeft = 0;
  16811. highestRight = 0;
  16812. return;
  16813. }
  16814. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16815. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16816. int* tempBuffer[3];
  16817. tempBuffer[0] = (int*) tempSpace.getData();
  16818. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16819. tempBuffer[2] = 0;
  16820. if (usesFloatingPointData)
  16821. {
  16822. float lmin = 1.0e6f;
  16823. float lmax = -lmin;
  16824. float rmin = lmin;
  16825. float rmax = lmax;
  16826. while (numSamples > 0)
  16827. {
  16828. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16829. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16830. numSamples -= numToDo;
  16831. startSampleInFile += numToDo;
  16832. float bufmin, bufmax;
  16833. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16834. lmin = jmin (lmin, bufmin);
  16835. lmax = jmax (lmax, bufmax);
  16836. if (numChannels > 1)
  16837. {
  16838. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16839. rmin = jmin (rmin, bufmin);
  16840. rmax = jmax (rmax, bufmax);
  16841. }
  16842. }
  16843. if (numChannels <= 1)
  16844. {
  16845. rmax = lmax;
  16846. rmin = lmin;
  16847. }
  16848. lowestLeft = lmin;
  16849. highestLeft = lmax;
  16850. lowestRight = rmin;
  16851. highestRight = rmax;
  16852. }
  16853. else
  16854. {
  16855. int lmax = std::numeric_limits<int>::min();
  16856. int lmin = std::numeric_limits<int>::max();
  16857. int rmax = std::numeric_limits<int>::min();
  16858. int rmin = std::numeric_limits<int>::max();
  16859. while (numSamples > 0)
  16860. {
  16861. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16862. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16863. numSamples -= numToDo;
  16864. startSampleInFile += numToDo;
  16865. for (int j = numChannels; --j >= 0;)
  16866. {
  16867. int bufMax = std::numeric_limits<int>::min();
  16868. int bufMin = std::numeric_limits<int>::max();
  16869. const int* const b = tempBuffer[j];
  16870. for (int i = 0; i < numToDo; ++i)
  16871. {
  16872. const int samp = b[i];
  16873. if (samp < bufMin)
  16874. bufMin = samp;
  16875. if (samp > bufMax)
  16876. bufMax = samp;
  16877. }
  16878. if (j == 0)
  16879. {
  16880. lmax = jmax (lmax, bufMax);
  16881. lmin = jmin (lmin, bufMin);
  16882. }
  16883. else
  16884. {
  16885. rmax = jmax (rmax, bufMax);
  16886. rmin = jmin (rmin, bufMin);
  16887. }
  16888. }
  16889. }
  16890. if (numChannels <= 1)
  16891. {
  16892. rmax = lmax;
  16893. rmin = lmin;
  16894. }
  16895. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16896. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16897. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16898. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16899. }
  16900. }
  16901. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16902. int64 numSamplesToSearch,
  16903. const double magnitudeRangeMinimum,
  16904. const double magnitudeRangeMaximum,
  16905. const int minimumConsecutiveSamples)
  16906. {
  16907. if (numSamplesToSearch == 0)
  16908. return -1;
  16909. const int bufferSize = 4096;
  16910. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16911. int* tempBuffer[3];
  16912. tempBuffer[0] = (int*) tempSpace.getData();
  16913. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16914. tempBuffer[2] = 0;
  16915. int consecutive = 0;
  16916. int64 firstMatchPos = -1;
  16917. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16918. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16919. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16920. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16921. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16922. while (numSamplesToSearch != 0)
  16923. {
  16924. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16925. int64 bufferStart = startSample;
  16926. if (numSamplesToSearch < 0)
  16927. bufferStart -= numThisTime;
  16928. if (bufferStart >= (int) lengthInSamples)
  16929. break;
  16930. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16931. int num = numThisTime;
  16932. while (--num >= 0)
  16933. {
  16934. if (numSamplesToSearch < 0)
  16935. --startSample;
  16936. bool matches = false;
  16937. const int index = (int) (startSample - bufferStart);
  16938. if (usesFloatingPointData)
  16939. {
  16940. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16941. if (sample1 >= magnitudeRangeMinimum
  16942. && sample1 <= magnitudeRangeMaximum)
  16943. {
  16944. matches = true;
  16945. }
  16946. else if (numChannels > 1)
  16947. {
  16948. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16949. matches = (sample2 >= magnitudeRangeMinimum
  16950. && sample2 <= magnitudeRangeMaximum);
  16951. }
  16952. }
  16953. else
  16954. {
  16955. const int sample1 = abs (tempBuffer[0] [index]);
  16956. if (sample1 >= intMagnitudeRangeMinimum
  16957. && sample1 <= intMagnitudeRangeMaximum)
  16958. {
  16959. matches = true;
  16960. }
  16961. else if (numChannels > 1)
  16962. {
  16963. const int sample2 = abs (tempBuffer[1][index]);
  16964. matches = (sample2 >= intMagnitudeRangeMinimum
  16965. && sample2 <= intMagnitudeRangeMaximum);
  16966. }
  16967. }
  16968. if (matches)
  16969. {
  16970. if (firstMatchPos < 0)
  16971. firstMatchPos = startSample;
  16972. if (++consecutive >= minimumConsecutiveSamples)
  16973. {
  16974. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16975. return -1;
  16976. return firstMatchPos;
  16977. }
  16978. }
  16979. else
  16980. {
  16981. consecutive = 0;
  16982. firstMatchPos = -1;
  16983. }
  16984. if (numSamplesToSearch > 0)
  16985. ++startSample;
  16986. }
  16987. if (numSamplesToSearch > 0)
  16988. numSamplesToSearch -= numThisTime;
  16989. else
  16990. numSamplesToSearch += numThisTime;
  16991. }
  16992. return -1;
  16993. }
  16994. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16995. const String& formatName_,
  16996. const double rate,
  16997. const unsigned int numChannels_,
  16998. const unsigned int bitsPerSample_)
  16999. : sampleRate (rate),
  17000. numChannels (numChannels_),
  17001. bitsPerSample (bitsPerSample_),
  17002. usesFloatingPointData (false),
  17003. output (out),
  17004. formatName (formatName_)
  17005. {
  17006. }
  17007. AudioFormatWriter::~AudioFormatWriter()
  17008. {
  17009. delete output;
  17010. }
  17011. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17012. int64 startSample,
  17013. int64 numSamplesToRead)
  17014. {
  17015. const int bufferSize = 16384;
  17016. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17017. int* buffers [128];
  17018. zerostruct (buffers);
  17019. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17020. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  17021. if (numSamplesToRead < 0)
  17022. numSamplesToRead = reader.lengthInSamples;
  17023. while (numSamplesToRead > 0)
  17024. {
  17025. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17026. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17027. return false;
  17028. if (reader.usesFloatingPointData != isFloatingPoint())
  17029. {
  17030. int** bufferChan = buffers;
  17031. while (*bufferChan != 0)
  17032. {
  17033. int* b = *bufferChan++;
  17034. if (isFloatingPoint())
  17035. {
  17036. // int -> float
  17037. const double factor = 1.0 / std::numeric_limits<int>::max();
  17038. for (int i = 0; i < numToDo; ++i)
  17039. ((float*) b)[i] = (float) (factor * b[i]);
  17040. }
  17041. else
  17042. {
  17043. // float -> int
  17044. for (int i = 0; i < numToDo; ++i)
  17045. {
  17046. const double samp = *(const float*) b;
  17047. if (samp <= -1.0)
  17048. *b++ = std::numeric_limits<int>::min();
  17049. else if (samp >= 1.0)
  17050. *b++ = std::numeric_limits<int>::max();
  17051. else
  17052. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17053. }
  17054. }
  17055. }
  17056. }
  17057. if (! write ((const int**) buffers, numToDo))
  17058. return false;
  17059. numSamplesToRead -= numToDo;
  17060. startSample += numToDo;
  17061. }
  17062. return true;
  17063. }
  17064. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  17065. int numSamplesToRead,
  17066. const int samplesPerBlock)
  17067. {
  17068. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17069. int* buffers [128];
  17070. zerostruct (buffers);
  17071. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17072. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  17073. while (numSamplesToRead > 0)
  17074. {
  17075. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17076. AudioSourceChannelInfo info;
  17077. info.buffer = &tempBuffer;
  17078. info.startSample = 0;
  17079. info.numSamples = numToDo;
  17080. info.clearActiveBufferRegion();
  17081. source.getNextAudioBlock (info);
  17082. if (! isFloatingPoint())
  17083. {
  17084. int** bufferChan = buffers;
  17085. while (*bufferChan != 0)
  17086. {
  17087. int* b = *bufferChan++;
  17088. // float -> int
  17089. for (int j = numToDo; --j >= 0;)
  17090. {
  17091. const double samp = *(const float*) b;
  17092. if (samp <= -1.0)
  17093. *b++ = std::numeric_limits<int>::min();
  17094. else if (samp >= 1.0)
  17095. *b++ = std::numeric_limits<int>::max();
  17096. else
  17097. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17098. }
  17099. }
  17100. }
  17101. if (! write ((const int**) buffers, numToDo))
  17102. return false;
  17103. numSamplesToRead -= numToDo;
  17104. }
  17105. return true;
  17106. }
  17107. AudioFormat::AudioFormat (const String& name,
  17108. const StringArray& extensions)
  17109. : formatName (name),
  17110. fileExtensions (extensions)
  17111. {
  17112. }
  17113. AudioFormat::~AudioFormat()
  17114. {
  17115. }
  17116. const String& AudioFormat::getFormatName() const
  17117. {
  17118. return formatName;
  17119. }
  17120. const StringArray& AudioFormat::getFileExtensions() const
  17121. {
  17122. return fileExtensions;
  17123. }
  17124. bool AudioFormat::canHandleFile (const File& f)
  17125. {
  17126. for (int i = 0; i < fileExtensions.size(); ++i)
  17127. if (f.hasFileExtension (fileExtensions[i]))
  17128. return true;
  17129. return false;
  17130. }
  17131. bool AudioFormat::isCompressed()
  17132. {
  17133. return false;
  17134. }
  17135. const StringArray AudioFormat::getQualityOptions()
  17136. {
  17137. return StringArray();
  17138. }
  17139. END_JUCE_NAMESPACE
  17140. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17141. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17142. BEGIN_JUCE_NAMESPACE
  17143. AudioFormatManager::AudioFormatManager()
  17144. : defaultFormatIndex (0)
  17145. {
  17146. }
  17147. AudioFormatManager::~AudioFormatManager()
  17148. {
  17149. clearFormats();
  17150. clearSingletonInstance();
  17151. }
  17152. juce_ImplementSingleton (AudioFormatManager);
  17153. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17154. const bool makeThisTheDefaultFormat)
  17155. {
  17156. jassert (newFormat != 0);
  17157. if (newFormat != 0)
  17158. {
  17159. #if JUCE_DEBUG
  17160. for (int i = getNumKnownFormats(); --i >= 0;)
  17161. {
  17162. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17163. {
  17164. jassertfalse; // trying to add the same format twice!
  17165. }
  17166. }
  17167. #endif
  17168. if (makeThisTheDefaultFormat)
  17169. defaultFormatIndex = getNumKnownFormats();
  17170. knownFormats.add (newFormat);
  17171. }
  17172. }
  17173. void AudioFormatManager::registerBasicFormats()
  17174. {
  17175. #if JUCE_MAC
  17176. registerFormat (new AiffAudioFormat(), true);
  17177. registerFormat (new WavAudioFormat(), false);
  17178. #else
  17179. registerFormat (new WavAudioFormat(), true);
  17180. registerFormat (new AiffAudioFormat(), false);
  17181. #endif
  17182. #if JUCE_USE_FLAC
  17183. registerFormat (new FlacAudioFormat(), false);
  17184. #endif
  17185. #if JUCE_USE_OGGVORBIS
  17186. registerFormat (new OggVorbisAudioFormat(), false);
  17187. #endif
  17188. }
  17189. void AudioFormatManager::clearFormats()
  17190. {
  17191. knownFormats.clear();
  17192. defaultFormatIndex = 0;
  17193. }
  17194. int AudioFormatManager::getNumKnownFormats() const
  17195. {
  17196. return knownFormats.size();
  17197. }
  17198. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17199. {
  17200. return knownFormats [index];
  17201. }
  17202. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17203. {
  17204. return getKnownFormat (defaultFormatIndex);
  17205. }
  17206. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17207. {
  17208. String e (fileExtension);
  17209. if (! e.startsWithChar ('.'))
  17210. e = "." + e;
  17211. for (int i = 0; i < getNumKnownFormats(); ++i)
  17212. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17213. return getKnownFormat(i);
  17214. return 0;
  17215. }
  17216. const String AudioFormatManager::getWildcardForAllFormats() const
  17217. {
  17218. StringArray allExtensions;
  17219. int i;
  17220. for (i = 0; i < getNumKnownFormats(); ++i)
  17221. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17222. allExtensions.trim();
  17223. allExtensions.removeEmptyStrings();
  17224. String s;
  17225. for (i = 0; i < allExtensions.size(); ++i)
  17226. {
  17227. s << '*';
  17228. if (! allExtensions[i].startsWithChar ('.'))
  17229. s << '.';
  17230. s << allExtensions[i];
  17231. if (i < allExtensions.size() - 1)
  17232. s << ';';
  17233. }
  17234. return s;
  17235. }
  17236. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17237. {
  17238. // you need to actually register some formats before the manager can
  17239. // use them to open a file!
  17240. jassert (getNumKnownFormats() > 0);
  17241. for (int i = 0; i < getNumKnownFormats(); ++i)
  17242. {
  17243. AudioFormat* const af = getKnownFormat(i);
  17244. if (af->canHandleFile (file))
  17245. {
  17246. InputStream* const in = file.createInputStream();
  17247. if (in != 0)
  17248. {
  17249. AudioFormatReader* const r = af->createReaderFor (in, true);
  17250. if (r != 0)
  17251. return r;
  17252. }
  17253. }
  17254. }
  17255. return 0;
  17256. }
  17257. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17258. {
  17259. // you need to actually register some formats before the manager can
  17260. // use them to open a file!
  17261. jassert (getNumKnownFormats() > 0);
  17262. ScopedPointer <InputStream> in (audioFileStream);
  17263. if (in != 0)
  17264. {
  17265. const int64 originalStreamPos = in->getPosition();
  17266. for (int i = 0; i < getNumKnownFormats(); ++i)
  17267. {
  17268. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17269. if (r != 0)
  17270. {
  17271. in.release();
  17272. return r;
  17273. }
  17274. in->setPosition (originalStreamPos);
  17275. // the stream that is passed-in must be capable of being repositioned so
  17276. // that all the formats can have a go at opening it.
  17277. jassert (in->getPosition() == originalStreamPos);
  17278. }
  17279. }
  17280. return 0;
  17281. }
  17282. END_JUCE_NAMESPACE
  17283. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17284. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17285. BEGIN_JUCE_NAMESPACE
  17286. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17287. const int64 startSample_,
  17288. const int64 length_,
  17289. const bool deleteSourceWhenDeleted_)
  17290. : AudioFormatReader (0, source_->getFormatName()),
  17291. source (source_),
  17292. startSample (startSample_),
  17293. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17294. {
  17295. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17296. sampleRate = source->sampleRate;
  17297. bitsPerSample = source->bitsPerSample;
  17298. lengthInSamples = length;
  17299. numChannels = source->numChannels;
  17300. usesFloatingPointData = source->usesFloatingPointData;
  17301. }
  17302. AudioSubsectionReader::~AudioSubsectionReader()
  17303. {
  17304. if (deleteSourceWhenDeleted)
  17305. delete source;
  17306. }
  17307. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17308. int64 startSampleInFile, int numSamples)
  17309. {
  17310. if (startSampleInFile + numSamples > length)
  17311. {
  17312. for (int i = numDestChannels; --i >= 0;)
  17313. if (destSamples[i] != 0)
  17314. zeromem (destSamples[i], sizeof (int) * numSamples);
  17315. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17316. if (numSamples <= 0)
  17317. return true;
  17318. }
  17319. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17320. startSampleInFile + startSample, numSamples);
  17321. }
  17322. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17323. int64 numSamples,
  17324. float& lowestLeft,
  17325. float& highestLeft,
  17326. float& lowestRight,
  17327. float& highestRight)
  17328. {
  17329. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17330. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17331. source->readMaxLevels (startSampleInFile + startSample,
  17332. numSamples,
  17333. lowestLeft,
  17334. highestLeft,
  17335. lowestRight,
  17336. highestRight);
  17337. }
  17338. END_JUCE_NAMESPACE
  17339. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17340. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17341. BEGIN_JUCE_NAMESPACE
  17342. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17343. AudioFormatManager& formatManagerToUse_,
  17344. AudioThumbnailCache& cacheToUse)
  17345. : formatManagerToUse (formatManagerToUse_),
  17346. cache (cacheToUse),
  17347. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17348. timeBeforeDeletingReader (2000)
  17349. {
  17350. clear();
  17351. }
  17352. AudioThumbnail::~AudioThumbnail()
  17353. {
  17354. cache.removeThumbnail (this);
  17355. const ScopedLock sl (readerLock);
  17356. reader = 0;
  17357. }
  17358. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17359. {
  17360. jassert (data.getData() != 0);
  17361. return static_cast <DataFormat*> (data.getData());
  17362. }
  17363. void AudioThumbnail::setSource (InputSource* const newSource)
  17364. {
  17365. cache.removeThumbnail (this);
  17366. timerCallback(); // stops the timer and deletes the reader
  17367. source = newSource;
  17368. clear();
  17369. if (newSource != 0
  17370. && ! (cache.loadThumb (*this, newSource->hashCode())
  17371. && isFullyLoaded()))
  17372. {
  17373. {
  17374. const ScopedLock sl (readerLock);
  17375. reader = createReader();
  17376. }
  17377. if (reader != 0)
  17378. {
  17379. initialiseFromAudioFile (*reader);
  17380. cache.addThumbnail (this);
  17381. }
  17382. }
  17383. sendChangeMessage (this);
  17384. }
  17385. bool AudioThumbnail::useTimeSlice()
  17386. {
  17387. const ScopedLock sl (readerLock);
  17388. if (isFullyLoaded())
  17389. {
  17390. if (reader != 0)
  17391. startTimer (timeBeforeDeletingReader);
  17392. cache.removeThumbnail (this);
  17393. return false;
  17394. }
  17395. if (reader == 0)
  17396. reader = createReader();
  17397. if (reader != 0)
  17398. {
  17399. readNextBlockFromAudioFile (*reader);
  17400. stopTimer();
  17401. sendChangeMessage (this);
  17402. const bool justFinished = isFullyLoaded();
  17403. if (justFinished)
  17404. cache.storeThumb (*this, source->hashCode());
  17405. return ! justFinished;
  17406. }
  17407. return false;
  17408. }
  17409. AudioFormatReader* AudioThumbnail::createReader() const
  17410. {
  17411. if (source != 0)
  17412. {
  17413. InputStream* const audioFileStream = source->createInputStream();
  17414. if (audioFileStream != 0)
  17415. return formatManagerToUse.createReaderFor (audioFileStream);
  17416. }
  17417. return 0;
  17418. }
  17419. void AudioThumbnail::timerCallback()
  17420. {
  17421. stopTimer();
  17422. const ScopedLock sl (readerLock);
  17423. reader = 0;
  17424. }
  17425. void AudioThumbnail::clear()
  17426. {
  17427. data.setSize (sizeof (DataFormat) + 3);
  17428. DataFormat* const d = getData();
  17429. d->thumbnailMagic[0] = 'j';
  17430. d->thumbnailMagic[1] = 'a';
  17431. d->thumbnailMagic[2] = 't';
  17432. d->thumbnailMagic[3] = 'm';
  17433. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17434. d->totalSamples = 0;
  17435. d->numFinishedSamples = 0;
  17436. d->numThumbnailSamples = 0;
  17437. d->numChannels = 0;
  17438. d->sampleRate = 0;
  17439. numSamplesCached = 0;
  17440. cacheNeedsRefilling = true;
  17441. }
  17442. void AudioThumbnail::loadFrom (InputStream& input)
  17443. {
  17444. const ScopedLock sl (readerLock);
  17445. data.setSize (0);
  17446. input.readIntoMemoryBlock (data);
  17447. DataFormat* const d = getData();
  17448. d->flipEndiannessIfBigEndian();
  17449. if (! (d->thumbnailMagic[0] == 'j'
  17450. && d->thumbnailMagic[1] == 'a'
  17451. && d->thumbnailMagic[2] == 't'
  17452. && d->thumbnailMagic[3] == 'm'))
  17453. {
  17454. clear();
  17455. }
  17456. numSamplesCached = 0;
  17457. cacheNeedsRefilling = true;
  17458. }
  17459. void AudioThumbnail::saveTo (OutputStream& output) const
  17460. {
  17461. const ScopedLock sl (readerLock);
  17462. DataFormat* const d = getData();
  17463. d->flipEndiannessIfBigEndian();
  17464. output.write (d, (int) data.getSize());
  17465. d->flipEndiannessIfBigEndian();
  17466. }
  17467. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17468. {
  17469. DataFormat* d = getData();
  17470. d->totalSamples = fileReader.lengthInSamples;
  17471. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17472. d->numFinishedSamples = 0;
  17473. d->sampleRate = roundToInt (fileReader.sampleRate);
  17474. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17475. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17476. d = getData();
  17477. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17478. return d->totalSamples > 0;
  17479. }
  17480. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17481. {
  17482. DataFormat* const d = getData();
  17483. if (d->numFinishedSamples < d->totalSamples)
  17484. {
  17485. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17486. generateSection (fileReader,
  17487. d->numFinishedSamples,
  17488. numToDo);
  17489. d->numFinishedSamples += numToDo;
  17490. }
  17491. cacheNeedsRefilling = true;
  17492. return d->numFinishedSamples < d->totalSamples;
  17493. }
  17494. int AudioThumbnail::getNumChannels() const throw()
  17495. {
  17496. return getData()->numChannels;
  17497. }
  17498. double AudioThumbnail::getTotalLength() const throw()
  17499. {
  17500. const DataFormat* const d = getData();
  17501. if (d->sampleRate > 0)
  17502. return d->totalSamples / (double) d->sampleRate;
  17503. else
  17504. return 0.0;
  17505. }
  17506. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17507. int64 startSample,
  17508. int numSamples)
  17509. {
  17510. DataFormat* const d = getData();
  17511. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17512. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17513. char* const l = getChannelData (0);
  17514. char* const r = getChannelData (1);
  17515. for (int i = firstDataPos; i < lastDataPos; ++i)
  17516. {
  17517. const int sourceStart = i * d->samplesPerThumbSample;
  17518. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17519. float lowestLeft, highestLeft, lowestRight, highestRight;
  17520. fileReader.readMaxLevels (sourceStart,
  17521. sourceEnd - sourceStart,
  17522. lowestLeft,
  17523. highestLeft,
  17524. lowestRight,
  17525. highestRight);
  17526. int n = i * 2;
  17527. if (r != 0)
  17528. {
  17529. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17530. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17531. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17532. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17533. }
  17534. else
  17535. {
  17536. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17537. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17538. }
  17539. }
  17540. }
  17541. char* AudioThumbnail::getChannelData (int channel) const
  17542. {
  17543. DataFormat* const d = getData();
  17544. if (channel >= 0 && channel < d->numChannels)
  17545. return d->data + (channel * 2 * d->numThumbnailSamples);
  17546. return 0;
  17547. }
  17548. bool AudioThumbnail::isFullyLoaded() const throw()
  17549. {
  17550. const DataFormat* const d = getData();
  17551. return d->numFinishedSamples >= d->totalSamples;
  17552. }
  17553. void AudioThumbnail::refillCache (const int numSamples,
  17554. double startTime,
  17555. const double timePerPixel)
  17556. {
  17557. const DataFormat* const d = getData();
  17558. if (numSamples <= 0
  17559. || timePerPixel <= 0.0
  17560. || d->sampleRate <= 0)
  17561. {
  17562. numSamplesCached = 0;
  17563. cacheNeedsRefilling = true;
  17564. return;
  17565. }
  17566. if (numSamples == numSamplesCached
  17567. && numChannelsCached == d->numChannels
  17568. && startTime == cachedStart
  17569. && timePerPixel == cachedTimePerPixel
  17570. && ! cacheNeedsRefilling)
  17571. {
  17572. return;
  17573. }
  17574. numSamplesCached = numSamples;
  17575. numChannelsCached = d->numChannels;
  17576. cachedStart = startTime;
  17577. cachedTimePerPixel = timePerPixel;
  17578. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17579. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17580. const ScopedLock sl (readerLock);
  17581. cacheNeedsRefilling = false;
  17582. if (needExtraDetail && reader == 0)
  17583. reader = createReader();
  17584. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17585. {
  17586. startTimer (timeBeforeDeletingReader);
  17587. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17588. int sample = roundToInt (startTime * d->sampleRate);
  17589. for (int i = numSamples; --i >= 0;)
  17590. {
  17591. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17592. if (sample >= 0)
  17593. {
  17594. if (sample >= reader->lengthInSamples)
  17595. break;
  17596. float lmin, lmax, rmin, rmax;
  17597. reader->readMaxLevels (sample,
  17598. jmax (1, nextSample - sample),
  17599. lmin, lmax, rmin, rmax);
  17600. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17601. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17602. if (numChannelsCached > 1)
  17603. {
  17604. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17605. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17606. }
  17607. cacheData += 2 * numChannelsCached;
  17608. }
  17609. startTime += timePerPixel;
  17610. sample = nextSample;
  17611. }
  17612. }
  17613. else
  17614. {
  17615. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17616. {
  17617. char* const channelData = getChannelData (channelNum);
  17618. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17619. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17620. startTime = cachedStart;
  17621. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17622. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17623. for (int i = numSamples; --i >= 0;)
  17624. {
  17625. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17626. if (sample >= 0 && channelData != 0)
  17627. {
  17628. char mx = -128;
  17629. char mn = 127;
  17630. while (sample <= nextSample)
  17631. {
  17632. if (sample >= numFinished)
  17633. break;
  17634. const int n = sample << 1;
  17635. const char sampMin = channelData [n];
  17636. const char sampMax = channelData [n + 1];
  17637. if (sampMin < mn)
  17638. mn = sampMin;
  17639. if (sampMax > mx)
  17640. mx = sampMax;
  17641. ++sample;
  17642. }
  17643. if (mn <= mx)
  17644. {
  17645. cacheData[0] = mn;
  17646. cacheData[1] = mx;
  17647. }
  17648. else
  17649. {
  17650. cacheData[0] = 1;
  17651. cacheData[1] = 0;
  17652. }
  17653. }
  17654. else
  17655. {
  17656. cacheData[0] = 1;
  17657. cacheData[1] = 0;
  17658. }
  17659. cacheData += numChannelsCached * 2;
  17660. startTime += timePerPixel;
  17661. sample = nextSample;
  17662. }
  17663. }
  17664. }
  17665. }
  17666. void AudioThumbnail::drawChannel (Graphics& g,
  17667. int x, int y, int w, int h,
  17668. double startTime,
  17669. double endTime,
  17670. int channelNum,
  17671. const float verticalZoomFactor)
  17672. {
  17673. refillCache (w, startTime, (endTime - startTime) / w);
  17674. if (numSamplesCached >= w
  17675. && channelNum >= 0
  17676. && channelNum < numChannelsCached)
  17677. {
  17678. const float topY = (float) y;
  17679. const float bottomY = topY + h;
  17680. const float midY = topY + h * 0.5f;
  17681. const float vscale = verticalZoomFactor * h / 256.0f;
  17682. const Rectangle<int> clip (g.getClipBounds());
  17683. const int skipLeft = jlimit (0, w, clip.getX() - x);
  17684. w -= skipLeft;
  17685. x += skipLeft;
  17686. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  17687. + (channelNum << 1)
  17688. + skipLeft * (numChannelsCached << 1);
  17689. while (--w >= 0)
  17690. {
  17691. const char mn = cacheData[0];
  17692. const char mx = cacheData[1];
  17693. cacheData += numChannelsCached << 1;
  17694. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  17695. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  17696. jmin (midY - mn * vscale + 0.3f, bottomY));
  17697. if (++x >= clip.getRight())
  17698. break;
  17699. }
  17700. }
  17701. }
  17702. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  17703. {
  17704. #if JUCE_BIG_ENDIAN
  17705. struct Flipper
  17706. {
  17707. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  17708. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  17709. };
  17710. Flipper::flip (samplesPerThumbSample);
  17711. Flipper::flip (totalSamples);
  17712. Flipper::flip (numFinishedSamples);
  17713. Flipper::flip (numThumbnailSamples);
  17714. Flipper::flip (numChannels);
  17715. Flipper::flip (sampleRate);
  17716. #endif
  17717. }
  17718. END_JUCE_NAMESPACE
  17719. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17720. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17721. BEGIN_JUCE_NAMESPACE
  17722. struct ThumbnailCacheEntry
  17723. {
  17724. int64 hash;
  17725. uint32 lastUsed;
  17726. MemoryBlock data;
  17727. juce_UseDebuggingNewOperator
  17728. };
  17729. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17730. : TimeSliceThread ("thumb cache"),
  17731. maxNumThumbsToStore (maxNumThumbsToStore_)
  17732. {
  17733. startThread (2);
  17734. }
  17735. AudioThumbnailCache::~AudioThumbnailCache()
  17736. {
  17737. }
  17738. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17739. {
  17740. for (int i = thumbs.size(); --i >= 0;)
  17741. {
  17742. if (thumbs[i]->hash == hashCode)
  17743. {
  17744. MemoryInputStream in (thumbs[i]->data, false);
  17745. thumb.loadFrom (in);
  17746. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17747. return true;
  17748. }
  17749. }
  17750. return false;
  17751. }
  17752. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17753. const int64 hashCode)
  17754. {
  17755. MemoryOutputStream out;
  17756. thumb.saveTo (out);
  17757. ThumbnailCacheEntry* te = 0;
  17758. for (int i = thumbs.size(); --i >= 0;)
  17759. {
  17760. if (thumbs[i]->hash == hashCode)
  17761. {
  17762. te = thumbs[i];
  17763. break;
  17764. }
  17765. }
  17766. if (te == 0)
  17767. {
  17768. te = new ThumbnailCacheEntry();
  17769. te->hash = hashCode;
  17770. if (thumbs.size() < maxNumThumbsToStore)
  17771. {
  17772. thumbs.add (te);
  17773. }
  17774. else
  17775. {
  17776. int oldest = 0;
  17777. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17778. int i;
  17779. for (i = thumbs.size(); --i >= 0;)
  17780. if (thumbs[i]->lastUsed < oldestTime)
  17781. oldest = i;
  17782. thumbs.set (i, te);
  17783. }
  17784. }
  17785. te->lastUsed = Time::getMillisecondCounter();
  17786. te->data.setSize (0);
  17787. te->data.append (out.getData(), out.getDataSize());
  17788. }
  17789. void AudioThumbnailCache::clear()
  17790. {
  17791. thumbs.clear();
  17792. }
  17793. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17794. {
  17795. addTimeSliceClient (thumb);
  17796. }
  17797. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17798. {
  17799. removeTimeSliceClient (thumb);
  17800. }
  17801. END_JUCE_NAMESPACE
  17802. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17803. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17804. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17805. #if ! JUCE_WINDOWS
  17806. #include <QuickTime/Movies.h>
  17807. #include <QuickTime/QTML.h>
  17808. #include <QuickTime/QuickTimeComponents.h>
  17809. #include <QuickTime/MediaHandlers.h>
  17810. #include <QuickTime/ImageCodec.h>
  17811. #else
  17812. #if JUCE_MSVC
  17813. #pragma warning (push)
  17814. #pragma warning (disable : 4100)
  17815. #endif
  17816. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17817. add its header directory to your include path.
  17818. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17819. flag in juce_Config.h
  17820. */
  17821. #include <Movies.h>
  17822. #include <QTML.h>
  17823. #include <QuickTimeComponents.h>
  17824. #include <MediaHandlers.h>
  17825. #include <ImageCodec.h>
  17826. #if JUCE_MSVC
  17827. #pragma warning (pop)
  17828. #endif
  17829. #endif
  17830. BEGIN_JUCE_NAMESPACE
  17831. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17832. static const char* const quickTimeFormatName = "QuickTime file";
  17833. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17834. class QTAudioReader : public AudioFormatReader
  17835. {
  17836. public:
  17837. QTAudioReader (InputStream* const input_, const int trackNum_)
  17838. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17839. ok (false),
  17840. movie (0),
  17841. trackNum (trackNum_),
  17842. lastSampleRead (0),
  17843. lastThreadId (0),
  17844. extractor (0),
  17845. dataHandle (0)
  17846. {
  17847. bufferList.calloc (256, 1);
  17848. #if JUCE_WINDOWS
  17849. if (InitializeQTML (0) != noErr)
  17850. return;
  17851. #endif
  17852. if (EnterMovies() != noErr)
  17853. return;
  17854. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17855. if (! opened)
  17856. return;
  17857. {
  17858. const int numTracks = GetMovieTrackCount (movie);
  17859. int trackCount = 0;
  17860. for (int i = 1; i <= numTracks; ++i)
  17861. {
  17862. track = GetMovieIndTrack (movie, i);
  17863. media = GetTrackMedia (track);
  17864. OSType mediaType;
  17865. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17866. if (mediaType == SoundMediaType
  17867. && trackCount++ == trackNum_)
  17868. {
  17869. ok = true;
  17870. break;
  17871. }
  17872. }
  17873. }
  17874. if (! ok)
  17875. return;
  17876. ok = false;
  17877. lengthInSamples = GetMediaDecodeDuration (media);
  17878. usesFloatingPointData = false;
  17879. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17880. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17881. / GetMediaTimeScale (media);
  17882. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17883. unsigned long output_layout_size;
  17884. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17885. kQTPropertyClass_MovieAudioExtraction_Audio,
  17886. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17887. 0, &output_layout_size, 0);
  17888. if (err != noErr)
  17889. return;
  17890. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17891. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17892. err = MovieAudioExtractionGetProperty (extractor,
  17893. kQTPropertyClass_MovieAudioExtraction_Audio,
  17894. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17895. output_layout_size, qt_audio_channel_layout, 0);
  17896. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17897. err = MovieAudioExtractionSetProperty (extractor,
  17898. kQTPropertyClass_MovieAudioExtraction_Audio,
  17899. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17900. output_layout_size,
  17901. qt_audio_channel_layout);
  17902. err = MovieAudioExtractionGetProperty (extractor,
  17903. kQTPropertyClass_MovieAudioExtraction_Audio,
  17904. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17905. sizeof (inputStreamDesc),
  17906. &inputStreamDesc, 0);
  17907. if (err != noErr)
  17908. return;
  17909. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17910. | kAudioFormatFlagIsPacked
  17911. | kAudioFormatFlagsNativeEndian;
  17912. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17913. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17914. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17915. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17916. err = MovieAudioExtractionSetProperty (extractor,
  17917. kQTPropertyClass_MovieAudioExtraction_Audio,
  17918. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17919. sizeof (inputStreamDesc),
  17920. &inputStreamDesc);
  17921. if (err != noErr)
  17922. return;
  17923. Boolean allChannelsDiscrete = false;
  17924. err = MovieAudioExtractionSetProperty (extractor,
  17925. kQTPropertyClass_MovieAudioExtraction_Movie,
  17926. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17927. sizeof (allChannelsDiscrete),
  17928. &allChannelsDiscrete);
  17929. if (err != noErr)
  17930. return;
  17931. bufferList->mNumberBuffers = 1;
  17932. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17933. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17934. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17935. bufferList->mBuffers[0].mData = dataBuffer;
  17936. sampleRate = inputStreamDesc.mSampleRate;
  17937. bitsPerSample = 16;
  17938. numChannels = inputStreamDesc.mChannelsPerFrame;
  17939. detachThread();
  17940. ok = true;
  17941. }
  17942. ~QTAudioReader()
  17943. {
  17944. if (dataHandle != 0)
  17945. DisposeHandle (dataHandle);
  17946. if (extractor != 0)
  17947. {
  17948. MovieAudioExtractionEnd (extractor);
  17949. extractor = 0;
  17950. }
  17951. checkThreadIsAttached();
  17952. DisposeMovie (movie);
  17953. #if JUCE_MAC
  17954. ExitMoviesOnThread ();
  17955. #endif
  17956. }
  17957. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17958. int64 startSampleInFile, int numSamples)
  17959. {
  17960. checkThreadIsAttached();
  17961. while (numSamples > 0)
  17962. {
  17963. if (! loadFrame ((int) startSampleInFile))
  17964. return false;
  17965. const int numToDo = jmin (numSamples, samplesPerFrame);
  17966. for (int j = numDestChannels; --j >= 0;)
  17967. {
  17968. if (destSamples[j] != 0)
  17969. {
  17970. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17971. for (int i = 0; i < numToDo; ++i)
  17972. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17973. }
  17974. }
  17975. startOffsetInDestBuffer += numToDo;
  17976. startSampleInFile += numToDo;
  17977. numSamples -= numToDo;
  17978. }
  17979. detachThread();
  17980. return true;
  17981. }
  17982. bool loadFrame (const int sampleNum)
  17983. {
  17984. if (lastSampleRead != sampleNum)
  17985. {
  17986. TimeRecord time;
  17987. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17988. time.base = 0;
  17989. time.value.hi = 0;
  17990. time.value.lo = (UInt32) sampleNum;
  17991. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17992. kQTPropertyClass_MovieAudioExtraction_Movie,
  17993. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17994. sizeof (time), &time);
  17995. if (err != noErr)
  17996. return false;
  17997. }
  17998. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17999. UInt32 outFlags = 0;
  18000. UInt32 actualNumSamples = samplesPerFrame;
  18001. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  18002. bufferList, &outFlags);
  18003. lastSampleRead = sampleNum + samplesPerFrame;
  18004. return err == noErr;
  18005. }
  18006. juce_UseDebuggingNewOperator
  18007. bool ok;
  18008. private:
  18009. Movie movie;
  18010. Media media;
  18011. Track track;
  18012. const int trackNum;
  18013. double trackUnitsPerFrame;
  18014. int samplesPerFrame;
  18015. int lastSampleRead;
  18016. Thread::ThreadID lastThreadId;
  18017. MovieAudioExtractionRef extractor;
  18018. AudioStreamBasicDescription inputStreamDesc;
  18019. HeapBlock <AudioBufferList> bufferList;
  18020. HeapBlock <char> dataBuffer;
  18021. Handle dataHandle;
  18022. void checkThreadIsAttached()
  18023. {
  18024. #if JUCE_MAC
  18025. if (Thread::getCurrentThreadId() != lastThreadId)
  18026. EnterMoviesOnThread (0);
  18027. AttachMovieToCurrentThread (movie);
  18028. #endif
  18029. }
  18030. void detachThread()
  18031. {
  18032. #if JUCE_MAC
  18033. DetachMovieFromCurrentThread (movie);
  18034. #endif
  18035. }
  18036. QTAudioReader (const QTAudioReader&);
  18037. QTAudioReader& operator= (const QTAudioReader&);
  18038. };
  18039. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18040. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18041. {
  18042. }
  18043. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18044. {
  18045. }
  18046. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  18047. {
  18048. return Array<int>();
  18049. }
  18050. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  18051. {
  18052. return Array<int>();
  18053. }
  18054. bool QuickTimeAudioFormat::canDoStereo()
  18055. {
  18056. return true;
  18057. }
  18058. bool QuickTimeAudioFormat::canDoMono()
  18059. {
  18060. return true;
  18061. }
  18062. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18063. const bool deleteStreamIfOpeningFails)
  18064. {
  18065. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18066. if (r->ok)
  18067. return r.release();
  18068. if (! deleteStreamIfOpeningFails)
  18069. r->input = 0;
  18070. return 0;
  18071. }
  18072. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18073. double /*sampleRateToUse*/,
  18074. unsigned int /*numberOfChannels*/,
  18075. int /*bitsPerSample*/,
  18076. const StringPairArray& /*metadataValues*/,
  18077. int /*qualityOptionIndex*/)
  18078. {
  18079. jassertfalse; // not yet implemented!
  18080. return 0;
  18081. }
  18082. END_JUCE_NAMESPACE
  18083. #endif
  18084. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18085. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18086. BEGIN_JUCE_NAMESPACE
  18087. static const char* const wavFormatName = "WAV file";
  18088. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18089. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18090. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18091. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18092. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18093. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18094. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18095. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18096. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18097. const String& originator,
  18098. const String& originatorRef,
  18099. const Time& date,
  18100. const int64 timeReferenceSamples,
  18101. const String& codingHistory)
  18102. {
  18103. StringPairArray m;
  18104. m.set (bwavDescription, description);
  18105. m.set (bwavOriginator, originator);
  18106. m.set (bwavOriginatorRef, originatorRef);
  18107. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18108. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18109. m.set (bwavTimeReference, String (timeReferenceSamples));
  18110. m.set (bwavCodingHistory, codingHistory);
  18111. return m;
  18112. }
  18113. #if JUCE_MSVC
  18114. #pragma pack (push, 1)
  18115. #define PACKED
  18116. #elif JUCE_GCC
  18117. #define PACKED __attribute__((packed))
  18118. #else
  18119. #define PACKED
  18120. #endif
  18121. struct BWAVChunk
  18122. {
  18123. char description [256];
  18124. char originator [32];
  18125. char originatorRef [32];
  18126. char originationDate [10];
  18127. char originationTime [8];
  18128. uint32 timeRefLow;
  18129. uint32 timeRefHigh;
  18130. uint16 version;
  18131. uint8 umid[64];
  18132. uint8 reserved[190];
  18133. char codingHistory[1];
  18134. void copyTo (StringPairArray& values) const
  18135. {
  18136. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18137. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18138. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18139. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18140. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18141. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18142. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18143. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18144. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18145. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18146. }
  18147. static MemoryBlock createFrom (const StringPairArray& values)
  18148. {
  18149. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18150. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18151. data.fillWith (0);
  18152. BWAVChunk* b = (BWAVChunk*) data.getData();
  18153. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18154. // as they get called in the right order..
  18155. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18156. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18157. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18158. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18159. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18160. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18161. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18162. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18163. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18164. if (b->description[0] != 0
  18165. || b->originator[0] != 0
  18166. || b->originationDate[0] != 0
  18167. || b->originationTime[0] != 0
  18168. || b->codingHistory[0] != 0
  18169. || time != 0)
  18170. {
  18171. return data;
  18172. }
  18173. return MemoryBlock();
  18174. }
  18175. } PACKED;
  18176. struct SMPLChunk
  18177. {
  18178. struct SampleLoop
  18179. {
  18180. uint32 identifier;
  18181. uint32 type;
  18182. uint32 start;
  18183. uint32 end;
  18184. uint32 fraction;
  18185. uint32 playCount;
  18186. } PACKED;
  18187. uint32 manufacturer;
  18188. uint32 product;
  18189. uint32 samplePeriod;
  18190. uint32 midiUnityNote;
  18191. uint32 midiPitchFraction;
  18192. uint32 smpteFormat;
  18193. uint32 smpteOffset;
  18194. uint32 numSampleLoops;
  18195. uint32 samplerData;
  18196. SampleLoop loops[1];
  18197. void copyTo (StringPairArray& values, const int totalSize) const
  18198. {
  18199. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18200. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18201. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18202. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18203. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18204. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18205. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18206. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18207. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18208. for (uint32 i = 0; i < numSampleLoops; ++i)
  18209. {
  18210. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18211. break;
  18212. const String prefix ("Loop" + String(i));
  18213. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18214. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18215. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18216. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18217. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18218. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18219. }
  18220. }
  18221. static MemoryBlock createFrom (const StringPairArray& values)
  18222. {
  18223. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18224. if (numLoops <= 0)
  18225. return MemoryBlock();
  18226. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18227. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18228. data.fillWith (0);
  18229. SMPLChunk* s = (SMPLChunk*) data.getData();
  18230. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18231. // as they get called in the right order..
  18232. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18233. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18234. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18235. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18236. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18237. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18238. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18239. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18240. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18241. for (int i = 0; i < numLoops; ++i)
  18242. {
  18243. const String prefix ("Loop" + String(i));
  18244. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18245. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18246. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18247. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18248. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18249. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18250. }
  18251. return data;
  18252. }
  18253. } PACKED;
  18254. struct ExtensibleWavSubFormat
  18255. {
  18256. uint32 data1;
  18257. uint16 data2;
  18258. uint16 data3;
  18259. uint8 data4[8];
  18260. } PACKED;
  18261. #if JUCE_MSVC
  18262. #pragma pack (pop)
  18263. #endif
  18264. #undef PACKED
  18265. class WavAudioFormatReader : public AudioFormatReader
  18266. {
  18267. int bytesPerFrame;
  18268. int64 dataChunkStart, dataLength;
  18269. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18270. WavAudioFormatReader (const WavAudioFormatReader&);
  18271. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18272. public:
  18273. int64 bwavChunkStart, bwavSize;
  18274. WavAudioFormatReader (InputStream* const in)
  18275. : AudioFormatReader (in, TRANS (wavFormatName)),
  18276. dataLength (0),
  18277. bwavChunkStart (0),
  18278. bwavSize (0)
  18279. {
  18280. if (input->readInt() == chunkName ("RIFF"))
  18281. {
  18282. const uint32 len = (uint32) input->readInt();
  18283. const int64 end = input->getPosition() + len;
  18284. bool hasGotType = false;
  18285. bool hasGotData = false;
  18286. if (input->readInt() == chunkName ("WAVE"))
  18287. {
  18288. while (input->getPosition() < end
  18289. && ! input->isExhausted())
  18290. {
  18291. const int chunkType = input->readInt();
  18292. uint32 length = (uint32) input->readInt();
  18293. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18294. if (chunkType == chunkName ("fmt "))
  18295. {
  18296. // read the format chunk
  18297. const unsigned short format = input->readShort();
  18298. const short numChans = input->readShort();
  18299. sampleRate = input->readInt();
  18300. const int bytesPerSec = input->readInt();
  18301. numChannels = numChans;
  18302. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18303. bitsPerSample = 8 * bytesPerFrame / numChans;
  18304. if (format == 3)
  18305. {
  18306. usesFloatingPointData = true;
  18307. }
  18308. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18309. {
  18310. if (length < 40) // too short
  18311. {
  18312. bytesPerFrame = 0;
  18313. }
  18314. else
  18315. {
  18316. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18317. ExtensibleWavSubFormat subFormat;
  18318. subFormat.data1 = input->readInt();
  18319. subFormat.data2 = input->readShort();
  18320. subFormat.data3 = input->readShort();
  18321. input->read (subFormat.data4, sizeof (subFormat.data4));
  18322. const ExtensibleWavSubFormat pcmFormat
  18323. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18324. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18325. {
  18326. const ExtensibleWavSubFormat ambisonicFormat
  18327. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18328. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18329. bytesPerFrame = 0;
  18330. }
  18331. }
  18332. }
  18333. else if (format != 1)
  18334. {
  18335. bytesPerFrame = 0;
  18336. }
  18337. hasGotType = true;
  18338. }
  18339. else if (chunkType == chunkName ("data"))
  18340. {
  18341. // get the data chunk's position
  18342. dataLength = length;
  18343. dataChunkStart = input->getPosition();
  18344. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18345. hasGotData = true;
  18346. }
  18347. else if (chunkType == chunkName ("bext"))
  18348. {
  18349. bwavChunkStart = input->getPosition();
  18350. bwavSize = length;
  18351. // Broadcast-wav extension chunk..
  18352. HeapBlock <BWAVChunk> bwav;
  18353. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18354. input->read (bwav, length);
  18355. bwav->copyTo (metadataValues);
  18356. }
  18357. else if (chunkType == chunkName ("smpl"))
  18358. {
  18359. HeapBlock <SMPLChunk> smpl;
  18360. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18361. input->read (smpl, length);
  18362. smpl->copyTo (metadataValues, length);
  18363. }
  18364. else if (chunkEnd <= input->getPosition())
  18365. {
  18366. break;
  18367. }
  18368. input->setPosition (chunkEnd);
  18369. }
  18370. }
  18371. }
  18372. }
  18373. ~WavAudioFormatReader()
  18374. {
  18375. }
  18376. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18377. int64 startSampleInFile, int numSamples)
  18378. {
  18379. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18380. if (samplesAvailable < numSamples)
  18381. {
  18382. for (int i = numDestChannels; --i >= 0;)
  18383. if (destSamples[i] != 0)
  18384. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18385. numSamples = (int) samplesAvailable;
  18386. }
  18387. if (numSamples <= 0)
  18388. return true;
  18389. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18390. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18391. char tempBuffer [tempBufSize];
  18392. while (numSamples > 0)
  18393. {
  18394. int* left = destSamples[0];
  18395. if (left != 0)
  18396. left += startOffsetInDestBuffer;
  18397. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  18398. if (right != 0)
  18399. right += startOffsetInDestBuffer;
  18400. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18401. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18402. if (bytesRead < numThisTime * bytesPerFrame)
  18403. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18404. if (bitsPerSample == 16)
  18405. {
  18406. const short* src = reinterpret_cast <const short*> (tempBuffer);
  18407. if (numChannels > 1)
  18408. {
  18409. if (left == 0)
  18410. {
  18411. for (int i = numThisTime; --i >= 0;)
  18412. {
  18413. ++src;
  18414. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18415. }
  18416. }
  18417. else if (right == 0)
  18418. {
  18419. for (int i = numThisTime; --i >= 0;)
  18420. {
  18421. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18422. ++src;
  18423. }
  18424. }
  18425. else
  18426. {
  18427. for (int i = numThisTime; --i >= 0;)
  18428. {
  18429. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18430. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18431. }
  18432. }
  18433. }
  18434. else
  18435. {
  18436. for (int i = numThisTime; --i >= 0;)
  18437. {
  18438. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18439. }
  18440. }
  18441. }
  18442. else if (bitsPerSample == 24)
  18443. {
  18444. const char* src = tempBuffer;
  18445. if (numChannels > 1)
  18446. {
  18447. if (left == 0)
  18448. {
  18449. for (int i = numThisTime; --i >= 0;)
  18450. {
  18451. src += 3;
  18452. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18453. src += 3;
  18454. }
  18455. }
  18456. else if (right == 0)
  18457. {
  18458. for (int i = numThisTime; --i >= 0;)
  18459. {
  18460. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18461. src += 6;
  18462. }
  18463. }
  18464. else
  18465. {
  18466. for (int i = 0; i < numThisTime; ++i)
  18467. {
  18468. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18469. src += 3;
  18470. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18471. src += 3;
  18472. }
  18473. }
  18474. }
  18475. else
  18476. {
  18477. for (int i = 0; i < numThisTime; ++i)
  18478. {
  18479. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18480. src += 3;
  18481. }
  18482. }
  18483. }
  18484. else if (bitsPerSample == 32)
  18485. {
  18486. const unsigned int* src = (const unsigned int*) tempBuffer;
  18487. unsigned int* l = (unsigned int*) left;
  18488. unsigned int* r = (unsigned int*) right;
  18489. if (numChannels > 1)
  18490. {
  18491. if (l == 0)
  18492. {
  18493. for (int i = numThisTime; --i >= 0;)
  18494. {
  18495. ++src;
  18496. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18497. }
  18498. }
  18499. else if (r == 0)
  18500. {
  18501. for (int i = numThisTime; --i >= 0;)
  18502. {
  18503. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18504. ++src;
  18505. }
  18506. }
  18507. else
  18508. {
  18509. for (int i = numThisTime; --i >= 0;)
  18510. {
  18511. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18512. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18513. }
  18514. }
  18515. }
  18516. else
  18517. {
  18518. for (int i = numThisTime; --i >= 0;)
  18519. {
  18520. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18521. }
  18522. }
  18523. left = (int*)l;
  18524. right = (int*)r;
  18525. }
  18526. else if (bitsPerSample == 8)
  18527. {
  18528. const unsigned char* src = (const unsigned char*) tempBuffer;
  18529. if (numChannels > 1)
  18530. {
  18531. if (left == 0)
  18532. {
  18533. for (int i = numThisTime; --i >= 0;)
  18534. {
  18535. ++src;
  18536. *right++ = ((int) *src++ - 128) << 24;
  18537. }
  18538. }
  18539. else if (right == 0)
  18540. {
  18541. for (int i = numThisTime; --i >= 0;)
  18542. {
  18543. *left++ = ((int) *src++ - 128) << 24;
  18544. ++src;
  18545. }
  18546. }
  18547. else
  18548. {
  18549. for (int i = numThisTime; --i >= 0;)
  18550. {
  18551. *left++ = ((int) *src++ - 128) << 24;
  18552. *right++ = ((int) *src++ - 128) << 24;
  18553. }
  18554. }
  18555. }
  18556. else
  18557. {
  18558. for (int i = numThisTime; --i >= 0;)
  18559. {
  18560. *left++ = ((int)*src++ - 128) << 24;
  18561. }
  18562. }
  18563. }
  18564. startOffsetInDestBuffer += numThisTime;
  18565. numSamples -= numThisTime;
  18566. }
  18567. if (numSamples > 0)
  18568. {
  18569. for (int i = numDestChannels; --i >= 0;)
  18570. if (destSamples[i] != 0)
  18571. zeromem (destSamples[i] + startOffsetInDestBuffer,
  18572. sizeof (int) * numSamples);
  18573. }
  18574. return true;
  18575. }
  18576. juce_UseDebuggingNewOperator
  18577. };
  18578. class WavAudioFormatWriter : public AudioFormatWriter
  18579. {
  18580. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18581. uint32 lengthInSamples, bytesWritten;
  18582. int64 headerPosition;
  18583. bool writeFailed;
  18584. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18585. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18586. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18587. void writeHeader()
  18588. {
  18589. const bool seekedOk = output->setPosition (headerPosition);
  18590. (void) seekedOk;
  18591. // if this fails, you've given it an output stream that can't seek! It needs
  18592. // to be able to seek back to write the header
  18593. jassert (seekedOk);
  18594. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18595. output->writeInt (chunkName ("RIFF"));
  18596. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18597. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18598. output->writeInt (chunkName ("WAVE"));
  18599. output->writeInt (chunkName ("fmt "));
  18600. output->writeInt (16);
  18601. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18602. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18603. output->writeShort ((short) numChannels);
  18604. output->writeInt ((int) sampleRate);
  18605. output->writeInt (bytesPerFrame * (int) sampleRate);
  18606. output->writeShort ((short) bytesPerFrame);
  18607. output->writeShort ((short) bitsPerSample);
  18608. if (bwavChunk.getSize() > 0)
  18609. {
  18610. output->writeInt (chunkName ("bext"));
  18611. output->writeInt ((int) bwavChunk.getSize());
  18612. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18613. }
  18614. if (smplChunk.getSize() > 0)
  18615. {
  18616. output->writeInt (chunkName ("smpl"));
  18617. output->writeInt ((int) smplChunk.getSize());
  18618. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18619. }
  18620. output->writeInt (chunkName ("data"));
  18621. output->writeInt (lengthInSamples * bytesPerFrame);
  18622. usesFloatingPointData = (bitsPerSample == 32);
  18623. }
  18624. public:
  18625. WavAudioFormatWriter (OutputStream* const out,
  18626. const double sampleRate_,
  18627. const unsigned int numChannels_,
  18628. const int bits,
  18629. const StringPairArray& metadataValues)
  18630. : AudioFormatWriter (out,
  18631. TRANS (wavFormatName),
  18632. sampleRate_,
  18633. numChannels_,
  18634. bits),
  18635. lengthInSamples (0),
  18636. bytesWritten (0),
  18637. writeFailed (false)
  18638. {
  18639. if (metadataValues.size() > 0)
  18640. {
  18641. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18642. smplChunk = SMPLChunk::createFrom (metadataValues);
  18643. }
  18644. headerPosition = out->getPosition();
  18645. writeHeader();
  18646. }
  18647. ~WavAudioFormatWriter()
  18648. {
  18649. writeHeader();
  18650. }
  18651. bool write (const int** data, int numSamples)
  18652. {
  18653. if (writeFailed)
  18654. return false;
  18655. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18656. tempBlock.ensureSize (bytes, false);
  18657. char* buffer = static_cast <char*> (tempBlock.getData());
  18658. const int* left = data[0];
  18659. const int* right = data[1];
  18660. if (right == 0)
  18661. right = left;
  18662. if (bitsPerSample == 16)
  18663. {
  18664. short* b = (short*) buffer;
  18665. if (numChannels > 1)
  18666. {
  18667. for (int i = numSamples; --i >= 0;)
  18668. {
  18669. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  18670. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  18671. }
  18672. }
  18673. else
  18674. {
  18675. for (int i = numSamples; --i >= 0;)
  18676. {
  18677. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  18678. }
  18679. }
  18680. }
  18681. else if (bitsPerSample == 24)
  18682. {
  18683. char* b = buffer;
  18684. if (numChannels > 1)
  18685. {
  18686. for (int i = numSamples; --i >= 0;)
  18687. {
  18688. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  18689. b += 3;
  18690. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  18691. b += 3;
  18692. }
  18693. }
  18694. else
  18695. {
  18696. for (int i = numSamples; --i >= 0;)
  18697. {
  18698. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  18699. b += 3;
  18700. }
  18701. }
  18702. }
  18703. else if (bitsPerSample == 32)
  18704. {
  18705. unsigned int* b = (unsigned int*) buffer;
  18706. if (numChannels > 1)
  18707. {
  18708. for (int i = numSamples; --i >= 0;)
  18709. {
  18710. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  18711. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  18712. }
  18713. }
  18714. else
  18715. {
  18716. for (int i = numSamples; --i >= 0;)
  18717. {
  18718. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  18719. }
  18720. }
  18721. }
  18722. else if (bitsPerSample == 8)
  18723. {
  18724. unsigned char* b = (unsigned char*) buffer;
  18725. if (numChannels > 1)
  18726. {
  18727. for (int i = numSamples; --i >= 0;)
  18728. {
  18729. *b++ = (unsigned char) (128 + (*left++ >> 24));
  18730. *b++ = (unsigned char) (128 + (*right++ >> 24));
  18731. }
  18732. }
  18733. else
  18734. {
  18735. for (int i = numSamples; --i >= 0;)
  18736. {
  18737. *b++ = (unsigned char) (128 + (*left++ >> 24));
  18738. }
  18739. }
  18740. }
  18741. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18742. || ! output->write (buffer, bytes))
  18743. {
  18744. // failed to write to disk, so let's try writing the header.
  18745. // If it's just run out of disk space, then if it does manage
  18746. // to write the header, we'll still have a useable file..
  18747. writeHeader();
  18748. writeFailed = true;
  18749. return false;
  18750. }
  18751. else
  18752. {
  18753. bytesWritten += bytes;
  18754. lengthInSamples += numSamples;
  18755. return true;
  18756. }
  18757. }
  18758. juce_UseDebuggingNewOperator
  18759. };
  18760. WavAudioFormat::WavAudioFormat()
  18761. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18762. {
  18763. }
  18764. WavAudioFormat::~WavAudioFormat()
  18765. {
  18766. }
  18767. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18768. {
  18769. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18770. return Array <int> (rates);
  18771. }
  18772. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18773. {
  18774. const int depths[] = { 8, 16, 24, 32, 0 };
  18775. return Array <int> (depths);
  18776. }
  18777. bool WavAudioFormat::canDoStereo()
  18778. {
  18779. return true;
  18780. }
  18781. bool WavAudioFormat::canDoMono()
  18782. {
  18783. return true;
  18784. }
  18785. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18786. const bool deleteStreamIfOpeningFails)
  18787. {
  18788. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18789. if (r->sampleRate != 0)
  18790. return r.release();
  18791. if (! deleteStreamIfOpeningFails)
  18792. r->input = 0;
  18793. return 0;
  18794. }
  18795. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18796. double sampleRate,
  18797. unsigned int numChannels,
  18798. int bitsPerSample,
  18799. const StringPairArray& metadataValues,
  18800. int /*qualityOptionIndex*/)
  18801. {
  18802. if (getPossibleBitDepths().contains (bitsPerSample))
  18803. {
  18804. return new WavAudioFormatWriter (out,
  18805. sampleRate,
  18806. numChannels,
  18807. bitsPerSample,
  18808. metadataValues);
  18809. }
  18810. return 0;
  18811. }
  18812. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18813. {
  18814. TemporaryFile tempFile (file);
  18815. WavAudioFormat wav;
  18816. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18817. if (reader != 0)
  18818. {
  18819. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18820. if (outStream != 0)
  18821. {
  18822. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18823. reader->numChannels, reader->bitsPerSample,
  18824. metadata, 0));
  18825. if (writer != 0)
  18826. {
  18827. outStream.release();
  18828. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18829. writer = 0;
  18830. reader = 0;
  18831. return ok && tempFile.overwriteTargetFileWithTemporary();
  18832. }
  18833. }
  18834. }
  18835. return false;
  18836. }
  18837. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18838. {
  18839. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18840. if (reader != 0)
  18841. {
  18842. const int64 bwavPos = reader->bwavChunkStart;
  18843. const int64 bwavSize = reader->bwavSize;
  18844. reader = 0;
  18845. if (bwavSize > 0)
  18846. {
  18847. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18848. if (chunk.getSize() <= (size_t) bwavSize)
  18849. {
  18850. // the new one will fit in the space available, so write it directly..
  18851. const int64 oldSize = wavFile.getSize();
  18852. {
  18853. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18854. out->setPosition (bwavPos);
  18855. out->write (chunk.getData(), (int) chunk.getSize());
  18856. out->setPosition (oldSize);
  18857. }
  18858. jassert (wavFile.getSize() == oldSize);
  18859. return true;
  18860. }
  18861. }
  18862. }
  18863. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18864. }
  18865. END_JUCE_NAMESPACE
  18866. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18867. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18868. #if JUCE_USE_CDREADER
  18869. BEGIN_JUCE_NAMESPACE
  18870. int AudioCDReader::getNumTracks() const
  18871. {
  18872. return trackStartSamples.size() - 1;
  18873. }
  18874. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18875. {
  18876. return trackStartSamples [trackNum];
  18877. }
  18878. const Array<int>& AudioCDReader::getTrackOffsets() const
  18879. {
  18880. return trackStartSamples;
  18881. }
  18882. int AudioCDReader::getCDDBId()
  18883. {
  18884. int checksum = 0;
  18885. const int numTracks = getNumTracks();
  18886. for (int i = 0; i < numTracks; ++i)
  18887. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18888. checksum += offset % 10;
  18889. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18890. // CCLLLLTT: checksum, length, tracks
  18891. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18892. }
  18893. END_JUCE_NAMESPACE
  18894. #endif
  18895. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18896. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18897. BEGIN_JUCE_NAMESPACE
  18898. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18899. const bool deleteReaderWhenThisIsDeleted)
  18900. : reader (reader_),
  18901. deleteReader (deleteReaderWhenThisIsDeleted),
  18902. nextPlayPos (0),
  18903. looping (false)
  18904. {
  18905. jassert (reader != 0);
  18906. }
  18907. AudioFormatReaderSource::~AudioFormatReaderSource()
  18908. {
  18909. releaseResources();
  18910. if (deleteReader)
  18911. delete reader;
  18912. }
  18913. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18914. {
  18915. nextPlayPos = newPosition;
  18916. }
  18917. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18918. {
  18919. looping = shouldLoop;
  18920. }
  18921. int AudioFormatReaderSource::getNextReadPosition() const
  18922. {
  18923. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18924. : nextPlayPos;
  18925. }
  18926. int AudioFormatReaderSource::getTotalLength() const
  18927. {
  18928. return (int) reader->lengthInSamples;
  18929. }
  18930. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18931. double /*sampleRate*/)
  18932. {
  18933. }
  18934. void AudioFormatReaderSource::releaseResources()
  18935. {
  18936. }
  18937. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18938. {
  18939. if (info.numSamples > 0)
  18940. {
  18941. const int start = nextPlayPos;
  18942. if (looping)
  18943. {
  18944. const int newStart = start % (int) reader->lengthInSamples;
  18945. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18946. if (newEnd > newStart)
  18947. {
  18948. info.buffer->readFromAudioReader (reader,
  18949. info.startSample,
  18950. newEnd - newStart,
  18951. newStart,
  18952. true, true);
  18953. }
  18954. else
  18955. {
  18956. const int endSamps = (int) reader->lengthInSamples - newStart;
  18957. info.buffer->readFromAudioReader (reader,
  18958. info.startSample,
  18959. endSamps,
  18960. newStart,
  18961. true, true);
  18962. info.buffer->readFromAudioReader (reader,
  18963. info.startSample + endSamps,
  18964. newEnd,
  18965. 0,
  18966. true, true);
  18967. }
  18968. nextPlayPos = newEnd;
  18969. }
  18970. else
  18971. {
  18972. info.buffer->readFromAudioReader (reader,
  18973. info.startSample,
  18974. info.numSamples,
  18975. start,
  18976. true, true);
  18977. nextPlayPos += info.numSamples;
  18978. }
  18979. }
  18980. }
  18981. END_JUCE_NAMESPACE
  18982. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18983. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18984. BEGIN_JUCE_NAMESPACE
  18985. AudioSourcePlayer::AudioSourcePlayer()
  18986. : source (0),
  18987. sampleRate (0),
  18988. bufferSize (0),
  18989. tempBuffer (2, 8),
  18990. lastGain (1.0f),
  18991. gain (1.0f)
  18992. {
  18993. }
  18994. AudioSourcePlayer::~AudioSourcePlayer()
  18995. {
  18996. setSource (0);
  18997. }
  18998. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18999. {
  19000. if (source != newSource)
  19001. {
  19002. AudioSource* const oldSource = source;
  19003. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19004. newSource->prepareToPlay (bufferSize, sampleRate);
  19005. {
  19006. const ScopedLock sl (readLock);
  19007. source = newSource;
  19008. }
  19009. if (oldSource != 0)
  19010. oldSource->releaseResources();
  19011. }
  19012. }
  19013. void AudioSourcePlayer::setGain (const float newGain) throw()
  19014. {
  19015. gain = newGain;
  19016. }
  19017. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19018. int totalNumInputChannels,
  19019. float** outputChannelData,
  19020. int totalNumOutputChannels,
  19021. int numSamples)
  19022. {
  19023. // these should have been prepared by audioDeviceAboutToStart()...
  19024. jassert (sampleRate > 0 && bufferSize > 0);
  19025. const ScopedLock sl (readLock);
  19026. if (source != 0)
  19027. {
  19028. AudioSourceChannelInfo info;
  19029. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19030. // messy stuff needed to compact the channels down into an array
  19031. // of non-zero pointers..
  19032. for (i = 0; i < totalNumInputChannels; ++i)
  19033. {
  19034. if (inputChannelData[i] != 0)
  19035. {
  19036. inputChans [numInputs++] = inputChannelData[i];
  19037. if (numInputs >= numElementsInArray (inputChans))
  19038. break;
  19039. }
  19040. }
  19041. for (i = 0; i < totalNumOutputChannels; ++i)
  19042. {
  19043. if (outputChannelData[i] != 0)
  19044. {
  19045. outputChans [numOutputs++] = outputChannelData[i];
  19046. if (numOutputs >= numElementsInArray (outputChans))
  19047. break;
  19048. }
  19049. }
  19050. if (numInputs > numOutputs)
  19051. {
  19052. // if there aren't enough output channels for the number of
  19053. // inputs, we need to create some temporary extra ones (can't
  19054. // use the input data in case it gets written to)
  19055. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19056. false, false, true);
  19057. for (i = 0; i < numOutputs; ++i)
  19058. {
  19059. channels[numActiveChans] = outputChans[i];
  19060. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19061. ++numActiveChans;
  19062. }
  19063. for (i = numOutputs; i < numInputs; ++i)
  19064. {
  19065. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19066. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19067. ++numActiveChans;
  19068. }
  19069. }
  19070. else
  19071. {
  19072. for (i = 0; i < numInputs; ++i)
  19073. {
  19074. channels[numActiveChans] = outputChans[i];
  19075. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19076. ++numActiveChans;
  19077. }
  19078. for (i = numInputs; i < numOutputs; ++i)
  19079. {
  19080. channels[numActiveChans] = outputChans[i];
  19081. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19082. ++numActiveChans;
  19083. }
  19084. }
  19085. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19086. info.buffer = &buffer;
  19087. info.startSample = 0;
  19088. info.numSamples = numSamples;
  19089. source->getNextAudioBlock (info);
  19090. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19091. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19092. lastGain = gain;
  19093. }
  19094. else
  19095. {
  19096. for (int i = 0; i < totalNumOutputChannels; ++i)
  19097. if (outputChannelData[i] != 0)
  19098. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19099. }
  19100. }
  19101. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19102. {
  19103. sampleRate = device->getCurrentSampleRate();
  19104. bufferSize = device->getCurrentBufferSizeSamples();
  19105. zeromem (channels, sizeof (channels));
  19106. if (source != 0)
  19107. source->prepareToPlay (bufferSize, sampleRate);
  19108. }
  19109. void AudioSourcePlayer::audioDeviceStopped()
  19110. {
  19111. if (source != 0)
  19112. source->releaseResources();
  19113. sampleRate = 0.0;
  19114. bufferSize = 0;
  19115. tempBuffer.setSize (2, 8);
  19116. }
  19117. END_JUCE_NAMESPACE
  19118. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19119. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19120. BEGIN_JUCE_NAMESPACE
  19121. AudioTransportSource::AudioTransportSource()
  19122. : source (0),
  19123. resamplerSource (0),
  19124. bufferingSource (0),
  19125. positionableSource (0),
  19126. masterSource (0),
  19127. gain (1.0f),
  19128. lastGain (1.0f),
  19129. playing (false),
  19130. stopped (true),
  19131. sampleRate (44100.0),
  19132. sourceSampleRate (0.0),
  19133. blockSize (128),
  19134. readAheadBufferSize (0),
  19135. isPrepared (false),
  19136. inputStreamEOF (false)
  19137. {
  19138. }
  19139. AudioTransportSource::~AudioTransportSource()
  19140. {
  19141. setSource (0);
  19142. releaseResources();
  19143. }
  19144. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19145. int readAheadBufferSize_,
  19146. double sourceSampleRateToCorrectFor)
  19147. {
  19148. if (source == newSource)
  19149. {
  19150. if (source == 0)
  19151. return;
  19152. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19153. }
  19154. readAheadBufferSize = readAheadBufferSize_;
  19155. sourceSampleRate = sourceSampleRateToCorrectFor;
  19156. ResamplingAudioSource* newResamplerSource = 0;
  19157. BufferingAudioSource* newBufferingSource = 0;
  19158. PositionableAudioSource* newPositionableSource = 0;
  19159. AudioSource* newMasterSource = 0;
  19160. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19161. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19162. AudioSource* oldMasterSource = masterSource;
  19163. if (newSource != 0)
  19164. {
  19165. newPositionableSource = newSource;
  19166. if (readAheadBufferSize_ > 0)
  19167. newPositionableSource = newBufferingSource
  19168. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19169. newPositionableSource->setNextReadPosition (0);
  19170. if (sourceSampleRateToCorrectFor != 0)
  19171. newMasterSource = newResamplerSource
  19172. = new ResamplingAudioSource (newPositionableSource, false);
  19173. else
  19174. newMasterSource = newPositionableSource;
  19175. if (isPrepared)
  19176. {
  19177. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19178. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19179. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19180. }
  19181. }
  19182. {
  19183. const ScopedLock sl (callbackLock);
  19184. source = newSource;
  19185. resamplerSource = newResamplerSource;
  19186. bufferingSource = newBufferingSource;
  19187. masterSource = newMasterSource;
  19188. positionableSource = newPositionableSource;
  19189. playing = false;
  19190. }
  19191. if (oldMasterSource != 0)
  19192. oldMasterSource->releaseResources();
  19193. }
  19194. void AudioTransportSource::start()
  19195. {
  19196. if ((! playing) && masterSource != 0)
  19197. {
  19198. {
  19199. const ScopedLock sl (callbackLock);
  19200. playing = true;
  19201. stopped = false;
  19202. inputStreamEOF = false;
  19203. }
  19204. sendChangeMessage (this);
  19205. }
  19206. }
  19207. void AudioTransportSource::stop()
  19208. {
  19209. if (playing)
  19210. {
  19211. {
  19212. const ScopedLock sl (callbackLock);
  19213. playing = false;
  19214. }
  19215. int n = 500;
  19216. while (--n >= 0 && ! stopped)
  19217. Thread::sleep (2);
  19218. sendChangeMessage (this);
  19219. }
  19220. }
  19221. void AudioTransportSource::setPosition (double newPosition)
  19222. {
  19223. if (sampleRate > 0.0)
  19224. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19225. }
  19226. double AudioTransportSource::getCurrentPosition() const
  19227. {
  19228. if (sampleRate > 0.0)
  19229. return getNextReadPosition() / sampleRate;
  19230. else
  19231. return 0.0;
  19232. }
  19233. void AudioTransportSource::setNextReadPosition (int newPosition)
  19234. {
  19235. if (positionableSource != 0)
  19236. {
  19237. if (sampleRate > 0 && sourceSampleRate > 0)
  19238. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19239. positionableSource->setNextReadPosition (newPosition);
  19240. }
  19241. }
  19242. int AudioTransportSource::getNextReadPosition() const
  19243. {
  19244. if (positionableSource != 0)
  19245. {
  19246. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19247. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19248. }
  19249. return 0;
  19250. }
  19251. int AudioTransportSource::getTotalLength() const
  19252. {
  19253. const ScopedLock sl (callbackLock);
  19254. if (positionableSource != 0)
  19255. {
  19256. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19257. return roundToInt (positionableSource->getTotalLength() * ratio);
  19258. }
  19259. return 0;
  19260. }
  19261. bool AudioTransportSource::isLooping() const
  19262. {
  19263. const ScopedLock sl (callbackLock);
  19264. return positionableSource != 0
  19265. && positionableSource->isLooping();
  19266. }
  19267. void AudioTransportSource::setGain (const float newGain) throw()
  19268. {
  19269. gain = newGain;
  19270. }
  19271. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19272. double sampleRate_)
  19273. {
  19274. const ScopedLock sl (callbackLock);
  19275. sampleRate = sampleRate_;
  19276. blockSize = samplesPerBlockExpected;
  19277. if (masterSource != 0)
  19278. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19279. if (resamplerSource != 0 && sourceSampleRate != 0)
  19280. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19281. isPrepared = true;
  19282. }
  19283. void AudioTransportSource::releaseResources()
  19284. {
  19285. const ScopedLock sl (callbackLock);
  19286. if (masterSource != 0)
  19287. masterSource->releaseResources();
  19288. isPrepared = false;
  19289. }
  19290. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19291. {
  19292. const ScopedLock sl (callbackLock);
  19293. inputStreamEOF = false;
  19294. if (masterSource != 0 && ! stopped)
  19295. {
  19296. masterSource->getNextAudioBlock (info);
  19297. if (! playing)
  19298. {
  19299. // just stopped playing, so fade out the last block..
  19300. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19301. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19302. if (info.numSamples > 256)
  19303. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19304. }
  19305. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19306. && ! positionableSource->isLooping())
  19307. {
  19308. playing = false;
  19309. inputStreamEOF = true;
  19310. sendChangeMessage (this);
  19311. }
  19312. stopped = ! playing;
  19313. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19314. {
  19315. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19316. lastGain, gain);
  19317. }
  19318. }
  19319. else
  19320. {
  19321. info.clearActiveBufferRegion();
  19322. stopped = true;
  19323. }
  19324. lastGain = gain;
  19325. }
  19326. END_JUCE_NAMESPACE
  19327. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19328. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19329. BEGIN_JUCE_NAMESPACE
  19330. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19331. public Thread,
  19332. private Timer
  19333. {
  19334. public:
  19335. SharedBufferingAudioSourceThread()
  19336. : Thread ("Audio Buffer")
  19337. {
  19338. }
  19339. ~SharedBufferingAudioSourceThread()
  19340. {
  19341. stopThread (10000);
  19342. clearSingletonInstance();
  19343. }
  19344. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19345. void addSource (BufferingAudioSource* source)
  19346. {
  19347. const ScopedLock sl (lock);
  19348. if (! sources.contains (source))
  19349. {
  19350. sources.add (source);
  19351. startThread();
  19352. stopTimer();
  19353. }
  19354. notify();
  19355. }
  19356. void removeSource (BufferingAudioSource* source)
  19357. {
  19358. const ScopedLock sl (lock);
  19359. sources.removeValue (source);
  19360. if (sources.size() == 0)
  19361. startTimer (5000);
  19362. }
  19363. private:
  19364. Array <BufferingAudioSource*> sources;
  19365. CriticalSection lock;
  19366. void run()
  19367. {
  19368. while (! threadShouldExit())
  19369. {
  19370. bool busy = false;
  19371. for (int i = sources.size(); --i >= 0;)
  19372. {
  19373. if (threadShouldExit())
  19374. return;
  19375. const ScopedLock sl (lock);
  19376. BufferingAudioSource* const b = sources[i];
  19377. if (b != 0 && b->readNextBufferChunk())
  19378. busy = true;
  19379. }
  19380. if (! busy)
  19381. wait (500);
  19382. }
  19383. }
  19384. void timerCallback()
  19385. {
  19386. stopTimer();
  19387. if (sources.size() == 0)
  19388. deleteInstance();
  19389. }
  19390. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19391. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19392. };
  19393. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19394. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19395. const bool deleteSourceWhenDeleted_,
  19396. int numberOfSamplesToBuffer_)
  19397. : source (source_),
  19398. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19399. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19400. buffer (2, 0),
  19401. bufferValidStart (0),
  19402. bufferValidEnd (0),
  19403. nextPlayPos (0),
  19404. wasSourceLooping (false)
  19405. {
  19406. jassert (source_ != 0);
  19407. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19408. // not using a larger buffer..
  19409. }
  19410. BufferingAudioSource::~BufferingAudioSource()
  19411. {
  19412. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19413. if (thread != 0)
  19414. thread->removeSource (this);
  19415. if (deleteSourceWhenDeleted)
  19416. delete source;
  19417. }
  19418. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19419. {
  19420. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19421. sampleRate = sampleRate_;
  19422. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19423. buffer.clear();
  19424. bufferValidStart = 0;
  19425. bufferValidEnd = 0;
  19426. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19427. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19428. buffer.getNumSamples() / 2))
  19429. {
  19430. SharedBufferingAudioSourceThread::getInstance()->notify();
  19431. Thread::sleep (5);
  19432. }
  19433. }
  19434. void BufferingAudioSource::releaseResources()
  19435. {
  19436. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19437. if (thread != 0)
  19438. thread->removeSource (this);
  19439. buffer.setSize (2, 0);
  19440. source->releaseResources();
  19441. }
  19442. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19443. {
  19444. const ScopedLock sl (bufferStartPosLock);
  19445. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19446. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19447. if (validStart == validEnd)
  19448. {
  19449. // total cache miss
  19450. info.clearActiveBufferRegion();
  19451. }
  19452. else
  19453. {
  19454. if (validStart > 0)
  19455. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19456. if (validEnd < info.numSamples)
  19457. info.buffer->clear (info.startSample + validEnd,
  19458. info.numSamples - validEnd); // partial cache miss at end
  19459. if (validStart < validEnd)
  19460. {
  19461. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19462. {
  19463. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19464. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19465. if (startBufferIndex < endBufferIndex)
  19466. {
  19467. info.buffer->copyFrom (chan, info.startSample + validStart,
  19468. buffer,
  19469. chan, startBufferIndex,
  19470. validEnd - validStart);
  19471. }
  19472. else
  19473. {
  19474. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19475. info.buffer->copyFrom (chan, info.startSample + validStart,
  19476. buffer,
  19477. chan, startBufferIndex,
  19478. initialSize);
  19479. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19480. buffer,
  19481. chan, 0,
  19482. (validEnd - validStart) - initialSize);
  19483. }
  19484. }
  19485. }
  19486. nextPlayPos += info.numSamples;
  19487. if (source->isLooping() && nextPlayPos > 0)
  19488. nextPlayPos %= source->getTotalLength();
  19489. }
  19490. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19491. if (thread != 0)
  19492. thread->notify();
  19493. }
  19494. int BufferingAudioSource::getNextReadPosition() const
  19495. {
  19496. return (source->isLooping() && nextPlayPos > 0)
  19497. ? nextPlayPos % source->getTotalLength()
  19498. : nextPlayPos;
  19499. }
  19500. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19501. {
  19502. const ScopedLock sl (bufferStartPosLock);
  19503. nextPlayPos = newPosition;
  19504. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19505. if (thread != 0)
  19506. thread->notify();
  19507. }
  19508. bool BufferingAudioSource::readNextBufferChunk()
  19509. {
  19510. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19511. {
  19512. const ScopedLock sl (bufferStartPosLock);
  19513. if (wasSourceLooping != isLooping())
  19514. {
  19515. wasSourceLooping = isLooping();
  19516. bufferValidStart = 0;
  19517. bufferValidEnd = 0;
  19518. }
  19519. newBVS = jmax (0, nextPlayPos);
  19520. newBVE = newBVS + buffer.getNumSamples() - 4;
  19521. sectionToReadStart = 0;
  19522. sectionToReadEnd = 0;
  19523. const int maxChunkSize = 2048;
  19524. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19525. {
  19526. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19527. sectionToReadStart = newBVS;
  19528. sectionToReadEnd = newBVE;
  19529. bufferValidStart = 0;
  19530. bufferValidEnd = 0;
  19531. }
  19532. else if (abs (newBVS - bufferValidStart) > 512
  19533. || abs (newBVE - bufferValidEnd) > 512)
  19534. {
  19535. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19536. sectionToReadStart = bufferValidEnd;
  19537. sectionToReadEnd = newBVE;
  19538. bufferValidStart = newBVS;
  19539. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19540. }
  19541. }
  19542. if (sectionToReadStart != sectionToReadEnd)
  19543. {
  19544. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19545. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19546. if (bufferIndexStart < bufferIndexEnd)
  19547. {
  19548. readBufferSection (sectionToReadStart,
  19549. sectionToReadEnd - sectionToReadStart,
  19550. bufferIndexStart);
  19551. }
  19552. else
  19553. {
  19554. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19555. readBufferSection (sectionToReadStart,
  19556. initialSize,
  19557. bufferIndexStart);
  19558. readBufferSection (sectionToReadStart + initialSize,
  19559. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19560. 0);
  19561. }
  19562. const ScopedLock sl2 (bufferStartPosLock);
  19563. bufferValidStart = newBVS;
  19564. bufferValidEnd = newBVE;
  19565. return true;
  19566. }
  19567. else
  19568. {
  19569. return false;
  19570. }
  19571. }
  19572. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19573. {
  19574. if (source->getNextReadPosition() != start)
  19575. source->setNextReadPosition (start);
  19576. AudioSourceChannelInfo info;
  19577. info.buffer = &buffer;
  19578. info.startSample = bufferOffset;
  19579. info.numSamples = length;
  19580. source->getNextAudioBlock (info);
  19581. }
  19582. END_JUCE_NAMESPACE
  19583. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19584. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19585. BEGIN_JUCE_NAMESPACE
  19586. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19587. const bool deleteSourceWhenDeleted_)
  19588. : requiredNumberOfChannels (2),
  19589. source (source_),
  19590. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19591. buffer (2, 16)
  19592. {
  19593. remappedInfo.buffer = &buffer;
  19594. remappedInfo.startSample = 0;
  19595. }
  19596. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19597. {
  19598. if (deleteSourceWhenDeleted)
  19599. delete source;
  19600. }
  19601. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19602. {
  19603. const ScopedLock sl (lock);
  19604. requiredNumberOfChannels = requiredNumberOfChannels_;
  19605. }
  19606. void ChannelRemappingAudioSource::clearAllMappings()
  19607. {
  19608. const ScopedLock sl (lock);
  19609. remappedInputs.clear();
  19610. remappedOutputs.clear();
  19611. }
  19612. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19613. {
  19614. const ScopedLock sl (lock);
  19615. while (remappedInputs.size() < destIndex)
  19616. remappedInputs.add (-1);
  19617. remappedInputs.set (destIndex, sourceIndex);
  19618. }
  19619. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19620. {
  19621. const ScopedLock sl (lock);
  19622. while (remappedOutputs.size() < sourceIndex)
  19623. remappedOutputs.add (-1);
  19624. remappedOutputs.set (sourceIndex, destIndex);
  19625. }
  19626. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19627. {
  19628. const ScopedLock sl (lock);
  19629. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19630. return remappedInputs.getUnchecked (inputChannelIndex);
  19631. return -1;
  19632. }
  19633. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19634. {
  19635. const ScopedLock sl (lock);
  19636. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19637. return remappedOutputs .getUnchecked (outputChannelIndex);
  19638. return -1;
  19639. }
  19640. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19641. {
  19642. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19643. }
  19644. void ChannelRemappingAudioSource::releaseResources()
  19645. {
  19646. source->releaseResources();
  19647. }
  19648. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19649. {
  19650. const ScopedLock sl (lock);
  19651. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19652. const int numChans = bufferToFill.buffer->getNumChannels();
  19653. int i;
  19654. for (i = 0; i < buffer.getNumChannels(); ++i)
  19655. {
  19656. const int remappedChan = getRemappedInputChannel (i);
  19657. if (remappedChan >= 0 && remappedChan < numChans)
  19658. {
  19659. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19660. remappedChan,
  19661. bufferToFill.startSample,
  19662. bufferToFill.numSamples);
  19663. }
  19664. else
  19665. {
  19666. buffer.clear (i, 0, bufferToFill.numSamples);
  19667. }
  19668. }
  19669. remappedInfo.numSamples = bufferToFill.numSamples;
  19670. source->getNextAudioBlock (remappedInfo);
  19671. bufferToFill.clearActiveBufferRegion();
  19672. for (i = 0; i < requiredNumberOfChannels; ++i)
  19673. {
  19674. const int remappedChan = getRemappedOutputChannel (i);
  19675. if (remappedChan >= 0 && remappedChan < numChans)
  19676. {
  19677. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19678. buffer, i, 0, bufferToFill.numSamples);
  19679. }
  19680. }
  19681. }
  19682. XmlElement* ChannelRemappingAudioSource::createXml() const
  19683. {
  19684. XmlElement* e = new XmlElement ("MAPPINGS");
  19685. String ins, outs;
  19686. int i;
  19687. const ScopedLock sl (lock);
  19688. for (i = 0; i < remappedInputs.size(); ++i)
  19689. ins << remappedInputs.getUnchecked(i) << ' ';
  19690. for (i = 0; i < remappedOutputs.size(); ++i)
  19691. outs << remappedOutputs.getUnchecked(i) << ' ';
  19692. e->setAttribute ("inputs", ins.trimEnd());
  19693. e->setAttribute ("outputs", outs.trimEnd());
  19694. return e;
  19695. }
  19696. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19697. {
  19698. if (e.hasTagName ("MAPPINGS"))
  19699. {
  19700. const ScopedLock sl (lock);
  19701. clearAllMappings();
  19702. StringArray ins, outs;
  19703. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19704. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19705. int i;
  19706. for (i = 0; i < ins.size(); ++i)
  19707. remappedInputs.add (ins[i].getIntValue());
  19708. for (i = 0; i < outs.size(); ++i)
  19709. remappedOutputs.add (outs[i].getIntValue());
  19710. }
  19711. }
  19712. END_JUCE_NAMESPACE
  19713. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19714. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19715. BEGIN_JUCE_NAMESPACE
  19716. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19717. const bool deleteInputWhenDeleted_)
  19718. : input (inputSource),
  19719. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19720. {
  19721. jassert (inputSource != 0);
  19722. for (int i = 2; --i >= 0;)
  19723. iirFilters.add (new IIRFilter());
  19724. }
  19725. IIRFilterAudioSource::~IIRFilterAudioSource()
  19726. {
  19727. if (deleteInputWhenDeleted)
  19728. delete input;
  19729. }
  19730. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19731. {
  19732. for (int i = iirFilters.size(); --i >= 0;)
  19733. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19734. }
  19735. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19736. {
  19737. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19738. for (int i = iirFilters.size(); --i >= 0;)
  19739. iirFilters.getUnchecked(i)->reset();
  19740. }
  19741. void IIRFilterAudioSource::releaseResources()
  19742. {
  19743. input->releaseResources();
  19744. }
  19745. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19746. {
  19747. input->getNextAudioBlock (bufferToFill);
  19748. const int numChannels = bufferToFill.buffer->getNumChannels();
  19749. while (numChannels > iirFilters.size())
  19750. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19751. for (int i = 0; i < numChannels; ++i)
  19752. iirFilters.getUnchecked(i)
  19753. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19754. bufferToFill.numSamples);
  19755. }
  19756. END_JUCE_NAMESPACE
  19757. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19758. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19759. BEGIN_JUCE_NAMESPACE
  19760. MixerAudioSource::MixerAudioSource()
  19761. : tempBuffer (2, 0),
  19762. currentSampleRate (0.0),
  19763. bufferSizeExpected (0)
  19764. {
  19765. }
  19766. MixerAudioSource::~MixerAudioSource()
  19767. {
  19768. removeAllInputs();
  19769. }
  19770. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19771. {
  19772. if (input != 0 && ! inputs.contains (input))
  19773. {
  19774. double localRate;
  19775. int localBufferSize;
  19776. {
  19777. const ScopedLock sl (lock);
  19778. localRate = currentSampleRate;
  19779. localBufferSize = bufferSizeExpected;
  19780. }
  19781. if (localRate != 0.0)
  19782. input->prepareToPlay (localBufferSize, localRate);
  19783. const ScopedLock sl (lock);
  19784. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19785. inputs.add (input);
  19786. }
  19787. }
  19788. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19789. {
  19790. if (input != 0)
  19791. {
  19792. int index;
  19793. {
  19794. const ScopedLock sl (lock);
  19795. index = inputs.indexOf (input);
  19796. if (index >= 0)
  19797. {
  19798. inputsToDelete.shiftBits (index, 1);
  19799. inputs.remove (index);
  19800. }
  19801. }
  19802. if (index >= 0)
  19803. {
  19804. input->releaseResources();
  19805. if (deleteInput)
  19806. delete input;
  19807. }
  19808. }
  19809. }
  19810. void MixerAudioSource::removeAllInputs()
  19811. {
  19812. OwnedArray<AudioSource> toDelete;
  19813. {
  19814. const ScopedLock sl (lock);
  19815. for (int i = inputs.size(); --i >= 0;)
  19816. if (inputsToDelete[i])
  19817. toDelete.add (inputs.getUnchecked(i));
  19818. }
  19819. }
  19820. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19821. {
  19822. tempBuffer.setSize (2, samplesPerBlockExpected);
  19823. const ScopedLock sl (lock);
  19824. currentSampleRate = sampleRate;
  19825. bufferSizeExpected = samplesPerBlockExpected;
  19826. for (int i = inputs.size(); --i >= 0;)
  19827. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19828. }
  19829. void MixerAudioSource::releaseResources()
  19830. {
  19831. const ScopedLock sl (lock);
  19832. for (int i = inputs.size(); --i >= 0;)
  19833. inputs.getUnchecked(i)->releaseResources();
  19834. tempBuffer.setSize (2, 0);
  19835. currentSampleRate = 0;
  19836. bufferSizeExpected = 0;
  19837. }
  19838. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19839. {
  19840. const ScopedLock sl (lock);
  19841. if (inputs.size() > 0)
  19842. {
  19843. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19844. if (inputs.size() > 1)
  19845. {
  19846. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19847. info.buffer->getNumSamples());
  19848. AudioSourceChannelInfo info2;
  19849. info2.buffer = &tempBuffer;
  19850. info2.numSamples = info.numSamples;
  19851. info2.startSample = 0;
  19852. for (int i = 1; i < inputs.size(); ++i)
  19853. {
  19854. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19855. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19856. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19857. }
  19858. }
  19859. }
  19860. else
  19861. {
  19862. info.clearActiveBufferRegion();
  19863. }
  19864. }
  19865. END_JUCE_NAMESPACE
  19866. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19867. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19868. BEGIN_JUCE_NAMESPACE
  19869. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19870. const bool deleteInputWhenDeleted_,
  19871. const int numChannels_)
  19872. : input (inputSource),
  19873. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19874. ratio (1.0),
  19875. lastRatio (1.0),
  19876. buffer (numChannels_, 0),
  19877. sampsInBuffer (0),
  19878. numChannels (numChannels_)
  19879. {
  19880. jassert (input != 0);
  19881. }
  19882. ResamplingAudioSource::~ResamplingAudioSource()
  19883. {
  19884. if (deleteInputWhenDeleted)
  19885. delete input;
  19886. }
  19887. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19888. {
  19889. jassert (samplesInPerOutputSample > 0);
  19890. const ScopedLock sl (ratioLock);
  19891. ratio = jmax (0.0, samplesInPerOutputSample);
  19892. }
  19893. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19894. double sampleRate)
  19895. {
  19896. const ScopedLock sl (ratioLock);
  19897. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19898. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19899. buffer.clear();
  19900. sampsInBuffer = 0;
  19901. bufferPos = 0;
  19902. subSampleOffset = 0.0;
  19903. filterStates.calloc (numChannels);
  19904. srcBuffers.calloc (numChannels);
  19905. destBuffers.calloc (numChannels);
  19906. createLowPass (ratio);
  19907. resetFilters();
  19908. }
  19909. void ResamplingAudioSource::releaseResources()
  19910. {
  19911. input->releaseResources();
  19912. buffer.setSize (numChannels, 0);
  19913. }
  19914. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19915. {
  19916. const ScopedLock sl (ratioLock);
  19917. if (lastRatio != ratio)
  19918. {
  19919. createLowPass (ratio);
  19920. lastRatio = ratio;
  19921. }
  19922. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19923. int bufferSize = buffer.getNumSamples();
  19924. if (bufferSize < sampsNeeded + 8)
  19925. {
  19926. bufferPos %= bufferSize;
  19927. bufferSize = sampsNeeded + 32;
  19928. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19929. }
  19930. bufferPos %= bufferSize;
  19931. int endOfBufferPos = bufferPos + sampsInBuffer;
  19932. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19933. while (sampsNeeded > sampsInBuffer)
  19934. {
  19935. endOfBufferPos %= bufferSize;
  19936. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19937. bufferSize - endOfBufferPos);
  19938. AudioSourceChannelInfo readInfo;
  19939. readInfo.buffer = &buffer;
  19940. readInfo.numSamples = numToDo;
  19941. readInfo.startSample = endOfBufferPos;
  19942. input->getNextAudioBlock (readInfo);
  19943. if (ratio > 1.0001)
  19944. {
  19945. // for down-sampling, pre-apply the filter..
  19946. for (int i = channelsToProcess; --i >= 0;)
  19947. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19948. }
  19949. sampsInBuffer += numToDo;
  19950. endOfBufferPos += numToDo;
  19951. }
  19952. for (int channel = 0; channel < channelsToProcess; ++channel)
  19953. {
  19954. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19955. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19956. }
  19957. int nextPos = (bufferPos + 1) % bufferSize;
  19958. for (int m = info.numSamples; --m >= 0;)
  19959. {
  19960. const float alpha = (float) subSampleOffset;
  19961. const float invAlpha = 1.0f - alpha;
  19962. for (int channel = 0; channel < channelsToProcess; ++channel)
  19963. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19964. subSampleOffset += ratio;
  19965. jassert (sampsInBuffer > 0);
  19966. while (subSampleOffset >= 1.0)
  19967. {
  19968. if (++bufferPos >= bufferSize)
  19969. bufferPos = 0;
  19970. --sampsInBuffer;
  19971. nextPos = (bufferPos + 1) % bufferSize;
  19972. subSampleOffset -= 1.0;
  19973. }
  19974. }
  19975. if (ratio < 0.9999)
  19976. {
  19977. // for up-sampling, apply the filter after transposing..
  19978. for (int i = channelsToProcess; --i >= 0;)
  19979. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19980. }
  19981. else if (ratio <= 1.0001)
  19982. {
  19983. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19984. for (int i = channelsToProcess; --i >= 0;)
  19985. {
  19986. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19987. FilterState& fs = filterStates[i];
  19988. if (info.numSamples > 1)
  19989. {
  19990. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19991. }
  19992. else
  19993. {
  19994. fs.y2 = fs.y1;
  19995. fs.x2 = fs.x1;
  19996. }
  19997. fs.y1 = fs.x1 = *endOfBuffer;
  19998. }
  19999. }
  20000. jassert (sampsInBuffer >= 0);
  20001. }
  20002. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20003. {
  20004. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20005. : 0.5 * frequencyRatio;
  20006. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20007. const double nSquared = n * n;
  20008. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20009. setFilterCoefficients (c1,
  20010. c1 * 2.0f,
  20011. c1,
  20012. 1.0,
  20013. c1 * 2.0 * (1.0 - nSquared),
  20014. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20015. }
  20016. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20017. {
  20018. const double a = 1.0 / c4;
  20019. c1 *= a;
  20020. c2 *= a;
  20021. c3 *= a;
  20022. c5 *= a;
  20023. c6 *= a;
  20024. coefficients[0] = c1;
  20025. coefficients[1] = c2;
  20026. coefficients[2] = c3;
  20027. coefficients[3] = c4;
  20028. coefficients[4] = c5;
  20029. coefficients[5] = c6;
  20030. }
  20031. void ResamplingAudioSource::resetFilters()
  20032. {
  20033. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20034. }
  20035. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20036. {
  20037. while (--num >= 0)
  20038. {
  20039. const double in = *samples;
  20040. double out = coefficients[0] * in
  20041. + coefficients[1] * fs.x1
  20042. + coefficients[2] * fs.x2
  20043. - coefficients[4] * fs.y1
  20044. - coefficients[5] * fs.y2;
  20045. #if JUCE_INTEL
  20046. if (! (out < -1.0e-8 || out > 1.0e-8))
  20047. out = 0;
  20048. #endif
  20049. fs.x2 = fs.x1;
  20050. fs.x1 = in;
  20051. fs.y2 = fs.y1;
  20052. fs.y1 = out;
  20053. *samples++ = (float) out;
  20054. }
  20055. }
  20056. END_JUCE_NAMESPACE
  20057. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20058. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20059. BEGIN_JUCE_NAMESPACE
  20060. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20061. : frequency (1000.0),
  20062. sampleRate (44100.0),
  20063. currentPhase (0.0),
  20064. phasePerSample (0.0),
  20065. amplitude (0.5f)
  20066. {
  20067. }
  20068. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20069. {
  20070. }
  20071. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20072. {
  20073. amplitude = newAmplitude;
  20074. }
  20075. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20076. {
  20077. frequency = newFrequencyHz;
  20078. phasePerSample = 0.0;
  20079. }
  20080. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20081. double sampleRate_)
  20082. {
  20083. currentPhase = 0.0;
  20084. phasePerSample = 0.0;
  20085. sampleRate = sampleRate_;
  20086. }
  20087. void ToneGeneratorAudioSource::releaseResources()
  20088. {
  20089. }
  20090. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20091. {
  20092. if (phasePerSample == 0.0)
  20093. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20094. for (int i = 0; i < info.numSamples; ++i)
  20095. {
  20096. const float sample = amplitude * (float) std::sin (currentPhase);
  20097. currentPhase += phasePerSample;
  20098. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20099. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20100. }
  20101. }
  20102. END_JUCE_NAMESPACE
  20103. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20104. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20105. BEGIN_JUCE_NAMESPACE
  20106. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20107. : sampleRate (0),
  20108. bufferSize (0),
  20109. useDefaultInputChannels (true),
  20110. useDefaultOutputChannels (true)
  20111. {
  20112. }
  20113. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20114. {
  20115. return outputDeviceName == other.outputDeviceName
  20116. && inputDeviceName == other.inputDeviceName
  20117. && sampleRate == other.sampleRate
  20118. && bufferSize == other.bufferSize
  20119. && inputChannels == other.inputChannels
  20120. && useDefaultInputChannels == other.useDefaultInputChannels
  20121. && outputChannels == other.outputChannels
  20122. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20123. }
  20124. AudioDeviceManager::AudioDeviceManager()
  20125. : currentAudioDevice (0),
  20126. numInputChansNeeded (0),
  20127. numOutputChansNeeded (2),
  20128. listNeedsScanning (true),
  20129. useInputNames (false),
  20130. inputLevelMeasurementEnabledCount (0),
  20131. inputLevel (0),
  20132. tempBuffer (2, 2),
  20133. defaultMidiOutput (0),
  20134. cpuUsageMs (0),
  20135. timeToCpuScale (0)
  20136. {
  20137. callbackHandler.owner = this;
  20138. }
  20139. AudioDeviceManager::~AudioDeviceManager()
  20140. {
  20141. currentAudioDevice = 0;
  20142. defaultMidiOutput = 0;
  20143. }
  20144. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20145. {
  20146. if (availableDeviceTypes.size() == 0)
  20147. {
  20148. createAudioDeviceTypes (availableDeviceTypes);
  20149. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20150. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20151. if (availableDeviceTypes.size() > 0)
  20152. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20153. }
  20154. }
  20155. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20156. {
  20157. scanDevicesIfNeeded();
  20158. return availableDeviceTypes;
  20159. }
  20160. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20161. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20162. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20163. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20164. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20165. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20166. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20167. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20168. {
  20169. (void) list; // (to avoid 'unused param' warnings)
  20170. #if JUCE_WINDOWS
  20171. #if JUCE_WASAPI
  20172. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20173. list.add (juce_createAudioIODeviceType_WASAPI());
  20174. #endif
  20175. #if JUCE_DIRECTSOUND
  20176. list.add (juce_createAudioIODeviceType_DirectSound());
  20177. #endif
  20178. #if JUCE_ASIO
  20179. list.add (juce_createAudioIODeviceType_ASIO());
  20180. #endif
  20181. #endif
  20182. #if JUCE_MAC
  20183. list.add (juce_createAudioIODeviceType_CoreAudio());
  20184. #endif
  20185. #if JUCE_IOS
  20186. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20187. #endif
  20188. #if JUCE_LINUX && JUCE_ALSA
  20189. list.add (juce_createAudioIODeviceType_ALSA());
  20190. #endif
  20191. #if JUCE_LINUX && JUCE_JACK
  20192. list.add (juce_createAudioIODeviceType_JACK());
  20193. #endif
  20194. }
  20195. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20196. const int numOutputChannelsNeeded,
  20197. const XmlElement* const e,
  20198. const bool selectDefaultDeviceOnFailure,
  20199. const String& preferredDefaultDeviceName,
  20200. const AudioDeviceSetup* preferredSetupOptions)
  20201. {
  20202. scanDevicesIfNeeded();
  20203. numInputChansNeeded = numInputChannelsNeeded;
  20204. numOutputChansNeeded = numOutputChannelsNeeded;
  20205. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20206. {
  20207. lastExplicitSettings = new XmlElement (*e);
  20208. String error;
  20209. AudioDeviceSetup setup;
  20210. if (preferredSetupOptions != 0)
  20211. setup = *preferredSetupOptions;
  20212. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20213. {
  20214. setup.inputDeviceName = setup.outputDeviceName
  20215. = e->getStringAttribute ("audioDeviceName");
  20216. }
  20217. else
  20218. {
  20219. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20220. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20221. }
  20222. currentDeviceType = e->getStringAttribute ("deviceType");
  20223. if (currentDeviceType.isEmpty())
  20224. {
  20225. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20226. if (type != 0)
  20227. currentDeviceType = type->getTypeName();
  20228. else if (availableDeviceTypes.size() > 0)
  20229. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20230. }
  20231. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20232. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20233. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20234. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20235. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20236. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20237. error = setAudioDeviceSetup (setup, true);
  20238. midiInsFromXml.clear();
  20239. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20240. midiInsFromXml.add (c->getStringAttribute ("name"));
  20241. const StringArray allMidiIns (MidiInput::getDevices());
  20242. for (int i = allMidiIns.size(); --i >= 0;)
  20243. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20244. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20245. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20246. false, preferredDefaultDeviceName);
  20247. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20248. return error;
  20249. }
  20250. else
  20251. {
  20252. AudioDeviceSetup setup;
  20253. if (preferredSetupOptions != 0)
  20254. {
  20255. setup = *preferredSetupOptions;
  20256. }
  20257. else if (preferredDefaultDeviceName.isNotEmpty())
  20258. {
  20259. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20260. {
  20261. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20262. StringArray outs (type->getDeviceNames (false));
  20263. int i;
  20264. for (i = 0; i < outs.size(); ++i)
  20265. {
  20266. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20267. {
  20268. setup.outputDeviceName = outs[i];
  20269. break;
  20270. }
  20271. }
  20272. StringArray ins (type->getDeviceNames (true));
  20273. for (i = 0; i < ins.size(); ++i)
  20274. {
  20275. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20276. {
  20277. setup.inputDeviceName = ins[i];
  20278. break;
  20279. }
  20280. }
  20281. }
  20282. }
  20283. insertDefaultDeviceNames (setup);
  20284. return setAudioDeviceSetup (setup, false);
  20285. }
  20286. }
  20287. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20288. {
  20289. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20290. if (type != 0)
  20291. {
  20292. if (setup.outputDeviceName.isEmpty())
  20293. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20294. if (setup.inputDeviceName.isEmpty())
  20295. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20296. }
  20297. }
  20298. XmlElement* AudioDeviceManager::createStateXml() const
  20299. {
  20300. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20301. }
  20302. void AudioDeviceManager::scanDevicesIfNeeded()
  20303. {
  20304. if (listNeedsScanning)
  20305. {
  20306. listNeedsScanning = false;
  20307. createDeviceTypesIfNeeded();
  20308. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20309. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20310. }
  20311. }
  20312. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20313. {
  20314. scanDevicesIfNeeded();
  20315. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20316. {
  20317. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20318. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20319. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20320. {
  20321. return type;
  20322. }
  20323. }
  20324. return 0;
  20325. }
  20326. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20327. {
  20328. setup = currentSetup;
  20329. }
  20330. void AudioDeviceManager::deleteCurrentDevice()
  20331. {
  20332. currentAudioDevice = 0;
  20333. currentSetup.inputDeviceName = String::empty;
  20334. currentSetup.outputDeviceName = String::empty;
  20335. }
  20336. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20337. const bool treatAsChosenDevice)
  20338. {
  20339. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20340. {
  20341. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20342. && currentDeviceType != type)
  20343. {
  20344. currentDeviceType = type;
  20345. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20346. insertDefaultDeviceNames (s);
  20347. setAudioDeviceSetup (s, treatAsChosenDevice);
  20348. sendChangeMessage (this);
  20349. break;
  20350. }
  20351. }
  20352. }
  20353. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20354. {
  20355. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20356. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20357. return availableDeviceTypes[i];
  20358. return availableDeviceTypes[0];
  20359. }
  20360. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20361. const bool treatAsChosenDevice)
  20362. {
  20363. jassert (&newSetup != &currentSetup); // this will have no effect
  20364. if (newSetup == currentSetup && currentAudioDevice != 0)
  20365. return String::empty;
  20366. if (! (newSetup == currentSetup))
  20367. sendChangeMessage (this);
  20368. stopDevice();
  20369. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20370. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20371. String error;
  20372. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20373. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20374. {
  20375. deleteCurrentDevice();
  20376. if (treatAsChosenDevice)
  20377. updateXml();
  20378. return String::empty;
  20379. }
  20380. if (currentSetup.inputDeviceName != newInputDeviceName
  20381. || currentSetup.outputDeviceName != newOutputDeviceName
  20382. || currentAudioDevice == 0)
  20383. {
  20384. deleteCurrentDevice();
  20385. scanDevicesIfNeeded();
  20386. if (newOutputDeviceName.isNotEmpty()
  20387. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20388. {
  20389. return "No such device: " + newOutputDeviceName;
  20390. }
  20391. if (newInputDeviceName.isNotEmpty()
  20392. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20393. {
  20394. return "No such device: " + newInputDeviceName;
  20395. }
  20396. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20397. if (currentAudioDevice == 0)
  20398. 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!";
  20399. else
  20400. error = currentAudioDevice->getLastError();
  20401. if (error.isNotEmpty())
  20402. {
  20403. deleteCurrentDevice();
  20404. return error;
  20405. }
  20406. if (newSetup.useDefaultInputChannels)
  20407. {
  20408. inputChannels.clear();
  20409. inputChannels.setRange (0, numInputChansNeeded, true);
  20410. }
  20411. if (newSetup.useDefaultOutputChannels)
  20412. {
  20413. outputChannels.clear();
  20414. outputChannels.setRange (0, numOutputChansNeeded, true);
  20415. }
  20416. if (newInputDeviceName.isEmpty())
  20417. inputChannels.clear();
  20418. if (newOutputDeviceName.isEmpty())
  20419. outputChannels.clear();
  20420. }
  20421. if (! newSetup.useDefaultInputChannels)
  20422. inputChannels = newSetup.inputChannels;
  20423. if (! newSetup.useDefaultOutputChannels)
  20424. outputChannels = newSetup.outputChannels;
  20425. currentSetup = newSetup;
  20426. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20427. error = currentAudioDevice->open (inputChannels,
  20428. outputChannels,
  20429. currentSetup.sampleRate,
  20430. currentSetup.bufferSize);
  20431. if (error.isEmpty())
  20432. {
  20433. currentDeviceType = currentAudioDevice->getTypeName();
  20434. currentAudioDevice->start (&callbackHandler);
  20435. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20436. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20437. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20438. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20439. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20440. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20441. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20442. if (treatAsChosenDevice)
  20443. updateXml();
  20444. }
  20445. else
  20446. {
  20447. deleteCurrentDevice();
  20448. }
  20449. return error;
  20450. }
  20451. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20452. {
  20453. jassert (currentAudioDevice != 0);
  20454. if (rate > 0)
  20455. {
  20456. bool ok = false;
  20457. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20458. {
  20459. const double sr = currentAudioDevice->getSampleRate (i);
  20460. if (sr == rate)
  20461. ok = true;
  20462. }
  20463. if (! ok)
  20464. rate = 0;
  20465. }
  20466. if (rate == 0)
  20467. {
  20468. double lowestAbove44 = 0.0;
  20469. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20470. {
  20471. const double sr = currentAudioDevice->getSampleRate (i);
  20472. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20473. lowestAbove44 = sr;
  20474. }
  20475. if (lowestAbove44 == 0.0)
  20476. rate = currentAudioDevice->getSampleRate (0);
  20477. else
  20478. rate = lowestAbove44;
  20479. }
  20480. return rate;
  20481. }
  20482. void AudioDeviceManager::stopDevice()
  20483. {
  20484. if (currentAudioDevice != 0)
  20485. currentAudioDevice->stop();
  20486. testSound = 0;
  20487. }
  20488. void AudioDeviceManager::closeAudioDevice()
  20489. {
  20490. stopDevice();
  20491. currentAudioDevice = 0;
  20492. }
  20493. void AudioDeviceManager::restartLastAudioDevice()
  20494. {
  20495. if (currentAudioDevice == 0)
  20496. {
  20497. if (currentSetup.inputDeviceName.isEmpty()
  20498. && currentSetup.outputDeviceName.isEmpty())
  20499. {
  20500. // This method will only reload the last device that was running
  20501. // before closeAudioDevice() was called - you need to actually open
  20502. // one first, with setAudioDevice().
  20503. jassertfalse;
  20504. return;
  20505. }
  20506. AudioDeviceSetup s (currentSetup);
  20507. setAudioDeviceSetup (s, false);
  20508. }
  20509. }
  20510. void AudioDeviceManager::updateXml()
  20511. {
  20512. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20513. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20514. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20515. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20516. if (currentAudioDevice != 0)
  20517. {
  20518. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20519. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20520. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20521. if (! currentSetup.useDefaultInputChannels)
  20522. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20523. if (! currentSetup.useDefaultOutputChannels)
  20524. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20525. }
  20526. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20527. {
  20528. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20529. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20530. }
  20531. if (midiInsFromXml.size() > 0)
  20532. {
  20533. // Add any midi devices that have been enabled before, but which aren't currently
  20534. // open because the device has been disconnected.
  20535. const StringArray availableMidiDevices (MidiInput::getDevices());
  20536. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20537. {
  20538. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20539. {
  20540. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20541. m->setAttribute ("name", midiInsFromXml[i]);
  20542. }
  20543. }
  20544. }
  20545. if (defaultMidiOutputName.isNotEmpty())
  20546. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20547. }
  20548. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20549. {
  20550. {
  20551. const ScopedLock sl (audioCallbackLock);
  20552. if (callbacks.contains (newCallback))
  20553. return;
  20554. }
  20555. if (currentAudioDevice != 0 && newCallback != 0)
  20556. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20557. const ScopedLock sl (audioCallbackLock);
  20558. callbacks.add (newCallback);
  20559. }
  20560. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20561. {
  20562. if (callback != 0)
  20563. {
  20564. bool needsDeinitialising = currentAudioDevice != 0;
  20565. {
  20566. const ScopedLock sl (audioCallbackLock);
  20567. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20568. callbacks.removeValue (callback);
  20569. }
  20570. if (needsDeinitialising)
  20571. callback->audioDeviceStopped();
  20572. }
  20573. }
  20574. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20575. int numInputChannels,
  20576. float** outputChannelData,
  20577. int numOutputChannels,
  20578. int numSamples)
  20579. {
  20580. const ScopedLock sl (audioCallbackLock);
  20581. if (inputLevelMeasurementEnabledCount > 0)
  20582. {
  20583. for (int j = 0; j < numSamples; ++j)
  20584. {
  20585. float s = 0;
  20586. for (int i = 0; i < numInputChannels; ++i)
  20587. s += std::abs (inputChannelData[i][j]);
  20588. s /= numInputChannels;
  20589. const double decayFactor = 0.99992;
  20590. if (s > inputLevel)
  20591. inputLevel = s;
  20592. else if (inputLevel > 0.001f)
  20593. inputLevel *= decayFactor;
  20594. else
  20595. inputLevel = 0;
  20596. }
  20597. }
  20598. if (callbacks.size() > 0)
  20599. {
  20600. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20601. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20602. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20603. outputChannelData, numOutputChannels, numSamples);
  20604. float** const tempChans = tempBuffer.getArrayOfChannels();
  20605. for (int i = callbacks.size(); --i > 0;)
  20606. {
  20607. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20608. tempChans, numOutputChannels, numSamples);
  20609. for (int chan = 0; chan < numOutputChannels; ++chan)
  20610. {
  20611. const float* const src = tempChans [chan];
  20612. float* const dst = outputChannelData [chan];
  20613. if (src != 0 && dst != 0)
  20614. for (int j = 0; j < numSamples; ++j)
  20615. dst[j] += src[j];
  20616. }
  20617. }
  20618. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20619. const double filterAmount = 0.2;
  20620. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20621. }
  20622. else
  20623. {
  20624. for (int i = 0; i < numOutputChannels; ++i)
  20625. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20626. }
  20627. if (testSound != 0)
  20628. {
  20629. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20630. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20631. for (int i = 0; i < numOutputChannels; ++i)
  20632. for (int j = 0; j < numSamps; ++j)
  20633. outputChannelData [i][j] += src[j];
  20634. testSoundPosition += numSamps;
  20635. if (testSoundPosition >= testSound->getNumSamples())
  20636. testSound = 0;
  20637. }
  20638. }
  20639. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20640. {
  20641. cpuUsageMs = 0;
  20642. const double sampleRate = device->getCurrentSampleRate();
  20643. const int blockSize = device->getCurrentBufferSizeSamples();
  20644. if (sampleRate > 0.0 && blockSize > 0)
  20645. {
  20646. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20647. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20648. }
  20649. {
  20650. const ScopedLock sl (audioCallbackLock);
  20651. for (int i = callbacks.size(); --i >= 0;)
  20652. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20653. }
  20654. sendChangeMessage (this);
  20655. }
  20656. void AudioDeviceManager::audioDeviceStoppedInt()
  20657. {
  20658. cpuUsageMs = 0;
  20659. timeToCpuScale = 0;
  20660. sendChangeMessage (this);
  20661. const ScopedLock sl (audioCallbackLock);
  20662. for (int i = callbacks.size(); --i >= 0;)
  20663. callbacks.getUnchecked(i)->audioDeviceStopped();
  20664. }
  20665. double AudioDeviceManager::getCpuUsage() const
  20666. {
  20667. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20668. }
  20669. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20670. const bool enabled)
  20671. {
  20672. if (enabled != isMidiInputEnabled (name))
  20673. {
  20674. if (enabled)
  20675. {
  20676. const int index = MidiInput::getDevices().indexOf (name);
  20677. if (index >= 0)
  20678. {
  20679. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20680. if (min != 0)
  20681. {
  20682. enabledMidiInputs.add (min);
  20683. min->start();
  20684. }
  20685. }
  20686. }
  20687. else
  20688. {
  20689. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20690. if (enabledMidiInputs[i]->getName() == name)
  20691. enabledMidiInputs.remove (i);
  20692. }
  20693. updateXml();
  20694. sendChangeMessage (this);
  20695. }
  20696. }
  20697. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20698. {
  20699. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20700. if (enabledMidiInputs[i]->getName() == name)
  20701. return true;
  20702. return false;
  20703. }
  20704. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20705. MidiInputCallback* callback)
  20706. {
  20707. removeMidiInputCallback (name, callback);
  20708. if (name.isEmpty())
  20709. {
  20710. midiCallbacks.add (callback);
  20711. midiCallbackDevices.add (0);
  20712. }
  20713. else
  20714. {
  20715. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20716. {
  20717. if (enabledMidiInputs[i]->getName() == name)
  20718. {
  20719. const ScopedLock sl (midiCallbackLock);
  20720. midiCallbacks.add (callback);
  20721. midiCallbackDevices.add (enabledMidiInputs[i]);
  20722. break;
  20723. }
  20724. }
  20725. }
  20726. }
  20727. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20728. MidiInputCallback* /*callback*/)
  20729. {
  20730. const ScopedLock sl (midiCallbackLock);
  20731. for (int i = midiCallbacks.size(); --i >= 0;)
  20732. {
  20733. String devName;
  20734. if (midiCallbackDevices.getUnchecked(i) != 0)
  20735. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20736. if (devName == name)
  20737. {
  20738. midiCallbacks.remove (i);
  20739. midiCallbackDevices.remove (i);
  20740. }
  20741. }
  20742. }
  20743. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20744. const MidiMessage& message)
  20745. {
  20746. if (! message.isActiveSense())
  20747. {
  20748. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20749. const ScopedLock sl (midiCallbackLock);
  20750. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20751. {
  20752. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20753. if (md == source || (md == 0 && isDefaultSource))
  20754. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20755. }
  20756. }
  20757. }
  20758. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20759. {
  20760. if (defaultMidiOutputName != deviceName)
  20761. {
  20762. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20763. {
  20764. const ScopedLock sl (audioCallbackLock);
  20765. oldCallbacks = callbacks;
  20766. callbacks.clear();
  20767. }
  20768. if (currentAudioDevice != 0)
  20769. for (int i = oldCallbacks.size(); --i >= 0;)
  20770. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20771. defaultMidiOutput = 0;
  20772. defaultMidiOutputName = deviceName;
  20773. if (deviceName.isNotEmpty())
  20774. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20775. if (currentAudioDevice != 0)
  20776. for (int i = oldCallbacks.size(); --i >= 0;)
  20777. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20778. {
  20779. const ScopedLock sl (audioCallbackLock);
  20780. callbacks = oldCallbacks;
  20781. }
  20782. updateXml();
  20783. sendChangeMessage (this);
  20784. }
  20785. }
  20786. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20787. int numInputChannels,
  20788. float** outputChannelData,
  20789. int numOutputChannels,
  20790. int numSamples)
  20791. {
  20792. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20793. }
  20794. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20795. {
  20796. owner->audioDeviceAboutToStartInt (device);
  20797. }
  20798. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20799. {
  20800. owner->audioDeviceStoppedInt();
  20801. }
  20802. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20803. {
  20804. owner->handleIncomingMidiMessageInt (source, message);
  20805. }
  20806. void AudioDeviceManager::playTestSound()
  20807. {
  20808. { // cunningly nested to swap, unlock and delete in that order.
  20809. ScopedPointer <AudioSampleBuffer> oldSound;
  20810. {
  20811. const ScopedLock sl (audioCallbackLock);
  20812. oldSound = testSound;
  20813. }
  20814. }
  20815. testSoundPosition = 0;
  20816. if (currentAudioDevice != 0)
  20817. {
  20818. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20819. const int soundLength = (int) sampleRate;
  20820. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20821. float* samples = newSound->getSampleData (0);
  20822. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20823. const float amplitude = 0.5f;
  20824. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20825. for (int i = 0; i < soundLength; ++i)
  20826. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20827. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20828. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20829. const ScopedLock sl (audioCallbackLock);
  20830. testSound = newSound;
  20831. }
  20832. }
  20833. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20834. {
  20835. const ScopedLock sl (audioCallbackLock);
  20836. if (enableMeasurement)
  20837. ++inputLevelMeasurementEnabledCount;
  20838. else
  20839. --inputLevelMeasurementEnabledCount;
  20840. inputLevel = 0;
  20841. }
  20842. double AudioDeviceManager::getCurrentInputLevel() const
  20843. {
  20844. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20845. return inputLevel;
  20846. }
  20847. END_JUCE_NAMESPACE
  20848. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20849. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20850. BEGIN_JUCE_NAMESPACE
  20851. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20852. : name (deviceName),
  20853. typeName (typeName_)
  20854. {
  20855. }
  20856. AudioIODevice::~AudioIODevice()
  20857. {
  20858. }
  20859. bool AudioIODevice::hasControlPanel() const
  20860. {
  20861. return false;
  20862. }
  20863. bool AudioIODevice::showControlPanel()
  20864. {
  20865. jassertfalse; // this should only be called for devices which return true from
  20866. // their hasControlPanel() method.
  20867. return false;
  20868. }
  20869. END_JUCE_NAMESPACE
  20870. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20871. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20872. BEGIN_JUCE_NAMESPACE
  20873. AudioIODeviceType::AudioIODeviceType (const String& name)
  20874. : typeName (name)
  20875. {
  20876. }
  20877. AudioIODeviceType::~AudioIODeviceType()
  20878. {
  20879. }
  20880. END_JUCE_NAMESPACE
  20881. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20882. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20883. BEGIN_JUCE_NAMESPACE
  20884. MidiOutput::MidiOutput()
  20885. : Thread ("midi out"),
  20886. internal (0),
  20887. firstMessage (0)
  20888. {
  20889. }
  20890. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20891. const double sampleNumber)
  20892. : message (data, len, sampleNumber)
  20893. {
  20894. }
  20895. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20896. const double millisecondCounterToStartAt,
  20897. double samplesPerSecondForBuffer)
  20898. {
  20899. // You've got to call startBackgroundThread() for this to actually work..
  20900. jassert (isThreadRunning());
  20901. // this needs to be a value in the future - RTFM for this method!
  20902. jassert (millisecondCounterToStartAt > 0);
  20903. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20904. MidiBuffer::Iterator i (buffer);
  20905. const uint8* data;
  20906. int len, time;
  20907. while (i.getNextEvent (data, len, time))
  20908. {
  20909. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20910. PendingMessage* const m
  20911. = new PendingMessage (data, len, eventTime);
  20912. const ScopedLock sl (lock);
  20913. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20914. {
  20915. m->next = firstMessage;
  20916. firstMessage = m;
  20917. }
  20918. else
  20919. {
  20920. PendingMessage* mm = firstMessage;
  20921. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20922. mm = mm->next;
  20923. m->next = mm->next;
  20924. mm->next = m;
  20925. }
  20926. }
  20927. notify();
  20928. }
  20929. void MidiOutput::clearAllPendingMessages()
  20930. {
  20931. const ScopedLock sl (lock);
  20932. while (firstMessage != 0)
  20933. {
  20934. PendingMessage* const m = firstMessage;
  20935. firstMessage = firstMessage->next;
  20936. delete m;
  20937. }
  20938. }
  20939. void MidiOutput::startBackgroundThread()
  20940. {
  20941. startThread (9);
  20942. }
  20943. void MidiOutput::stopBackgroundThread()
  20944. {
  20945. stopThread (5000);
  20946. }
  20947. void MidiOutput::run()
  20948. {
  20949. while (! threadShouldExit())
  20950. {
  20951. uint32 now = Time::getMillisecondCounter();
  20952. uint32 eventTime = 0;
  20953. uint32 timeToWait = 500;
  20954. PendingMessage* message;
  20955. {
  20956. const ScopedLock sl (lock);
  20957. message = firstMessage;
  20958. if (message != 0)
  20959. {
  20960. eventTime = roundToInt (message->message.getTimeStamp());
  20961. if (eventTime > now + 20)
  20962. {
  20963. timeToWait = eventTime - (now + 20);
  20964. message = 0;
  20965. }
  20966. else
  20967. {
  20968. firstMessage = message->next;
  20969. }
  20970. }
  20971. }
  20972. if (message != 0)
  20973. {
  20974. if (eventTime > now)
  20975. {
  20976. Time::waitForMillisecondCounter (eventTime);
  20977. if (threadShouldExit())
  20978. break;
  20979. }
  20980. if (eventTime > now - 200)
  20981. sendMessageNow (message->message);
  20982. delete message;
  20983. }
  20984. else
  20985. {
  20986. jassert (timeToWait < 1000 * 30);
  20987. wait (timeToWait);
  20988. }
  20989. }
  20990. clearAllPendingMessages();
  20991. }
  20992. END_JUCE_NAMESPACE
  20993. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20994. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20995. BEGIN_JUCE_NAMESPACE
  20996. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20997. {
  20998. const double maxVal = (double) 0x7fff;
  20999. char* intData = static_cast <char*> (dest);
  21000. if (dest != (void*) source || destBytesPerSample <= 4)
  21001. {
  21002. for (int i = 0; i < numSamples; ++i)
  21003. {
  21004. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21005. intData += destBytesPerSample;
  21006. }
  21007. }
  21008. else
  21009. {
  21010. intData += destBytesPerSample * numSamples;
  21011. for (int i = numSamples; --i >= 0;)
  21012. {
  21013. intData -= destBytesPerSample;
  21014. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21015. }
  21016. }
  21017. }
  21018. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21019. {
  21020. const double maxVal = (double) 0x7fff;
  21021. char* intData = static_cast <char*> (dest);
  21022. if (dest != (void*) source || destBytesPerSample <= 4)
  21023. {
  21024. for (int i = 0; i < numSamples; ++i)
  21025. {
  21026. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21027. intData += destBytesPerSample;
  21028. }
  21029. }
  21030. else
  21031. {
  21032. intData += destBytesPerSample * numSamples;
  21033. for (int i = numSamples; --i >= 0;)
  21034. {
  21035. intData -= destBytesPerSample;
  21036. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21037. }
  21038. }
  21039. }
  21040. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21041. {
  21042. const double maxVal = (double) 0x7fffff;
  21043. char* intData = static_cast <char*> (dest);
  21044. if (dest != (void*) source || destBytesPerSample <= 4)
  21045. {
  21046. for (int i = 0; i < numSamples; ++i)
  21047. {
  21048. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21049. intData += destBytesPerSample;
  21050. }
  21051. }
  21052. else
  21053. {
  21054. intData += destBytesPerSample * numSamples;
  21055. for (int i = numSamples; --i >= 0;)
  21056. {
  21057. intData -= destBytesPerSample;
  21058. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21059. }
  21060. }
  21061. }
  21062. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21063. {
  21064. const double maxVal = (double) 0x7fffff;
  21065. char* intData = static_cast <char*> (dest);
  21066. if (dest != (void*) source || destBytesPerSample <= 4)
  21067. {
  21068. for (int i = 0; i < numSamples; ++i)
  21069. {
  21070. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21071. intData += destBytesPerSample;
  21072. }
  21073. }
  21074. else
  21075. {
  21076. intData += destBytesPerSample * numSamples;
  21077. for (int i = numSamples; --i >= 0;)
  21078. {
  21079. intData -= destBytesPerSample;
  21080. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21081. }
  21082. }
  21083. }
  21084. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21085. {
  21086. const double maxVal = (double) 0x7fffffff;
  21087. char* intData = static_cast <char*> (dest);
  21088. if (dest != (void*) source || destBytesPerSample <= 4)
  21089. {
  21090. for (int i = 0; i < numSamples; ++i)
  21091. {
  21092. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21093. intData += destBytesPerSample;
  21094. }
  21095. }
  21096. else
  21097. {
  21098. intData += destBytesPerSample * numSamples;
  21099. for (int i = numSamples; --i >= 0;)
  21100. {
  21101. intData -= destBytesPerSample;
  21102. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21103. }
  21104. }
  21105. }
  21106. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21107. {
  21108. const double maxVal = (double) 0x7fffffff;
  21109. char* intData = static_cast <char*> (dest);
  21110. if (dest != (void*) source || destBytesPerSample <= 4)
  21111. {
  21112. for (int i = 0; i < numSamples; ++i)
  21113. {
  21114. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21115. intData += destBytesPerSample;
  21116. }
  21117. }
  21118. else
  21119. {
  21120. intData += destBytesPerSample * numSamples;
  21121. for (int i = numSamples; --i >= 0;)
  21122. {
  21123. intData -= destBytesPerSample;
  21124. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21125. }
  21126. }
  21127. }
  21128. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21129. {
  21130. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21131. char* d = static_cast <char*> (dest);
  21132. for (int i = 0; i < numSamples; ++i)
  21133. {
  21134. *(float*) d = source[i];
  21135. #if JUCE_BIG_ENDIAN
  21136. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21137. #endif
  21138. d += destBytesPerSample;
  21139. }
  21140. }
  21141. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21142. {
  21143. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21144. char* d = static_cast <char*> (dest);
  21145. for (int i = 0; i < numSamples; ++i)
  21146. {
  21147. *(float*) d = source[i];
  21148. #if JUCE_LITTLE_ENDIAN
  21149. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21150. #endif
  21151. d += destBytesPerSample;
  21152. }
  21153. }
  21154. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21155. {
  21156. const float scale = 1.0f / 0x7fff;
  21157. const char* intData = static_cast <const char*> (source);
  21158. if (source != (void*) dest || srcBytesPerSample >= 4)
  21159. {
  21160. for (int i = 0; i < numSamples; ++i)
  21161. {
  21162. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21163. intData += srcBytesPerSample;
  21164. }
  21165. }
  21166. else
  21167. {
  21168. intData += srcBytesPerSample * numSamples;
  21169. for (int i = numSamples; --i >= 0;)
  21170. {
  21171. intData -= srcBytesPerSample;
  21172. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21173. }
  21174. }
  21175. }
  21176. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21177. {
  21178. const float scale = 1.0f / 0x7fff;
  21179. const char* intData = static_cast <const char*> (source);
  21180. if (source != (void*) dest || srcBytesPerSample >= 4)
  21181. {
  21182. for (int i = 0; i < numSamples; ++i)
  21183. {
  21184. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21185. intData += srcBytesPerSample;
  21186. }
  21187. }
  21188. else
  21189. {
  21190. intData += srcBytesPerSample * numSamples;
  21191. for (int i = numSamples; --i >= 0;)
  21192. {
  21193. intData -= srcBytesPerSample;
  21194. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21195. }
  21196. }
  21197. }
  21198. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21199. {
  21200. const float scale = 1.0f / 0x7fffff;
  21201. const char* intData = static_cast <const char*> (source);
  21202. if (source != (void*) dest || srcBytesPerSample >= 4)
  21203. {
  21204. for (int i = 0; i < numSamples; ++i)
  21205. {
  21206. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21207. intData += srcBytesPerSample;
  21208. }
  21209. }
  21210. else
  21211. {
  21212. intData += srcBytesPerSample * numSamples;
  21213. for (int i = numSamples; --i >= 0;)
  21214. {
  21215. intData -= srcBytesPerSample;
  21216. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21217. }
  21218. }
  21219. }
  21220. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21221. {
  21222. const float scale = 1.0f / 0x7fffff;
  21223. const char* intData = static_cast <const char*> (source);
  21224. if (source != (void*) dest || srcBytesPerSample >= 4)
  21225. {
  21226. for (int i = 0; i < numSamples; ++i)
  21227. {
  21228. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21229. intData += srcBytesPerSample;
  21230. }
  21231. }
  21232. else
  21233. {
  21234. intData += srcBytesPerSample * numSamples;
  21235. for (int i = numSamples; --i >= 0;)
  21236. {
  21237. intData -= srcBytesPerSample;
  21238. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21239. }
  21240. }
  21241. }
  21242. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21243. {
  21244. const float scale = 1.0f / 0x7fffffff;
  21245. const char* intData = static_cast <const char*> (source);
  21246. if (source != (void*) dest || srcBytesPerSample >= 4)
  21247. {
  21248. for (int i = 0; i < numSamples; ++i)
  21249. {
  21250. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21251. intData += srcBytesPerSample;
  21252. }
  21253. }
  21254. else
  21255. {
  21256. intData += srcBytesPerSample * numSamples;
  21257. for (int i = numSamples; --i >= 0;)
  21258. {
  21259. intData -= srcBytesPerSample;
  21260. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21261. }
  21262. }
  21263. }
  21264. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21265. {
  21266. const float scale = 1.0f / 0x7fffffff;
  21267. const char* intData = static_cast <const char*> (source);
  21268. if (source != (void*) dest || srcBytesPerSample >= 4)
  21269. {
  21270. for (int i = 0; i < numSamples; ++i)
  21271. {
  21272. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21273. intData += srcBytesPerSample;
  21274. }
  21275. }
  21276. else
  21277. {
  21278. intData += srcBytesPerSample * numSamples;
  21279. for (int i = numSamples; --i >= 0;)
  21280. {
  21281. intData -= srcBytesPerSample;
  21282. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21283. }
  21284. }
  21285. }
  21286. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21287. {
  21288. const char* s = static_cast <const char*> (source);
  21289. for (int i = 0; i < numSamples; ++i)
  21290. {
  21291. dest[i] = *(float*)s;
  21292. #if JUCE_BIG_ENDIAN
  21293. uint32* const d = (uint32*) (dest + i);
  21294. *d = ByteOrder::swap (*d);
  21295. #endif
  21296. s += srcBytesPerSample;
  21297. }
  21298. }
  21299. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21300. {
  21301. const char* s = static_cast <const char*> (source);
  21302. for (int i = 0; i < numSamples; ++i)
  21303. {
  21304. dest[i] = *(float*)s;
  21305. #if JUCE_LITTLE_ENDIAN
  21306. uint32* const d = (uint32*) (dest + i);
  21307. *d = ByteOrder::swap (*d);
  21308. #endif
  21309. s += srcBytesPerSample;
  21310. }
  21311. }
  21312. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21313. const float* const source,
  21314. void* const dest,
  21315. const int numSamples)
  21316. {
  21317. switch (destFormat)
  21318. {
  21319. case int16LE:
  21320. convertFloatToInt16LE (source, dest, numSamples);
  21321. break;
  21322. case int16BE:
  21323. convertFloatToInt16BE (source, dest, numSamples);
  21324. break;
  21325. case int24LE:
  21326. convertFloatToInt24LE (source, dest, numSamples);
  21327. break;
  21328. case int24BE:
  21329. convertFloatToInt24BE (source, dest, numSamples);
  21330. break;
  21331. case int32LE:
  21332. convertFloatToInt32LE (source, dest, numSamples);
  21333. break;
  21334. case int32BE:
  21335. convertFloatToInt32BE (source, dest, numSamples);
  21336. break;
  21337. case float32LE:
  21338. convertFloatToFloat32LE (source, dest, numSamples);
  21339. break;
  21340. case float32BE:
  21341. convertFloatToFloat32BE (source, dest, numSamples);
  21342. break;
  21343. default:
  21344. jassertfalse;
  21345. break;
  21346. }
  21347. }
  21348. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21349. const void* const source,
  21350. float* const dest,
  21351. const int numSamples)
  21352. {
  21353. switch (sourceFormat)
  21354. {
  21355. case int16LE:
  21356. convertInt16LEToFloat (source, dest, numSamples);
  21357. break;
  21358. case int16BE:
  21359. convertInt16BEToFloat (source, dest, numSamples);
  21360. break;
  21361. case int24LE:
  21362. convertInt24LEToFloat (source, dest, numSamples);
  21363. break;
  21364. case int24BE:
  21365. convertInt24BEToFloat (source, dest, numSamples);
  21366. break;
  21367. case int32LE:
  21368. convertInt32LEToFloat (source, dest, numSamples);
  21369. break;
  21370. case int32BE:
  21371. convertInt32BEToFloat (source, dest, numSamples);
  21372. break;
  21373. case float32LE:
  21374. convertFloat32LEToFloat (source, dest, numSamples);
  21375. break;
  21376. case float32BE:
  21377. convertFloat32BEToFloat (source, dest, numSamples);
  21378. break;
  21379. default:
  21380. jassertfalse;
  21381. break;
  21382. }
  21383. }
  21384. void AudioDataConverters::interleaveSamples (const float** const source,
  21385. float* const dest,
  21386. const int numSamples,
  21387. const int numChannels)
  21388. {
  21389. for (int chan = 0; chan < numChannels; ++chan)
  21390. {
  21391. int i = chan;
  21392. const float* src = source [chan];
  21393. for (int j = 0; j < numSamples; ++j)
  21394. {
  21395. dest [i] = src [j];
  21396. i += numChannels;
  21397. }
  21398. }
  21399. }
  21400. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21401. float** const dest,
  21402. const int numSamples,
  21403. const int numChannels)
  21404. {
  21405. for (int chan = 0; chan < numChannels; ++chan)
  21406. {
  21407. int i = chan;
  21408. float* dst = dest [chan];
  21409. for (int j = 0; j < numSamples; ++j)
  21410. {
  21411. dst [j] = source [i];
  21412. i += numChannels;
  21413. }
  21414. }
  21415. }
  21416. END_JUCE_NAMESPACE
  21417. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21418. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21419. BEGIN_JUCE_NAMESPACE
  21420. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21421. const int numSamples) throw()
  21422. : numChannels (numChannels_),
  21423. size (numSamples)
  21424. {
  21425. jassert (numSamples >= 0);
  21426. jassert (numChannels_ > 0);
  21427. allocateData();
  21428. }
  21429. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21430. : numChannels (other.numChannels),
  21431. size (other.size)
  21432. {
  21433. allocateData();
  21434. const size_t numBytes = size * sizeof (float);
  21435. for (int i = 0; i < numChannels; ++i)
  21436. memcpy (channels[i], other.channels[i], numBytes);
  21437. }
  21438. void AudioSampleBuffer::allocateData()
  21439. {
  21440. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21441. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21442. allocatedData.malloc (allocatedBytes);
  21443. channels = reinterpret_cast <float**> (allocatedData.getData());
  21444. float* chan = (float*) (allocatedData + channelListSize);
  21445. for (int i = 0; i < numChannels; ++i)
  21446. {
  21447. channels[i] = chan;
  21448. chan += size;
  21449. }
  21450. channels [numChannels] = 0;
  21451. }
  21452. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21453. const int numChannels_,
  21454. const int numSamples) throw()
  21455. : numChannels (numChannels_),
  21456. size (numSamples),
  21457. allocatedBytes (0)
  21458. {
  21459. jassert (numChannels_ > 0);
  21460. allocateChannels (dataToReferTo);
  21461. }
  21462. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21463. const int newNumChannels,
  21464. const int newNumSamples) throw()
  21465. {
  21466. jassert (newNumChannels > 0);
  21467. allocatedBytes = 0;
  21468. allocatedData.free();
  21469. numChannels = newNumChannels;
  21470. size = newNumSamples;
  21471. allocateChannels (dataToReferTo);
  21472. }
  21473. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21474. {
  21475. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21476. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21477. {
  21478. channels = static_cast <float**> (preallocatedChannelSpace);
  21479. }
  21480. else
  21481. {
  21482. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21483. channels = reinterpret_cast <float**> (allocatedData.getData());
  21484. }
  21485. for (int i = 0; i < numChannels; ++i)
  21486. {
  21487. // you have to pass in the same number of valid pointers as numChannels
  21488. jassert (dataToReferTo[i] != 0);
  21489. channels[i] = dataToReferTo[i];
  21490. }
  21491. channels [numChannels] = 0;
  21492. }
  21493. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21494. {
  21495. if (this != &other)
  21496. {
  21497. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21498. const size_t numBytes = size * sizeof (float);
  21499. for (int i = 0; i < numChannels; ++i)
  21500. memcpy (channels[i], other.channels[i], numBytes);
  21501. }
  21502. return *this;
  21503. }
  21504. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21505. {
  21506. }
  21507. void AudioSampleBuffer::setSize (const int newNumChannels,
  21508. const int newNumSamples,
  21509. const bool keepExistingContent,
  21510. const bool clearExtraSpace,
  21511. const bool avoidReallocating) throw()
  21512. {
  21513. jassert (newNumChannels > 0);
  21514. if (newNumSamples != size || newNumChannels != numChannels)
  21515. {
  21516. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21517. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21518. if (keepExistingContent)
  21519. {
  21520. HeapBlock <char> newData;
  21521. newData.allocate (newTotalBytes, clearExtraSpace);
  21522. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21523. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21524. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21525. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21526. for (int i = 0; i < numChansToCopy; ++i)
  21527. {
  21528. memcpy (newChan, channels[i], numBytesToCopy);
  21529. newChannels[i] = newChan;
  21530. newChan += newNumSamples;
  21531. }
  21532. allocatedData.swapWith (newData);
  21533. allocatedBytes = (int) newTotalBytes;
  21534. channels = newChannels;
  21535. }
  21536. else
  21537. {
  21538. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21539. {
  21540. if (clearExtraSpace)
  21541. zeromem (allocatedData, newTotalBytes);
  21542. }
  21543. else
  21544. {
  21545. allocatedBytes = newTotalBytes;
  21546. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21547. channels = reinterpret_cast <float**> (allocatedData.getData());
  21548. }
  21549. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21550. for (int i = 0; i < newNumChannels; ++i)
  21551. {
  21552. channels[i] = chan;
  21553. chan += newNumSamples;
  21554. }
  21555. }
  21556. channels [newNumChannels] = 0;
  21557. size = newNumSamples;
  21558. numChannels = newNumChannels;
  21559. }
  21560. }
  21561. void AudioSampleBuffer::clear() throw()
  21562. {
  21563. for (int i = 0; i < numChannels; ++i)
  21564. zeromem (channels[i], size * sizeof (float));
  21565. }
  21566. void AudioSampleBuffer::clear (const int startSample,
  21567. const int numSamples) throw()
  21568. {
  21569. jassert (startSample >= 0 && startSample + numSamples <= size);
  21570. for (int i = 0; i < numChannels; ++i)
  21571. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21572. }
  21573. void AudioSampleBuffer::clear (const int channel,
  21574. const int startSample,
  21575. const int numSamples) throw()
  21576. {
  21577. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21578. jassert (startSample >= 0 && startSample + numSamples <= size);
  21579. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21580. }
  21581. void AudioSampleBuffer::applyGain (const int channel,
  21582. const int startSample,
  21583. int numSamples,
  21584. const float gain) throw()
  21585. {
  21586. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21587. jassert (startSample >= 0 && startSample + numSamples <= size);
  21588. if (gain != 1.0f)
  21589. {
  21590. float* d = channels [channel] + startSample;
  21591. if (gain == 0.0f)
  21592. {
  21593. zeromem (d, sizeof (float) * numSamples);
  21594. }
  21595. else
  21596. {
  21597. while (--numSamples >= 0)
  21598. *d++ *= gain;
  21599. }
  21600. }
  21601. }
  21602. void AudioSampleBuffer::applyGainRamp (const int channel,
  21603. const int startSample,
  21604. int numSamples,
  21605. float startGain,
  21606. float endGain) throw()
  21607. {
  21608. if (startGain == endGain)
  21609. {
  21610. applyGain (channel, startSample, numSamples, startGain);
  21611. }
  21612. else
  21613. {
  21614. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21615. jassert (startSample >= 0 && startSample + numSamples <= size);
  21616. const float increment = (endGain - startGain) / numSamples;
  21617. float* d = channels [channel] + startSample;
  21618. while (--numSamples >= 0)
  21619. {
  21620. *d++ *= startGain;
  21621. startGain += increment;
  21622. }
  21623. }
  21624. }
  21625. void AudioSampleBuffer::applyGain (const int startSample,
  21626. const int numSamples,
  21627. const float gain) throw()
  21628. {
  21629. for (int i = 0; i < numChannels; ++i)
  21630. applyGain (i, startSample, numSamples, gain);
  21631. }
  21632. void AudioSampleBuffer::addFrom (const int destChannel,
  21633. const int destStartSample,
  21634. const AudioSampleBuffer& source,
  21635. const int sourceChannel,
  21636. const int sourceStartSample,
  21637. int numSamples,
  21638. const float gain) throw()
  21639. {
  21640. jassert (&source != this || sourceChannel != destChannel);
  21641. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21642. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21643. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21644. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21645. if (gain != 0.0f && numSamples > 0)
  21646. {
  21647. float* d = channels [destChannel] + destStartSample;
  21648. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21649. if (gain != 1.0f)
  21650. {
  21651. while (--numSamples >= 0)
  21652. *d++ += gain * *s++;
  21653. }
  21654. else
  21655. {
  21656. while (--numSamples >= 0)
  21657. *d++ += *s++;
  21658. }
  21659. }
  21660. }
  21661. void AudioSampleBuffer::addFrom (const int destChannel,
  21662. const int destStartSample,
  21663. const float* source,
  21664. int numSamples,
  21665. const float gain) throw()
  21666. {
  21667. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21668. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21669. jassert (source != 0);
  21670. if (gain != 0.0f && numSamples > 0)
  21671. {
  21672. float* d = channels [destChannel] + destStartSample;
  21673. if (gain != 1.0f)
  21674. {
  21675. while (--numSamples >= 0)
  21676. *d++ += gain * *source++;
  21677. }
  21678. else
  21679. {
  21680. while (--numSamples >= 0)
  21681. *d++ += *source++;
  21682. }
  21683. }
  21684. }
  21685. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21686. const int destStartSample,
  21687. const float* source,
  21688. int numSamples,
  21689. float startGain,
  21690. const float endGain) throw()
  21691. {
  21692. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21693. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21694. jassert (source != 0);
  21695. if (startGain == endGain)
  21696. {
  21697. addFrom (destChannel,
  21698. destStartSample,
  21699. source,
  21700. numSamples,
  21701. startGain);
  21702. }
  21703. else
  21704. {
  21705. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21706. {
  21707. const float increment = (endGain - startGain) / numSamples;
  21708. float* d = channels [destChannel] + destStartSample;
  21709. while (--numSamples >= 0)
  21710. {
  21711. *d++ += startGain * *source++;
  21712. startGain += increment;
  21713. }
  21714. }
  21715. }
  21716. }
  21717. void AudioSampleBuffer::copyFrom (const int destChannel,
  21718. const int destStartSample,
  21719. const AudioSampleBuffer& source,
  21720. const int sourceChannel,
  21721. const int sourceStartSample,
  21722. int numSamples) throw()
  21723. {
  21724. jassert (&source != this || sourceChannel != destChannel);
  21725. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21726. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21727. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21728. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21729. if (numSamples > 0)
  21730. {
  21731. memcpy (channels [destChannel] + destStartSample,
  21732. source.channels [sourceChannel] + sourceStartSample,
  21733. sizeof (float) * numSamples);
  21734. }
  21735. }
  21736. void AudioSampleBuffer::copyFrom (const int destChannel,
  21737. const int destStartSample,
  21738. const float* source,
  21739. int numSamples) throw()
  21740. {
  21741. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21742. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21743. jassert (source != 0);
  21744. if (numSamples > 0)
  21745. {
  21746. memcpy (channels [destChannel] + destStartSample,
  21747. source,
  21748. sizeof (float) * numSamples);
  21749. }
  21750. }
  21751. void AudioSampleBuffer::copyFrom (const int destChannel,
  21752. const int destStartSample,
  21753. const float* source,
  21754. int numSamples,
  21755. const float gain) throw()
  21756. {
  21757. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21758. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21759. jassert (source != 0);
  21760. if (numSamples > 0)
  21761. {
  21762. float* d = channels [destChannel] + destStartSample;
  21763. if (gain != 1.0f)
  21764. {
  21765. if (gain == 0)
  21766. {
  21767. zeromem (d, sizeof (float) * numSamples);
  21768. }
  21769. else
  21770. {
  21771. while (--numSamples >= 0)
  21772. *d++ = gain * *source++;
  21773. }
  21774. }
  21775. else
  21776. {
  21777. memcpy (d, source, sizeof (float) * numSamples);
  21778. }
  21779. }
  21780. }
  21781. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21782. const int destStartSample,
  21783. const float* source,
  21784. int numSamples,
  21785. float startGain,
  21786. float endGain) throw()
  21787. {
  21788. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21789. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21790. jassert (source != 0);
  21791. if (startGain == endGain)
  21792. {
  21793. copyFrom (destChannel,
  21794. destStartSample,
  21795. source,
  21796. numSamples,
  21797. startGain);
  21798. }
  21799. else
  21800. {
  21801. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21802. {
  21803. const float increment = (endGain - startGain) / numSamples;
  21804. float* d = channels [destChannel] + destStartSample;
  21805. while (--numSamples >= 0)
  21806. {
  21807. *d++ = startGain * *source++;
  21808. startGain += increment;
  21809. }
  21810. }
  21811. }
  21812. }
  21813. void AudioSampleBuffer::findMinMax (const int channel,
  21814. const int startSample,
  21815. int numSamples,
  21816. float& minVal,
  21817. float& maxVal) const throw()
  21818. {
  21819. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21820. jassert (startSample >= 0 && startSample + numSamples <= size);
  21821. if (numSamples <= 0)
  21822. {
  21823. minVal = 0.0f;
  21824. maxVal = 0.0f;
  21825. }
  21826. else
  21827. {
  21828. const float* d = channels [channel] + startSample;
  21829. float mn = *d++;
  21830. float mx = mn;
  21831. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21832. {
  21833. const float samp = *d++;
  21834. if (samp > mx)
  21835. mx = samp;
  21836. if (samp < mn)
  21837. mn = samp;
  21838. }
  21839. maxVal = mx;
  21840. minVal = mn;
  21841. }
  21842. }
  21843. float AudioSampleBuffer::getMagnitude (const int channel,
  21844. const int startSample,
  21845. const int numSamples) const throw()
  21846. {
  21847. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21848. jassert (startSample >= 0 && startSample + numSamples <= size);
  21849. float mn, mx;
  21850. findMinMax (channel, startSample, numSamples, mn, mx);
  21851. return jmax (mn, -mn, mx, -mx);
  21852. }
  21853. float AudioSampleBuffer::getMagnitude (const int startSample,
  21854. const int numSamples) const throw()
  21855. {
  21856. float mag = 0.0f;
  21857. for (int i = 0; i < numChannels; ++i)
  21858. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21859. return mag;
  21860. }
  21861. float AudioSampleBuffer::getRMSLevel (const int channel,
  21862. const int startSample,
  21863. const int numSamples) const throw()
  21864. {
  21865. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21866. jassert (startSample >= 0 && startSample + numSamples <= size);
  21867. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21868. return 0.0f;
  21869. const float* const data = channels [channel] + startSample;
  21870. double sum = 0.0;
  21871. for (int i = 0; i < numSamples; ++i)
  21872. {
  21873. const float sample = data [i];
  21874. sum += sample * sample;
  21875. }
  21876. return (float) std::sqrt (sum / numSamples);
  21877. }
  21878. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21879. const int startSample,
  21880. const int numSamples,
  21881. const int readerStartSample,
  21882. const bool useLeftChan,
  21883. const bool useRightChan)
  21884. {
  21885. jassert (reader != 0);
  21886. jassert (startSample >= 0 && startSample + numSamples <= size);
  21887. if (numSamples > 0)
  21888. {
  21889. int* chans[3];
  21890. if (useLeftChan == useRightChan)
  21891. {
  21892. chans[0] = (int*) getSampleData (0, startSample);
  21893. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21894. }
  21895. else if (useLeftChan || (reader->numChannels == 1))
  21896. {
  21897. chans[0] = (int*) getSampleData (0, startSample);
  21898. chans[1] = 0;
  21899. }
  21900. else if (useRightChan)
  21901. {
  21902. chans[0] = 0;
  21903. chans[1] = (int*) getSampleData (0, startSample);
  21904. }
  21905. chans[2] = 0;
  21906. reader->read (chans, 2, readerStartSample, numSamples, true);
  21907. if (! reader->usesFloatingPointData)
  21908. {
  21909. for (int j = 0; j < 2; ++j)
  21910. {
  21911. float* const d = reinterpret_cast <float*> (chans[j]);
  21912. if (d != 0)
  21913. {
  21914. const float multiplier = 1.0f / 0x7fffffff;
  21915. for (int i = 0; i < numSamples; ++i)
  21916. d[i] = *(int*)(d + i) * multiplier;
  21917. }
  21918. }
  21919. }
  21920. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21921. {
  21922. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21923. memcpy (getSampleData (1, startSample),
  21924. getSampleData (0, startSample),
  21925. sizeof (float) * numSamples);
  21926. }
  21927. }
  21928. }
  21929. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21930. const int startSample,
  21931. const int numSamples) const
  21932. {
  21933. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  21934. if (numSamples > 0)
  21935. {
  21936. HeapBlock<int> tempBuffer;
  21937. HeapBlock<int*> chans (numChannels + 1);
  21938. chans [numChannels] = 0;
  21939. if (writer->isFloatingPoint())
  21940. {
  21941. for (int i = numChannels; --i >= 0;)
  21942. chans[i] = (int*) channels[i] + startSample;
  21943. }
  21944. else
  21945. {
  21946. tempBuffer.malloc (numSamples * numChannels);
  21947. for (int j = 0; j < numChannels; ++j)
  21948. {
  21949. int* const dest = tempBuffer + j * numSamples;
  21950. const float* const src = channels[j] + startSample;
  21951. chans[j] = dest;
  21952. for (int i = 0; i < numSamples; ++i)
  21953. {
  21954. const double samp = src[i];
  21955. if (samp <= -1.0)
  21956. dest[i] = std::numeric_limits<int>::min();
  21957. else if (samp >= 1.0)
  21958. dest[i] = std::numeric_limits<int>::max();
  21959. else
  21960. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21961. }
  21962. }
  21963. }
  21964. writer->write ((const int**) chans.getData(), numSamples);
  21965. }
  21966. }
  21967. END_JUCE_NAMESPACE
  21968. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21969. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21970. BEGIN_JUCE_NAMESPACE
  21971. IIRFilter::IIRFilter()
  21972. : active (false)
  21973. {
  21974. reset();
  21975. }
  21976. IIRFilter::IIRFilter (const IIRFilter& other)
  21977. : active (other.active)
  21978. {
  21979. const ScopedLock sl (other.processLock);
  21980. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21981. reset();
  21982. }
  21983. IIRFilter::~IIRFilter()
  21984. {
  21985. }
  21986. void IIRFilter::reset() throw()
  21987. {
  21988. const ScopedLock sl (processLock);
  21989. x1 = 0;
  21990. x2 = 0;
  21991. y1 = 0;
  21992. y2 = 0;
  21993. }
  21994. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21995. {
  21996. float out = coefficients[0] * in
  21997. + coefficients[1] * x1
  21998. + coefficients[2] * x2
  21999. - coefficients[4] * y1
  22000. - coefficients[5] * y2;
  22001. #if JUCE_INTEL
  22002. if (! (out < -1.0e-8 || out > 1.0e-8))
  22003. out = 0;
  22004. #endif
  22005. x2 = x1;
  22006. x1 = in;
  22007. y2 = y1;
  22008. y1 = out;
  22009. return out;
  22010. }
  22011. void IIRFilter::processSamples (float* const samples,
  22012. const int numSamples) throw()
  22013. {
  22014. const ScopedLock sl (processLock);
  22015. if (active)
  22016. {
  22017. for (int i = 0; i < numSamples; ++i)
  22018. {
  22019. const float in = samples[i];
  22020. float out = coefficients[0] * in
  22021. + coefficients[1] * x1
  22022. + coefficients[2] * x2
  22023. - coefficients[4] * y1
  22024. - coefficients[5] * y2;
  22025. #if JUCE_INTEL
  22026. if (! (out < -1.0e-8 || out > 1.0e-8))
  22027. out = 0;
  22028. #endif
  22029. x2 = x1;
  22030. x1 = in;
  22031. y2 = y1;
  22032. y1 = out;
  22033. samples[i] = out;
  22034. }
  22035. }
  22036. }
  22037. void IIRFilter::makeLowPass (const double sampleRate,
  22038. const double frequency) throw()
  22039. {
  22040. jassert (sampleRate > 0);
  22041. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22042. const double nSquared = n * n;
  22043. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22044. setCoefficients (c1,
  22045. c1 * 2.0f,
  22046. c1,
  22047. 1.0,
  22048. c1 * 2.0 * (1.0 - nSquared),
  22049. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22050. }
  22051. void IIRFilter::makeHighPass (const double sampleRate,
  22052. const double frequency) throw()
  22053. {
  22054. const double n = tan (double_Pi * frequency / sampleRate);
  22055. const double nSquared = n * n;
  22056. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22057. setCoefficients (c1,
  22058. c1 * -2.0f,
  22059. c1,
  22060. 1.0,
  22061. c1 * 2.0 * (nSquared - 1.0),
  22062. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22063. }
  22064. void IIRFilter::makeLowShelf (const double sampleRate,
  22065. const double cutOffFrequency,
  22066. const double Q,
  22067. const float gainFactor) throw()
  22068. {
  22069. jassert (sampleRate > 0);
  22070. jassert (Q > 0);
  22071. const double A = jmax (0.0f, gainFactor);
  22072. const double aminus1 = A - 1.0;
  22073. const double aplus1 = A + 1.0;
  22074. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22075. const double coso = std::cos (omega);
  22076. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22077. const double aminus1TimesCoso = aminus1 * coso;
  22078. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22079. A * 2.0 * (aminus1 - aplus1 * coso),
  22080. A * (aplus1 - aminus1TimesCoso - beta),
  22081. aplus1 + aminus1TimesCoso + beta,
  22082. -2.0 * (aminus1 + aplus1 * coso),
  22083. aplus1 + aminus1TimesCoso - beta);
  22084. }
  22085. void IIRFilter::makeHighShelf (const double sampleRate,
  22086. const double cutOffFrequency,
  22087. const double Q,
  22088. const float gainFactor) throw()
  22089. {
  22090. jassert (sampleRate > 0);
  22091. jassert (Q > 0);
  22092. const double A = jmax (0.0f, gainFactor);
  22093. const double aminus1 = A - 1.0;
  22094. const double aplus1 = A + 1.0;
  22095. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22096. const double coso = std::cos (omega);
  22097. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22098. const double aminus1TimesCoso = aminus1 * coso;
  22099. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22100. A * -2.0 * (aminus1 + aplus1 * coso),
  22101. A * (aplus1 + aminus1TimesCoso - beta),
  22102. aplus1 - aminus1TimesCoso + beta,
  22103. 2.0 * (aminus1 - aplus1 * coso),
  22104. aplus1 - aminus1TimesCoso - beta);
  22105. }
  22106. void IIRFilter::makeBandPass (const double sampleRate,
  22107. const double centreFrequency,
  22108. const double Q,
  22109. const float gainFactor) throw()
  22110. {
  22111. jassert (sampleRate > 0);
  22112. jassert (Q > 0);
  22113. const double A = jmax (0.0f, gainFactor);
  22114. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22115. const double alpha = 0.5 * std::sin (omega) / Q;
  22116. const double c2 = -2.0 * std::cos (omega);
  22117. const double alphaTimesA = alpha * A;
  22118. const double alphaOverA = alpha / A;
  22119. setCoefficients (1.0 + alphaTimesA,
  22120. c2,
  22121. 1.0 - alphaTimesA,
  22122. 1.0 + alphaOverA,
  22123. c2,
  22124. 1.0 - alphaOverA);
  22125. }
  22126. void IIRFilter::makeInactive() throw()
  22127. {
  22128. const ScopedLock sl (processLock);
  22129. active = false;
  22130. }
  22131. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22132. {
  22133. const ScopedLock sl (processLock);
  22134. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22135. active = other.active;
  22136. }
  22137. void IIRFilter::setCoefficients (double c1,
  22138. double c2,
  22139. double c3,
  22140. double c4,
  22141. double c5,
  22142. double c6) throw()
  22143. {
  22144. const double a = 1.0 / c4;
  22145. c1 *= a;
  22146. c2 *= a;
  22147. c3 *= a;
  22148. c5 *= a;
  22149. c6 *= a;
  22150. const ScopedLock sl (processLock);
  22151. coefficients[0] = (float) c1;
  22152. coefficients[1] = (float) c2;
  22153. coefficients[2] = (float) c3;
  22154. coefficients[3] = (float) c4;
  22155. coefficients[4] = (float) c5;
  22156. coefficients[5] = (float) c6;
  22157. active = true;
  22158. }
  22159. END_JUCE_NAMESPACE
  22160. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22161. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22162. BEGIN_JUCE_NAMESPACE
  22163. MidiBuffer::MidiBuffer() throw()
  22164. : bytesUsed (0)
  22165. {
  22166. }
  22167. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22168. : bytesUsed (0)
  22169. {
  22170. addEvent (message, 0);
  22171. }
  22172. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22173. : data (other.data),
  22174. bytesUsed (other.bytesUsed)
  22175. {
  22176. }
  22177. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22178. {
  22179. bytesUsed = other.bytesUsed;
  22180. data = other.data;
  22181. return *this;
  22182. }
  22183. void MidiBuffer::swapWith (MidiBuffer& other)
  22184. {
  22185. data.swapWith (other.data);
  22186. swapVariables <int> (bytesUsed, other.bytesUsed);
  22187. }
  22188. MidiBuffer::~MidiBuffer()
  22189. {
  22190. }
  22191. inline uint8* MidiBuffer::getData() const throw()
  22192. {
  22193. return static_cast <uint8*> (data.getData());
  22194. }
  22195. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22196. {
  22197. return *static_cast <const int*> (d);
  22198. }
  22199. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22200. {
  22201. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22202. }
  22203. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22204. {
  22205. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22206. }
  22207. void MidiBuffer::clear() throw()
  22208. {
  22209. bytesUsed = 0;
  22210. }
  22211. void MidiBuffer::clear (const int startSample, const int numSamples)
  22212. {
  22213. uint8* const start = findEventAfter (getData(), startSample - 1);
  22214. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22215. if (end > start)
  22216. {
  22217. const int bytesToMove = bytesUsed - (int) (end - getData());
  22218. if (bytesToMove > 0)
  22219. memmove (start, end, bytesToMove);
  22220. bytesUsed -= (int) (end - start);
  22221. }
  22222. }
  22223. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22224. {
  22225. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22226. }
  22227. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22228. {
  22229. unsigned int byte = (unsigned int) *data;
  22230. int size = 0;
  22231. if (byte == 0xf0 || byte == 0xf7)
  22232. {
  22233. const uint8* d = data + 1;
  22234. while (d < data + maxBytes)
  22235. if (*d++ == 0xf7)
  22236. break;
  22237. size = (int) (d - data);
  22238. }
  22239. else if (byte == 0xff)
  22240. {
  22241. int n;
  22242. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22243. size = jmin (maxBytes, n + 2 + bytesLeft);
  22244. }
  22245. else if (byte >= 0x80)
  22246. {
  22247. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22248. }
  22249. return size;
  22250. }
  22251. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22252. {
  22253. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22254. if (numBytes > 0)
  22255. {
  22256. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22257. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22258. uint8* d = findEventAfter (getData(), sampleNumber);
  22259. const int bytesToMove = bytesUsed - (int) (d - getData());
  22260. if (bytesToMove > 0)
  22261. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22262. *reinterpret_cast <int*> (d) = sampleNumber;
  22263. d += sizeof (int);
  22264. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22265. d += sizeof (uint16);
  22266. memcpy (d, newData, numBytes);
  22267. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22268. }
  22269. }
  22270. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22271. const int startSample,
  22272. const int numSamples,
  22273. const int sampleDeltaToAdd)
  22274. {
  22275. Iterator i (otherBuffer);
  22276. i.setNextSamplePosition (startSample);
  22277. const uint8* eventData;
  22278. int eventSize, position;
  22279. while (i.getNextEvent (eventData, eventSize, position)
  22280. && (position < startSample + numSamples || numSamples < 0))
  22281. {
  22282. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22283. }
  22284. }
  22285. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22286. {
  22287. data.ensureSize (minimumNumBytes);
  22288. }
  22289. bool MidiBuffer::isEmpty() const throw()
  22290. {
  22291. return bytesUsed == 0;
  22292. }
  22293. int MidiBuffer::getNumEvents() const throw()
  22294. {
  22295. int n = 0;
  22296. const uint8* d = getData();
  22297. const uint8* const end = d + bytesUsed;
  22298. while (d < end)
  22299. {
  22300. d += getEventTotalSize (d);
  22301. ++n;
  22302. }
  22303. return n;
  22304. }
  22305. int MidiBuffer::getFirstEventTime() const throw()
  22306. {
  22307. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22308. }
  22309. int MidiBuffer::getLastEventTime() const throw()
  22310. {
  22311. if (bytesUsed == 0)
  22312. return 0;
  22313. const uint8* d = getData();
  22314. const uint8* const endData = d + bytesUsed;
  22315. for (;;)
  22316. {
  22317. const uint8* const nextOne = d + getEventTotalSize (d);
  22318. if (nextOne >= endData)
  22319. return getEventTime (d);
  22320. d = nextOne;
  22321. }
  22322. }
  22323. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22324. {
  22325. const uint8* const endData = getData() + bytesUsed;
  22326. while (d < endData && getEventTime (d) <= samplePosition)
  22327. d += getEventTotalSize (d);
  22328. return d;
  22329. }
  22330. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22331. : buffer (buffer_),
  22332. data (buffer_.getData())
  22333. {
  22334. }
  22335. MidiBuffer::Iterator::~Iterator() throw()
  22336. {
  22337. }
  22338. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22339. {
  22340. data = buffer.getData();
  22341. const uint8* dataEnd = data + buffer.bytesUsed;
  22342. while (data < dataEnd && getEventTime (data) < samplePosition)
  22343. data += getEventTotalSize (data);
  22344. }
  22345. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22346. {
  22347. if (data >= buffer.getData() + buffer.bytesUsed)
  22348. return false;
  22349. samplePosition = getEventTime (data);
  22350. numBytes = getEventDataSize (data);
  22351. data += sizeof (int) + sizeof (uint16);
  22352. midiData = data;
  22353. data += numBytes;
  22354. return true;
  22355. }
  22356. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22357. {
  22358. if (data >= buffer.getData() + buffer.bytesUsed)
  22359. return false;
  22360. samplePosition = getEventTime (data);
  22361. const int numBytes = getEventDataSize (data);
  22362. data += sizeof (int) + sizeof (uint16);
  22363. result = MidiMessage (data, numBytes, samplePosition);
  22364. data += numBytes;
  22365. return true;
  22366. }
  22367. END_JUCE_NAMESPACE
  22368. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22369. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22370. BEGIN_JUCE_NAMESPACE
  22371. namespace MidiFileHelpers
  22372. {
  22373. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22374. {
  22375. unsigned int buffer = v & 0x7F;
  22376. while ((v >>= 7) != 0)
  22377. {
  22378. buffer <<= 8;
  22379. buffer |= ((v & 0x7F) | 0x80);
  22380. }
  22381. for (;;)
  22382. {
  22383. out.writeByte ((char) buffer);
  22384. if (buffer & 0x80)
  22385. buffer >>= 8;
  22386. else
  22387. break;
  22388. }
  22389. }
  22390. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22391. {
  22392. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22393. data += 4;
  22394. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22395. {
  22396. bool ok = false;
  22397. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22398. {
  22399. for (int i = 0; i < 8; ++i)
  22400. {
  22401. ch = ByteOrder::bigEndianInt (data);
  22402. data += 4;
  22403. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22404. {
  22405. ok = true;
  22406. break;
  22407. }
  22408. }
  22409. }
  22410. if (! ok)
  22411. return false;
  22412. }
  22413. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22414. data += 4;
  22415. fileType = (short) ByteOrder::bigEndianShort (data);
  22416. data += 2;
  22417. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22418. data += 2;
  22419. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22420. data += 2;
  22421. bytesRemaining -= 6;
  22422. data += bytesRemaining;
  22423. return true;
  22424. }
  22425. static double convertTicksToSeconds (const double time,
  22426. const MidiMessageSequence& tempoEvents,
  22427. const int timeFormat)
  22428. {
  22429. if (timeFormat > 0)
  22430. {
  22431. int numer = 4, denom = 4;
  22432. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22433. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22434. double secsPerTick = 0.5 * tickLen;
  22435. const int numEvents = tempoEvents.getNumEvents();
  22436. for (int i = 0; i < numEvents; ++i)
  22437. {
  22438. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22439. if (time <= m.getTimeStamp())
  22440. break;
  22441. if (timeFormat > 0)
  22442. {
  22443. correctedTempoTime = correctedTempoTime
  22444. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22445. }
  22446. else
  22447. {
  22448. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22449. }
  22450. tempoTime = m.getTimeStamp();
  22451. if (m.isTempoMetaEvent())
  22452. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22453. else if (m.isTimeSignatureMetaEvent())
  22454. m.getTimeSignatureInfo (numer, denom);
  22455. while (i + 1 < numEvents)
  22456. {
  22457. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22458. if (m2.getTimeStamp() == tempoTime)
  22459. {
  22460. ++i;
  22461. if (m2.isTempoMetaEvent())
  22462. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22463. else if (m2.isTimeSignatureMetaEvent())
  22464. m2.getTimeSignatureInfo (numer, denom);
  22465. }
  22466. else
  22467. {
  22468. break;
  22469. }
  22470. }
  22471. }
  22472. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22473. }
  22474. else
  22475. {
  22476. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22477. }
  22478. }
  22479. // a comparator that puts all the note-offs before note-ons that have the same time
  22480. struct Sorter
  22481. {
  22482. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22483. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22484. {
  22485. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22486. if (diff == 0)
  22487. {
  22488. if (first->message.isNoteOff() && second->message.isNoteOn())
  22489. return -1;
  22490. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22491. return 1;
  22492. else
  22493. return 0;
  22494. }
  22495. else
  22496. {
  22497. return (diff > 0) ? 1 : -1;
  22498. }
  22499. }
  22500. };
  22501. }
  22502. MidiFile::MidiFile()
  22503. : timeFormat ((short) (unsigned short) 0xe728)
  22504. {
  22505. }
  22506. MidiFile::~MidiFile()
  22507. {
  22508. clear();
  22509. }
  22510. void MidiFile::clear()
  22511. {
  22512. tracks.clear();
  22513. }
  22514. int MidiFile::getNumTracks() const throw()
  22515. {
  22516. return tracks.size();
  22517. }
  22518. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22519. {
  22520. return tracks [index];
  22521. }
  22522. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22523. {
  22524. tracks.add (new MidiMessageSequence (trackSequence));
  22525. }
  22526. short MidiFile::getTimeFormat() const throw()
  22527. {
  22528. return timeFormat;
  22529. }
  22530. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22531. {
  22532. timeFormat = (short) ticks;
  22533. }
  22534. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22535. const int subframeResolution) throw()
  22536. {
  22537. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22538. }
  22539. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22540. {
  22541. for (int i = tracks.size(); --i >= 0;)
  22542. {
  22543. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22544. for (int j = 0; j < numEvents; ++j)
  22545. {
  22546. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22547. if (m.isTempoMetaEvent())
  22548. tempoChangeEvents.addEvent (m);
  22549. }
  22550. }
  22551. }
  22552. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22553. {
  22554. for (int i = tracks.size(); --i >= 0;)
  22555. {
  22556. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22557. for (int j = 0; j < numEvents; ++j)
  22558. {
  22559. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22560. if (m.isTimeSignatureMetaEvent())
  22561. timeSigEvents.addEvent (m);
  22562. }
  22563. }
  22564. }
  22565. double MidiFile::getLastTimestamp() const
  22566. {
  22567. double t = 0.0;
  22568. for (int i = tracks.size(); --i >= 0;)
  22569. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22570. return t;
  22571. }
  22572. bool MidiFile::readFrom (InputStream& sourceStream)
  22573. {
  22574. clear();
  22575. MemoryBlock data;
  22576. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22577. // (put a sanity-check on the file size, as midi files are generally small)
  22578. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22579. {
  22580. size_t size = data.getSize();
  22581. const uint8* d = static_cast <const uint8*> (data.getData());
  22582. short fileType, expectedTracks;
  22583. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22584. {
  22585. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22586. int track = 0;
  22587. while (size > 0 && track < expectedTracks)
  22588. {
  22589. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22590. d += 4;
  22591. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22592. d += 4;
  22593. if (chunkSize <= 0)
  22594. break;
  22595. if (size < 0)
  22596. return false;
  22597. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22598. {
  22599. readNextTrack (d, chunkSize);
  22600. }
  22601. size -= chunkSize + 8;
  22602. d += chunkSize;
  22603. ++track;
  22604. }
  22605. return true;
  22606. }
  22607. }
  22608. return false;
  22609. }
  22610. void MidiFile::readNextTrack (const uint8* data, int size)
  22611. {
  22612. double time = 0;
  22613. char lastStatusByte = 0;
  22614. MidiMessageSequence result;
  22615. while (size > 0)
  22616. {
  22617. int bytesUsed;
  22618. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22619. data += bytesUsed;
  22620. size -= bytesUsed;
  22621. time += delay;
  22622. int messSize = 0;
  22623. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22624. if (messSize <= 0)
  22625. break;
  22626. size -= messSize;
  22627. data += messSize;
  22628. result.addEvent (mm);
  22629. const char firstByte = *(mm.getRawData());
  22630. if ((firstByte & 0xf0) != 0xf0)
  22631. lastStatusByte = firstByte;
  22632. }
  22633. // use a sort that puts all the note-offs before note-ons that have the same time
  22634. MidiFileHelpers::Sorter sorter;
  22635. result.list.sort (sorter, true);
  22636. result.updateMatchedPairs();
  22637. addTrack (result);
  22638. }
  22639. void MidiFile::convertTimestampTicksToSeconds()
  22640. {
  22641. MidiMessageSequence tempoEvents;
  22642. findAllTempoEvents (tempoEvents);
  22643. findAllTimeSigEvents (tempoEvents);
  22644. for (int i = 0; i < tracks.size(); ++i)
  22645. {
  22646. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22647. for (int j = ms.getNumEvents(); --j >= 0;)
  22648. {
  22649. MidiMessage& m = ms.getEventPointer(j)->message;
  22650. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22651. tempoEvents,
  22652. timeFormat));
  22653. }
  22654. }
  22655. }
  22656. bool MidiFile::writeTo (OutputStream& out)
  22657. {
  22658. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22659. out.writeIntBigEndian (6);
  22660. out.writeShortBigEndian (1); // type
  22661. out.writeShortBigEndian ((short) tracks.size());
  22662. out.writeShortBigEndian (timeFormat);
  22663. for (int i = 0; i < tracks.size(); ++i)
  22664. writeTrack (out, i);
  22665. out.flush();
  22666. return true;
  22667. }
  22668. void MidiFile::writeTrack (OutputStream& mainOut,
  22669. const int trackNum)
  22670. {
  22671. MemoryOutputStream out;
  22672. const MidiMessageSequence& ms = *tracks[trackNum];
  22673. int lastTick = 0;
  22674. char lastStatusByte = 0;
  22675. for (int i = 0; i < ms.getNumEvents(); ++i)
  22676. {
  22677. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22678. const int tick = roundToInt (mm.getTimeStamp());
  22679. const int delta = jmax (0, tick - lastTick);
  22680. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22681. lastTick = tick;
  22682. const char statusByte = *(mm.getRawData());
  22683. if ((statusByte == lastStatusByte)
  22684. && ((statusByte & 0xf0) != 0xf0)
  22685. && i > 0
  22686. && mm.getRawDataSize() > 1)
  22687. {
  22688. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22689. }
  22690. else
  22691. {
  22692. out.write (mm.getRawData(), mm.getRawDataSize());
  22693. }
  22694. lastStatusByte = statusByte;
  22695. }
  22696. out.writeByte (0);
  22697. const MidiMessage m (MidiMessage::endOfTrack());
  22698. out.write (m.getRawData(),
  22699. m.getRawDataSize());
  22700. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22701. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22702. mainOut.write (out.getData(), (int) out.getDataSize());
  22703. }
  22704. END_JUCE_NAMESPACE
  22705. /*** End of inlined file: juce_MidiFile.cpp ***/
  22706. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22707. BEGIN_JUCE_NAMESPACE
  22708. MidiKeyboardState::MidiKeyboardState()
  22709. {
  22710. zerostruct (noteStates);
  22711. }
  22712. MidiKeyboardState::~MidiKeyboardState()
  22713. {
  22714. }
  22715. void MidiKeyboardState::reset()
  22716. {
  22717. const ScopedLock sl (lock);
  22718. zerostruct (noteStates);
  22719. eventsToAdd.clear();
  22720. }
  22721. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22722. {
  22723. jassert (midiChannel >= 0 && midiChannel <= 16);
  22724. return ((unsigned int) n) < 128
  22725. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22726. }
  22727. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22728. {
  22729. return ((unsigned int) n) < 128
  22730. && (noteStates[n] & midiChannelMask) != 0;
  22731. }
  22732. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22733. {
  22734. jassert (midiChannel >= 0 && midiChannel <= 16);
  22735. jassert (((unsigned int) midiNoteNumber) < 128);
  22736. const ScopedLock sl (lock);
  22737. if (((unsigned int) midiNoteNumber) < 128)
  22738. {
  22739. const int timeNow = (int) Time::getMillisecondCounter();
  22740. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22741. eventsToAdd.clear (0, timeNow - 500);
  22742. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22743. }
  22744. }
  22745. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22746. {
  22747. if (((unsigned int) midiNoteNumber) < 128)
  22748. {
  22749. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22750. for (int i = listeners.size(); --i >= 0;)
  22751. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22752. }
  22753. }
  22754. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22755. {
  22756. const ScopedLock sl (lock);
  22757. if (isNoteOn (midiChannel, midiNoteNumber))
  22758. {
  22759. const int timeNow = (int) Time::getMillisecondCounter();
  22760. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22761. eventsToAdd.clear (0, timeNow - 500);
  22762. noteOffInternal (midiChannel, midiNoteNumber);
  22763. }
  22764. }
  22765. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22766. {
  22767. if (isNoteOn (midiChannel, midiNoteNumber))
  22768. {
  22769. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22770. for (int i = listeners.size(); --i >= 0;)
  22771. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22772. }
  22773. }
  22774. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22775. {
  22776. const ScopedLock sl (lock);
  22777. if (midiChannel <= 0)
  22778. {
  22779. for (int i = 1; i <= 16; ++i)
  22780. allNotesOff (i);
  22781. }
  22782. else
  22783. {
  22784. for (int i = 0; i < 128; ++i)
  22785. noteOff (midiChannel, i);
  22786. }
  22787. }
  22788. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22789. {
  22790. if (message.isNoteOn())
  22791. {
  22792. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22793. }
  22794. else if (message.isNoteOff())
  22795. {
  22796. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22797. }
  22798. else if (message.isAllNotesOff())
  22799. {
  22800. for (int i = 0; i < 128; ++i)
  22801. noteOffInternal (message.getChannel(), i);
  22802. }
  22803. }
  22804. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22805. const int startSample,
  22806. const int numSamples,
  22807. const bool injectIndirectEvents)
  22808. {
  22809. MidiBuffer::Iterator i (buffer);
  22810. MidiMessage message (0xf4, 0.0);
  22811. int time;
  22812. const ScopedLock sl (lock);
  22813. while (i.getNextEvent (message, time))
  22814. processNextMidiEvent (message);
  22815. if (injectIndirectEvents)
  22816. {
  22817. MidiBuffer::Iterator i2 (eventsToAdd);
  22818. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22819. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22820. while (i2.getNextEvent (message, time))
  22821. {
  22822. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22823. buffer.addEvent (message, startSample + pos);
  22824. }
  22825. }
  22826. eventsToAdd.clear();
  22827. }
  22828. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22829. {
  22830. const ScopedLock sl (lock);
  22831. listeners.addIfNotAlreadyThere (listener);
  22832. }
  22833. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22834. {
  22835. const ScopedLock sl (lock);
  22836. listeners.removeValue (listener);
  22837. }
  22838. END_JUCE_NAMESPACE
  22839. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22840. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22841. BEGIN_JUCE_NAMESPACE
  22842. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22843. {
  22844. numBytesUsed = 0;
  22845. int v = 0;
  22846. int i;
  22847. do
  22848. {
  22849. i = (int) *data++;
  22850. if (++numBytesUsed > 6)
  22851. break;
  22852. v = (v << 7) + (i & 0x7f);
  22853. } while (i & 0x80);
  22854. return v;
  22855. }
  22856. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22857. {
  22858. // this method only works for valid starting bytes of a short midi message
  22859. jassert (firstByte >= 0x80
  22860. && firstByte != 0xf0
  22861. && firstByte != 0xf7);
  22862. static const char messageLengths[] =
  22863. {
  22864. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22865. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22866. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22867. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22868. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22869. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22870. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22871. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22872. };
  22873. return messageLengths [firstByte & 0x7f];
  22874. }
  22875. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22876. : timeStamp (t),
  22877. size (dataSize)
  22878. {
  22879. jassert (dataSize > 0);
  22880. if (dataSize <= 4)
  22881. data = static_cast<uint8*> (preallocatedData.asBytes);
  22882. else
  22883. data = new uint8 [dataSize];
  22884. memcpy (data, d, dataSize);
  22885. // check that the length matches the data..
  22886. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22887. }
  22888. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22889. : timeStamp (t),
  22890. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22891. size (1)
  22892. {
  22893. data[0] = (uint8) byte1;
  22894. // check that the length matches the data..
  22895. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22896. }
  22897. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22898. : timeStamp (t),
  22899. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22900. size (2)
  22901. {
  22902. data[0] = (uint8) byte1;
  22903. data[1] = (uint8) byte2;
  22904. // check that the length matches the data..
  22905. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22906. }
  22907. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22908. : timeStamp (t),
  22909. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22910. size (3)
  22911. {
  22912. data[0] = (uint8) byte1;
  22913. data[1] = (uint8) byte2;
  22914. data[2] = (uint8) byte3;
  22915. // check that the length matches the data..
  22916. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22917. }
  22918. MidiMessage::MidiMessage (const MidiMessage& other)
  22919. : timeStamp (other.timeStamp),
  22920. size (other.size)
  22921. {
  22922. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22923. {
  22924. data = new uint8 [size];
  22925. memcpy (data, other.data, size);
  22926. }
  22927. else
  22928. {
  22929. data = static_cast<uint8*> (preallocatedData.asBytes);
  22930. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22931. }
  22932. }
  22933. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22934. : timeStamp (newTimeStamp),
  22935. size (other.size)
  22936. {
  22937. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22938. {
  22939. data = new uint8 [size];
  22940. memcpy (data, other.data, size);
  22941. }
  22942. else
  22943. {
  22944. data = static_cast<uint8*> (preallocatedData.asBytes);
  22945. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22946. }
  22947. }
  22948. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22949. : timeStamp (t),
  22950. data (static_cast<uint8*> (preallocatedData.asBytes))
  22951. {
  22952. const uint8* src = static_cast <const uint8*> (src_);
  22953. unsigned int byte = (unsigned int) *src;
  22954. if (byte < 0x80)
  22955. {
  22956. byte = (unsigned int) (uint8) lastStatusByte;
  22957. numBytesUsed = -1;
  22958. }
  22959. else
  22960. {
  22961. numBytesUsed = 0;
  22962. --sz;
  22963. ++src;
  22964. }
  22965. if (byte >= 0x80)
  22966. {
  22967. if (byte == 0xf0)
  22968. {
  22969. const uint8* d = src;
  22970. while (d < src + sz)
  22971. {
  22972. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22973. {
  22974. if (*d == 0xf7) // include an 0xf7 if we hit one
  22975. ++d;
  22976. break;
  22977. }
  22978. ++d;
  22979. }
  22980. size = 1 + (int) (d - src);
  22981. data = new uint8 [size];
  22982. *data = (uint8) byte;
  22983. memcpy (data + 1, src, size - 1);
  22984. }
  22985. else if (byte == 0xff)
  22986. {
  22987. int n;
  22988. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22989. size = jmin (sz + 1, n + 2 + bytesLeft);
  22990. data = new uint8 [size];
  22991. *data = (uint8) byte;
  22992. memcpy (data + 1, src, size - 1);
  22993. }
  22994. else
  22995. {
  22996. preallocatedData.asInt32 = 0;
  22997. size = getMessageLengthFromFirstByte ((uint8) byte);
  22998. data[0] = (uint8) byte;
  22999. if (size > 1)
  23000. {
  23001. data[1] = src[0];
  23002. if (size > 2)
  23003. data[2] = src[1];
  23004. }
  23005. }
  23006. numBytesUsed += size;
  23007. }
  23008. else
  23009. {
  23010. preallocatedData.asInt32 = 0;
  23011. size = 0;
  23012. }
  23013. }
  23014. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23015. {
  23016. if (this != &other)
  23017. {
  23018. timeStamp = other.timeStamp;
  23019. size = other.size;
  23020. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23021. delete[] data;
  23022. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23023. {
  23024. data = new uint8 [size];
  23025. memcpy (data, other.data, size);
  23026. }
  23027. else
  23028. {
  23029. data = static_cast<uint8*> (preallocatedData.asBytes);
  23030. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23031. }
  23032. }
  23033. return *this;
  23034. }
  23035. MidiMessage::~MidiMessage()
  23036. {
  23037. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23038. delete[] data;
  23039. }
  23040. int MidiMessage::getChannel() const throw()
  23041. {
  23042. if ((data[0] & 0xf0) != 0xf0)
  23043. return (data[0] & 0xf) + 1;
  23044. else
  23045. return 0;
  23046. }
  23047. bool MidiMessage::isForChannel (const int channel) const throw()
  23048. {
  23049. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23050. return ((data[0] & 0xf) == channel - 1)
  23051. && ((data[0] & 0xf0) != 0xf0);
  23052. }
  23053. void MidiMessage::setChannel (const int channel) throw()
  23054. {
  23055. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23056. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23057. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23058. | (uint8)(channel - 1));
  23059. }
  23060. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23061. {
  23062. return ((data[0] & 0xf0) == 0x90)
  23063. && (returnTrueForVelocity0 || data[2] != 0);
  23064. }
  23065. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23066. {
  23067. return ((data[0] & 0xf0) == 0x80)
  23068. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23069. }
  23070. bool MidiMessage::isNoteOnOrOff() const throw()
  23071. {
  23072. const int d = data[0] & 0xf0;
  23073. return (d == 0x90) || (d == 0x80);
  23074. }
  23075. int MidiMessage::getNoteNumber() const throw()
  23076. {
  23077. return data[1];
  23078. }
  23079. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23080. {
  23081. if (isNoteOnOrOff())
  23082. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23083. }
  23084. uint8 MidiMessage::getVelocity() const throw()
  23085. {
  23086. if (isNoteOnOrOff())
  23087. return data[2];
  23088. else
  23089. return 0;
  23090. }
  23091. float MidiMessage::getFloatVelocity() const throw()
  23092. {
  23093. return getVelocity() * (1.0f / 127.0f);
  23094. }
  23095. void MidiMessage::setVelocity (const float newVelocity) throw()
  23096. {
  23097. if (isNoteOnOrOff())
  23098. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23099. }
  23100. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23101. {
  23102. if (isNoteOnOrOff())
  23103. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23104. }
  23105. bool MidiMessage::isAftertouch() const throw()
  23106. {
  23107. return (data[0] & 0xf0) == 0xa0;
  23108. }
  23109. int MidiMessage::getAfterTouchValue() const throw()
  23110. {
  23111. return data[2];
  23112. }
  23113. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23114. const int noteNum,
  23115. const int aftertouchValue) throw()
  23116. {
  23117. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23118. jassert (((unsigned int) noteNum) <= 127);
  23119. jassert (((unsigned int) aftertouchValue) <= 127);
  23120. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23121. noteNum & 0x7f,
  23122. aftertouchValue & 0x7f);
  23123. }
  23124. bool MidiMessage::isChannelPressure() const throw()
  23125. {
  23126. return (data[0] & 0xf0) == 0xd0;
  23127. }
  23128. int MidiMessage::getChannelPressureValue() const throw()
  23129. {
  23130. jassert (isChannelPressure());
  23131. return data[1];
  23132. }
  23133. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23134. const int pressure) throw()
  23135. {
  23136. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23137. jassert (((unsigned int) pressure) <= 127);
  23138. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23139. pressure & 0x7f);
  23140. }
  23141. bool MidiMessage::isProgramChange() const throw()
  23142. {
  23143. return (data[0] & 0xf0) == 0xc0;
  23144. }
  23145. int MidiMessage::getProgramChangeNumber() const throw()
  23146. {
  23147. return data[1];
  23148. }
  23149. const MidiMessage MidiMessage::programChange (const int channel,
  23150. const int programNumber) throw()
  23151. {
  23152. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23153. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23154. programNumber & 0x7f);
  23155. }
  23156. bool MidiMessage::isPitchWheel() const throw()
  23157. {
  23158. return (data[0] & 0xf0) == 0xe0;
  23159. }
  23160. int MidiMessage::getPitchWheelValue() const throw()
  23161. {
  23162. return data[1] | (data[2] << 7);
  23163. }
  23164. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23165. const int position) throw()
  23166. {
  23167. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23168. jassert (((unsigned int) position) <= 0x3fff);
  23169. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23170. position & 127,
  23171. (position >> 7) & 127);
  23172. }
  23173. bool MidiMessage::isController() const throw()
  23174. {
  23175. return (data[0] & 0xf0) == 0xb0;
  23176. }
  23177. int MidiMessage::getControllerNumber() const throw()
  23178. {
  23179. jassert (isController());
  23180. return data[1];
  23181. }
  23182. int MidiMessage::getControllerValue() const throw()
  23183. {
  23184. jassert (isController());
  23185. return data[2];
  23186. }
  23187. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23188. const int controllerType,
  23189. const int value) throw()
  23190. {
  23191. // the channel must be between 1 and 16 inclusive
  23192. jassert (channel > 0 && channel <= 16);
  23193. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23194. controllerType & 127,
  23195. value & 127);
  23196. }
  23197. const MidiMessage MidiMessage::noteOn (const int channel,
  23198. const int noteNumber,
  23199. const float velocity) throw()
  23200. {
  23201. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23202. }
  23203. const MidiMessage MidiMessage::noteOn (const int channel,
  23204. const int noteNumber,
  23205. const uint8 velocity) throw()
  23206. {
  23207. jassert (channel > 0 && channel <= 16);
  23208. jassert (((unsigned int) noteNumber) <= 127);
  23209. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23210. noteNumber & 127,
  23211. jlimit (0, 127, roundToInt (velocity)));
  23212. }
  23213. const MidiMessage MidiMessage::noteOff (const int channel,
  23214. const int noteNumber) throw()
  23215. {
  23216. jassert (channel > 0 && channel <= 16);
  23217. jassert (((unsigned int) noteNumber) <= 127);
  23218. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23219. }
  23220. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23221. {
  23222. jassert (channel > 0 && channel <= 16);
  23223. return controllerEvent (channel, 123, 0);
  23224. }
  23225. bool MidiMessage::isAllNotesOff() const throw()
  23226. {
  23227. return (data[0] & 0xf0) == 0xb0
  23228. && data[1] == 123;
  23229. }
  23230. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23231. {
  23232. return controllerEvent (channel, 120, 0);
  23233. }
  23234. bool MidiMessage::isAllSoundOff() const throw()
  23235. {
  23236. return (data[0] & 0xf0) == 0xb0
  23237. && data[1] == 120;
  23238. }
  23239. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23240. {
  23241. return controllerEvent (channel, 121, 0);
  23242. }
  23243. const MidiMessage MidiMessage::masterVolume (const float volume)
  23244. {
  23245. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23246. uint8 buf[8];
  23247. buf[0] = 0xf0;
  23248. buf[1] = 0x7f;
  23249. buf[2] = 0x7f;
  23250. buf[3] = 0x04;
  23251. buf[4] = 0x01;
  23252. buf[5] = (uint8) (vol & 0x7f);
  23253. buf[6] = (uint8) (vol >> 7);
  23254. buf[7] = 0xf7;
  23255. return MidiMessage (buf, 8);
  23256. }
  23257. bool MidiMessage::isSysEx() const throw()
  23258. {
  23259. return *data == 0xf0;
  23260. }
  23261. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23262. {
  23263. MemoryBlock mm (dataSize + 2);
  23264. uint8* const m = static_cast <uint8*> (mm.getData());
  23265. m[0] = 0xf0;
  23266. memcpy (m + 1, sysexData, dataSize);
  23267. m[dataSize + 1] = 0xf7;
  23268. return MidiMessage (m, dataSize + 2);
  23269. }
  23270. const uint8* MidiMessage::getSysExData() const throw()
  23271. {
  23272. return (isSysEx()) ? getRawData() + 1 : 0;
  23273. }
  23274. int MidiMessage::getSysExDataSize() const throw()
  23275. {
  23276. return (isSysEx()) ? size - 2 : 0;
  23277. }
  23278. bool MidiMessage::isMetaEvent() const throw()
  23279. {
  23280. return *data == 0xff;
  23281. }
  23282. bool MidiMessage::isActiveSense() const throw()
  23283. {
  23284. return *data == 0xfe;
  23285. }
  23286. int MidiMessage::getMetaEventType() const throw()
  23287. {
  23288. if (*data != 0xff)
  23289. return -1;
  23290. else
  23291. return data[1];
  23292. }
  23293. int MidiMessage::getMetaEventLength() const throw()
  23294. {
  23295. if (*data == 0xff)
  23296. {
  23297. int n;
  23298. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23299. }
  23300. return 0;
  23301. }
  23302. const uint8* MidiMessage::getMetaEventData() const throw()
  23303. {
  23304. int n;
  23305. const uint8* d = data + 2;
  23306. readVariableLengthVal (d, n);
  23307. return d + n;
  23308. }
  23309. bool MidiMessage::isTrackMetaEvent() const throw()
  23310. {
  23311. return getMetaEventType() == 0;
  23312. }
  23313. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23314. {
  23315. return getMetaEventType() == 47;
  23316. }
  23317. bool MidiMessage::isTextMetaEvent() const throw()
  23318. {
  23319. const int t = getMetaEventType();
  23320. return t > 0 && t < 16;
  23321. }
  23322. const String MidiMessage::getTextFromTextMetaEvent() const
  23323. {
  23324. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23325. }
  23326. bool MidiMessage::isTrackNameEvent() const throw()
  23327. {
  23328. return (data[1] == 3)
  23329. && (*data == 0xff);
  23330. }
  23331. bool MidiMessage::isTempoMetaEvent() const throw()
  23332. {
  23333. return (data[1] == 81)
  23334. && (*data == 0xff);
  23335. }
  23336. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23337. {
  23338. return (data[1] == 0x20)
  23339. && (*data == 0xff)
  23340. && (data[2] == 1);
  23341. }
  23342. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23343. {
  23344. return data[3] + 1;
  23345. }
  23346. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23347. {
  23348. if (! isTempoMetaEvent())
  23349. return 0.0;
  23350. const uint8* const d = getMetaEventData();
  23351. return (((unsigned int) d[0] << 16)
  23352. | ((unsigned int) d[1] << 8)
  23353. | d[2])
  23354. / 1000000.0;
  23355. }
  23356. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23357. {
  23358. if (timeFormat > 0)
  23359. {
  23360. if (! isTempoMetaEvent())
  23361. return 0.5 / timeFormat;
  23362. return getTempoSecondsPerQuarterNote() / timeFormat;
  23363. }
  23364. else
  23365. {
  23366. const int frameCode = (-timeFormat) >> 8;
  23367. double framesPerSecond;
  23368. switch (frameCode)
  23369. {
  23370. case 24: framesPerSecond = 24.0; break;
  23371. case 25: framesPerSecond = 25.0; break;
  23372. case 29: framesPerSecond = 29.97; break;
  23373. case 30: framesPerSecond = 30.0; break;
  23374. default: framesPerSecond = 30.0; break;
  23375. }
  23376. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23377. }
  23378. }
  23379. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23380. {
  23381. uint8 d[8];
  23382. d[0] = 0xff;
  23383. d[1] = 81;
  23384. d[2] = 3;
  23385. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23386. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23387. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23388. return MidiMessage (d, 6, 0.0);
  23389. }
  23390. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23391. {
  23392. return (data[1] == 0x58)
  23393. && (*data == (uint8) 0xff);
  23394. }
  23395. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23396. {
  23397. if (isTimeSignatureMetaEvent())
  23398. {
  23399. const uint8* const d = getMetaEventData();
  23400. numerator = d[0];
  23401. denominator = 1 << d[1];
  23402. }
  23403. else
  23404. {
  23405. numerator = 4;
  23406. denominator = 4;
  23407. }
  23408. }
  23409. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23410. {
  23411. uint8 d[8];
  23412. d[0] = 0xff;
  23413. d[1] = 0x58;
  23414. d[2] = 0x04;
  23415. d[3] = (uint8) numerator;
  23416. int n = 1;
  23417. int powerOfTwo = 0;
  23418. while (n < denominator)
  23419. {
  23420. n <<= 1;
  23421. ++powerOfTwo;
  23422. }
  23423. d[4] = (uint8) powerOfTwo;
  23424. d[5] = 0x01;
  23425. d[6] = 96;
  23426. return MidiMessage (d, 7, 0.0);
  23427. }
  23428. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23429. {
  23430. uint8 d[8];
  23431. d[0] = 0xff;
  23432. d[1] = 0x20;
  23433. d[2] = 0x01;
  23434. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23435. return MidiMessage (d, 4, 0.0);
  23436. }
  23437. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23438. {
  23439. return getMetaEventType() == 89;
  23440. }
  23441. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23442. {
  23443. return (int) *getMetaEventData();
  23444. }
  23445. const MidiMessage MidiMessage::endOfTrack() throw()
  23446. {
  23447. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23448. }
  23449. bool MidiMessage::isSongPositionPointer() const throw()
  23450. {
  23451. return *data == 0xf2;
  23452. }
  23453. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23454. {
  23455. return data[1] | (data[2] << 7);
  23456. }
  23457. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23458. {
  23459. return MidiMessage (0xf2,
  23460. positionInMidiBeats & 127,
  23461. (positionInMidiBeats >> 7) & 127);
  23462. }
  23463. bool MidiMessage::isMidiStart() const throw()
  23464. {
  23465. return *data == 0xfa;
  23466. }
  23467. const MidiMessage MidiMessage::midiStart() throw()
  23468. {
  23469. return MidiMessage (0xfa);
  23470. }
  23471. bool MidiMessage::isMidiContinue() const throw()
  23472. {
  23473. return *data == 0xfb;
  23474. }
  23475. const MidiMessage MidiMessage::midiContinue() throw()
  23476. {
  23477. return MidiMessage (0xfb);
  23478. }
  23479. bool MidiMessage::isMidiStop() const throw()
  23480. {
  23481. return *data == 0xfc;
  23482. }
  23483. const MidiMessage MidiMessage::midiStop() throw()
  23484. {
  23485. return MidiMessage (0xfc);
  23486. }
  23487. bool MidiMessage::isMidiClock() const throw()
  23488. {
  23489. return *data == 0xf8;
  23490. }
  23491. const MidiMessage MidiMessage::midiClock() throw()
  23492. {
  23493. return MidiMessage (0xf8);
  23494. }
  23495. bool MidiMessage::isQuarterFrame() const throw()
  23496. {
  23497. return *data == 0xf1;
  23498. }
  23499. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23500. {
  23501. return ((int) data[1]) >> 4;
  23502. }
  23503. int MidiMessage::getQuarterFrameValue() const throw()
  23504. {
  23505. return ((int) data[1]) & 0x0f;
  23506. }
  23507. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23508. const int value) throw()
  23509. {
  23510. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23511. }
  23512. bool MidiMessage::isFullFrame() const throw()
  23513. {
  23514. return data[0] == 0xf0
  23515. && data[1] == 0x7f
  23516. && size >= 10
  23517. && data[3] == 0x01
  23518. && data[4] == 0x01;
  23519. }
  23520. void MidiMessage::getFullFrameParameters (int& hours,
  23521. int& minutes,
  23522. int& seconds,
  23523. int& frames,
  23524. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23525. {
  23526. jassert (isFullFrame());
  23527. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23528. hours = data[5] & 0x1f;
  23529. minutes = data[6];
  23530. seconds = data[7];
  23531. frames = data[8];
  23532. }
  23533. const MidiMessage MidiMessage::fullFrame (const int hours,
  23534. const int minutes,
  23535. const int seconds,
  23536. const int frames,
  23537. MidiMessage::SmpteTimecodeType timecodeType)
  23538. {
  23539. uint8 d[10];
  23540. d[0] = 0xf0;
  23541. d[1] = 0x7f;
  23542. d[2] = 0x7f;
  23543. d[3] = 0x01;
  23544. d[4] = 0x01;
  23545. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23546. d[6] = (uint8) minutes;
  23547. d[7] = (uint8) seconds;
  23548. d[8] = (uint8) frames;
  23549. d[9] = 0xf7;
  23550. return MidiMessage (d, 10, 0.0);
  23551. }
  23552. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23553. {
  23554. return data[0] == 0xf0
  23555. && data[1] == 0x7f
  23556. && data[3] == 0x06
  23557. && size > 5;
  23558. }
  23559. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23560. {
  23561. jassert (isMidiMachineControlMessage());
  23562. return (MidiMachineControlCommand) data[4];
  23563. }
  23564. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23565. {
  23566. uint8 d[6];
  23567. d[0] = 0xf0;
  23568. d[1] = 0x7f;
  23569. d[2] = 0x00;
  23570. d[3] = 0x06;
  23571. d[4] = (uint8) command;
  23572. d[5] = 0xf7;
  23573. return MidiMessage (d, 6, 0.0);
  23574. }
  23575. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23576. int& minutes,
  23577. int& seconds,
  23578. int& frames) const throw()
  23579. {
  23580. if (size >= 12
  23581. && data[0] == 0xf0
  23582. && data[1] == 0x7f
  23583. && data[3] == 0x06
  23584. && data[4] == 0x44
  23585. && data[5] == 0x06
  23586. && data[6] == 0x01)
  23587. {
  23588. hours = data[7] % 24; // (that some machines send out hours > 24)
  23589. minutes = data[8];
  23590. seconds = data[9];
  23591. frames = data[10];
  23592. return true;
  23593. }
  23594. return false;
  23595. }
  23596. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23597. int minutes,
  23598. int seconds,
  23599. int frames)
  23600. {
  23601. uint8 d[12];
  23602. d[0] = 0xf0;
  23603. d[1] = 0x7f;
  23604. d[2] = 0x00;
  23605. d[3] = 0x06;
  23606. d[4] = 0x44;
  23607. d[5] = 0x06;
  23608. d[6] = 0x01;
  23609. d[7] = (uint8) hours;
  23610. d[8] = (uint8) minutes;
  23611. d[9] = (uint8) seconds;
  23612. d[10] = (uint8) frames;
  23613. d[11] = 0xf7;
  23614. return MidiMessage (d, 12, 0.0);
  23615. }
  23616. const String MidiMessage::getMidiNoteName (int note,
  23617. bool useSharps,
  23618. bool includeOctaveNumber,
  23619. int octaveNumForMiddleC) throw()
  23620. {
  23621. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  23622. "F", "F#", "G", "G#", "A",
  23623. "A#", "B" };
  23624. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  23625. "F", "Gb", "G", "Ab", "A",
  23626. "Bb", "B" };
  23627. if (((unsigned int) note) < 128)
  23628. {
  23629. const String s ((useSharps) ? sharpNoteNames [note % 12]
  23630. : flatNoteNames [note % 12]);
  23631. if (includeOctaveNumber)
  23632. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  23633. else
  23634. return s;
  23635. }
  23636. return String::empty;
  23637. }
  23638. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  23639. {
  23640. noteNumber -= 12 * 6 + 9; // now 0 = A440
  23641. return 440.0 * pow (2.0, noteNumber / 12.0);
  23642. }
  23643. const String MidiMessage::getGMInstrumentName (int n) throw()
  23644. {
  23645. const char *names[] =
  23646. {
  23647. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23648. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23649. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23650. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23651. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23652. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23653. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23654. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23655. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23656. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23657. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23658. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23659. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23660. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23661. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23662. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23663. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23664. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23665. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23666. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23667. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23668. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23669. "Applause", "Gunshot"
  23670. };
  23671. return (((unsigned int) n) < 128) ? names[n]
  23672. : (const char*)0;
  23673. }
  23674. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  23675. {
  23676. const char* names[] =
  23677. {
  23678. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23679. "Bass", "Strings", "Ensemble", "Brass",
  23680. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23681. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23682. };
  23683. return (((unsigned int) n) <= 15) ? names[n]
  23684. : (const char*)0;
  23685. }
  23686. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  23687. {
  23688. const char* names[] =
  23689. {
  23690. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23691. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23692. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23693. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23694. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23695. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23696. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23697. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23698. "Mute Triangle", "Open Triangle"
  23699. };
  23700. return (n >= 35 && n <= 81) ? names [n - 35]
  23701. : (const char*)0;
  23702. }
  23703. const String MidiMessage::getControllerName (int n) throw()
  23704. {
  23705. const char* names[] =
  23706. {
  23707. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23708. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23709. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23710. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23711. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23712. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23713. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23714. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23715. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23716. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23717. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23718. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23719. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23720. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23721. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23722. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23723. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23724. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23725. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23727. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23728. "Poly Operation"
  23729. };
  23730. return (((unsigned int) n) < 128) ? names[n]
  23731. : (const char*)0;
  23732. }
  23733. END_JUCE_NAMESPACE
  23734. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23735. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23736. BEGIN_JUCE_NAMESPACE
  23737. MidiMessageCollector::MidiMessageCollector()
  23738. : lastCallbackTime (0),
  23739. sampleRate (44100.0001)
  23740. {
  23741. }
  23742. MidiMessageCollector::~MidiMessageCollector()
  23743. {
  23744. }
  23745. void MidiMessageCollector::reset (const double sampleRate_)
  23746. {
  23747. jassert (sampleRate_ > 0);
  23748. const ScopedLock sl (midiCallbackLock);
  23749. sampleRate = sampleRate_;
  23750. incomingMessages.clear();
  23751. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23752. }
  23753. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23754. {
  23755. // you need to call reset() to set the correct sample rate before using this object
  23756. jassert (sampleRate != 44100.0001);
  23757. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23758. // for details of what the number should be.
  23759. jassert (message.getTimeStamp() != 0);
  23760. const ScopedLock sl (midiCallbackLock);
  23761. const int sampleNumber
  23762. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23763. incomingMessages.addEvent (message, sampleNumber);
  23764. // if the messages don't get used for over a second, we'd better
  23765. // get rid of any old ones to avoid the queue getting too big
  23766. if (sampleNumber > sampleRate)
  23767. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23768. }
  23769. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23770. const int numSamples)
  23771. {
  23772. // you need to call reset() to set the correct sample rate before using this object
  23773. jassert (sampleRate != 44100.0001);
  23774. const double timeNow = Time::getMillisecondCounterHiRes();
  23775. const double msElapsed = timeNow - lastCallbackTime;
  23776. const ScopedLock sl (midiCallbackLock);
  23777. lastCallbackTime = timeNow;
  23778. if (! incomingMessages.isEmpty())
  23779. {
  23780. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23781. int startSample = 0;
  23782. int scale = 1 << 16;
  23783. const uint8* midiData;
  23784. int numBytes, samplePosition;
  23785. MidiBuffer::Iterator iter (incomingMessages);
  23786. if (numSourceSamples > numSamples)
  23787. {
  23788. // if our list of events is longer than the buffer we're being
  23789. // asked for, scale them down to squeeze them all in..
  23790. const int maxBlockLengthToUse = numSamples << 5;
  23791. if (numSourceSamples > maxBlockLengthToUse)
  23792. {
  23793. startSample = numSourceSamples - maxBlockLengthToUse;
  23794. numSourceSamples = maxBlockLengthToUse;
  23795. iter.setNextSamplePosition (startSample);
  23796. }
  23797. scale = (numSamples << 10) / numSourceSamples;
  23798. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23799. {
  23800. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23801. destBuffer.addEvent (midiData, numBytes,
  23802. jlimit (0, numSamples - 1, samplePosition));
  23803. }
  23804. }
  23805. else
  23806. {
  23807. // if our event list is shorter than the number we need, put them
  23808. // towards the end of the buffer
  23809. startSample = numSamples - numSourceSamples;
  23810. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23811. {
  23812. destBuffer.addEvent (midiData, numBytes,
  23813. jlimit (0, numSamples - 1, samplePosition + startSample));
  23814. }
  23815. }
  23816. incomingMessages.clear();
  23817. }
  23818. }
  23819. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23820. {
  23821. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23822. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23823. addMessageToQueue (m);
  23824. }
  23825. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23826. {
  23827. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23828. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23829. addMessageToQueue (m);
  23830. }
  23831. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23832. {
  23833. addMessageToQueue (message);
  23834. }
  23835. END_JUCE_NAMESPACE
  23836. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23837. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23838. BEGIN_JUCE_NAMESPACE
  23839. MidiMessageSequence::MidiMessageSequence()
  23840. {
  23841. }
  23842. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23843. {
  23844. list.ensureStorageAllocated (other.list.size());
  23845. for (int i = 0; i < other.list.size(); ++i)
  23846. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23847. }
  23848. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23849. {
  23850. MidiMessageSequence otherCopy (other);
  23851. swapWith (otherCopy);
  23852. return *this;
  23853. }
  23854. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23855. {
  23856. list.swapWithArray (other.list);
  23857. }
  23858. MidiMessageSequence::~MidiMessageSequence()
  23859. {
  23860. }
  23861. void MidiMessageSequence::clear()
  23862. {
  23863. list.clear();
  23864. }
  23865. int MidiMessageSequence::getNumEvents() const
  23866. {
  23867. return list.size();
  23868. }
  23869. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23870. {
  23871. return list [index];
  23872. }
  23873. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23874. {
  23875. const MidiEventHolder* const meh = list [index];
  23876. if (meh != 0 && meh->noteOffObject != 0)
  23877. return meh->noteOffObject->message.getTimeStamp();
  23878. else
  23879. return 0.0;
  23880. }
  23881. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23882. {
  23883. const MidiEventHolder* const meh = list [index];
  23884. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23885. }
  23886. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23887. {
  23888. return list.indexOf (event);
  23889. }
  23890. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23891. {
  23892. const int numEvents = list.size();
  23893. int i;
  23894. for (i = 0; i < numEvents; ++i)
  23895. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23896. break;
  23897. return i;
  23898. }
  23899. double MidiMessageSequence::getStartTime() const
  23900. {
  23901. if (list.size() > 0)
  23902. return list.getUnchecked(0)->message.getTimeStamp();
  23903. else
  23904. return 0;
  23905. }
  23906. double MidiMessageSequence::getEndTime() const
  23907. {
  23908. if (list.size() > 0)
  23909. return list.getLast()->message.getTimeStamp();
  23910. else
  23911. return 0;
  23912. }
  23913. double MidiMessageSequence::getEventTime (const int index) const
  23914. {
  23915. if (((unsigned int) index) < (unsigned int) list.size())
  23916. return list.getUnchecked (index)->message.getTimeStamp();
  23917. return 0.0;
  23918. }
  23919. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23920. double timeAdjustment)
  23921. {
  23922. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23923. timeAdjustment += newMessage.getTimeStamp();
  23924. newOne->message.setTimeStamp (timeAdjustment);
  23925. int i;
  23926. for (i = list.size(); --i >= 0;)
  23927. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23928. break;
  23929. list.insert (i + 1, newOne);
  23930. }
  23931. void MidiMessageSequence::deleteEvent (const int index,
  23932. const bool deleteMatchingNoteUp)
  23933. {
  23934. if (((unsigned int) index) < (unsigned int) list.size())
  23935. {
  23936. if (deleteMatchingNoteUp)
  23937. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23938. list.remove (index);
  23939. }
  23940. }
  23941. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23942. double timeAdjustment,
  23943. double firstAllowableTime,
  23944. double endOfAllowableDestTimes)
  23945. {
  23946. firstAllowableTime -= timeAdjustment;
  23947. endOfAllowableDestTimes -= timeAdjustment;
  23948. for (int i = 0; i < other.list.size(); ++i)
  23949. {
  23950. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23951. const double t = m.getTimeStamp();
  23952. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23953. {
  23954. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23955. newOne->message.setTimeStamp (timeAdjustment + t);
  23956. list.add (newOne);
  23957. }
  23958. }
  23959. sort();
  23960. }
  23961. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23962. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23963. {
  23964. const double diff = first->message.getTimeStamp()
  23965. - second->message.getTimeStamp();
  23966. return (diff > 0) - (diff < 0);
  23967. }
  23968. void MidiMessageSequence::sort()
  23969. {
  23970. list.sort (*this, true);
  23971. }
  23972. void MidiMessageSequence::updateMatchedPairs()
  23973. {
  23974. for (int i = 0; i < list.size(); ++i)
  23975. {
  23976. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23977. if (m1.isNoteOn())
  23978. {
  23979. list.getUnchecked(i)->noteOffObject = 0;
  23980. const int note = m1.getNoteNumber();
  23981. const int chan = m1.getChannel();
  23982. const int len = list.size();
  23983. for (int j = i + 1; j < len; ++j)
  23984. {
  23985. const MidiMessage& m = list.getUnchecked(j)->message;
  23986. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23987. {
  23988. if (m.isNoteOff())
  23989. {
  23990. list.getUnchecked(i)->noteOffObject = list[j];
  23991. break;
  23992. }
  23993. else if (m.isNoteOn())
  23994. {
  23995. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23996. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23997. list.getUnchecked(i)->noteOffObject = list[j];
  23998. break;
  23999. }
  24000. }
  24001. }
  24002. }
  24003. }
  24004. }
  24005. void MidiMessageSequence::addTimeToMessages (const double delta)
  24006. {
  24007. for (int i = list.size(); --i >= 0;)
  24008. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24009. + delta);
  24010. }
  24011. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24012. MidiMessageSequence& destSequence,
  24013. const bool alsoIncludeMetaEvents) const
  24014. {
  24015. for (int i = 0; i < list.size(); ++i)
  24016. {
  24017. const MidiMessage& mm = list.getUnchecked(i)->message;
  24018. if (mm.isForChannel (channelNumberToExtract)
  24019. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24020. {
  24021. destSequence.addEvent (mm);
  24022. }
  24023. }
  24024. }
  24025. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24026. {
  24027. for (int i = 0; i < list.size(); ++i)
  24028. {
  24029. const MidiMessage& mm = list.getUnchecked(i)->message;
  24030. if (mm.isSysEx())
  24031. destSequence.addEvent (mm);
  24032. }
  24033. }
  24034. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24035. {
  24036. for (int i = list.size(); --i >= 0;)
  24037. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24038. list.remove(i);
  24039. }
  24040. void MidiMessageSequence::deleteSysExMessages()
  24041. {
  24042. for (int i = list.size(); --i >= 0;)
  24043. if (list.getUnchecked(i)->message.isSysEx())
  24044. list.remove(i);
  24045. }
  24046. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24047. const double time,
  24048. OwnedArray<MidiMessage>& dest)
  24049. {
  24050. bool doneProg = false;
  24051. bool donePitchWheel = false;
  24052. Array <int> doneControllers;
  24053. doneControllers.ensureStorageAllocated (32);
  24054. for (int i = list.size(); --i >= 0;)
  24055. {
  24056. const MidiMessage& mm = list.getUnchecked(i)->message;
  24057. if (mm.isForChannel (channelNumber)
  24058. && mm.getTimeStamp() <= time)
  24059. {
  24060. if (mm.isProgramChange())
  24061. {
  24062. if (! doneProg)
  24063. {
  24064. dest.add (new MidiMessage (mm, 0.0));
  24065. doneProg = true;
  24066. }
  24067. }
  24068. else if (mm.isController())
  24069. {
  24070. if (! doneControllers.contains (mm.getControllerNumber()))
  24071. {
  24072. dest.add (new MidiMessage (mm, 0.0));
  24073. doneControllers.add (mm.getControllerNumber());
  24074. }
  24075. }
  24076. else if (mm.isPitchWheel())
  24077. {
  24078. if (! donePitchWheel)
  24079. {
  24080. dest.add (new MidiMessage (mm, 0.0));
  24081. donePitchWheel = true;
  24082. }
  24083. }
  24084. }
  24085. }
  24086. }
  24087. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24088. : message (message_),
  24089. noteOffObject (0)
  24090. {
  24091. }
  24092. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24093. {
  24094. }
  24095. END_JUCE_NAMESPACE
  24096. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24097. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24098. BEGIN_JUCE_NAMESPACE
  24099. AudioPluginFormat::AudioPluginFormat() throw()
  24100. {
  24101. }
  24102. AudioPluginFormat::~AudioPluginFormat()
  24103. {
  24104. }
  24105. END_JUCE_NAMESPACE
  24106. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24107. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24108. BEGIN_JUCE_NAMESPACE
  24109. AudioPluginFormatManager::AudioPluginFormatManager()
  24110. {
  24111. }
  24112. AudioPluginFormatManager::~AudioPluginFormatManager()
  24113. {
  24114. clearSingletonInstance();
  24115. }
  24116. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24117. void AudioPluginFormatManager::addDefaultFormats()
  24118. {
  24119. #if JUCE_DEBUG
  24120. // you should only call this method once!
  24121. for (int i = formats.size(); --i >= 0;)
  24122. {
  24123. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24124. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24125. #endif
  24126. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24127. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24128. #endif
  24129. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24130. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24131. #endif
  24132. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24133. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24134. #endif
  24135. }
  24136. #endif
  24137. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24138. formats.add (new AudioUnitPluginFormat());
  24139. #endif
  24140. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24141. formats.add (new VSTPluginFormat());
  24142. #endif
  24143. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24144. formats.add (new DirectXPluginFormat());
  24145. #endif
  24146. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24147. formats.add (new LADSPAPluginFormat());
  24148. #endif
  24149. }
  24150. int AudioPluginFormatManager::getNumFormats()
  24151. {
  24152. return formats.size();
  24153. }
  24154. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24155. {
  24156. return formats [index];
  24157. }
  24158. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24159. {
  24160. formats.add (format);
  24161. }
  24162. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24163. String& errorMessage) const
  24164. {
  24165. AudioPluginInstance* result = 0;
  24166. for (int i = 0; i < formats.size(); ++i)
  24167. {
  24168. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24169. if (result != 0)
  24170. break;
  24171. }
  24172. if (result == 0)
  24173. {
  24174. if (! doesPluginStillExist (description))
  24175. errorMessage = TRANS ("This plug-in file no longer exists");
  24176. else
  24177. errorMessage = TRANS ("This plug-in failed to load correctly");
  24178. }
  24179. return result;
  24180. }
  24181. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24182. {
  24183. for (int i = 0; i < formats.size(); ++i)
  24184. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24185. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24186. return false;
  24187. }
  24188. END_JUCE_NAMESPACE
  24189. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24190. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24191. #define JUCE_PLUGIN_HOST 1
  24192. BEGIN_JUCE_NAMESPACE
  24193. AudioPluginInstance::AudioPluginInstance()
  24194. {
  24195. }
  24196. AudioPluginInstance::~AudioPluginInstance()
  24197. {
  24198. }
  24199. END_JUCE_NAMESPACE
  24200. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24201. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24202. BEGIN_JUCE_NAMESPACE
  24203. KnownPluginList::KnownPluginList()
  24204. {
  24205. }
  24206. KnownPluginList::~KnownPluginList()
  24207. {
  24208. }
  24209. void KnownPluginList::clear()
  24210. {
  24211. if (types.size() > 0)
  24212. {
  24213. types.clear();
  24214. sendChangeMessage (this);
  24215. }
  24216. }
  24217. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24218. {
  24219. for (int i = 0; i < types.size(); ++i)
  24220. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24221. return types.getUnchecked(i);
  24222. return 0;
  24223. }
  24224. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24225. {
  24226. for (int i = 0; i < types.size(); ++i)
  24227. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24228. return types.getUnchecked(i);
  24229. return 0;
  24230. }
  24231. bool KnownPluginList::addType (const PluginDescription& type)
  24232. {
  24233. for (int i = types.size(); --i >= 0;)
  24234. {
  24235. if (types.getUnchecked(i)->isDuplicateOf (type))
  24236. {
  24237. // strange - found a duplicate plugin with different info..
  24238. jassert (types.getUnchecked(i)->name == type.name);
  24239. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24240. *types.getUnchecked(i) = type;
  24241. return false;
  24242. }
  24243. }
  24244. types.add (new PluginDescription (type));
  24245. sendChangeMessage (this);
  24246. return true;
  24247. }
  24248. void KnownPluginList::removeType (const int index)
  24249. {
  24250. types.remove (index);
  24251. sendChangeMessage (this);
  24252. }
  24253. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24254. {
  24255. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24256. return File (fileOrIdentifier).getLastModificationTime();
  24257. return Time (0);
  24258. }
  24259. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24260. {
  24261. return t1 != t2 || t1 == Time (0);
  24262. }
  24263. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24264. {
  24265. if (getTypeForFile (fileOrIdentifier) == 0)
  24266. return false;
  24267. for (int i = types.size(); --i >= 0;)
  24268. {
  24269. const PluginDescription* const d = types.getUnchecked(i);
  24270. if (d->fileOrIdentifier == fileOrIdentifier
  24271. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24272. {
  24273. return false;
  24274. }
  24275. }
  24276. return true;
  24277. }
  24278. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24279. const bool dontRescanIfAlreadyInList,
  24280. OwnedArray <PluginDescription>& typesFound,
  24281. AudioPluginFormat& format)
  24282. {
  24283. bool addedOne = false;
  24284. if (dontRescanIfAlreadyInList
  24285. && getTypeForFile (fileOrIdentifier) != 0)
  24286. {
  24287. bool needsRescanning = false;
  24288. for (int i = types.size(); --i >= 0;)
  24289. {
  24290. const PluginDescription* const d = types.getUnchecked(i);
  24291. if (d->fileOrIdentifier == fileOrIdentifier)
  24292. {
  24293. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24294. needsRescanning = true;
  24295. else
  24296. typesFound.add (new PluginDescription (*d));
  24297. }
  24298. }
  24299. if (! needsRescanning)
  24300. return false;
  24301. }
  24302. OwnedArray <PluginDescription> found;
  24303. format.findAllTypesForFile (found, fileOrIdentifier);
  24304. for (int i = 0; i < found.size(); ++i)
  24305. {
  24306. PluginDescription* const desc = found.getUnchecked(i);
  24307. jassert (desc != 0);
  24308. if (addType (*desc))
  24309. addedOne = true;
  24310. typesFound.add (new PluginDescription (*desc));
  24311. }
  24312. return addedOne;
  24313. }
  24314. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24315. OwnedArray <PluginDescription>& typesFound)
  24316. {
  24317. for (int i = 0; i < files.size(); ++i)
  24318. {
  24319. bool loaded = false;
  24320. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24321. {
  24322. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24323. if (scanAndAddFile (files[i], true, typesFound, *format))
  24324. loaded = true;
  24325. }
  24326. if (! loaded)
  24327. {
  24328. const File f (files[i]);
  24329. if (f.isDirectory())
  24330. {
  24331. StringArray s;
  24332. {
  24333. Array<File> subFiles;
  24334. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24335. for (int j = 0; j < subFiles.size(); ++j)
  24336. s.add (subFiles.getReference(j).getFullPathName());
  24337. }
  24338. scanAndAddDragAndDroppedFiles (s, typesFound);
  24339. }
  24340. }
  24341. }
  24342. }
  24343. class PluginSorter
  24344. {
  24345. public:
  24346. KnownPluginList::SortMethod method;
  24347. PluginSorter() throw() {}
  24348. int compareElements (const PluginDescription* const first,
  24349. const PluginDescription* const second) const
  24350. {
  24351. int diff = 0;
  24352. if (method == KnownPluginList::sortByCategory)
  24353. diff = first->category.compareLexicographically (second->category);
  24354. else if (method == KnownPluginList::sortByManufacturer)
  24355. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24356. else if (method == KnownPluginList::sortByFileSystemLocation)
  24357. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24358. .upToLastOccurrenceOf ("/", false, false)
  24359. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24360. .upToLastOccurrenceOf ("/", false, false));
  24361. if (diff == 0)
  24362. diff = first->name.compareLexicographically (second->name);
  24363. return diff;
  24364. }
  24365. };
  24366. void KnownPluginList::sort (const SortMethod method)
  24367. {
  24368. if (method != defaultOrder)
  24369. {
  24370. PluginSorter sorter;
  24371. sorter.method = method;
  24372. types.sort (sorter, true);
  24373. sendChangeMessage (this);
  24374. }
  24375. }
  24376. XmlElement* KnownPluginList::createXml() const
  24377. {
  24378. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24379. for (int i = 0; i < types.size(); ++i)
  24380. e->addChildElement (types.getUnchecked(i)->createXml());
  24381. return e;
  24382. }
  24383. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24384. {
  24385. clear();
  24386. if (xml.hasTagName ("KNOWNPLUGINS"))
  24387. {
  24388. forEachXmlChildElement (xml, e)
  24389. {
  24390. PluginDescription info;
  24391. if (info.loadFromXml (*e))
  24392. addType (info);
  24393. }
  24394. }
  24395. }
  24396. const int menuIdBase = 0x324503f4;
  24397. // This is used to turn a bunch of paths into a nested menu structure.
  24398. struct PluginFilesystemTree
  24399. {
  24400. private:
  24401. String folder;
  24402. OwnedArray <PluginFilesystemTree> subFolders;
  24403. Array <PluginDescription*> plugins;
  24404. void addPlugin (PluginDescription* const pd, const String& path)
  24405. {
  24406. if (path.isEmpty())
  24407. {
  24408. plugins.add (pd);
  24409. }
  24410. else
  24411. {
  24412. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24413. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24414. for (int i = subFolders.size(); --i >= 0;)
  24415. {
  24416. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24417. {
  24418. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24419. return;
  24420. }
  24421. }
  24422. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24423. newFolder->folder = firstSubFolder;
  24424. subFolders.add (newFolder);
  24425. newFolder->addPlugin (pd, remainingPath);
  24426. }
  24427. }
  24428. // removes any deeply nested folders that don't contain any actual plugins
  24429. void optimise()
  24430. {
  24431. for (int i = subFolders.size(); --i >= 0;)
  24432. {
  24433. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24434. sub->optimise();
  24435. if (sub->plugins.size() == 0)
  24436. {
  24437. for (int j = 0; j < sub->subFolders.size(); ++j)
  24438. subFolders.add (sub->subFolders.getUnchecked(j));
  24439. sub->subFolders.clear (false);
  24440. subFolders.remove (i);
  24441. }
  24442. }
  24443. }
  24444. public:
  24445. void buildTree (const Array <PluginDescription*>& allPlugins)
  24446. {
  24447. for (int i = 0; i < allPlugins.size(); ++i)
  24448. {
  24449. String path (allPlugins.getUnchecked(i)
  24450. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24451. .upToLastOccurrenceOf ("/", false, false));
  24452. if (path.substring (1, 2) == ":")
  24453. path = path.substring (2);
  24454. addPlugin (allPlugins.getUnchecked(i), path);
  24455. }
  24456. optimise();
  24457. }
  24458. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24459. {
  24460. int i;
  24461. for (i = 0; i < subFolders.size(); ++i)
  24462. {
  24463. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24464. PopupMenu subMenu;
  24465. sub->addToMenu (subMenu, allPlugins);
  24466. #if JUCE_MAC
  24467. // avoid the special AU formatting nonsense on Mac..
  24468. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24469. #else
  24470. m.addSubMenu (sub->folder, subMenu);
  24471. #endif
  24472. }
  24473. for (i = 0; i < plugins.size(); ++i)
  24474. {
  24475. PluginDescription* const plugin = plugins.getUnchecked(i);
  24476. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24477. plugin->name, true, false);
  24478. }
  24479. }
  24480. };
  24481. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24482. {
  24483. Array <PluginDescription*> sorted;
  24484. {
  24485. PluginSorter sorter;
  24486. sorter.method = sortMethod;
  24487. for (int i = 0; i < types.size(); ++i)
  24488. sorted.addSorted (sorter, types.getUnchecked(i));
  24489. }
  24490. if (sortMethod == sortByCategory
  24491. || sortMethod == sortByManufacturer)
  24492. {
  24493. String lastSubMenuName;
  24494. PopupMenu sub;
  24495. for (int i = 0; i < sorted.size(); ++i)
  24496. {
  24497. const PluginDescription* const pd = sorted.getUnchecked(i);
  24498. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24499. : pd->manufacturerName);
  24500. if (! thisSubMenuName.containsNonWhitespaceChars())
  24501. thisSubMenuName = "Other";
  24502. if (thisSubMenuName != lastSubMenuName)
  24503. {
  24504. if (sub.getNumItems() > 0)
  24505. {
  24506. menu.addSubMenu (lastSubMenuName, sub);
  24507. sub.clear();
  24508. }
  24509. lastSubMenuName = thisSubMenuName;
  24510. }
  24511. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24512. }
  24513. if (sub.getNumItems() > 0)
  24514. menu.addSubMenu (lastSubMenuName, sub);
  24515. }
  24516. else if (sortMethod == sortByFileSystemLocation)
  24517. {
  24518. PluginFilesystemTree root;
  24519. root.buildTree (sorted);
  24520. root.addToMenu (menu, types);
  24521. }
  24522. else
  24523. {
  24524. for (int i = 0; i < sorted.size(); ++i)
  24525. {
  24526. const PluginDescription* const pd = sorted.getUnchecked(i);
  24527. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24528. }
  24529. }
  24530. }
  24531. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24532. {
  24533. const int i = menuResultCode - menuIdBase;
  24534. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24535. }
  24536. END_JUCE_NAMESPACE
  24537. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24538. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24539. BEGIN_JUCE_NAMESPACE
  24540. PluginDescription::PluginDescription()
  24541. : uid (0),
  24542. isInstrument (false),
  24543. numInputChannels (0),
  24544. numOutputChannels (0)
  24545. {
  24546. }
  24547. PluginDescription::~PluginDescription()
  24548. {
  24549. }
  24550. PluginDescription::PluginDescription (const PluginDescription& other)
  24551. : name (other.name),
  24552. pluginFormatName (other.pluginFormatName),
  24553. category (other.category),
  24554. manufacturerName (other.manufacturerName),
  24555. version (other.version),
  24556. fileOrIdentifier (other.fileOrIdentifier),
  24557. lastFileModTime (other.lastFileModTime),
  24558. uid (other.uid),
  24559. isInstrument (other.isInstrument),
  24560. numInputChannels (other.numInputChannels),
  24561. numOutputChannels (other.numOutputChannels)
  24562. {
  24563. }
  24564. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24565. {
  24566. name = other.name;
  24567. pluginFormatName = other.pluginFormatName;
  24568. category = other.category;
  24569. manufacturerName = other.manufacturerName;
  24570. version = other.version;
  24571. fileOrIdentifier = other.fileOrIdentifier;
  24572. uid = other.uid;
  24573. isInstrument = other.isInstrument;
  24574. lastFileModTime = other.lastFileModTime;
  24575. numInputChannels = other.numInputChannels;
  24576. numOutputChannels = other.numOutputChannels;
  24577. return *this;
  24578. }
  24579. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24580. {
  24581. return fileOrIdentifier == other.fileOrIdentifier
  24582. && uid == other.uid;
  24583. }
  24584. const String PluginDescription::createIdentifierString() const
  24585. {
  24586. return pluginFormatName
  24587. + "-" + name
  24588. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24589. + "-" + String::toHexString (uid);
  24590. }
  24591. XmlElement* PluginDescription::createXml() const
  24592. {
  24593. XmlElement* const e = new XmlElement ("PLUGIN");
  24594. e->setAttribute ("name", name);
  24595. e->setAttribute ("format", pluginFormatName);
  24596. e->setAttribute ("category", category);
  24597. e->setAttribute ("manufacturer", manufacturerName);
  24598. e->setAttribute ("version", version);
  24599. e->setAttribute ("file", fileOrIdentifier);
  24600. e->setAttribute ("uid", String::toHexString (uid));
  24601. e->setAttribute ("isInstrument", isInstrument);
  24602. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24603. e->setAttribute ("numInputs", numInputChannels);
  24604. e->setAttribute ("numOutputs", numOutputChannels);
  24605. return e;
  24606. }
  24607. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24608. {
  24609. if (xml.hasTagName ("PLUGIN"))
  24610. {
  24611. name = xml.getStringAttribute ("name");
  24612. pluginFormatName = xml.getStringAttribute ("format");
  24613. category = xml.getStringAttribute ("category");
  24614. manufacturerName = xml.getStringAttribute ("manufacturer");
  24615. version = xml.getStringAttribute ("version");
  24616. fileOrIdentifier = xml.getStringAttribute ("file");
  24617. uid = xml.getStringAttribute ("uid").getHexValue32();
  24618. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24619. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24620. numInputChannels = xml.getIntAttribute ("numInputs");
  24621. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24622. return true;
  24623. }
  24624. return false;
  24625. }
  24626. END_JUCE_NAMESPACE
  24627. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24628. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24629. BEGIN_JUCE_NAMESPACE
  24630. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24631. AudioPluginFormat& formatToLookFor,
  24632. FileSearchPath directoriesToSearch,
  24633. const bool recursive,
  24634. const File& deadMansPedalFile_)
  24635. : list (listToAddTo),
  24636. format (formatToLookFor),
  24637. deadMansPedalFile (deadMansPedalFile_),
  24638. nextIndex (0),
  24639. progress (0)
  24640. {
  24641. directoriesToSearch.removeRedundantPaths();
  24642. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24643. // If any plugins have crashed recently when being loaded, move them to the
  24644. // end of the list to give the others a chance to load correctly..
  24645. const StringArray crashedPlugins (getDeadMansPedalFile());
  24646. for (int i = 0; i < crashedPlugins.size(); ++i)
  24647. {
  24648. const String f = crashedPlugins[i];
  24649. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24650. if (f == filesOrIdentifiersToScan[j])
  24651. filesOrIdentifiersToScan.move (j, -1);
  24652. }
  24653. }
  24654. PluginDirectoryScanner::~PluginDirectoryScanner()
  24655. {
  24656. }
  24657. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24658. {
  24659. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24660. }
  24661. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24662. {
  24663. String file (filesOrIdentifiersToScan [nextIndex]);
  24664. if (file.isNotEmpty())
  24665. {
  24666. if (! list.isListingUpToDate (file))
  24667. {
  24668. OwnedArray <PluginDescription> typesFound;
  24669. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24670. StringArray crashedPlugins (getDeadMansPedalFile());
  24671. crashedPlugins.removeString (file);
  24672. crashedPlugins.add (file);
  24673. setDeadMansPedalFile (crashedPlugins);
  24674. list.scanAndAddFile (file,
  24675. dontRescanIfAlreadyInList,
  24676. typesFound,
  24677. format);
  24678. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24679. crashedPlugins.removeString (file);
  24680. setDeadMansPedalFile (crashedPlugins);
  24681. if (typesFound.size() == 0)
  24682. failedFiles.add (file);
  24683. }
  24684. ++nextIndex;
  24685. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  24686. }
  24687. return nextIndex < filesOrIdentifiersToScan.size();
  24688. }
  24689. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24690. {
  24691. StringArray lines;
  24692. if (deadMansPedalFile != File::nonexistent)
  24693. {
  24694. lines.addLines (deadMansPedalFile.loadFileAsString());
  24695. lines.removeEmptyStrings();
  24696. }
  24697. return lines;
  24698. }
  24699. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24700. {
  24701. if (deadMansPedalFile != File::nonexistent)
  24702. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24703. }
  24704. END_JUCE_NAMESPACE
  24705. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24706. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24707. BEGIN_JUCE_NAMESPACE
  24708. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24709. const File& deadMansPedalFile_,
  24710. PropertiesFile* const propertiesToUse_)
  24711. : list (listToEdit),
  24712. deadMansPedalFile (deadMansPedalFile_),
  24713. propertiesToUse (propertiesToUse_)
  24714. {
  24715. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24716. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24717. optionsButton->addButtonListener (this);
  24718. optionsButton->setTriggeredOnMouseDown (true);
  24719. setSize (400, 600);
  24720. list.addChangeListener (this);
  24721. changeListenerCallback (0);
  24722. }
  24723. PluginListComponent::~PluginListComponent()
  24724. {
  24725. list.removeChangeListener (this);
  24726. deleteAllChildren();
  24727. }
  24728. void PluginListComponent::resized()
  24729. {
  24730. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24731. optionsButton->changeWidthToFitText (24);
  24732. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24733. }
  24734. void PluginListComponent::changeListenerCallback (void*)
  24735. {
  24736. listBox->updateContent();
  24737. listBox->repaint();
  24738. }
  24739. int PluginListComponent::getNumRows()
  24740. {
  24741. return list.getNumTypes();
  24742. }
  24743. void PluginListComponent::paintListBoxItem (int row,
  24744. Graphics& g,
  24745. int width, int height,
  24746. bool rowIsSelected)
  24747. {
  24748. if (rowIsSelected)
  24749. g.fillAll (findColour (TextEditor::highlightColourId));
  24750. const PluginDescription* const pd = list.getType (row);
  24751. if (pd != 0)
  24752. {
  24753. GlyphArrangement ga;
  24754. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24755. g.setColour (Colours::black);
  24756. ga.draw (g);
  24757. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24758. String desc;
  24759. desc << pd->pluginFormatName
  24760. << (pd->isInstrument ? " instrument" : " effect")
  24761. << " - "
  24762. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24763. << " / "
  24764. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24765. if (pd->manufacturerName.isNotEmpty())
  24766. desc << " - " << pd->manufacturerName;
  24767. if (pd->version.isNotEmpty())
  24768. desc << " - " << pd->version;
  24769. if (pd->category.isNotEmpty())
  24770. desc << " - category: '" << pd->category << '\'';
  24771. g.setColour (Colours::grey);
  24772. ga.clear();
  24773. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24774. ga.draw (g);
  24775. }
  24776. }
  24777. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24778. {
  24779. list.removeType (lastRowSelected);
  24780. }
  24781. void PluginListComponent::buttonClicked (Button* b)
  24782. {
  24783. if (optionsButton == b)
  24784. {
  24785. PopupMenu menu;
  24786. menu.addItem (1, TRANS("Clear list"));
  24787. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24788. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24789. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24790. menu.addSeparator();
  24791. menu.addItem (2, TRANS("Sort alphabetically"));
  24792. menu.addItem (3, TRANS("Sort by category"));
  24793. menu.addItem (4, TRANS("Sort by manufacturer"));
  24794. menu.addSeparator();
  24795. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24796. {
  24797. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24798. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24799. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24800. }
  24801. const int r = menu.showAt (optionsButton);
  24802. if (r == 1)
  24803. {
  24804. list.clear();
  24805. }
  24806. else if (r == 2)
  24807. {
  24808. list.sort (KnownPluginList::sortAlphabetically);
  24809. }
  24810. else if (r == 3)
  24811. {
  24812. list.sort (KnownPluginList::sortByCategory);
  24813. }
  24814. else if (r == 4)
  24815. {
  24816. list.sort (KnownPluginList::sortByManufacturer);
  24817. }
  24818. else if (r == 5)
  24819. {
  24820. const SparseSet <int> selected (listBox->getSelectedRows());
  24821. for (int i = list.getNumTypes(); --i >= 0;)
  24822. if (selected.contains (i))
  24823. list.removeType (i);
  24824. }
  24825. else if (r == 6)
  24826. {
  24827. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24828. if (desc != 0)
  24829. {
  24830. if (File (desc->fileOrIdentifier).existsAsFile())
  24831. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24832. }
  24833. }
  24834. else if (r == 7)
  24835. {
  24836. for (int i = list.getNumTypes(); --i >= 0;)
  24837. {
  24838. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24839. {
  24840. list.removeType (i);
  24841. }
  24842. }
  24843. }
  24844. else if (r != 0)
  24845. {
  24846. typeToScan = r - 10;
  24847. startTimer (1);
  24848. }
  24849. }
  24850. }
  24851. void PluginListComponent::timerCallback()
  24852. {
  24853. stopTimer();
  24854. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24855. }
  24856. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24857. {
  24858. return true;
  24859. }
  24860. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24861. {
  24862. OwnedArray <PluginDescription> typesFound;
  24863. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24864. }
  24865. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24866. {
  24867. if (format == 0)
  24868. return;
  24869. FileSearchPath path (format->getDefaultLocationsToSearch());
  24870. if (propertiesToUse != 0)
  24871. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24872. {
  24873. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24874. FileSearchPathListComponent pathList;
  24875. pathList.setSize (500, 300);
  24876. pathList.setPath (path);
  24877. aw.addCustomComponent (&pathList);
  24878. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24879. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24880. if (aw.runModalLoop() == 0)
  24881. return;
  24882. path = pathList.getPath();
  24883. }
  24884. if (propertiesToUse != 0)
  24885. {
  24886. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24887. propertiesToUse->saveIfNeeded();
  24888. }
  24889. double progress = 0.0;
  24890. AlertWindow aw (TRANS("Scanning for plugins..."),
  24891. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24892. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24893. aw.addProgressBarComponent (progress);
  24894. aw.enterModalState();
  24895. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24896. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24897. for (;;)
  24898. {
  24899. aw.setMessage (TRANS("Testing:\n\n")
  24900. + scanner.getNextPluginFileThatWillBeScanned());
  24901. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24902. if (! scanner.scanNextFile (true))
  24903. break;
  24904. if (! aw.isCurrentlyModal())
  24905. break;
  24906. progress = scanner.getProgress();
  24907. }
  24908. if (scanner.getFailedFiles().size() > 0)
  24909. {
  24910. StringArray shortNames;
  24911. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24912. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24913. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24914. TRANS("Scan complete"),
  24915. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24916. + shortNames.joinIntoString (", "));
  24917. }
  24918. }
  24919. END_JUCE_NAMESPACE
  24920. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24921. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24922. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24923. #include <AudioUnit/AudioUnit.h>
  24924. #include <AudioUnit/AUCocoaUIView.h>
  24925. #include <CoreAudioKit/AUGenericView.h>
  24926. #if JUCE_SUPPORT_CARBON
  24927. #include <AudioToolbox/AudioUnitUtilities.h>
  24928. #include <AudioUnit/AudioUnitCarbonView.h>
  24929. #endif
  24930. BEGIN_JUCE_NAMESPACE
  24931. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24932. #endif
  24933. #if JUCE_MAC
  24934. // Change this to disable logging of various activities
  24935. #ifndef AU_LOGGING
  24936. #define AU_LOGGING 1
  24937. #endif
  24938. #if AU_LOGGING
  24939. #define log(a) Logger::writeToLog(a);
  24940. #else
  24941. #define log(a)
  24942. #endif
  24943. namespace AudioUnitFormatHelpers
  24944. {
  24945. static int insideCallback = 0;
  24946. static const String osTypeToString (OSType type)
  24947. {
  24948. char s[4];
  24949. s[0] = (char) (((uint32) type) >> 24);
  24950. s[1] = (char) (((uint32) type) >> 16);
  24951. s[2] = (char) (((uint32) type) >> 8);
  24952. s[3] = (char) ((uint32) type);
  24953. return String (s, 4);
  24954. }
  24955. static OSType stringToOSType (const String& s1)
  24956. {
  24957. const String s (s1 + " ");
  24958. return (((OSType) (unsigned char) s[0]) << 24)
  24959. | (((OSType) (unsigned char) s[1]) << 16)
  24960. | (((OSType) (unsigned char) s[2]) << 8)
  24961. | ((OSType) (unsigned char) s[3]);
  24962. }
  24963. static const char* auIdentifierPrefix = "AudioUnit:";
  24964. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24965. {
  24966. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24967. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24968. String s (auIdentifierPrefix);
  24969. if (desc.componentType == kAudioUnitType_MusicDevice)
  24970. s << "Synths/";
  24971. else if (desc.componentType == kAudioUnitType_MusicEffect
  24972. || desc.componentType == kAudioUnitType_Effect)
  24973. s << "Effects/";
  24974. else if (desc.componentType == kAudioUnitType_Generator)
  24975. s << "Generators/";
  24976. else if (desc.componentType == kAudioUnitType_Panner)
  24977. s << "Panners/";
  24978. s << osTypeToString (desc.componentType) << ","
  24979. << osTypeToString (desc.componentSubType) << ","
  24980. << osTypeToString (desc.componentManufacturer);
  24981. return s;
  24982. }
  24983. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24984. {
  24985. Handle componentNameHandle = NewHandle (sizeof (void*));
  24986. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24987. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24988. {
  24989. ComponentDescription desc;
  24990. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24991. {
  24992. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24993. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24994. if (nameString != 0 && nameString[0] != 0)
  24995. {
  24996. const String all ((const char*) nameString + 1, nameString[0]);
  24997. DBG ("name: "+ all);
  24998. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24999. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25000. }
  25001. if (infoString != 0 && infoString[0] != 0)
  25002. {
  25003. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25004. }
  25005. if (name.isEmpty())
  25006. name = "<Unknown>";
  25007. }
  25008. DisposeHandle (componentNameHandle);
  25009. DisposeHandle (componentInfoHandle);
  25010. }
  25011. }
  25012. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25013. String& name, String& version, String& manufacturer)
  25014. {
  25015. zerostruct (desc);
  25016. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25017. {
  25018. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25019. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25020. StringArray tokens;
  25021. tokens.addTokens (s, ",", String::empty);
  25022. tokens.trim();
  25023. tokens.removeEmptyStrings();
  25024. if (tokens.size() == 3)
  25025. {
  25026. desc.componentType = stringToOSType (tokens[0]);
  25027. desc.componentSubType = stringToOSType (tokens[1]);
  25028. desc.componentManufacturer = stringToOSType (tokens[2]);
  25029. ComponentRecord* comp = FindNextComponent (0, &desc);
  25030. if (comp != 0)
  25031. {
  25032. getAUDetails (comp, name, manufacturer);
  25033. return true;
  25034. }
  25035. }
  25036. }
  25037. return false;
  25038. }
  25039. }
  25040. class AudioUnitPluginWindowCarbon;
  25041. class AudioUnitPluginWindowCocoa;
  25042. class AudioUnitPluginInstance : public AudioPluginInstance
  25043. {
  25044. public:
  25045. ~AudioUnitPluginInstance();
  25046. // AudioPluginInstance methods:
  25047. void fillInPluginDescription (PluginDescription& desc) const
  25048. {
  25049. desc.name = pluginName;
  25050. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25051. desc.uid = ((int) componentDesc.componentType)
  25052. ^ ((int) componentDesc.componentSubType)
  25053. ^ ((int) componentDesc.componentManufacturer);
  25054. desc.lastFileModTime = 0;
  25055. desc.pluginFormatName = "AudioUnit";
  25056. desc.category = getCategory();
  25057. desc.manufacturerName = manufacturer;
  25058. desc.version = version;
  25059. desc.numInputChannels = getNumInputChannels();
  25060. desc.numOutputChannels = getNumOutputChannels();
  25061. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25062. }
  25063. const String getName() const { return pluginName; }
  25064. bool acceptsMidi() const { return wantsMidiMessages; }
  25065. bool producesMidi() const { return false; }
  25066. // AudioProcessor methods:
  25067. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25068. void releaseResources();
  25069. void processBlock (AudioSampleBuffer& buffer,
  25070. MidiBuffer& midiMessages);
  25071. AudioProcessorEditor* createEditor();
  25072. const String getInputChannelName (int index) const;
  25073. bool isInputChannelStereoPair (int index) const;
  25074. const String getOutputChannelName (int index) const;
  25075. bool isOutputChannelStereoPair (int index) const;
  25076. int getNumParameters();
  25077. float getParameter (int index);
  25078. void setParameter (int index, float newValue);
  25079. const String getParameterName (int index);
  25080. const String getParameterText (int index);
  25081. bool isParameterAutomatable (int index) const;
  25082. int getNumPrograms();
  25083. int getCurrentProgram();
  25084. void setCurrentProgram (int index);
  25085. const String getProgramName (int index);
  25086. void changeProgramName (int index, const String& newName);
  25087. void getStateInformation (MemoryBlock& destData);
  25088. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25089. void setStateInformation (const void* data, int sizeInBytes);
  25090. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25091. juce_UseDebuggingNewOperator
  25092. private:
  25093. friend class AudioUnitPluginWindowCarbon;
  25094. friend class AudioUnitPluginWindowCocoa;
  25095. friend class AudioUnitPluginFormat;
  25096. ComponentDescription componentDesc;
  25097. String pluginName, manufacturer, version;
  25098. String fileOrIdentifier;
  25099. CriticalSection lock;
  25100. bool initialised, wantsMidiMessages, wasPlaying;
  25101. HeapBlock <AudioBufferList> outputBufferList;
  25102. AudioTimeStamp timeStamp;
  25103. AudioSampleBuffer* currentBuffer;
  25104. AudioUnit audioUnit;
  25105. Array <int> parameterIds;
  25106. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25107. void initialise();
  25108. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25109. const AudioTimeStamp* inTimeStamp,
  25110. UInt32 inBusNumber,
  25111. UInt32 inNumberFrames,
  25112. AudioBufferList* ioData) const;
  25113. static OSStatus renderGetInputCallback (void* inRefCon,
  25114. AudioUnitRenderActionFlags* ioActionFlags,
  25115. const AudioTimeStamp* inTimeStamp,
  25116. UInt32 inBusNumber,
  25117. UInt32 inNumberFrames,
  25118. AudioBufferList* ioData)
  25119. {
  25120. return ((AudioUnitPluginInstance*) inRefCon)
  25121. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25122. }
  25123. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25124. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25125. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25126. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25127. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25128. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25129. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25130. {
  25131. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25132. }
  25133. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25134. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25135. Float64* outCurrentMeasureDownBeat)
  25136. {
  25137. return ((AudioUnitPluginInstance*) inHostUserData)
  25138. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25139. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25140. }
  25141. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25142. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25143. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25144. {
  25145. return ((AudioUnitPluginInstance*) inHostUserData)
  25146. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25147. outCurrentSampleInTimeLine, outIsCycling,
  25148. outCycleStartBeat, outCycleEndBeat);
  25149. }
  25150. void getNumChannels (int& numIns, int& numOuts)
  25151. {
  25152. numIns = 0;
  25153. numOuts = 0;
  25154. AUChannelInfo supportedChannels [128];
  25155. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25156. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25157. 0, supportedChannels, &supportedChannelsSize) == noErr
  25158. && supportedChannelsSize > 0)
  25159. {
  25160. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25161. {
  25162. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  25163. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  25164. }
  25165. }
  25166. else
  25167. {
  25168. // (this really means the plugin will take any number of ins/outs as long
  25169. // as they are the same)
  25170. numIns = numOuts = 2;
  25171. }
  25172. }
  25173. const String getCategory() const;
  25174. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25175. };
  25176. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25177. : fileOrIdentifier (fileOrIdentifier),
  25178. initialised (false),
  25179. wantsMidiMessages (false),
  25180. audioUnit (0),
  25181. currentBuffer (0)
  25182. {
  25183. using namespace AudioUnitFormatHelpers;
  25184. try
  25185. {
  25186. ++insideCallback;
  25187. log ("Opening AU: " + fileOrIdentifier);
  25188. if (getComponentDescFromFile (fileOrIdentifier))
  25189. {
  25190. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25191. if (comp != 0)
  25192. {
  25193. audioUnit = (AudioUnit) OpenComponent (comp);
  25194. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25195. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25196. }
  25197. }
  25198. --insideCallback;
  25199. }
  25200. catch (...)
  25201. {
  25202. --insideCallback;
  25203. }
  25204. }
  25205. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25206. {
  25207. const ScopedLock sl (lock);
  25208. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25209. if (audioUnit != 0)
  25210. {
  25211. AudioUnitUninitialize (audioUnit);
  25212. CloseComponent (audioUnit);
  25213. audioUnit = 0;
  25214. }
  25215. }
  25216. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25217. {
  25218. zerostruct (componentDesc);
  25219. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25220. return true;
  25221. const File file (fileOrIdentifier);
  25222. if (! file.hasFileExtension (".component"))
  25223. return false;
  25224. const char* const utf8 = fileOrIdentifier.toUTF8();
  25225. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25226. strlen (utf8), file.isDirectory());
  25227. if (url != 0)
  25228. {
  25229. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25230. CFRelease (url);
  25231. if (bundleRef != 0)
  25232. {
  25233. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25234. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25235. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25236. if (pluginName.isEmpty())
  25237. pluginName = file.getFileNameWithoutExtension();
  25238. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25239. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25240. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25241. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25242. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25243. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25244. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25245. UseResFile (resFileId);
  25246. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25247. {
  25248. Handle h = Get1IndResource ('thng', i);
  25249. if (h != 0)
  25250. {
  25251. HLock (h);
  25252. const uint32* const types = (const uint32*) *h;
  25253. if (types[0] == kAudioUnitType_MusicDevice
  25254. || types[0] == kAudioUnitType_MusicEffect
  25255. || types[0] == kAudioUnitType_Effect
  25256. || types[0] == kAudioUnitType_Generator
  25257. || types[0] == kAudioUnitType_Panner)
  25258. {
  25259. componentDesc.componentType = types[0];
  25260. componentDesc.componentSubType = types[1];
  25261. componentDesc.componentManufacturer = types[2];
  25262. break;
  25263. }
  25264. HUnlock (h);
  25265. ReleaseResource (h);
  25266. }
  25267. }
  25268. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25269. CFRelease (bundleRef);
  25270. }
  25271. }
  25272. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25273. }
  25274. void AudioUnitPluginInstance::initialise()
  25275. {
  25276. if (initialised || audioUnit == 0)
  25277. return;
  25278. log ("Initialising AU: " + pluginName);
  25279. parameterIds.clear();
  25280. {
  25281. UInt32 paramListSize = 0;
  25282. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25283. 0, 0, &paramListSize);
  25284. if (paramListSize > 0)
  25285. {
  25286. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25287. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25288. 0, &parameterIds.getReference(0), &paramListSize);
  25289. }
  25290. }
  25291. {
  25292. AURenderCallbackStruct info;
  25293. zerostruct (info);
  25294. info.inputProcRefCon = this;
  25295. info.inputProc = renderGetInputCallback;
  25296. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25297. 0, &info, sizeof (info));
  25298. }
  25299. {
  25300. HostCallbackInfo info;
  25301. zerostruct (info);
  25302. info.hostUserData = this;
  25303. info.beatAndTempoProc = getBeatAndTempoCallback;
  25304. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25305. info.transportStateProc = getTransportStateCallback;
  25306. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25307. 0, &info, sizeof (info));
  25308. }
  25309. int numIns, numOuts;
  25310. getNumChannels (numIns, numOuts);
  25311. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25312. initialised = AudioUnitInitialize (audioUnit) == noErr;
  25313. setLatencySamples (0);
  25314. }
  25315. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25316. int samplesPerBlockExpected)
  25317. {
  25318. if (audioUnit != 0)
  25319. {
  25320. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25321. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25322. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25323. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25324. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25325. {
  25326. if (initialised)
  25327. {
  25328. AudioUnitUninitialize (audioUnit);
  25329. initialised = false;
  25330. }
  25331. Float64 sr = sampleRate_;
  25332. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25333. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25334. }
  25335. }
  25336. initialise();
  25337. if (initialised)
  25338. {
  25339. int numIns, numOuts;
  25340. getNumChannels (numIns, numOuts);
  25341. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25342. Float64 latencySecs = 0.0;
  25343. UInt32 latencySize = sizeof (latencySecs);
  25344. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25345. 0, &latencySecs, &latencySize);
  25346. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25347. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25348. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25349. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25350. AudioStreamBasicDescription stream;
  25351. zerostruct (stream);
  25352. stream.mSampleRate = sampleRate_;
  25353. stream.mFormatID = kAudioFormatLinearPCM;
  25354. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25355. stream.mFramesPerPacket = 1;
  25356. stream.mBytesPerPacket = 4;
  25357. stream.mBytesPerFrame = 4;
  25358. stream.mBitsPerChannel = 32;
  25359. stream.mChannelsPerFrame = numIns;
  25360. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25361. 0, &stream, sizeof (stream));
  25362. stream.mChannelsPerFrame = numOuts;
  25363. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25364. 0, &stream, sizeof (stream));
  25365. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25366. outputBufferList->mNumberBuffers = numOuts;
  25367. for (int i = numOuts; --i >= 0;)
  25368. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25369. zerostruct (timeStamp);
  25370. timeStamp.mSampleTime = 0;
  25371. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25372. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25373. currentBuffer = 0;
  25374. wasPlaying = false;
  25375. }
  25376. }
  25377. void AudioUnitPluginInstance::releaseResources()
  25378. {
  25379. if (initialised)
  25380. {
  25381. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25382. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25383. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25384. outputBufferList.free();
  25385. currentBuffer = 0;
  25386. }
  25387. }
  25388. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25389. const AudioTimeStamp* inTimeStamp,
  25390. UInt32 inBusNumber,
  25391. UInt32 inNumberFrames,
  25392. AudioBufferList* ioData) const
  25393. {
  25394. if (inBusNumber == 0
  25395. && currentBuffer != 0)
  25396. {
  25397. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25398. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25399. {
  25400. if (i < currentBuffer->getNumChannels())
  25401. {
  25402. memcpy (ioData->mBuffers[i].mData,
  25403. currentBuffer->getSampleData (i, 0),
  25404. sizeof (float) * inNumberFrames);
  25405. }
  25406. else
  25407. {
  25408. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25409. }
  25410. }
  25411. }
  25412. return noErr;
  25413. }
  25414. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25415. MidiBuffer& midiMessages)
  25416. {
  25417. const int numSamples = buffer.getNumSamples();
  25418. if (initialised)
  25419. {
  25420. AudioUnitRenderActionFlags flags = 0;
  25421. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25422. for (int i = getNumOutputChannels(); --i >= 0;)
  25423. {
  25424. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25425. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25426. }
  25427. currentBuffer = &buffer;
  25428. if (wantsMidiMessages)
  25429. {
  25430. const uint8* midiEventData;
  25431. int midiEventSize, midiEventPosition;
  25432. MidiBuffer::Iterator i (midiMessages);
  25433. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25434. {
  25435. if (midiEventSize <= 3)
  25436. MusicDeviceMIDIEvent (audioUnit,
  25437. midiEventData[0], midiEventData[1], midiEventData[2],
  25438. midiEventPosition);
  25439. else
  25440. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25441. }
  25442. midiMessages.clear();
  25443. }
  25444. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25445. 0, numSamples, outputBufferList);
  25446. timeStamp.mSampleTime += numSamples;
  25447. }
  25448. else
  25449. {
  25450. // Not initialised, so just bypass..
  25451. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25452. buffer.clear (i, 0, buffer.getNumSamples());
  25453. }
  25454. }
  25455. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25456. {
  25457. AudioPlayHead* const ph = getPlayHead();
  25458. AudioPlayHead::CurrentPositionInfo result;
  25459. if (ph != 0 && ph->getCurrentPosition (result))
  25460. {
  25461. if (outCurrentBeat != 0)
  25462. *outCurrentBeat = result.ppqPosition;
  25463. if (outCurrentTempo != 0)
  25464. *outCurrentTempo = result.bpm;
  25465. }
  25466. else
  25467. {
  25468. if (outCurrentBeat != 0)
  25469. *outCurrentBeat = 0;
  25470. if (outCurrentTempo != 0)
  25471. *outCurrentTempo = 120.0;
  25472. }
  25473. return noErr;
  25474. }
  25475. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25476. Float32* outTimeSig_Numerator,
  25477. UInt32* outTimeSig_Denominator,
  25478. Float64* outCurrentMeasureDownBeat) const
  25479. {
  25480. AudioPlayHead* const ph = getPlayHead();
  25481. AudioPlayHead::CurrentPositionInfo result;
  25482. if (ph != 0 && ph->getCurrentPosition (result))
  25483. {
  25484. if (outTimeSig_Numerator != 0)
  25485. *outTimeSig_Numerator = result.timeSigNumerator;
  25486. if (outTimeSig_Denominator != 0)
  25487. *outTimeSig_Denominator = result.timeSigDenominator;
  25488. if (outDeltaSampleOffsetToNextBeat != 0)
  25489. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25490. if (outCurrentMeasureDownBeat != 0)
  25491. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25492. }
  25493. else
  25494. {
  25495. if (outDeltaSampleOffsetToNextBeat != 0)
  25496. *outDeltaSampleOffsetToNextBeat = 0;
  25497. if (outTimeSig_Numerator != 0)
  25498. *outTimeSig_Numerator = 4;
  25499. if (outTimeSig_Denominator != 0)
  25500. *outTimeSig_Denominator = 4;
  25501. if (outCurrentMeasureDownBeat != 0)
  25502. *outCurrentMeasureDownBeat = 0;
  25503. }
  25504. return noErr;
  25505. }
  25506. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25507. Boolean* outTransportStateChanged,
  25508. Float64* outCurrentSampleInTimeLine,
  25509. Boolean* outIsCycling,
  25510. Float64* outCycleStartBeat,
  25511. Float64* outCycleEndBeat)
  25512. {
  25513. AudioPlayHead* const ph = getPlayHead();
  25514. AudioPlayHead::CurrentPositionInfo result;
  25515. if (ph != 0 && ph->getCurrentPosition (result))
  25516. {
  25517. if (outIsPlaying != 0)
  25518. *outIsPlaying = result.isPlaying;
  25519. if (outTransportStateChanged != 0)
  25520. {
  25521. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25522. wasPlaying = result.isPlaying;
  25523. }
  25524. if (outCurrentSampleInTimeLine != 0)
  25525. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25526. if (outIsCycling != 0)
  25527. *outIsCycling = false;
  25528. if (outCycleStartBeat != 0)
  25529. *outCycleStartBeat = 0;
  25530. if (outCycleEndBeat != 0)
  25531. *outCycleEndBeat = 0;
  25532. }
  25533. else
  25534. {
  25535. if (outIsPlaying != 0)
  25536. *outIsPlaying = false;
  25537. if (outTransportStateChanged != 0)
  25538. *outTransportStateChanged = false;
  25539. if (outCurrentSampleInTimeLine != 0)
  25540. *outCurrentSampleInTimeLine = 0;
  25541. if (outIsCycling != 0)
  25542. *outIsCycling = false;
  25543. if (outCycleStartBeat != 0)
  25544. *outCycleStartBeat = 0;
  25545. if (outCycleEndBeat != 0)
  25546. *outCycleEndBeat = 0;
  25547. }
  25548. return noErr;
  25549. }
  25550. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25551. {
  25552. public:
  25553. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25554. : AudioProcessorEditor (&plugin_),
  25555. plugin (plugin_)
  25556. {
  25557. addAndMakeVisible (&wrapper);
  25558. setOpaque (true);
  25559. setVisible (true);
  25560. setSize (100, 100);
  25561. createView (createGenericViewIfNeeded);
  25562. }
  25563. ~AudioUnitPluginWindowCocoa()
  25564. {
  25565. const bool wasValid = isValid();
  25566. wrapper.setView (0);
  25567. if (wasValid)
  25568. plugin.editorBeingDeleted (this);
  25569. }
  25570. bool isValid() const { return wrapper.getView() != 0; }
  25571. void paint (Graphics& g)
  25572. {
  25573. g.fillAll (Colours::white);
  25574. }
  25575. void resized()
  25576. {
  25577. wrapper.setSize (getWidth(), getHeight());
  25578. }
  25579. private:
  25580. AudioUnitPluginInstance& plugin;
  25581. NSViewComponent wrapper;
  25582. bool createView (const bool createGenericViewIfNeeded)
  25583. {
  25584. NSView* pluginView = 0;
  25585. UInt32 dataSize = 0;
  25586. Boolean isWritable = false;
  25587. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25588. 0, &dataSize, &isWritable) == noErr
  25589. && dataSize != 0
  25590. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25591. 0, &dataSize, &isWritable) == noErr)
  25592. {
  25593. HeapBlock <AudioUnitCocoaViewInfo> info;
  25594. info.calloc (dataSize, 1);
  25595. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25596. 0, info, &dataSize) == noErr)
  25597. {
  25598. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25599. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25600. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25601. Class viewClass = [viewBundle classNamed: viewClassName];
  25602. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25603. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25604. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25605. {
  25606. id factory = [[[viewClass alloc] init] autorelease];
  25607. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25608. withSize: NSMakeSize (getWidth(), getHeight())];
  25609. }
  25610. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25611. {
  25612. CFRelease (info->mCocoaAUViewClass[i]);
  25613. CFRelease (info->mCocoaAUViewBundleLocation);
  25614. }
  25615. }
  25616. }
  25617. if (createGenericViewIfNeeded && (pluginView == 0))
  25618. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25619. wrapper.setView (pluginView);
  25620. if (pluginView != 0)
  25621. setSize ([pluginView frame].size.width,
  25622. [pluginView frame].size.height);
  25623. return pluginView != 0;
  25624. }
  25625. };
  25626. #if JUCE_SUPPORT_CARBON
  25627. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25628. {
  25629. public:
  25630. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25631. : AudioProcessorEditor (&plugin_),
  25632. plugin (plugin_),
  25633. viewComponent (0)
  25634. {
  25635. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25636. setOpaque (true);
  25637. setVisible (true);
  25638. setSize (400, 300);
  25639. ComponentDescription viewList [16];
  25640. UInt32 viewListSize = sizeof (viewList);
  25641. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25642. 0, &viewList, &viewListSize);
  25643. componentRecord = FindNextComponent (0, &viewList[0]);
  25644. }
  25645. ~AudioUnitPluginWindowCarbon()
  25646. {
  25647. innerWrapper = 0;
  25648. if (isValid())
  25649. plugin.editorBeingDeleted (this);
  25650. }
  25651. bool isValid() const throw() { return componentRecord != 0; }
  25652. void paint (Graphics& g)
  25653. {
  25654. g.fillAll (Colours::black);
  25655. }
  25656. void resized()
  25657. {
  25658. innerWrapper->setSize (getWidth(), getHeight());
  25659. }
  25660. bool keyStateChanged (bool)
  25661. {
  25662. return false;
  25663. }
  25664. bool keyPressed (const KeyPress&)
  25665. {
  25666. return false;
  25667. }
  25668. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25669. AudioUnitCarbonView getViewComponent()
  25670. {
  25671. if (viewComponent == 0 && componentRecord != 0)
  25672. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25673. return viewComponent;
  25674. }
  25675. void closeViewComponent()
  25676. {
  25677. if (viewComponent != 0)
  25678. {
  25679. log ("Closing AU GUI: " + plugin.getName());
  25680. CloseComponent (viewComponent);
  25681. viewComponent = 0;
  25682. }
  25683. }
  25684. juce_UseDebuggingNewOperator
  25685. private:
  25686. AudioUnitPluginInstance& plugin;
  25687. ComponentRecord* componentRecord;
  25688. AudioUnitCarbonView viewComponent;
  25689. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25690. {
  25691. public:
  25692. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25693. : owner (owner_)
  25694. {
  25695. }
  25696. ~InnerWrapperComponent()
  25697. {
  25698. deleteWindow();
  25699. }
  25700. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25701. {
  25702. log ("Opening AU GUI: " + owner->plugin.getName());
  25703. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25704. if (viewComponent == 0)
  25705. return 0;
  25706. Float32Point pos = { 0, 0 };
  25707. Float32Point size = { 250, 200 };
  25708. HIViewRef pluginView = 0;
  25709. AudioUnitCarbonViewCreate (viewComponent,
  25710. owner->getAudioUnit(),
  25711. windowRef,
  25712. rootView,
  25713. &pos,
  25714. &size,
  25715. (ControlRef*) &pluginView);
  25716. return pluginView;
  25717. }
  25718. void removeView (HIViewRef)
  25719. {
  25720. owner->closeViewComponent();
  25721. }
  25722. private:
  25723. AudioUnitPluginWindowCarbon* const owner;
  25724. };
  25725. friend class InnerWrapperComponent;
  25726. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25727. };
  25728. #endif
  25729. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25730. {
  25731. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25732. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25733. w = 0;
  25734. #if JUCE_SUPPORT_CARBON
  25735. if (w == 0)
  25736. {
  25737. w = new AudioUnitPluginWindowCarbon (*this);
  25738. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25739. w = 0;
  25740. }
  25741. #endif
  25742. if (w == 0)
  25743. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25744. return w.release();
  25745. }
  25746. const String AudioUnitPluginInstance::getCategory() const
  25747. {
  25748. const char* result = 0;
  25749. switch (componentDesc.componentType)
  25750. {
  25751. case kAudioUnitType_Effect:
  25752. case kAudioUnitType_MusicEffect:
  25753. result = "Effect";
  25754. break;
  25755. case kAudioUnitType_MusicDevice:
  25756. result = "Synth";
  25757. break;
  25758. case kAudioUnitType_Generator:
  25759. result = "Generator";
  25760. break;
  25761. case kAudioUnitType_Panner:
  25762. result = "Panner";
  25763. break;
  25764. default:
  25765. break;
  25766. }
  25767. return result;
  25768. }
  25769. int AudioUnitPluginInstance::getNumParameters()
  25770. {
  25771. return parameterIds.size();
  25772. }
  25773. float AudioUnitPluginInstance::getParameter (int index)
  25774. {
  25775. const ScopedLock sl (lock);
  25776. Float32 value = 0.0f;
  25777. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25778. {
  25779. AudioUnitGetParameter (audioUnit,
  25780. (UInt32) parameterIds.getUnchecked (index),
  25781. kAudioUnitScope_Global, 0,
  25782. &value);
  25783. }
  25784. return value;
  25785. }
  25786. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25787. {
  25788. const ScopedLock sl (lock);
  25789. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25790. {
  25791. AudioUnitSetParameter (audioUnit,
  25792. (UInt32) parameterIds.getUnchecked (index),
  25793. kAudioUnitScope_Global, 0,
  25794. newValue, 0);
  25795. }
  25796. }
  25797. const String AudioUnitPluginInstance::getParameterName (int index)
  25798. {
  25799. AudioUnitParameterInfo info;
  25800. zerostruct (info);
  25801. UInt32 sz = sizeof (info);
  25802. String name;
  25803. if (AudioUnitGetProperty (audioUnit,
  25804. kAudioUnitProperty_ParameterInfo,
  25805. kAudioUnitScope_Global,
  25806. parameterIds [index], &info, &sz) == noErr)
  25807. {
  25808. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25809. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25810. else
  25811. name = String (info.name, sizeof (info.name));
  25812. }
  25813. return name;
  25814. }
  25815. const String AudioUnitPluginInstance::getParameterText (int index)
  25816. {
  25817. return String (getParameter (index));
  25818. }
  25819. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25820. {
  25821. AudioUnitParameterInfo info;
  25822. UInt32 sz = sizeof (info);
  25823. if (AudioUnitGetProperty (audioUnit,
  25824. kAudioUnitProperty_ParameterInfo,
  25825. kAudioUnitScope_Global,
  25826. parameterIds [index], &info, &sz) == noErr)
  25827. {
  25828. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25829. }
  25830. return true;
  25831. }
  25832. int AudioUnitPluginInstance::getNumPrograms()
  25833. {
  25834. CFArrayRef presets;
  25835. UInt32 sz = sizeof (CFArrayRef);
  25836. int num = 0;
  25837. if (AudioUnitGetProperty (audioUnit,
  25838. kAudioUnitProperty_FactoryPresets,
  25839. kAudioUnitScope_Global,
  25840. 0, &presets, &sz) == noErr)
  25841. {
  25842. num = (int) CFArrayGetCount (presets);
  25843. CFRelease (presets);
  25844. }
  25845. return num;
  25846. }
  25847. int AudioUnitPluginInstance::getCurrentProgram()
  25848. {
  25849. AUPreset current;
  25850. current.presetNumber = 0;
  25851. UInt32 sz = sizeof (AUPreset);
  25852. AudioUnitGetProperty (audioUnit,
  25853. kAudioUnitProperty_FactoryPresets,
  25854. kAudioUnitScope_Global,
  25855. 0, &current, &sz);
  25856. return current.presetNumber;
  25857. }
  25858. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25859. {
  25860. AUPreset current;
  25861. current.presetNumber = newIndex;
  25862. current.presetName = 0;
  25863. AudioUnitSetProperty (audioUnit,
  25864. kAudioUnitProperty_FactoryPresets,
  25865. kAudioUnitScope_Global,
  25866. 0, &current, sizeof (AUPreset));
  25867. }
  25868. const String AudioUnitPluginInstance::getProgramName (int index)
  25869. {
  25870. String s;
  25871. CFArrayRef presets;
  25872. UInt32 sz = sizeof (CFArrayRef);
  25873. if (AudioUnitGetProperty (audioUnit,
  25874. kAudioUnitProperty_FactoryPresets,
  25875. kAudioUnitScope_Global,
  25876. 0, &presets, &sz) == noErr)
  25877. {
  25878. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25879. {
  25880. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25881. if (p != 0 && p->presetNumber == index)
  25882. {
  25883. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25884. break;
  25885. }
  25886. }
  25887. CFRelease (presets);
  25888. }
  25889. return s;
  25890. }
  25891. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25892. {
  25893. jassertfalse; // xxx not implemented!
  25894. }
  25895. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25896. {
  25897. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25898. return "Input " + String (index + 1);
  25899. return String::empty;
  25900. }
  25901. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25902. {
  25903. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25904. return false;
  25905. return true;
  25906. }
  25907. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  25908. {
  25909. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25910. return "Output " + String (index + 1);
  25911. return String::empty;
  25912. }
  25913. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25914. {
  25915. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25916. return false;
  25917. return true;
  25918. }
  25919. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25920. {
  25921. getCurrentProgramStateInformation (destData);
  25922. }
  25923. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25924. {
  25925. CFPropertyListRef propertyList = 0;
  25926. UInt32 sz = sizeof (CFPropertyListRef);
  25927. if (AudioUnitGetProperty (audioUnit,
  25928. kAudioUnitProperty_ClassInfo,
  25929. kAudioUnitScope_Global,
  25930. 0, &propertyList, &sz) == noErr)
  25931. {
  25932. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25933. CFWriteStreamOpen (stream);
  25934. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25935. CFWriteStreamClose (stream);
  25936. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25937. destData.setSize (bytesWritten);
  25938. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25939. CFRelease (data);
  25940. CFRelease (stream);
  25941. CFRelease (propertyList);
  25942. }
  25943. }
  25944. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25945. {
  25946. setCurrentProgramStateInformation (data, sizeInBytes);
  25947. }
  25948. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25949. {
  25950. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25951. (const UInt8*) data,
  25952. sizeInBytes,
  25953. kCFAllocatorNull);
  25954. CFReadStreamOpen (stream);
  25955. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25956. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25957. stream,
  25958. 0,
  25959. kCFPropertyListImmutable,
  25960. &format,
  25961. 0);
  25962. CFRelease (stream);
  25963. if (propertyList != 0)
  25964. AudioUnitSetProperty (audioUnit,
  25965. kAudioUnitProperty_ClassInfo,
  25966. kAudioUnitScope_Global,
  25967. 0, &propertyList, sizeof (propertyList));
  25968. }
  25969. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25970. {
  25971. }
  25972. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25973. {
  25974. }
  25975. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25976. const String& fileOrIdentifier)
  25977. {
  25978. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25979. return;
  25980. PluginDescription desc;
  25981. desc.fileOrIdentifier = fileOrIdentifier;
  25982. desc.uid = 0;
  25983. try
  25984. {
  25985. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25986. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25987. if (auInstance != 0)
  25988. {
  25989. auInstance->fillInPluginDescription (desc);
  25990. results.add (new PluginDescription (desc));
  25991. }
  25992. }
  25993. catch (...)
  25994. {
  25995. // crashed while loading...
  25996. }
  25997. }
  25998. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25999. {
  26000. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26001. {
  26002. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26003. if (result->audioUnit != 0)
  26004. {
  26005. result->initialise();
  26006. return result.release();
  26007. }
  26008. }
  26009. return 0;
  26010. }
  26011. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26012. const bool /*recursive*/)
  26013. {
  26014. StringArray result;
  26015. ComponentRecord* comp = 0;
  26016. ComponentDescription desc;
  26017. zerostruct (desc);
  26018. for (;;)
  26019. {
  26020. zerostruct (desc);
  26021. comp = FindNextComponent (comp, &desc);
  26022. if (comp == 0)
  26023. break;
  26024. GetComponentInfo (comp, &desc, 0, 0, 0);
  26025. if (desc.componentType == kAudioUnitType_MusicDevice
  26026. || desc.componentType == kAudioUnitType_MusicEffect
  26027. || desc.componentType == kAudioUnitType_Effect
  26028. || desc.componentType == kAudioUnitType_Generator
  26029. || desc.componentType == kAudioUnitType_Panner)
  26030. {
  26031. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26032. DBG (s);
  26033. result.add (s);
  26034. }
  26035. }
  26036. return result;
  26037. }
  26038. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26039. {
  26040. ComponentDescription desc;
  26041. String name, version, manufacturer;
  26042. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26043. return FindNextComponent (0, &desc) != 0;
  26044. const File f (fileOrIdentifier);
  26045. return f.hasFileExtension (".component")
  26046. && f.isDirectory();
  26047. }
  26048. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26049. {
  26050. ComponentDescription desc;
  26051. String name, version, manufacturer;
  26052. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26053. if (name.isEmpty())
  26054. name = fileOrIdentifier;
  26055. return name;
  26056. }
  26057. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26058. {
  26059. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26060. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26061. else
  26062. return File (desc.fileOrIdentifier).exists();
  26063. }
  26064. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26065. {
  26066. return FileSearchPath ("/(Default AudioUnit locations)");
  26067. }
  26068. #endif
  26069. END_JUCE_NAMESPACE
  26070. #undef log
  26071. #endif
  26072. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26073. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26074. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26075. #define JUCE_MAC_VST_INCLUDED 1
  26076. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26077. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26078. #if JUCE_WINDOWS
  26079. #undef _WIN32_WINNT
  26080. #define _WIN32_WINNT 0x500
  26081. #undef STRICT
  26082. #define STRICT
  26083. #include <windows.h>
  26084. #include <float.h>
  26085. #pragma warning (disable : 4312 4355)
  26086. #elif JUCE_LINUX
  26087. #include <float.h>
  26088. #include <sys/time.h>
  26089. #include <X11/Xlib.h>
  26090. #include <X11/Xutil.h>
  26091. #include <X11/Xatom.h>
  26092. #undef Font
  26093. #undef KeyPress
  26094. #undef Drawable
  26095. #undef Time
  26096. #else
  26097. #include <Cocoa/Cocoa.h>
  26098. #include <Carbon/Carbon.h>
  26099. #endif
  26100. #if ! (JUCE_MAC && JUCE_64BIT)
  26101. BEGIN_JUCE_NAMESPACE
  26102. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26103. #endif
  26104. #undef PRAGMA_ALIGN_SUPPORTED
  26105. #define VST_FORCE_DEPRECATED 0
  26106. #if JUCE_MSVC
  26107. #pragma warning (push)
  26108. #pragma warning (disable: 4996)
  26109. #endif
  26110. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26111. your include path if you want to add VST support.
  26112. If you're not interested in VSTs, you can disable them by changing the
  26113. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26114. */
  26115. #include "pluginterfaces/vst2.x/aeffectx.h"
  26116. #if JUCE_MSVC
  26117. #pragma warning (pop)
  26118. #endif
  26119. #if JUCE_LINUX
  26120. #define Font JUCE_NAMESPACE::Font
  26121. #define KeyPress JUCE_NAMESPACE::KeyPress
  26122. #define Drawable JUCE_NAMESPACE::Drawable
  26123. #define Time JUCE_NAMESPACE::Time
  26124. #endif
  26125. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26126. #ifdef __aeffect__
  26127. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26128. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26129. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26130. events to the list.
  26131. This is used by both the VST hosting code and the plugin wrapper.
  26132. */
  26133. class VSTMidiEventList
  26134. {
  26135. public:
  26136. VSTMidiEventList()
  26137. : numEventsUsed (0), numEventsAllocated (0)
  26138. {
  26139. }
  26140. ~VSTMidiEventList()
  26141. {
  26142. freeEvents();
  26143. }
  26144. void clear()
  26145. {
  26146. numEventsUsed = 0;
  26147. if (events != 0)
  26148. events->numEvents = 0;
  26149. }
  26150. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26151. {
  26152. ensureSize (numEventsUsed + 1);
  26153. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26154. events->numEvents = ++numEventsUsed;
  26155. if (numBytes <= 4)
  26156. {
  26157. if (e->type == kVstSysExType)
  26158. {
  26159. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26160. e->type = kVstMidiType;
  26161. e->byteSize = sizeof (VstMidiEvent);
  26162. e->noteLength = 0;
  26163. e->noteOffset = 0;
  26164. e->detune = 0;
  26165. e->noteOffVelocity = 0;
  26166. }
  26167. e->deltaFrames = frameOffset;
  26168. memcpy (e->midiData, midiData, numBytes);
  26169. }
  26170. else
  26171. {
  26172. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26173. if (se->type == kVstSysExType)
  26174. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26175. else
  26176. se->sysexDump = (char*) juce_malloc (numBytes);
  26177. memcpy (se->sysexDump, midiData, numBytes);
  26178. se->type = kVstSysExType;
  26179. se->byteSize = sizeof (VstMidiSysexEvent);
  26180. se->deltaFrames = frameOffset;
  26181. se->flags = 0;
  26182. se->dumpBytes = numBytes;
  26183. se->resvd1 = 0;
  26184. se->resvd2 = 0;
  26185. }
  26186. }
  26187. // Handy method to pull the events out of an event buffer supplied by the host
  26188. // or plugin.
  26189. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26190. {
  26191. for (int i = 0; i < events->numEvents; ++i)
  26192. {
  26193. const VstEvent* const e = events->events[i];
  26194. if (e != 0)
  26195. {
  26196. if (e->type == kVstMidiType)
  26197. {
  26198. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26199. 4, e->deltaFrames);
  26200. }
  26201. else if (e->type == kVstSysExType)
  26202. {
  26203. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26204. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26205. e->deltaFrames);
  26206. }
  26207. }
  26208. }
  26209. }
  26210. void ensureSize (int numEventsNeeded)
  26211. {
  26212. if (numEventsNeeded > numEventsAllocated)
  26213. {
  26214. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26215. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26216. if (events == 0)
  26217. events.calloc (size, 1);
  26218. else
  26219. events.realloc (size, 1);
  26220. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26221. {
  26222. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26223. (int) sizeof (VstMidiSysexEvent)));
  26224. e->type = kVstMidiType;
  26225. e->byteSize = sizeof (VstMidiEvent);
  26226. events->events[i] = (VstEvent*) e;
  26227. }
  26228. numEventsAllocated = numEventsNeeded;
  26229. }
  26230. }
  26231. void freeEvents()
  26232. {
  26233. if (events != 0)
  26234. {
  26235. for (int i = numEventsAllocated; --i >= 0;)
  26236. {
  26237. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26238. if (e->type == kVstSysExType)
  26239. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26240. juce_free (e);
  26241. }
  26242. events.free();
  26243. numEventsUsed = 0;
  26244. numEventsAllocated = 0;
  26245. }
  26246. }
  26247. HeapBlock <VstEvents> events;
  26248. private:
  26249. int numEventsUsed, numEventsAllocated;
  26250. };
  26251. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26252. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26253. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26254. #if ! JUCE_WINDOWS
  26255. static void _fpreset() {}
  26256. static void _clearfp() {}
  26257. #endif
  26258. extern void juce_callAnyTimersSynchronously();
  26259. const int fxbVersionNum = 1;
  26260. struct fxProgram
  26261. {
  26262. long chunkMagic; // 'CcnK'
  26263. long byteSize; // of this chunk, excl. magic + byteSize
  26264. long fxMagic; // 'FxCk'
  26265. long version;
  26266. long fxID; // fx unique id
  26267. long fxVersion;
  26268. long numParams;
  26269. char prgName[28];
  26270. float params[1]; // variable no. of parameters
  26271. };
  26272. struct fxSet
  26273. {
  26274. long chunkMagic; // 'CcnK'
  26275. long byteSize; // of this chunk, excl. magic + byteSize
  26276. long fxMagic; // 'FxBk'
  26277. long version;
  26278. long fxID; // fx unique id
  26279. long fxVersion;
  26280. long numPrograms;
  26281. char future[128];
  26282. fxProgram programs[1]; // variable no. of programs
  26283. };
  26284. struct fxChunkSet
  26285. {
  26286. long chunkMagic; // 'CcnK'
  26287. long byteSize; // of this chunk, excl. magic + byteSize
  26288. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26289. long version;
  26290. long fxID; // fx unique id
  26291. long fxVersion;
  26292. long numPrograms;
  26293. char future[128];
  26294. long chunkSize;
  26295. char chunk[8]; // variable
  26296. };
  26297. struct fxProgramSet
  26298. {
  26299. long chunkMagic; // 'CcnK'
  26300. long byteSize; // of this chunk, excl. magic + byteSize
  26301. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26302. long version;
  26303. long fxID; // fx unique id
  26304. long fxVersion;
  26305. long numPrograms;
  26306. char name[28];
  26307. long chunkSize;
  26308. char chunk[8]; // variable
  26309. };
  26310. static long vst_swap (const long x) throw()
  26311. {
  26312. #ifdef JUCE_LITTLE_ENDIAN
  26313. return (long) ByteOrder::swap ((uint32) x);
  26314. #else
  26315. return x;
  26316. #endif
  26317. }
  26318. static float vst_swapFloat (const float x) throw()
  26319. {
  26320. #ifdef JUCE_LITTLE_ENDIAN
  26321. union { uint32 asInt; float asFloat; } n;
  26322. n.asFloat = x;
  26323. n.asInt = ByteOrder::swap (n.asInt);
  26324. return n.asFloat;
  26325. #else
  26326. return x;
  26327. #endif
  26328. }
  26329. typedef AEffect* (*MainCall) (audioMasterCallback);
  26330. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26331. static int shellUIDToCreate = 0;
  26332. static int insideVSTCallback = 0;
  26333. class VSTPluginWindow;
  26334. // Change this to disable logging of various VST activities
  26335. #ifndef VST_LOGGING
  26336. #define VST_LOGGING 1
  26337. #endif
  26338. #if VST_LOGGING
  26339. #define log(a) Logger::writeToLog(a);
  26340. #else
  26341. #define log(a)
  26342. #endif
  26343. #if JUCE_MAC && JUCE_PPC
  26344. static void* NewCFMFromMachO (void* const machofp) throw()
  26345. {
  26346. void* result = juce_malloc (8);
  26347. ((void**) result)[0] = machofp;
  26348. ((void**) result)[1] = result;
  26349. return result;
  26350. }
  26351. #endif
  26352. #if JUCE_LINUX
  26353. extern Display* display;
  26354. extern XContext windowHandleXContext;
  26355. typedef void (*EventProcPtr) (XEvent* ev);
  26356. static bool xErrorTriggered;
  26357. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26358. {
  26359. xErrorTriggered = true;
  26360. return 0;
  26361. }
  26362. static int getPropertyFromXWindow (Window handle, Atom atom)
  26363. {
  26364. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26365. xErrorTriggered = false;
  26366. int userSize;
  26367. unsigned long bytes, userCount;
  26368. unsigned char* data;
  26369. Atom userType;
  26370. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26371. &userType, &userSize, &userCount, &bytes, &data);
  26372. XSetErrorHandler (oldErrorHandler);
  26373. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  26374. : 0;
  26375. }
  26376. static Window getChildWindow (Window windowToCheck)
  26377. {
  26378. Window rootWindow, parentWindow;
  26379. Window* childWindows;
  26380. unsigned int numChildren;
  26381. XQueryTree (display,
  26382. windowToCheck,
  26383. &rootWindow,
  26384. &parentWindow,
  26385. &childWindows,
  26386. &numChildren);
  26387. if (numChildren > 0)
  26388. return childWindows [0];
  26389. return 0;
  26390. }
  26391. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26392. {
  26393. if (e.mods.isLeftButtonDown())
  26394. {
  26395. ev.xbutton.button = Button1;
  26396. ev.xbutton.state |= Button1Mask;
  26397. }
  26398. else if (e.mods.isRightButtonDown())
  26399. {
  26400. ev.xbutton.button = Button3;
  26401. ev.xbutton.state |= Button3Mask;
  26402. }
  26403. else if (e.mods.isMiddleButtonDown())
  26404. {
  26405. ev.xbutton.button = Button2;
  26406. ev.xbutton.state |= Button2Mask;
  26407. }
  26408. }
  26409. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26410. {
  26411. if (e.mods.isLeftButtonDown())
  26412. ev.xmotion.state |= Button1Mask;
  26413. else if (e.mods.isRightButtonDown())
  26414. ev.xmotion.state |= Button3Mask;
  26415. else if (e.mods.isMiddleButtonDown())
  26416. ev.xmotion.state |= Button2Mask;
  26417. }
  26418. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26419. {
  26420. if (e.mods.isLeftButtonDown())
  26421. ev.xcrossing.state |= Button1Mask;
  26422. else if (e.mods.isRightButtonDown())
  26423. ev.xcrossing.state |= Button3Mask;
  26424. else if (e.mods.isMiddleButtonDown())
  26425. ev.xcrossing.state |= Button2Mask;
  26426. }
  26427. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26428. {
  26429. if (increment < 0)
  26430. {
  26431. ev.xbutton.button = Button5;
  26432. ev.xbutton.state |= Button5Mask;
  26433. }
  26434. else if (increment > 0)
  26435. {
  26436. ev.xbutton.button = Button4;
  26437. ev.xbutton.state |= Button4Mask;
  26438. }
  26439. }
  26440. #endif
  26441. class ModuleHandle : public ReferenceCountedObject
  26442. {
  26443. public:
  26444. File file;
  26445. MainCall moduleMain;
  26446. String pluginName;
  26447. static Array <ModuleHandle*>& getActiveModules()
  26448. {
  26449. static Array <ModuleHandle*> activeModules;
  26450. return activeModules;
  26451. }
  26452. static ModuleHandle* findOrCreateModule (const File& file)
  26453. {
  26454. for (int i = getActiveModules().size(); --i >= 0;)
  26455. {
  26456. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26457. if (module->file == file)
  26458. return module;
  26459. }
  26460. _fpreset(); // (doesn't do any harm)
  26461. ++insideVSTCallback;
  26462. shellUIDToCreate = 0;
  26463. log ("Attempting to load VST: " + file.getFullPathName());
  26464. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26465. if (! m->open())
  26466. m = 0;
  26467. --insideVSTCallback;
  26468. _fpreset(); // (doesn't do any harm)
  26469. return m.release();
  26470. }
  26471. ModuleHandle (const File& file_)
  26472. : file (file_),
  26473. moduleMain (0),
  26474. #if JUCE_WINDOWS || JUCE_LINUX
  26475. hModule (0)
  26476. #elif JUCE_MAC
  26477. fragId (0),
  26478. resHandle (0),
  26479. bundleRef (0),
  26480. resFileId (0)
  26481. #endif
  26482. {
  26483. getActiveModules().add (this);
  26484. #if JUCE_WINDOWS || JUCE_LINUX
  26485. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26486. #elif JUCE_MAC
  26487. FSRef ref;
  26488. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26489. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26490. #endif
  26491. }
  26492. ~ModuleHandle()
  26493. {
  26494. getActiveModules().removeValue (this);
  26495. close();
  26496. }
  26497. juce_UseDebuggingNewOperator
  26498. #if JUCE_WINDOWS || JUCE_LINUX
  26499. void* hModule;
  26500. String fullParentDirectoryPathName;
  26501. bool open()
  26502. {
  26503. #if JUCE_WINDOWS
  26504. static bool timePeriodSet = false;
  26505. if (! timePeriodSet)
  26506. {
  26507. timePeriodSet = true;
  26508. timeBeginPeriod (2);
  26509. }
  26510. #endif
  26511. pluginName = file.getFileNameWithoutExtension();
  26512. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26513. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26514. if (moduleMain == 0)
  26515. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26516. return moduleMain != 0;
  26517. }
  26518. void close()
  26519. {
  26520. _fpreset(); // (doesn't do any harm)
  26521. PlatformUtilities::freeDynamicLibrary (hModule);
  26522. }
  26523. void closeEffect (AEffect* eff)
  26524. {
  26525. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26526. }
  26527. #else
  26528. CFragConnectionID fragId;
  26529. Handle resHandle;
  26530. CFBundleRef bundleRef;
  26531. FSSpec parentDirFSSpec;
  26532. short resFileId;
  26533. bool open()
  26534. {
  26535. bool ok = false;
  26536. const String filename (file.getFullPathName());
  26537. if (file.hasFileExtension (".vst"))
  26538. {
  26539. const char* const utf8 = filename.toUTF8();
  26540. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26541. strlen (utf8), file.isDirectory());
  26542. if (url != 0)
  26543. {
  26544. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26545. CFRelease (url);
  26546. if (bundleRef != 0)
  26547. {
  26548. if (CFBundleLoadExecutable (bundleRef))
  26549. {
  26550. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26551. if (moduleMain == 0)
  26552. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26553. if (moduleMain != 0)
  26554. {
  26555. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26556. if (name != 0)
  26557. {
  26558. if (CFGetTypeID (name) == CFStringGetTypeID())
  26559. {
  26560. char buffer[1024];
  26561. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26562. pluginName = buffer;
  26563. }
  26564. }
  26565. if (pluginName.isEmpty())
  26566. pluginName = file.getFileNameWithoutExtension();
  26567. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26568. ok = true;
  26569. }
  26570. }
  26571. if (! ok)
  26572. {
  26573. CFBundleUnloadExecutable (bundleRef);
  26574. CFRelease (bundleRef);
  26575. bundleRef = 0;
  26576. }
  26577. }
  26578. }
  26579. }
  26580. #if JUCE_PPC
  26581. else
  26582. {
  26583. FSRef fn;
  26584. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26585. {
  26586. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26587. if (resFileId != -1)
  26588. {
  26589. const int numEffs = Count1Resources ('aEff');
  26590. for (int i = 0; i < numEffs; ++i)
  26591. {
  26592. resHandle = Get1IndResource ('aEff', i + 1);
  26593. if (resHandle != 0)
  26594. {
  26595. OSType type;
  26596. Str255 name;
  26597. SInt16 id;
  26598. GetResInfo (resHandle, &id, &type, name);
  26599. pluginName = String ((const char*) name + 1, name[0]);
  26600. DetachResource (resHandle);
  26601. HLock (resHandle);
  26602. Ptr ptr;
  26603. Str255 errorText;
  26604. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26605. name, kPrivateCFragCopy,
  26606. &fragId, &ptr, errorText);
  26607. if (err == noErr)
  26608. {
  26609. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26610. ok = true;
  26611. }
  26612. else
  26613. {
  26614. HUnlock (resHandle);
  26615. }
  26616. break;
  26617. }
  26618. }
  26619. if (! ok)
  26620. CloseResFile (resFileId);
  26621. }
  26622. }
  26623. }
  26624. #endif
  26625. return ok;
  26626. }
  26627. void close()
  26628. {
  26629. #if JUCE_PPC
  26630. if (fragId != 0)
  26631. {
  26632. if (moduleMain != 0)
  26633. disposeMachOFromCFM ((void*) moduleMain);
  26634. CloseConnection (&fragId);
  26635. HUnlock (resHandle);
  26636. if (resFileId != 0)
  26637. CloseResFile (resFileId);
  26638. }
  26639. else
  26640. #endif
  26641. if (bundleRef != 0)
  26642. {
  26643. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26644. if (CFGetRetainCount (bundleRef) == 1)
  26645. CFBundleUnloadExecutable (bundleRef);
  26646. if (CFGetRetainCount (bundleRef) > 0)
  26647. CFRelease (bundleRef);
  26648. }
  26649. }
  26650. void closeEffect (AEffect* eff)
  26651. {
  26652. #if JUCE_PPC
  26653. if (fragId != 0)
  26654. {
  26655. Array<void*> thingsToDelete;
  26656. thingsToDelete.add ((void*) eff->dispatcher);
  26657. thingsToDelete.add ((void*) eff->process);
  26658. thingsToDelete.add ((void*) eff->setParameter);
  26659. thingsToDelete.add ((void*) eff->getParameter);
  26660. thingsToDelete.add ((void*) eff->processReplacing);
  26661. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26662. for (int i = thingsToDelete.size(); --i >= 0;)
  26663. disposeMachOFromCFM (thingsToDelete[i]);
  26664. }
  26665. else
  26666. #endif
  26667. {
  26668. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26669. }
  26670. }
  26671. #if JUCE_PPC
  26672. static void* newMachOFromCFM (void* cfmfp)
  26673. {
  26674. if (cfmfp == 0)
  26675. return 0;
  26676. UInt32* const mfp = new UInt32[6];
  26677. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26678. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26679. mfp[2] = 0x800c0000;
  26680. mfp[3] = 0x804c0004;
  26681. mfp[4] = 0x7c0903a6;
  26682. mfp[5] = 0x4e800420;
  26683. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26684. return mfp;
  26685. }
  26686. static void disposeMachOFromCFM (void* ptr)
  26687. {
  26688. delete[] static_cast <UInt32*> (ptr);
  26689. }
  26690. void coerceAEffectFunctionCalls (AEffect* eff)
  26691. {
  26692. if (fragId != 0)
  26693. {
  26694. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26695. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26696. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26697. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26698. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26699. }
  26700. }
  26701. #endif
  26702. #endif
  26703. };
  26704. /**
  26705. An instance of a plugin, created by a VSTPluginFormat.
  26706. */
  26707. class VSTPluginInstance : public AudioPluginInstance,
  26708. private Timer,
  26709. private AsyncUpdater
  26710. {
  26711. public:
  26712. ~VSTPluginInstance();
  26713. // AudioPluginInstance methods:
  26714. void fillInPluginDescription (PluginDescription& desc) const
  26715. {
  26716. desc.name = name;
  26717. desc.fileOrIdentifier = module->file.getFullPathName();
  26718. desc.uid = getUID();
  26719. desc.lastFileModTime = module->file.getLastModificationTime();
  26720. desc.pluginFormatName = "VST";
  26721. desc.category = getCategory();
  26722. {
  26723. char buffer [kVstMaxVendorStrLen + 8];
  26724. zerostruct (buffer);
  26725. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26726. desc.manufacturerName = buffer;
  26727. }
  26728. desc.version = getVersion();
  26729. desc.numInputChannels = getNumInputChannels();
  26730. desc.numOutputChannels = getNumOutputChannels();
  26731. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26732. }
  26733. const String getName() const { return name; }
  26734. int getUID() const throw();
  26735. bool acceptsMidi() const { return wantsMidiMessages; }
  26736. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26737. // AudioProcessor methods:
  26738. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26739. void releaseResources();
  26740. void processBlock (AudioSampleBuffer& buffer,
  26741. MidiBuffer& midiMessages);
  26742. AudioProcessorEditor* createEditor();
  26743. const String getInputChannelName (int index) const;
  26744. bool isInputChannelStereoPair (int index) const;
  26745. const String getOutputChannelName (int index) const;
  26746. bool isOutputChannelStereoPair (int index) const;
  26747. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26748. float getParameter (int index);
  26749. void setParameter (int index, float newValue);
  26750. const String getParameterName (int index);
  26751. const String getParameterText (int index);
  26752. bool isParameterAutomatable (int index) const;
  26753. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26754. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26755. void setCurrentProgram (int index);
  26756. const String getProgramName (int index);
  26757. void changeProgramName (int index, const String& newName);
  26758. void getStateInformation (MemoryBlock& destData);
  26759. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26760. void setStateInformation (const void* data, int sizeInBytes);
  26761. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26762. void timerCallback();
  26763. void handleAsyncUpdate();
  26764. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26765. juce_UseDebuggingNewOperator
  26766. private:
  26767. friend class VSTPluginWindow;
  26768. friend class VSTPluginFormat;
  26769. AEffect* effect;
  26770. String name;
  26771. CriticalSection lock;
  26772. bool wantsMidiMessages, initialised, isPowerOn;
  26773. mutable StringArray programNames;
  26774. AudioSampleBuffer tempBuffer;
  26775. CriticalSection midiInLock;
  26776. MidiBuffer incomingMidi;
  26777. VSTMidiEventList midiEventsToSend;
  26778. VstTimeInfo vstHostTime;
  26779. HeapBlock <float*> channels;
  26780. ReferenceCountedObjectPtr <ModuleHandle> module;
  26781. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26782. bool restoreProgramSettings (const fxProgram* const prog);
  26783. const String getCurrentProgramName();
  26784. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26785. void updateStoredProgramNames();
  26786. void initialise();
  26787. void handleMidiFromPlugin (const VstEvents* const events);
  26788. void createTempParameterStore (MemoryBlock& dest);
  26789. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26790. const String getParameterLabel (int index) const;
  26791. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26792. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26793. void setChunkData (const char* data, int size, bool isPreset);
  26794. bool loadFromFXBFile (const void* data, int numBytes);
  26795. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26796. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26797. const String getVersion() const throw();
  26798. const String getCategory() const throw();
  26799. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26800. void setPower (const bool on);
  26801. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26802. };
  26803. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26804. : effect (0),
  26805. wantsMidiMessages (false),
  26806. initialised (false),
  26807. isPowerOn (false),
  26808. tempBuffer (1, 1),
  26809. module (module_)
  26810. {
  26811. try
  26812. {
  26813. _fpreset();
  26814. ++insideVSTCallback;
  26815. name = module->pluginName;
  26816. log ("Creating VST instance: " + name);
  26817. #if JUCE_MAC
  26818. if (module->resFileId != 0)
  26819. UseResFile (module->resFileId);
  26820. #if JUCE_PPC
  26821. if (module->fragId != 0)
  26822. {
  26823. static void* audioMasterCoerced = 0;
  26824. if (audioMasterCoerced == 0)
  26825. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26826. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26827. }
  26828. else
  26829. #endif
  26830. #endif
  26831. {
  26832. effect = module->moduleMain (&audioMaster);
  26833. }
  26834. --insideVSTCallback;
  26835. if (effect != 0 && effect->magic == kEffectMagic)
  26836. {
  26837. #if JUCE_PPC
  26838. module->coerceAEffectFunctionCalls (effect);
  26839. #endif
  26840. jassert (effect->resvd2 == 0);
  26841. jassert (effect->object != 0);
  26842. _fpreset(); // some dodgy plugs fuck around with this
  26843. }
  26844. else
  26845. {
  26846. effect = 0;
  26847. }
  26848. }
  26849. catch (...)
  26850. {
  26851. --insideVSTCallback;
  26852. }
  26853. }
  26854. VSTPluginInstance::~VSTPluginInstance()
  26855. {
  26856. {
  26857. const ScopedLock sl (lock);
  26858. jassert (insideVSTCallback == 0);
  26859. if (effect != 0 && effect->magic == kEffectMagic)
  26860. {
  26861. try
  26862. {
  26863. #if JUCE_MAC
  26864. if (module->resFileId != 0)
  26865. UseResFile (module->resFileId);
  26866. #endif
  26867. // Must delete any editors before deleting the plugin instance!
  26868. jassert (getActiveEditor() == 0);
  26869. _fpreset(); // some dodgy plugs fuck around with this
  26870. module->closeEffect (effect);
  26871. }
  26872. catch (...)
  26873. {}
  26874. }
  26875. module = 0;
  26876. effect = 0;
  26877. }
  26878. }
  26879. void VSTPluginInstance::initialise()
  26880. {
  26881. if (initialised || effect == 0)
  26882. return;
  26883. log ("Initialising VST: " + module->pluginName);
  26884. initialised = true;
  26885. dispatch (effIdentify, 0, 0, 0, 0);
  26886. // this code would ask the plugin for its name, but so few plugins
  26887. // actually bother implementing this correctly, that it's better to
  26888. // just ignore it and use the file name instead.
  26889. /* {
  26890. char buffer [256];
  26891. zerostruct (buffer);
  26892. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26893. name = String (buffer).trim();
  26894. if (name.isEmpty())
  26895. name = module->pluginName;
  26896. }
  26897. */
  26898. if (getSampleRate() > 0)
  26899. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26900. if (getBlockSize() > 0)
  26901. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26902. dispatch (effOpen, 0, 0, 0, 0);
  26903. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26904. getSampleRate(), getBlockSize());
  26905. if (getNumPrograms() > 1)
  26906. setCurrentProgram (0);
  26907. else
  26908. dispatch (effSetProgram, 0, 0, 0, 0);
  26909. int i;
  26910. for (i = effect->numInputs; --i >= 0;)
  26911. dispatch (effConnectInput, i, 1, 0, 0);
  26912. for (i = effect->numOutputs; --i >= 0;)
  26913. dispatch (effConnectOutput, i, 1, 0, 0);
  26914. updateStoredProgramNames();
  26915. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26916. setLatencySamples (effect->initialDelay);
  26917. }
  26918. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26919. int samplesPerBlockExpected)
  26920. {
  26921. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26922. sampleRate_, samplesPerBlockExpected);
  26923. setLatencySamples (effect->initialDelay);
  26924. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26925. vstHostTime.tempo = 120.0;
  26926. vstHostTime.timeSigNumerator = 4;
  26927. vstHostTime.timeSigDenominator = 4;
  26928. vstHostTime.sampleRate = sampleRate_;
  26929. vstHostTime.samplePos = 0;
  26930. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26931. initialise();
  26932. if (initialised)
  26933. {
  26934. wantsMidiMessages = wantsMidiMessages
  26935. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26936. if (wantsMidiMessages)
  26937. midiEventsToSend.ensureSize (256);
  26938. else
  26939. midiEventsToSend.freeEvents();
  26940. incomingMidi.clear();
  26941. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26942. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26943. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26944. if (! isPowerOn)
  26945. setPower (true);
  26946. // dodgy hack to force some plugins to initialise the sample rate..
  26947. if ((! hasEditor()) && getNumParameters() > 0)
  26948. {
  26949. const float old = getParameter (0);
  26950. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26951. setParameter (0, old);
  26952. }
  26953. dispatch (effStartProcess, 0, 0, 0, 0);
  26954. }
  26955. }
  26956. void VSTPluginInstance::releaseResources()
  26957. {
  26958. if (initialised)
  26959. {
  26960. dispatch (effStopProcess, 0, 0, 0, 0);
  26961. setPower (false);
  26962. }
  26963. tempBuffer.setSize (1, 1);
  26964. incomingMidi.clear();
  26965. midiEventsToSend.freeEvents();
  26966. channels.free();
  26967. }
  26968. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26969. MidiBuffer& midiMessages)
  26970. {
  26971. const int numSamples = buffer.getNumSamples();
  26972. if (initialised)
  26973. {
  26974. AudioPlayHead* playHead = getPlayHead();
  26975. if (playHead != 0)
  26976. {
  26977. AudioPlayHead::CurrentPositionInfo position;
  26978. playHead->getCurrentPosition (position);
  26979. vstHostTime.tempo = position.bpm;
  26980. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26981. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26982. vstHostTime.ppqPos = position.ppqPosition;
  26983. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26984. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26985. if (position.isPlaying)
  26986. vstHostTime.flags |= kVstTransportPlaying;
  26987. else
  26988. vstHostTime.flags &= ~kVstTransportPlaying;
  26989. }
  26990. #if JUCE_WINDOWS
  26991. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26992. #elif JUCE_LINUX
  26993. timeval micro;
  26994. gettimeofday (&micro, 0);
  26995. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26996. #elif JUCE_MAC
  26997. UnsignedWide micro;
  26998. Microseconds (&micro);
  26999. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  27000. #endif
  27001. if (wantsMidiMessages)
  27002. {
  27003. midiEventsToSend.clear();
  27004. midiEventsToSend.ensureSize (1);
  27005. MidiBuffer::Iterator iter (midiMessages);
  27006. const uint8* midiData;
  27007. int numBytesOfMidiData, samplePosition;
  27008. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27009. {
  27010. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27011. jlimit (0, numSamples - 1, samplePosition));
  27012. }
  27013. try
  27014. {
  27015. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27016. }
  27017. catch (...)
  27018. {}
  27019. }
  27020. int i;
  27021. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  27022. for (i = 0; i < maxChans; ++i)
  27023. channels[i] = buffer.getSampleData (i);
  27024. channels [maxChans] = 0;
  27025. _clearfp();
  27026. if ((effect->flags & effFlagsCanReplacing) != 0)
  27027. {
  27028. try
  27029. {
  27030. effect->processReplacing (effect, channels, channels, numSamples);
  27031. }
  27032. catch (...)
  27033. {}
  27034. }
  27035. else
  27036. {
  27037. tempBuffer.setSize (effect->numOutputs, numSamples);
  27038. tempBuffer.clear();
  27039. float* outs [64];
  27040. for (i = effect->numOutputs; --i >= 0;)
  27041. outs[i] = tempBuffer.getSampleData (i);
  27042. outs [effect->numOutputs] = 0;
  27043. try
  27044. {
  27045. effect->process (effect, channels, outs, numSamples);
  27046. }
  27047. catch (...)
  27048. {}
  27049. for (i = effect->numOutputs; --i >= 0;)
  27050. buffer.copyFrom (i, 0, outs[i], numSamples);
  27051. }
  27052. }
  27053. else
  27054. {
  27055. // Not initialised, so just bypass..
  27056. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27057. buffer.clear (i, 0, buffer.getNumSamples());
  27058. }
  27059. {
  27060. // copy any incoming midi..
  27061. const ScopedLock sl (midiInLock);
  27062. midiMessages.swapWith (incomingMidi);
  27063. incomingMidi.clear();
  27064. }
  27065. }
  27066. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27067. {
  27068. if (events != 0)
  27069. {
  27070. const ScopedLock sl (midiInLock);
  27071. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27072. }
  27073. }
  27074. static Array <VSTPluginWindow*> activeVSTWindows;
  27075. class VSTPluginWindow : public AudioProcessorEditor,
  27076. #if ! JUCE_MAC
  27077. public ComponentMovementWatcher,
  27078. #endif
  27079. public Timer
  27080. {
  27081. public:
  27082. VSTPluginWindow (VSTPluginInstance& plugin_)
  27083. : AudioProcessorEditor (&plugin_),
  27084. #if ! JUCE_MAC
  27085. ComponentMovementWatcher (this),
  27086. #endif
  27087. plugin (plugin_),
  27088. isOpen (false),
  27089. wasShowing (false),
  27090. pluginRefusesToResize (false),
  27091. pluginWantsKeys (false),
  27092. alreadyInside (false),
  27093. recursiveResize (false)
  27094. {
  27095. #if JUCE_WINDOWS
  27096. sizeCheckCount = 0;
  27097. pluginHWND = 0;
  27098. #elif JUCE_LINUX
  27099. pluginWindow = None;
  27100. pluginProc = None;
  27101. #else
  27102. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27103. #endif
  27104. activeVSTWindows.add (this);
  27105. setSize (1, 1);
  27106. setOpaque (true);
  27107. setVisible (true);
  27108. }
  27109. ~VSTPluginWindow()
  27110. {
  27111. #if JUCE_MAC
  27112. innerWrapper = 0;
  27113. #else
  27114. closePluginWindow();
  27115. #endif
  27116. activeVSTWindows.removeValue (this);
  27117. plugin.editorBeingDeleted (this);
  27118. }
  27119. #if ! JUCE_MAC
  27120. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27121. {
  27122. if (recursiveResize)
  27123. return;
  27124. Component* const topComp = getTopLevelComponent();
  27125. if (topComp->getPeer() != 0)
  27126. {
  27127. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27128. recursiveResize = true;
  27129. #if JUCE_WINDOWS
  27130. if (pluginHWND != 0)
  27131. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27132. #elif JUCE_LINUX
  27133. if (pluginWindow != 0)
  27134. {
  27135. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27136. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27137. XMapRaised (display, pluginWindow);
  27138. }
  27139. #endif
  27140. recursiveResize = false;
  27141. }
  27142. }
  27143. void componentVisibilityChanged (Component&)
  27144. {
  27145. const bool isShowingNow = isShowing();
  27146. if (wasShowing != isShowingNow)
  27147. {
  27148. wasShowing = isShowingNow;
  27149. if (isShowingNow)
  27150. openPluginWindow();
  27151. else
  27152. closePluginWindow();
  27153. }
  27154. componentMovedOrResized (true, true);
  27155. }
  27156. void componentPeerChanged()
  27157. {
  27158. closePluginWindow();
  27159. openPluginWindow();
  27160. }
  27161. #endif
  27162. bool keyStateChanged (bool)
  27163. {
  27164. return pluginWantsKeys;
  27165. }
  27166. bool keyPressed (const KeyPress&)
  27167. {
  27168. return pluginWantsKeys;
  27169. }
  27170. #if JUCE_MAC
  27171. void paint (Graphics& g)
  27172. {
  27173. g.fillAll (Colours::black);
  27174. }
  27175. #else
  27176. void paint (Graphics& g)
  27177. {
  27178. if (isOpen)
  27179. {
  27180. ComponentPeer* const peer = getPeer();
  27181. if (peer != 0)
  27182. {
  27183. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27184. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27185. #if JUCE_LINUX
  27186. if (pluginWindow != 0)
  27187. {
  27188. const Rectangle<int> clip (g.getClipBounds());
  27189. XEvent ev;
  27190. zerostruct (ev);
  27191. ev.xexpose.type = Expose;
  27192. ev.xexpose.display = display;
  27193. ev.xexpose.window = pluginWindow;
  27194. ev.xexpose.x = clip.getX();
  27195. ev.xexpose.y = clip.getY();
  27196. ev.xexpose.width = clip.getWidth();
  27197. ev.xexpose.height = clip.getHeight();
  27198. sendEventToChild (&ev);
  27199. }
  27200. #endif
  27201. }
  27202. }
  27203. else
  27204. {
  27205. g.fillAll (Colours::black);
  27206. }
  27207. }
  27208. #endif
  27209. void timerCallback()
  27210. {
  27211. #if JUCE_WINDOWS
  27212. if (--sizeCheckCount <= 0)
  27213. {
  27214. sizeCheckCount = 10;
  27215. checkPluginWindowSize();
  27216. }
  27217. #endif
  27218. try
  27219. {
  27220. static bool reentrant = false;
  27221. if (! reentrant)
  27222. {
  27223. reentrant = true;
  27224. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27225. reentrant = false;
  27226. }
  27227. }
  27228. catch (...)
  27229. {}
  27230. }
  27231. void mouseDown (const MouseEvent& e)
  27232. {
  27233. #if JUCE_LINUX
  27234. if (pluginWindow == 0)
  27235. return;
  27236. toFront (true);
  27237. XEvent ev;
  27238. zerostruct (ev);
  27239. ev.xbutton.display = display;
  27240. ev.xbutton.type = ButtonPress;
  27241. ev.xbutton.window = pluginWindow;
  27242. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27243. ev.xbutton.time = CurrentTime;
  27244. ev.xbutton.x = e.x;
  27245. ev.xbutton.y = e.y;
  27246. ev.xbutton.x_root = e.getScreenX();
  27247. ev.xbutton.y_root = e.getScreenY();
  27248. translateJuceToXButtonModifiers (e, ev);
  27249. sendEventToChild (&ev);
  27250. #elif JUCE_WINDOWS
  27251. (void) e;
  27252. toFront (true);
  27253. #endif
  27254. }
  27255. void broughtToFront()
  27256. {
  27257. activeVSTWindows.removeValue (this);
  27258. activeVSTWindows.add (this);
  27259. #if JUCE_MAC
  27260. dispatch (effEditTop, 0, 0, 0, 0);
  27261. #endif
  27262. }
  27263. juce_UseDebuggingNewOperator
  27264. private:
  27265. VSTPluginInstance& plugin;
  27266. bool isOpen, wasShowing, recursiveResize;
  27267. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27268. #if JUCE_WINDOWS
  27269. HWND pluginHWND;
  27270. void* originalWndProc;
  27271. int sizeCheckCount;
  27272. #elif JUCE_LINUX
  27273. Window pluginWindow;
  27274. EventProcPtr pluginProc;
  27275. #endif
  27276. #if JUCE_MAC
  27277. void openPluginWindow (WindowRef parentWindow)
  27278. {
  27279. if (isOpen || parentWindow == 0)
  27280. return;
  27281. isOpen = true;
  27282. ERect* rect = 0;
  27283. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27284. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27285. // do this before and after like in the steinberg example
  27286. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27287. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27288. // Install keyboard hooks
  27289. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27290. // double-check it's not too tiny
  27291. int w = 250, h = 150;
  27292. if (rect != 0)
  27293. {
  27294. w = rect->right - rect->left;
  27295. h = rect->bottom - rect->top;
  27296. if (w == 0 || h == 0)
  27297. {
  27298. w = 250;
  27299. h = 150;
  27300. }
  27301. }
  27302. w = jmax (w, 32);
  27303. h = jmax (h, 32);
  27304. setSize (w, h);
  27305. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27306. repaint();
  27307. }
  27308. #else
  27309. void openPluginWindow()
  27310. {
  27311. if (isOpen || getWindowHandle() == 0)
  27312. return;
  27313. log ("Opening VST UI: " + plugin.name);
  27314. isOpen = true;
  27315. ERect* rect = 0;
  27316. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27317. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27318. // do this before and after like in the steinberg example
  27319. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27320. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27321. // Install keyboard hooks
  27322. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27323. #if JUCE_WINDOWS
  27324. originalWndProc = 0;
  27325. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27326. if (pluginHWND == 0)
  27327. {
  27328. isOpen = false;
  27329. setSize (300, 150);
  27330. return;
  27331. }
  27332. #pragma warning (push)
  27333. #pragma warning (disable: 4244)
  27334. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  27335. if (! pluginWantsKeys)
  27336. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27337. #pragma warning (pop)
  27338. int w, h;
  27339. RECT r;
  27340. GetWindowRect (pluginHWND, &r);
  27341. w = r.right - r.left;
  27342. h = r.bottom - r.top;
  27343. if (rect != 0)
  27344. {
  27345. const int rw = rect->right - rect->left;
  27346. const int rh = rect->bottom - rect->top;
  27347. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27348. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27349. {
  27350. // very dodgy logic to decide which size is right.
  27351. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27352. {
  27353. SetWindowPos (pluginHWND, 0,
  27354. 0, 0, rw, rh,
  27355. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27356. GetWindowRect (pluginHWND, &r);
  27357. w = r.right - r.left;
  27358. h = r.bottom - r.top;
  27359. pluginRefusesToResize = (w != rw) || (h != rh);
  27360. w = rw;
  27361. h = rh;
  27362. }
  27363. }
  27364. }
  27365. #elif JUCE_LINUX
  27366. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27367. if (pluginWindow != 0)
  27368. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27369. XInternAtom (display, "_XEventProc", False));
  27370. int w = 250, h = 150;
  27371. if (rect != 0)
  27372. {
  27373. w = rect->right - rect->left;
  27374. h = rect->bottom - rect->top;
  27375. if (w == 0 || h == 0)
  27376. {
  27377. w = 250;
  27378. h = 150;
  27379. }
  27380. }
  27381. if (pluginWindow != 0)
  27382. XMapRaised (display, pluginWindow);
  27383. #endif
  27384. // double-check it's not too tiny
  27385. w = jmax (w, 32);
  27386. h = jmax (h, 32);
  27387. setSize (w, h);
  27388. #if JUCE_WINDOWS
  27389. checkPluginWindowSize();
  27390. #endif
  27391. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27392. repaint();
  27393. }
  27394. #endif
  27395. #if ! JUCE_MAC
  27396. void closePluginWindow()
  27397. {
  27398. if (isOpen)
  27399. {
  27400. log ("Closing VST UI: " + plugin.getName());
  27401. isOpen = false;
  27402. dispatch (effEditClose, 0, 0, 0, 0);
  27403. #if JUCE_WINDOWS
  27404. #pragma warning (push)
  27405. #pragma warning (disable: 4244)
  27406. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27407. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27408. #pragma warning (pop)
  27409. stopTimer();
  27410. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27411. DestroyWindow (pluginHWND);
  27412. pluginHWND = 0;
  27413. #elif JUCE_LINUX
  27414. stopTimer();
  27415. pluginWindow = 0;
  27416. pluginProc = 0;
  27417. #endif
  27418. }
  27419. }
  27420. #endif
  27421. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27422. {
  27423. return plugin.dispatch (opcode, index, value, ptr, opt);
  27424. }
  27425. #if JUCE_WINDOWS
  27426. void checkPluginWindowSize() throw()
  27427. {
  27428. RECT r;
  27429. GetWindowRect (pluginHWND, &r);
  27430. const int w = r.right - r.left;
  27431. const int h = r.bottom - r.top;
  27432. if (isShowing() && w > 0 && h > 0
  27433. && (w != getWidth() || h != getHeight())
  27434. && ! pluginRefusesToResize)
  27435. {
  27436. setSize (w, h);
  27437. sizeCheckCount = 0;
  27438. }
  27439. }
  27440. // hooks to get keyboard events from VST windows..
  27441. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27442. {
  27443. for (int i = activeVSTWindows.size(); --i >= 0;)
  27444. {
  27445. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  27446. if (w->pluginHWND == hW)
  27447. {
  27448. if (message == WM_CHAR
  27449. || message == WM_KEYDOWN
  27450. || message == WM_SYSKEYDOWN
  27451. || message == WM_KEYUP
  27452. || message == WM_SYSKEYUP
  27453. || message == WM_APPCOMMAND)
  27454. {
  27455. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27456. message, wParam, lParam);
  27457. }
  27458. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27459. (HWND) w->pluginHWND,
  27460. message,
  27461. wParam,
  27462. lParam);
  27463. }
  27464. }
  27465. return DefWindowProc (hW, message, wParam, lParam);
  27466. }
  27467. #endif
  27468. #if JUCE_LINUX
  27469. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27470. void sendEventToChild (XEvent* event)
  27471. {
  27472. if (pluginProc != 0)
  27473. {
  27474. // if the plugin publishes an event procedure, pass the event directly..
  27475. pluginProc (event);
  27476. }
  27477. else if (pluginWindow != 0)
  27478. {
  27479. // if the plugin has a window, then send the event to the window so that
  27480. // its message thread will pick it up..
  27481. XSendEvent (display, pluginWindow, False, 0L, event);
  27482. XFlush (display);
  27483. }
  27484. }
  27485. void mouseEnter (const MouseEvent& e)
  27486. {
  27487. if (pluginWindow != 0)
  27488. {
  27489. XEvent ev;
  27490. zerostruct (ev);
  27491. ev.xcrossing.display = display;
  27492. ev.xcrossing.type = EnterNotify;
  27493. ev.xcrossing.window = pluginWindow;
  27494. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27495. ev.xcrossing.time = CurrentTime;
  27496. ev.xcrossing.x = e.x;
  27497. ev.xcrossing.y = e.y;
  27498. ev.xcrossing.x_root = e.getScreenX();
  27499. ev.xcrossing.y_root = e.getScreenY();
  27500. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27501. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27502. translateJuceToXCrossingModifiers (e, ev);
  27503. sendEventToChild (&ev);
  27504. }
  27505. }
  27506. void mouseExit (const MouseEvent& e)
  27507. {
  27508. if (pluginWindow != 0)
  27509. {
  27510. XEvent ev;
  27511. zerostruct (ev);
  27512. ev.xcrossing.display = display;
  27513. ev.xcrossing.type = LeaveNotify;
  27514. ev.xcrossing.window = pluginWindow;
  27515. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27516. ev.xcrossing.time = CurrentTime;
  27517. ev.xcrossing.x = e.x;
  27518. ev.xcrossing.y = e.y;
  27519. ev.xcrossing.x_root = e.getScreenX();
  27520. ev.xcrossing.y_root = e.getScreenY();
  27521. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27522. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27523. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27524. translateJuceToXCrossingModifiers (e, ev);
  27525. sendEventToChild (&ev);
  27526. }
  27527. }
  27528. void mouseMove (const MouseEvent& e)
  27529. {
  27530. if (pluginWindow != 0)
  27531. {
  27532. XEvent ev;
  27533. zerostruct (ev);
  27534. ev.xmotion.display = display;
  27535. ev.xmotion.type = MotionNotify;
  27536. ev.xmotion.window = pluginWindow;
  27537. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27538. ev.xmotion.time = CurrentTime;
  27539. ev.xmotion.is_hint = NotifyNormal;
  27540. ev.xmotion.x = e.x;
  27541. ev.xmotion.y = e.y;
  27542. ev.xmotion.x_root = e.getScreenX();
  27543. ev.xmotion.y_root = e.getScreenY();
  27544. sendEventToChild (&ev);
  27545. }
  27546. }
  27547. void mouseDrag (const MouseEvent& e)
  27548. {
  27549. if (pluginWindow != 0)
  27550. {
  27551. XEvent ev;
  27552. zerostruct (ev);
  27553. ev.xmotion.display = display;
  27554. ev.xmotion.type = MotionNotify;
  27555. ev.xmotion.window = pluginWindow;
  27556. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27557. ev.xmotion.time = CurrentTime;
  27558. ev.xmotion.x = e.x ;
  27559. ev.xmotion.y = e.y;
  27560. ev.xmotion.x_root = e.getScreenX();
  27561. ev.xmotion.y_root = e.getScreenY();
  27562. ev.xmotion.is_hint = NotifyNormal;
  27563. translateJuceToXMotionModifiers (e, ev);
  27564. sendEventToChild (&ev);
  27565. }
  27566. }
  27567. void mouseUp (const MouseEvent& e)
  27568. {
  27569. if (pluginWindow != 0)
  27570. {
  27571. XEvent ev;
  27572. zerostruct (ev);
  27573. ev.xbutton.display = display;
  27574. ev.xbutton.type = ButtonRelease;
  27575. ev.xbutton.window = pluginWindow;
  27576. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27577. ev.xbutton.time = CurrentTime;
  27578. ev.xbutton.x = e.x;
  27579. ev.xbutton.y = e.y;
  27580. ev.xbutton.x_root = e.getScreenX();
  27581. ev.xbutton.y_root = e.getScreenY();
  27582. translateJuceToXButtonModifiers (e, ev);
  27583. sendEventToChild (&ev);
  27584. }
  27585. }
  27586. void mouseWheelMove (const MouseEvent& e,
  27587. float incrementX,
  27588. float incrementY)
  27589. {
  27590. if (pluginWindow != 0)
  27591. {
  27592. XEvent ev;
  27593. zerostruct (ev);
  27594. ev.xbutton.display = display;
  27595. ev.xbutton.type = ButtonPress;
  27596. ev.xbutton.window = pluginWindow;
  27597. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27598. ev.xbutton.time = CurrentTime;
  27599. ev.xbutton.x = e.x;
  27600. ev.xbutton.y = e.y;
  27601. ev.xbutton.x_root = e.getScreenX();
  27602. ev.xbutton.y_root = e.getScreenY();
  27603. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27604. sendEventToChild (&ev);
  27605. // TODO - put a usleep here ?
  27606. ev.xbutton.type = ButtonRelease;
  27607. sendEventToChild (&ev);
  27608. }
  27609. }
  27610. #endif
  27611. #if JUCE_MAC
  27612. #if ! JUCE_SUPPORT_CARBON
  27613. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27614. #endif
  27615. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27616. {
  27617. public:
  27618. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27619. : owner (owner_),
  27620. alreadyInside (false)
  27621. {
  27622. }
  27623. ~InnerWrapperComponent()
  27624. {
  27625. deleteWindow();
  27626. }
  27627. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27628. {
  27629. owner->openPluginWindow (windowRef);
  27630. return 0;
  27631. }
  27632. void removeView (HIViewRef)
  27633. {
  27634. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27635. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27636. }
  27637. bool getEmbeddedViewSize (int& w, int& h)
  27638. {
  27639. ERect* rect = 0;
  27640. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27641. w = rect->right - rect->left;
  27642. h = rect->bottom - rect->top;
  27643. return true;
  27644. }
  27645. void mouseDown (int x, int y)
  27646. {
  27647. if (! alreadyInside)
  27648. {
  27649. alreadyInside = true;
  27650. getTopLevelComponent()->toFront (true);
  27651. owner->dispatch (effEditMouse, x, y, 0, 0);
  27652. alreadyInside = false;
  27653. }
  27654. else
  27655. {
  27656. PostEvent (::mouseDown, 0);
  27657. }
  27658. }
  27659. void paint()
  27660. {
  27661. ComponentPeer* const peer = getPeer();
  27662. if (peer != 0)
  27663. {
  27664. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27665. ERect r;
  27666. r.left = pos.getX();
  27667. r.right = r.left + getWidth();
  27668. r.top = pos.getY();
  27669. r.bottom = r.top + getHeight();
  27670. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27671. }
  27672. }
  27673. private:
  27674. VSTPluginWindow* const owner;
  27675. bool alreadyInside;
  27676. };
  27677. friend class InnerWrapperComponent;
  27678. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27679. void resized()
  27680. {
  27681. innerWrapper->setSize (getWidth(), getHeight());
  27682. }
  27683. #endif
  27684. };
  27685. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27686. {
  27687. if (hasEditor())
  27688. return new VSTPluginWindow (*this);
  27689. return 0;
  27690. }
  27691. void VSTPluginInstance::handleAsyncUpdate()
  27692. {
  27693. // indicates that something about the plugin has changed..
  27694. updateHostDisplay();
  27695. }
  27696. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27697. {
  27698. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27699. {
  27700. changeProgramName (getCurrentProgram(), prog->prgName);
  27701. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27702. setParameter (i, vst_swapFloat (prog->params[i]));
  27703. return true;
  27704. }
  27705. return false;
  27706. }
  27707. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27708. const int dataSize)
  27709. {
  27710. if (dataSize < 28)
  27711. return false;
  27712. const fxSet* const set = (const fxSet*) data;
  27713. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27714. || vst_swap (set->version) > fxbVersionNum)
  27715. return false;
  27716. if (vst_swap (set->fxMagic) == 'FxBk')
  27717. {
  27718. // bank of programs
  27719. if (vst_swap (set->numPrograms) >= 0)
  27720. {
  27721. const int oldProg = getCurrentProgram();
  27722. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27723. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27724. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27725. {
  27726. if (i != oldProg)
  27727. {
  27728. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27729. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27730. return false;
  27731. if (vst_swap (set->numPrograms) > 0)
  27732. setCurrentProgram (i);
  27733. if (! restoreProgramSettings (prog))
  27734. return false;
  27735. }
  27736. }
  27737. if (vst_swap (set->numPrograms) > 0)
  27738. setCurrentProgram (oldProg);
  27739. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27740. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27741. return false;
  27742. if (! restoreProgramSettings (prog))
  27743. return false;
  27744. }
  27745. }
  27746. else if (vst_swap (set->fxMagic) == 'FxCk')
  27747. {
  27748. // single program
  27749. const fxProgram* const prog = (const fxProgram*) data;
  27750. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27751. return false;
  27752. changeProgramName (getCurrentProgram(), prog->prgName);
  27753. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27754. setParameter (i, vst_swapFloat (prog->params[i]));
  27755. }
  27756. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27757. {
  27758. // non-preset chunk
  27759. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27760. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27761. return false;
  27762. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27763. }
  27764. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27765. {
  27766. // preset chunk
  27767. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27768. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27769. return false;
  27770. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27771. changeProgramName (getCurrentProgram(), cset->name);
  27772. }
  27773. else
  27774. {
  27775. return false;
  27776. }
  27777. return true;
  27778. }
  27779. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27780. {
  27781. const int numParams = getNumParameters();
  27782. prog->chunkMagic = vst_swap ('CcnK');
  27783. prog->byteSize = 0;
  27784. prog->fxMagic = vst_swap ('FxCk');
  27785. prog->version = vst_swap (fxbVersionNum);
  27786. prog->fxID = vst_swap (getUID());
  27787. prog->fxVersion = vst_swap (getVersionNumber());
  27788. prog->numParams = vst_swap (numParams);
  27789. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27790. for (int i = 0; i < numParams; ++i)
  27791. prog->params[i] = vst_swapFloat (getParameter (i));
  27792. }
  27793. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27794. {
  27795. const int numPrograms = getNumPrograms();
  27796. const int numParams = getNumParameters();
  27797. if (usesChunks())
  27798. {
  27799. if (isFXB)
  27800. {
  27801. MemoryBlock chunk;
  27802. getChunkData (chunk, false, maxSizeMB);
  27803. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27804. dest.setSize (totalLen, true);
  27805. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27806. set->chunkMagic = vst_swap ('CcnK');
  27807. set->byteSize = 0;
  27808. set->fxMagic = vst_swap ('FBCh');
  27809. set->version = vst_swap (fxbVersionNum);
  27810. set->fxID = vst_swap (getUID());
  27811. set->fxVersion = vst_swap (getVersionNumber());
  27812. set->numPrograms = vst_swap (numPrograms);
  27813. set->chunkSize = vst_swap ((long) chunk.getSize());
  27814. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27815. }
  27816. else
  27817. {
  27818. MemoryBlock chunk;
  27819. getChunkData (chunk, true, maxSizeMB);
  27820. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27821. dest.setSize (totalLen, true);
  27822. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27823. set->chunkMagic = vst_swap ('CcnK');
  27824. set->byteSize = 0;
  27825. set->fxMagic = vst_swap ('FPCh');
  27826. set->version = vst_swap (fxbVersionNum);
  27827. set->fxID = vst_swap (getUID());
  27828. set->fxVersion = vst_swap (getVersionNumber());
  27829. set->numPrograms = vst_swap (numPrograms);
  27830. set->chunkSize = vst_swap ((long) chunk.getSize());
  27831. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27832. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27833. }
  27834. }
  27835. else
  27836. {
  27837. if (isFXB)
  27838. {
  27839. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27840. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27841. dest.setSize (len, true);
  27842. fxSet* const set = (fxSet*) dest.getData();
  27843. set->chunkMagic = vst_swap ('CcnK');
  27844. set->byteSize = 0;
  27845. set->fxMagic = vst_swap ('FxBk');
  27846. set->version = vst_swap (fxbVersionNum);
  27847. set->fxID = vst_swap (getUID());
  27848. set->fxVersion = vst_swap (getVersionNumber());
  27849. set->numPrograms = vst_swap (numPrograms);
  27850. const int oldProgram = getCurrentProgram();
  27851. MemoryBlock oldSettings;
  27852. createTempParameterStore (oldSettings);
  27853. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27854. for (int i = 0; i < numPrograms; ++i)
  27855. {
  27856. if (i != oldProgram)
  27857. {
  27858. setCurrentProgram (i);
  27859. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27860. }
  27861. }
  27862. setCurrentProgram (oldProgram);
  27863. restoreFromTempParameterStore (oldSettings);
  27864. }
  27865. else
  27866. {
  27867. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27868. dest.setSize (totalLen, true);
  27869. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27870. }
  27871. }
  27872. return true;
  27873. }
  27874. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27875. {
  27876. if (usesChunks())
  27877. {
  27878. void* data = 0;
  27879. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27880. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27881. {
  27882. mb.setSize (bytes);
  27883. mb.copyFrom (data, 0, bytes);
  27884. }
  27885. }
  27886. }
  27887. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27888. {
  27889. if (size > 0 && usesChunks())
  27890. {
  27891. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27892. if (! isPreset)
  27893. updateStoredProgramNames();
  27894. }
  27895. }
  27896. void VSTPluginInstance::timerCallback()
  27897. {
  27898. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27899. stopTimer();
  27900. }
  27901. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27902. {
  27903. const ScopedLock sl (lock);
  27904. ++insideVSTCallback;
  27905. int result = 0;
  27906. try
  27907. {
  27908. if (effect != 0)
  27909. {
  27910. #if JUCE_MAC
  27911. if (module->resFileId != 0)
  27912. UseResFile (module->resFileId);
  27913. CGrafPtr oldPort;
  27914. if (getActiveEditor() != 0)
  27915. {
  27916. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27917. GetPort (&oldPort);
  27918. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27919. SetOrigin (-pos.getX(), -pos.getY());
  27920. }
  27921. #endif
  27922. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27923. #if JUCE_MAC
  27924. if (getActiveEditor() != 0)
  27925. SetPort (oldPort);
  27926. module->resFileId = CurResFile();
  27927. #endif
  27928. --insideVSTCallback;
  27929. return result;
  27930. }
  27931. }
  27932. catch (...)
  27933. {
  27934. }
  27935. --insideVSTCallback;
  27936. return result;
  27937. }
  27938. // handles non plugin-specific callbacks..
  27939. static const int defaultVSTSampleRateValue = 16384;
  27940. static const int defaultVSTBlockSizeValue = 512;
  27941. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27942. {
  27943. (void) index;
  27944. (void) value;
  27945. (void) opt;
  27946. switch (opcode)
  27947. {
  27948. case audioMasterCanDo:
  27949. {
  27950. static const char* canDos[] = { "supplyIdle",
  27951. "sendVstEvents",
  27952. "sendVstMidiEvent",
  27953. "sendVstTimeInfo",
  27954. "receiveVstEvents",
  27955. "receiveVstMidiEvent",
  27956. "supportShell",
  27957. "shellCategory" };
  27958. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27959. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27960. return 1;
  27961. return 0;
  27962. }
  27963. case audioMasterVersion:
  27964. return 0x2400;
  27965. case audioMasterCurrentId:
  27966. return shellUIDToCreate;
  27967. case audioMasterGetNumAutomatableParameters:
  27968. return 0;
  27969. case audioMasterGetAutomationState:
  27970. return 1;
  27971. case audioMasterGetVendorVersion:
  27972. return 0x0101;
  27973. case audioMasterGetVendorString:
  27974. case audioMasterGetProductString:
  27975. {
  27976. String hostName ("Juce VST Host");
  27977. if (JUCEApplication::getInstance() != 0)
  27978. hostName = JUCEApplication::getInstance()->getApplicationName();
  27979. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27980. }
  27981. break;
  27982. case audioMasterGetSampleRate:
  27983. return (VstIntPtr) defaultVSTSampleRateValue;
  27984. case audioMasterGetBlockSize:
  27985. return (VstIntPtr) defaultVSTBlockSizeValue;
  27986. case audioMasterSetOutputSampleRate:
  27987. return 0;
  27988. default:
  27989. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27990. break;
  27991. }
  27992. return 0;
  27993. }
  27994. // handles callbacks for a specific plugin
  27995. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27996. {
  27997. switch (opcode)
  27998. {
  27999. case audioMasterAutomate:
  28000. sendParamChangeMessageToListeners (index, opt);
  28001. break;
  28002. case audioMasterProcessEvents:
  28003. handleMidiFromPlugin ((const VstEvents*) ptr);
  28004. break;
  28005. case audioMasterGetTime:
  28006. #if JUCE_MSVC
  28007. #pragma warning (push)
  28008. #pragma warning (disable: 4311)
  28009. #endif
  28010. return (VstIntPtr) &vstHostTime;
  28011. #if JUCE_MSVC
  28012. #pragma warning (pop)
  28013. #endif
  28014. break;
  28015. case audioMasterIdle:
  28016. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28017. {
  28018. ++insideVSTCallback;
  28019. #if JUCE_MAC
  28020. if (getActiveEditor() != 0)
  28021. dispatch (effEditIdle, 0, 0, 0, 0);
  28022. #endif
  28023. juce_callAnyTimersSynchronously();
  28024. handleUpdateNowIfNeeded();
  28025. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28026. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28027. --insideVSTCallback;
  28028. }
  28029. break;
  28030. case audioMasterUpdateDisplay:
  28031. triggerAsyncUpdate();
  28032. break;
  28033. case audioMasterTempoAt:
  28034. // returns (10000 * bpm)
  28035. break;
  28036. case audioMasterNeedIdle:
  28037. startTimer (50);
  28038. break;
  28039. case audioMasterSizeWindow:
  28040. if (getActiveEditor() != 0)
  28041. getActiveEditor()->setSize (index, value);
  28042. return 1;
  28043. case audioMasterGetSampleRate:
  28044. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28045. case audioMasterGetBlockSize:
  28046. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28047. case audioMasterWantMidi:
  28048. wantsMidiMessages = true;
  28049. break;
  28050. case audioMasterGetDirectory:
  28051. #if JUCE_MAC
  28052. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28053. #else
  28054. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28055. #endif
  28056. case audioMasterGetAutomationState:
  28057. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28058. break;
  28059. // none of these are handled (yet)..
  28060. case audioMasterBeginEdit:
  28061. case audioMasterEndEdit:
  28062. case audioMasterSetTime:
  28063. case audioMasterPinConnected:
  28064. case audioMasterGetParameterQuantization:
  28065. case audioMasterIOChanged:
  28066. case audioMasterGetInputLatency:
  28067. case audioMasterGetOutputLatency:
  28068. case audioMasterGetPreviousPlug:
  28069. case audioMasterGetNextPlug:
  28070. case audioMasterWillReplaceOrAccumulate:
  28071. case audioMasterGetCurrentProcessLevel:
  28072. case audioMasterOfflineStart:
  28073. case audioMasterOfflineRead:
  28074. case audioMasterOfflineWrite:
  28075. case audioMasterOfflineGetCurrentPass:
  28076. case audioMasterOfflineGetCurrentMetaPass:
  28077. case audioMasterVendorSpecific:
  28078. case audioMasterSetIcon:
  28079. case audioMasterGetLanguage:
  28080. case audioMasterOpenWindow:
  28081. case audioMasterCloseWindow:
  28082. break;
  28083. default:
  28084. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28085. }
  28086. return 0;
  28087. }
  28088. // entry point for all callbacks from the plugin
  28089. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28090. {
  28091. try
  28092. {
  28093. if (effect != 0 && effect->resvd2 != 0)
  28094. {
  28095. return ((VSTPluginInstance*)(effect->resvd2))
  28096. ->handleCallback (opcode, index, value, ptr, opt);
  28097. }
  28098. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28099. }
  28100. catch (...)
  28101. {
  28102. return 0;
  28103. }
  28104. }
  28105. const String VSTPluginInstance::getVersion() const throw()
  28106. {
  28107. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28108. String s;
  28109. if (v == 0 || v == -1)
  28110. v = getVersionNumber();
  28111. if (v != 0)
  28112. {
  28113. int versionBits[4];
  28114. int n = 0;
  28115. while (v != 0)
  28116. {
  28117. versionBits [n++] = (v & 0xff);
  28118. v >>= 8;
  28119. }
  28120. s << 'V';
  28121. while (n > 0)
  28122. {
  28123. s << versionBits [--n];
  28124. if (n > 0)
  28125. s << '.';
  28126. }
  28127. }
  28128. return s;
  28129. }
  28130. int VSTPluginInstance::getUID() const throw()
  28131. {
  28132. int uid = effect != 0 ? effect->uniqueID : 0;
  28133. if (uid == 0)
  28134. uid = module->file.hashCode();
  28135. return uid;
  28136. }
  28137. const String VSTPluginInstance::getCategory() const throw()
  28138. {
  28139. const char* result = 0;
  28140. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28141. {
  28142. case kPlugCategEffect:
  28143. result = "Effect";
  28144. break;
  28145. case kPlugCategSynth:
  28146. result = "Synth";
  28147. break;
  28148. case kPlugCategAnalysis:
  28149. result = "Anaylsis";
  28150. break;
  28151. case kPlugCategMastering:
  28152. result = "Mastering";
  28153. break;
  28154. case kPlugCategSpacializer:
  28155. result = "Spacial";
  28156. break;
  28157. case kPlugCategRoomFx:
  28158. result = "Reverb";
  28159. break;
  28160. case kPlugSurroundFx:
  28161. result = "Surround";
  28162. break;
  28163. case kPlugCategRestoration:
  28164. result = "Restoration";
  28165. break;
  28166. case kPlugCategGenerator:
  28167. result = "Tone generation";
  28168. break;
  28169. default:
  28170. break;
  28171. }
  28172. return result;
  28173. }
  28174. float VSTPluginInstance::getParameter (int index)
  28175. {
  28176. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28177. {
  28178. try
  28179. {
  28180. const ScopedLock sl (lock);
  28181. return effect->getParameter (effect, index);
  28182. }
  28183. catch (...)
  28184. {
  28185. }
  28186. }
  28187. return 0.0f;
  28188. }
  28189. void VSTPluginInstance::setParameter (int index, float newValue)
  28190. {
  28191. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28192. {
  28193. try
  28194. {
  28195. const ScopedLock sl (lock);
  28196. if (effect->getParameter (effect, index) != newValue)
  28197. effect->setParameter (effect, index, newValue);
  28198. }
  28199. catch (...)
  28200. {
  28201. }
  28202. }
  28203. }
  28204. const String VSTPluginInstance::getParameterName (int index)
  28205. {
  28206. if (effect != 0)
  28207. {
  28208. jassert (index >= 0 && index < effect->numParams);
  28209. char nm [256];
  28210. zerostruct (nm);
  28211. dispatch (effGetParamName, index, 0, nm, 0);
  28212. return String (nm).trim();
  28213. }
  28214. return String::empty;
  28215. }
  28216. const String VSTPluginInstance::getParameterLabel (int index) const
  28217. {
  28218. if (effect != 0)
  28219. {
  28220. jassert (index >= 0 && index < effect->numParams);
  28221. char nm [256];
  28222. zerostruct (nm);
  28223. dispatch (effGetParamLabel, index, 0, nm, 0);
  28224. return String (nm).trim();
  28225. }
  28226. return String::empty;
  28227. }
  28228. const String VSTPluginInstance::getParameterText (int index)
  28229. {
  28230. if (effect != 0)
  28231. {
  28232. jassert (index >= 0 && index < effect->numParams);
  28233. char nm [256];
  28234. zerostruct (nm);
  28235. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28236. return String (nm).trim();
  28237. }
  28238. return String::empty;
  28239. }
  28240. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28241. {
  28242. if (effect != 0)
  28243. {
  28244. jassert (index >= 0 && index < effect->numParams);
  28245. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28246. }
  28247. return false;
  28248. }
  28249. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28250. {
  28251. dest.setSize (64 + 4 * getNumParameters());
  28252. dest.fillWith (0);
  28253. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28254. float* const p = (float*) (((char*) dest.getData()) + 64);
  28255. for (int i = 0; i < getNumParameters(); ++i)
  28256. p[i] = getParameter(i);
  28257. }
  28258. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28259. {
  28260. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28261. float* p = (float*) (((char*) m.getData()) + 64);
  28262. for (int i = 0; i < getNumParameters(); ++i)
  28263. setParameter (i, p[i]);
  28264. }
  28265. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28266. {
  28267. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28268. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28269. }
  28270. const String VSTPluginInstance::getProgramName (int index)
  28271. {
  28272. if (index == getCurrentProgram())
  28273. {
  28274. return getCurrentProgramName();
  28275. }
  28276. else if (effect != 0)
  28277. {
  28278. char nm [256];
  28279. zerostruct (nm);
  28280. if (dispatch (effGetProgramNameIndexed,
  28281. jlimit (0, getNumPrograms(), index),
  28282. -1, nm, 0) != 0)
  28283. {
  28284. return String (nm).trim();
  28285. }
  28286. }
  28287. return programNames [index];
  28288. }
  28289. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28290. {
  28291. if (index == getCurrentProgram())
  28292. {
  28293. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28294. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28295. }
  28296. else
  28297. {
  28298. jassertfalse; // xxx not implemented!
  28299. }
  28300. }
  28301. void VSTPluginInstance::updateStoredProgramNames()
  28302. {
  28303. if (effect != 0 && getNumPrograms() > 0)
  28304. {
  28305. char nm [256];
  28306. zerostruct (nm);
  28307. // only do this if the plugin can't use indexed names..
  28308. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28309. {
  28310. const int oldProgram = getCurrentProgram();
  28311. MemoryBlock oldSettings;
  28312. createTempParameterStore (oldSettings);
  28313. for (int i = 0; i < getNumPrograms(); ++i)
  28314. {
  28315. setCurrentProgram (i);
  28316. getCurrentProgramName(); // (this updates the list)
  28317. }
  28318. setCurrentProgram (oldProgram);
  28319. restoreFromTempParameterStore (oldSettings);
  28320. }
  28321. }
  28322. }
  28323. const String VSTPluginInstance::getCurrentProgramName()
  28324. {
  28325. if (effect != 0)
  28326. {
  28327. char nm [256];
  28328. zerostruct (nm);
  28329. dispatch (effGetProgramName, 0, 0, nm, 0);
  28330. const int index = getCurrentProgram();
  28331. if (programNames[index].isEmpty())
  28332. {
  28333. while (programNames.size() < index)
  28334. programNames.add (String::empty);
  28335. programNames.set (index, String (nm).trim());
  28336. }
  28337. return String (nm).trim();
  28338. }
  28339. return String::empty;
  28340. }
  28341. const String VSTPluginInstance::getInputChannelName (int index) const
  28342. {
  28343. if (index >= 0 && index < getNumInputChannels())
  28344. {
  28345. VstPinProperties pinProps;
  28346. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28347. return String (pinProps.label, sizeof (pinProps.label));
  28348. }
  28349. return String::empty;
  28350. }
  28351. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28352. {
  28353. if (index < 0 || index >= getNumInputChannels())
  28354. return false;
  28355. VstPinProperties pinProps;
  28356. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28357. return (pinProps.flags & kVstPinIsStereo) != 0;
  28358. return true;
  28359. }
  28360. const String VSTPluginInstance::getOutputChannelName (int index) const
  28361. {
  28362. if (index >= 0 && index < getNumOutputChannels())
  28363. {
  28364. VstPinProperties pinProps;
  28365. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28366. return String (pinProps.label, sizeof (pinProps.label));
  28367. }
  28368. return String::empty;
  28369. }
  28370. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28371. {
  28372. if (index < 0 || index >= getNumOutputChannels())
  28373. return false;
  28374. VstPinProperties pinProps;
  28375. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28376. return (pinProps.flags & kVstPinIsStereo) != 0;
  28377. return true;
  28378. }
  28379. void VSTPluginInstance::setPower (const bool on)
  28380. {
  28381. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28382. isPowerOn = on;
  28383. }
  28384. const int defaultMaxSizeMB = 64;
  28385. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28386. {
  28387. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28388. }
  28389. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28390. {
  28391. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28392. }
  28393. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28394. {
  28395. loadFromFXBFile (data, sizeInBytes);
  28396. }
  28397. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28398. {
  28399. loadFromFXBFile (data, sizeInBytes);
  28400. }
  28401. VSTPluginFormat::VSTPluginFormat()
  28402. {
  28403. }
  28404. VSTPluginFormat::~VSTPluginFormat()
  28405. {
  28406. }
  28407. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28408. const String& fileOrIdentifier)
  28409. {
  28410. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28411. return;
  28412. PluginDescription desc;
  28413. desc.fileOrIdentifier = fileOrIdentifier;
  28414. desc.uid = 0;
  28415. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28416. if (instance == 0)
  28417. return;
  28418. try
  28419. {
  28420. #if JUCE_MAC
  28421. if (instance->module->resFileId != 0)
  28422. UseResFile (instance->module->resFileId);
  28423. #endif
  28424. instance->fillInPluginDescription (desc);
  28425. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28426. if (category != kPlugCategShell)
  28427. {
  28428. // Normal plugin...
  28429. results.add (new PluginDescription (desc));
  28430. ++insideVSTCallback;
  28431. instance->dispatch (effOpen, 0, 0, 0, 0);
  28432. --insideVSTCallback;
  28433. }
  28434. else
  28435. {
  28436. // It's a shell plugin, so iterate all the subtypes...
  28437. char shellEffectName [64];
  28438. for (;;)
  28439. {
  28440. zerostruct (shellEffectName);
  28441. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28442. if (uid == 0)
  28443. {
  28444. break;
  28445. }
  28446. else
  28447. {
  28448. desc.uid = uid;
  28449. desc.name = shellEffectName;
  28450. bool alreadyThere = false;
  28451. for (int i = results.size(); --i >= 0;)
  28452. {
  28453. PluginDescription* const d = results.getUnchecked(i);
  28454. if (d->isDuplicateOf (desc))
  28455. {
  28456. alreadyThere = true;
  28457. break;
  28458. }
  28459. }
  28460. if (! alreadyThere)
  28461. results.add (new PluginDescription (desc));
  28462. }
  28463. }
  28464. }
  28465. }
  28466. catch (...)
  28467. {
  28468. // crashed while loading...
  28469. }
  28470. }
  28471. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28472. {
  28473. ScopedPointer <VSTPluginInstance> result;
  28474. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28475. {
  28476. File file (desc.fileOrIdentifier);
  28477. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28478. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28479. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28480. if (module != 0)
  28481. {
  28482. shellUIDToCreate = desc.uid;
  28483. result = new VSTPluginInstance (module);
  28484. if (result->effect != 0)
  28485. {
  28486. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28487. result->initialise();
  28488. }
  28489. else
  28490. {
  28491. result = 0;
  28492. }
  28493. }
  28494. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28495. }
  28496. return result.release();
  28497. }
  28498. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28499. {
  28500. const File f (fileOrIdentifier);
  28501. #if JUCE_MAC
  28502. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28503. return true;
  28504. #if JUCE_PPC
  28505. FSRef fileRef;
  28506. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28507. {
  28508. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28509. if (resFileId != -1)
  28510. {
  28511. const int numEffects = Count1Resources ('aEff');
  28512. CloseResFile (resFileId);
  28513. if (numEffects > 0)
  28514. return true;
  28515. }
  28516. }
  28517. #endif
  28518. return false;
  28519. #elif JUCE_WINDOWS
  28520. return f.existsAsFile()
  28521. && f.hasFileExtension (".dll");
  28522. #elif JUCE_LINUX
  28523. return f.existsAsFile()
  28524. && f.hasFileExtension (".so");
  28525. #endif
  28526. }
  28527. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28528. {
  28529. return fileOrIdentifier;
  28530. }
  28531. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28532. {
  28533. return File (desc.fileOrIdentifier).exists();
  28534. }
  28535. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28536. {
  28537. StringArray results;
  28538. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28539. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28540. return results;
  28541. }
  28542. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28543. {
  28544. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28545. // .component or .vst directories.
  28546. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28547. while (iter.next())
  28548. {
  28549. const File f (iter.getFile());
  28550. bool isPlugin = false;
  28551. if (fileMightContainThisPluginType (f.getFullPathName()))
  28552. {
  28553. isPlugin = true;
  28554. results.add (f.getFullPathName());
  28555. }
  28556. if (recursive && (! isPlugin) && f.isDirectory())
  28557. recursiveFileSearch (results, f, true);
  28558. }
  28559. }
  28560. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28561. {
  28562. #if JUCE_MAC
  28563. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28564. #elif JUCE_WINDOWS
  28565. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28566. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28567. #elif JUCE_LINUX
  28568. return FileSearchPath ("/usr/lib/vst");
  28569. #endif
  28570. }
  28571. END_JUCE_NAMESPACE
  28572. #endif
  28573. #undef log
  28574. #endif
  28575. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28576. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28577. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28578. BEGIN_JUCE_NAMESPACE
  28579. AudioProcessor::AudioProcessor()
  28580. : playHead (0),
  28581. activeEditor (0),
  28582. sampleRate (0),
  28583. blockSize (0),
  28584. numInputChannels (0),
  28585. numOutputChannels (0),
  28586. latencySamples (0),
  28587. suspended (false),
  28588. nonRealtime (false)
  28589. {
  28590. }
  28591. AudioProcessor::~AudioProcessor()
  28592. {
  28593. // ooh, nasty - the editor should have been deleted before the filter
  28594. // that it refers to is deleted..
  28595. jassert (activeEditor == 0);
  28596. #if JUCE_DEBUG
  28597. // This will fail if you've called beginParameterChangeGesture() for one
  28598. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28599. jassert (changingParams.countNumberOfSetBits() == 0);
  28600. #endif
  28601. }
  28602. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28603. {
  28604. playHead = newPlayHead;
  28605. }
  28606. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28607. {
  28608. const ScopedLock sl (listenerLock);
  28609. listeners.addIfNotAlreadyThere (newListener);
  28610. }
  28611. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28612. {
  28613. const ScopedLock sl (listenerLock);
  28614. listeners.removeValue (listenerToRemove);
  28615. }
  28616. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28617. const int numOuts,
  28618. const double sampleRate_,
  28619. const int blockSize_) throw()
  28620. {
  28621. numInputChannels = numIns;
  28622. numOutputChannels = numOuts;
  28623. sampleRate = sampleRate_;
  28624. blockSize = blockSize_;
  28625. }
  28626. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28627. {
  28628. nonRealtime = nonRealtime_;
  28629. }
  28630. void AudioProcessor::setLatencySamples (const int newLatency)
  28631. {
  28632. if (latencySamples != newLatency)
  28633. {
  28634. latencySamples = newLatency;
  28635. updateHostDisplay();
  28636. }
  28637. }
  28638. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28639. const float newValue)
  28640. {
  28641. setParameter (parameterIndex, newValue);
  28642. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28643. }
  28644. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28645. {
  28646. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28647. for (int i = listeners.size(); --i >= 0;)
  28648. {
  28649. AudioProcessorListener* l;
  28650. {
  28651. const ScopedLock sl (listenerLock);
  28652. l = listeners [i];
  28653. }
  28654. if (l != 0)
  28655. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28656. }
  28657. }
  28658. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28659. {
  28660. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28661. #if JUCE_DEBUG
  28662. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28663. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28664. jassert (! changingParams [parameterIndex]);
  28665. changingParams.setBit (parameterIndex);
  28666. #endif
  28667. for (int i = listeners.size(); --i >= 0;)
  28668. {
  28669. AudioProcessorListener* l;
  28670. {
  28671. const ScopedLock sl (listenerLock);
  28672. l = listeners [i];
  28673. }
  28674. if (l != 0)
  28675. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28676. }
  28677. }
  28678. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28679. {
  28680. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28681. #if JUCE_DEBUG
  28682. // This means you've called endParameterChangeGesture without having previously called
  28683. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28684. // calls matched correctly.
  28685. jassert (changingParams [parameterIndex]);
  28686. changingParams.clearBit (parameterIndex);
  28687. #endif
  28688. for (int i = listeners.size(); --i >= 0;)
  28689. {
  28690. AudioProcessorListener* l;
  28691. {
  28692. const ScopedLock sl (listenerLock);
  28693. l = listeners [i];
  28694. }
  28695. if (l != 0)
  28696. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28697. }
  28698. }
  28699. void AudioProcessor::updateHostDisplay()
  28700. {
  28701. for (int i = listeners.size(); --i >= 0;)
  28702. {
  28703. AudioProcessorListener* l;
  28704. {
  28705. const ScopedLock sl (listenerLock);
  28706. l = listeners [i];
  28707. }
  28708. if (l != 0)
  28709. l->audioProcessorChanged (this);
  28710. }
  28711. }
  28712. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28713. {
  28714. return true;
  28715. }
  28716. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28717. {
  28718. return false;
  28719. }
  28720. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28721. {
  28722. const ScopedLock sl (callbackLock);
  28723. suspended = shouldBeSuspended;
  28724. }
  28725. void AudioProcessor::reset()
  28726. {
  28727. }
  28728. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28729. {
  28730. const ScopedLock sl (callbackLock);
  28731. jassert (activeEditor == editor);
  28732. if (activeEditor == editor)
  28733. activeEditor = 0;
  28734. }
  28735. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28736. {
  28737. if (activeEditor != 0)
  28738. return activeEditor;
  28739. AudioProcessorEditor* const ed = createEditor();
  28740. if (ed != 0)
  28741. {
  28742. // you must give your editor comp a size before returning it..
  28743. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28744. const ScopedLock sl (callbackLock);
  28745. activeEditor = ed;
  28746. }
  28747. return ed;
  28748. }
  28749. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28750. {
  28751. getStateInformation (destData);
  28752. }
  28753. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28754. {
  28755. setStateInformation (data, sizeInBytes);
  28756. }
  28757. // magic number to identify memory blocks that we've stored as XML
  28758. const uint32 magicXmlNumber = 0x21324356;
  28759. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28760. JUCE_NAMESPACE::MemoryBlock& destData)
  28761. {
  28762. const String xmlString (xml.createDocument (String::empty, true, false));
  28763. const int stringLength = xmlString.getNumBytesAsUTF8();
  28764. destData.setSize (stringLength + 10);
  28765. char* const d = (char*) destData.getData();
  28766. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28767. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28768. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28769. }
  28770. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28771. const int sizeInBytes)
  28772. {
  28773. if (sizeInBytes > 8
  28774. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28775. {
  28776. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28777. if (stringLength > 0)
  28778. {
  28779. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28780. jmin ((sizeInBytes - 8), stringLength)));
  28781. return doc.getDocumentElement();
  28782. }
  28783. }
  28784. return 0;
  28785. }
  28786. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28787. {
  28788. }
  28789. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28790. {
  28791. }
  28792. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28793. {
  28794. return timeInSeconds == other.timeInSeconds
  28795. && ppqPosition == other.ppqPosition
  28796. && editOriginTime == other.editOriginTime
  28797. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28798. && frameRate == other.frameRate
  28799. && isPlaying == other.isPlaying
  28800. && isRecording == other.isRecording
  28801. && bpm == other.bpm
  28802. && timeSigNumerator == other.timeSigNumerator
  28803. && timeSigDenominator == other.timeSigDenominator;
  28804. }
  28805. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28806. {
  28807. return ! operator== (other);
  28808. }
  28809. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28810. {
  28811. zerostruct (*this);
  28812. timeSigNumerator = 4;
  28813. timeSigDenominator = 4;
  28814. bpm = 120;
  28815. }
  28816. END_JUCE_NAMESPACE
  28817. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28818. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28819. BEGIN_JUCE_NAMESPACE
  28820. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28821. : owner (owner_)
  28822. {
  28823. // the filter must be valid..
  28824. jassert (owner != 0);
  28825. }
  28826. AudioProcessorEditor::~AudioProcessorEditor()
  28827. {
  28828. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28829. // filter for some reason..
  28830. jassert (owner->getActiveEditor() != this);
  28831. }
  28832. END_JUCE_NAMESPACE
  28833. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28834. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28835. BEGIN_JUCE_NAMESPACE
  28836. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28837. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28838. : id (id_),
  28839. processor (processor_),
  28840. isPrepared (false)
  28841. {
  28842. jassert (processor_ != 0);
  28843. }
  28844. AudioProcessorGraph::Node::~Node()
  28845. {
  28846. }
  28847. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28848. AudioProcessorGraph* const graph)
  28849. {
  28850. if (! isPrepared)
  28851. {
  28852. isPrepared = true;
  28853. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28854. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28855. if (ioProc != 0)
  28856. ioProc->setParentGraph (graph);
  28857. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28858. processor->getNumOutputChannels(),
  28859. sampleRate, blockSize);
  28860. processor->prepareToPlay (sampleRate, blockSize);
  28861. }
  28862. }
  28863. void AudioProcessorGraph::Node::unprepare()
  28864. {
  28865. if (isPrepared)
  28866. {
  28867. isPrepared = false;
  28868. processor->releaseResources();
  28869. }
  28870. }
  28871. AudioProcessorGraph::AudioProcessorGraph()
  28872. : lastNodeId (0),
  28873. renderingBuffers (1, 1),
  28874. currentAudioOutputBuffer (1, 1)
  28875. {
  28876. }
  28877. AudioProcessorGraph::~AudioProcessorGraph()
  28878. {
  28879. clearRenderingSequence();
  28880. clear();
  28881. }
  28882. const String AudioProcessorGraph::getName() const
  28883. {
  28884. return "Audio Graph";
  28885. }
  28886. void AudioProcessorGraph::clear()
  28887. {
  28888. nodes.clear();
  28889. connections.clear();
  28890. triggerAsyncUpdate();
  28891. }
  28892. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28893. {
  28894. for (int i = nodes.size(); --i >= 0;)
  28895. if (nodes.getUnchecked(i)->id == nodeId)
  28896. return nodes.getUnchecked(i);
  28897. return 0;
  28898. }
  28899. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28900. uint32 nodeId)
  28901. {
  28902. if (newProcessor == 0)
  28903. {
  28904. jassertfalse;
  28905. return 0;
  28906. }
  28907. if (nodeId == 0)
  28908. {
  28909. nodeId = ++lastNodeId;
  28910. }
  28911. else
  28912. {
  28913. // you can't add a node with an id that already exists in the graph..
  28914. jassert (getNodeForId (nodeId) == 0);
  28915. removeNode (nodeId);
  28916. }
  28917. lastNodeId = nodeId;
  28918. Node* const n = new Node (nodeId, newProcessor);
  28919. nodes.add (n);
  28920. triggerAsyncUpdate();
  28921. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28922. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28923. if (ioProc != 0)
  28924. ioProc->setParentGraph (this);
  28925. return n;
  28926. }
  28927. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28928. {
  28929. disconnectNode (nodeId);
  28930. for (int i = nodes.size(); --i >= 0;)
  28931. {
  28932. if (nodes.getUnchecked(i)->id == nodeId)
  28933. {
  28934. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28935. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28936. if (ioProc != 0)
  28937. ioProc->setParentGraph (0);
  28938. nodes.remove (i);
  28939. triggerAsyncUpdate();
  28940. return true;
  28941. }
  28942. }
  28943. return false;
  28944. }
  28945. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28946. const int sourceChannelIndex,
  28947. const uint32 destNodeId,
  28948. const int destChannelIndex) const
  28949. {
  28950. for (int i = connections.size(); --i >= 0;)
  28951. {
  28952. const Connection* const c = connections.getUnchecked(i);
  28953. if (c->sourceNodeId == sourceNodeId
  28954. && c->destNodeId == destNodeId
  28955. && c->sourceChannelIndex == sourceChannelIndex
  28956. && c->destChannelIndex == destChannelIndex)
  28957. {
  28958. return c;
  28959. }
  28960. }
  28961. return 0;
  28962. }
  28963. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28964. const uint32 possibleDestNodeId) const
  28965. {
  28966. for (int i = connections.size(); --i >= 0;)
  28967. {
  28968. const Connection* const c = connections.getUnchecked(i);
  28969. if (c->sourceNodeId == possibleSourceNodeId
  28970. && c->destNodeId == possibleDestNodeId)
  28971. {
  28972. return true;
  28973. }
  28974. }
  28975. return false;
  28976. }
  28977. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28978. const int sourceChannelIndex,
  28979. const uint32 destNodeId,
  28980. const int destChannelIndex) const
  28981. {
  28982. if (sourceChannelIndex < 0
  28983. || destChannelIndex < 0
  28984. || sourceNodeId == destNodeId
  28985. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28986. return false;
  28987. const Node* const source = getNodeForId (sourceNodeId);
  28988. if (source == 0
  28989. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28990. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28991. return false;
  28992. const Node* const dest = getNodeForId (destNodeId);
  28993. if (dest == 0
  28994. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28995. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28996. return false;
  28997. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28998. destNodeId, destChannelIndex) == 0;
  28999. }
  29000. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29001. const int sourceChannelIndex,
  29002. const uint32 destNodeId,
  29003. const int destChannelIndex)
  29004. {
  29005. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29006. return false;
  29007. Connection* const c = new Connection();
  29008. c->sourceNodeId = sourceNodeId;
  29009. c->sourceChannelIndex = sourceChannelIndex;
  29010. c->destNodeId = destNodeId;
  29011. c->destChannelIndex = destChannelIndex;
  29012. connections.add (c);
  29013. triggerAsyncUpdate();
  29014. return true;
  29015. }
  29016. void AudioProcessorGraph::removeConnection (const int index)
  29017. {
  29018. connections.remove (index);
  29019. triggerAsyncUpdate();
  29020. }
  29021. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29022. const uint32 destNodeId, const int destChannelIndex)
  29023. {
  29024. bool doneAnything = false;
  29025. for (int i = connections.size(); --i >= 0;)
  29026. {
  29027. const Connection* const c = connections.getUnchecked(i);
  29028. if (c->sourceNodeId == sourceNodeId
  29029. && c->destNodeId == destNodeId
  29030. && c->sourceChannelIndex == sourceChannelIndex
  29031. && c->destChannelIndex == destChannelIndex)
  29032. {
  29033. removeConnection (i);
  29034. doneAnything = true;
  29035. triggerAsyncUpdate();
  29036. }
  29037. }
  29038. return doneAnything;
  29039. }
  29040. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29041. {
  29042. bool doneAnything = false;
  29043. for (int i = connections.size(); --i >= 0;)
  29044. {
  29045. const Connection* const c = connections.getUnchecked(i);
  29046. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29047. {
  29048. removeConnection (i);
  29049. doneAnything = true;
  29050. triggerAsyncUpdate();
  29051. }
  29052. }
  29053. return doneAnything;
  29054. }
  29055. bool AudioProcessorGraph::removeIllegalConnections()
  29056. {
  29057. bool doneAnything = false;
  29058. for (int i = connections.size(); --i >= 0;)
  29059. {
  29060. const Connection* const c = connections.getUnchecked(i);
  29061. const Node* const source = getNodeForId (c->sourceNodeId);
  29062. const Node* const dest = getNodeForId (c->destNodeId);
  29063. if (source == 0 || dest == 0
  29064. || (c->sourceChannelIndex != midiChannelIndex
  29065. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29066. || (c->sourceChannelIndex == midiChannelIndex
  29067. && ! source->processor->producesMidi())
  29068. || (c->destChannelIndex != midiChannelIndex
  29069. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29070. || (c->destChannelIndex == midiChannelIndex
  29071. && ! dest->processor->acceptsMidi()))
  29072. {
  29073. removeConnection (i);
  29074. doneAnything = true;
  29075. triggerAsyncUpdate();
  29076. }
  29077. }
  29078. return doneAnything;
  29079. }
  29080. namespace GraphRenderingOps
  29081. {
  29082. class AudioGraphRenderingOp
  29083. {
  29084. public:
  29085. AudioGraphRenderingOp() {}
  29086. virtual ~AudioGraphRenderingOp() {}
  29087. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29088. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29089. const int numSamples) = 0;
  29090. juce_UseDebuggingNewOperator
  29091. };
  29092. class ClearChannelOp : public AudioGraphRenderingOp
  29093. {
  29094. public:
  29095. ClearChannelOp (const int channelNum_)
  29096. : channelNum (channelNum_)
  29097. {}
  29098. ~ClearChannelOp() {}
  29099. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29100. {
  29101. sharedBufferChans.clear (channelNum, 0, numSamples);
  29102. }
  29103. private:
  29104. const int channelNum;
  29105. ClearChannelOp (const ClearChannelOp&);
  29106. ClearChannelOp& operator= (const ClearChannelOp&);
  29107. };
  29108. class CopyChannelOp : public AudioGraphRenderingOp
  29109. {
  29110. public:
  29111. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29112. : srcChannelNum (srcChannelNum_),
  29113. dstChannelNum (dstChannelNum_)
  29114. {}
  29115. ~CopyChannelOp() {}
  29116. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29117. {
  29118. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29119. }
  29120. private:
  29121. const int srcChannelNum, dstChannelNum;
  29122. CopyChannelOp (const CopyChannelOp&);
  29123. CopyChannelOp& operator= (const CopyChannelOp&);
  29124. };
  29125. class AddChannelOp : public AudioGraphRenderingOp
  29126. {
  29127. public:
  29128. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29129. : srcChannelNum (srcChannelNum_),
  29130. dstChannelNum (dstChannelNum_)
  29131. {}
  29132. ~AddChannelOp() {}
  29133. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29134. {
  29135. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29136. }
  29137. private:
  29138. const int srcChannelNum, dstChannelNum;
  29139. AddChannelOp (const AddChannelOp&);
  29140. AddChannelOp& operator= (const AddChannelOp&);
  29141. };
  29142. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29143. {
  29144. public:
  29145. ClearMidiBufferOp (const int bufferNum_)
  29146. : bufferNum (bufferNum_)
  29147. {}
  29148. ~ClearMidiBufferOp() {}
  29149. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29150. {
  29151. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29152. }
  29153. private:
  29154. const int bufferNum;
  29155. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29156. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29157. };
  29158. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29159. {
  29160. public:
  29161. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29162. : srcBufferNum (srcBufferNum_),
  29163. dstBufferNum (dstBufferNum_)
  29164. {}
  29165. ~CopyMidiBufferOp() {}
  29166. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29167. {
  29168. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29169. }
  29170. private:
  29171. const int srcBufferNum, dstBufferNum;
  29172. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29173. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29174. };
  29175. class AddMidiBufferOp : public AudioGraphRenderingOp
  29176. {
  29177. public:
  29178. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29179. : srcBufferNum (srcBufferNum_),
  29180. dstBufferNum (dstBufferNum_)
  29181. {}
  29182. ~AddMidiBufferOp() {}
  29183. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29184. {
  29185. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29186. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29187. }
  29188. private:
  29189. const int srcBufferNum, dstBufferNum;
  29190. AddMidiBufferOp (const AddMidiBufferOp&);
  29191. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29192. };
  29193. class ProcessBufferOp : public AudioGraphRenderingOp
  29194. {
  29195. public:
  29196. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29197. const Array <int>& audioChannelsToUse_,
  29198. const int totalChans_,
  29199. const int midiBufferToUse_)
  29200. : node (node_),
  29201. processor (node_->getProcessor()),
  29202. audioChannelsToUse (audioChannelsToUse_),
  29203. totalChans (jmax (1, totalChans_)),
  29204. midiBufferToUse (midiBufferToUse_)
  29205. {
  29206. channels.calloc (totalChans);
  29207. while (audioChannelsToUse.size() < totalChans)
  29208. audioChannelsToUse.add (0);
  29209. }
  29210. ~ProcessBufferOp()
  29211. {
  29212. }
  29213. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29214. {
  29215. for (int i = totalChans; --i >= 0;)
  29216. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29217. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29218. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29219. }
  29220. const AudioProcessorGraph::Node::Ptr node;
  29221. AudioProcessor* const processor;
  29222. private:
  29223. Array <int> audioChannelsToUse;
  29224. HeapBlock <float*> channels;
  29225. int totalChans;
  29226. int midiBufferToUse;
  29227. ProcessBufferOp (const ProcessBufferOp&);
  29228. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29229. };
  29230. /** Used to calculate the correct sequence of rendering ops needed, based on
  29231. the best re-use of shared buffers at each stage.
  29232. */
  29233. class RenderingOpSequenceCalculator
  29234. {
  29235. public:
  29236. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29237. const Array<void*>& orderedNodes_,
  29238. Array<void*>& renderingOps)
  29239. : graph (graph_),
  29240. orderedNodes (orderedNodes_)
  29241. {
  29242. nodeIds.add (-2); // first buffer is read-only zeros
  29243. channels.add (0);
  29244. midiNodeIds.add (-2);
  29245. for (int i = 0; i < orderedNodes.size(); ++i)
  29246. {
  29247. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29248. renderingOps, i);
  29249. markAnyUnusedBuffersAsFree (i);
  29250. }
  29251. }
  29252. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29253. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29254. juce_UseDebuggingNewOperator
  29255. private:
  29256. AudioProcessorGraph& graph;
  29257. const Array<void*>& orderedNodes;
  29258. Array <int> nodeIds, channels, midiNodeIds;
  29259. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29260. Array<void*>& renderingOps,
  29261. const int ourRenderingIndex)
  29262. {
  29263. const int numIns = node->getProcessor()->getNumInputChannels();
  29264. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29265. const int totalChans = jmax (numIns, numOuts);
  29266. Array <int> audioChannelsToUse;
  29267. int midiBufferToUse = -1;
  29268. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29269. {
  29270. // get a list of all the inputs to this node
  29271. Array <int> sourceNodes, sourceOutputChans;
  29272. for (int i = graph.getNumConnections(); --i >= 0;)
  29273. {
  29274. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29275. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29276. {
  29277. sourceNodes.add (c->sourceNodeId);
  29278. sourceOutputChans.add (c->sourceChannelIndex);
  29279. }
  29280. }
  29281. int bufIndex = -1;
  29282. if (sourceNodes.size() == 0)
  29283. {
  29284. // unconnected input channel
  29285. if (inputChan >= numOuts)
  29286. {
  29287. bufIndex = getReadOnlyEmptyBuffer();
  29288. jassert (bufIndex >= 0);
  29289. }
  29290. else
  29291. {
  29292. bufIndex = getFreeBuffer (false);
  29293. renderingOps.add (new ClearChannelOp (bufIndex));
  29294. }
  29295. }
  29296. else if (sourceNodes.size() == 1)
  29297. {
  29298. // channel with a straightforward single input..
  29299. const int srcNode = sourceNodes.getUnchecked(0);
  29300. const int srcChan = sourceOutputChans.getUnchecked(0);
  29301. bufIndex = getBufferContaining (srcNode, srcChan);
  29302. if (bufIndex < 0)
  29303. {
  29304. // if not found, this is probably a feedback loop
  29305. bufIndex = getReadOnlyEmptyBuffer();
  29306. jassert (bufIndex >= 0);
  29307. }
  29308. if (inputChan < numOuts
  29309. && isBufferNeededLater (ourRenderingIndex,
  29310. inputChan,
  29311. srcNode, srcChan))
  29312. {
  29313. // can't mess up this channel because it's needed later by another node, so we
  29314. // need to use a copy of it..
  29315. const int newFreeBuffer = getFreeBuffer (false);
  29316. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29317. bufIndex = newFreeBuffer;
  29318. }
  29319. }
  29320. else
  29321. {
  29322. // channel with a mix of several inputs..
  29323. // try to find a re-usable channel from our inputs..
  29324. int reusableInputIndex = -1;
  29325. for (int i = 0; i < sourceNodes.size(); ++i)
  29326. {
  29327. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29328. sourceOutputChans.getUnchecked(i));
  29329. if (sourceBufIndex >= 0
  29330. && ! isBufferNeededLater (ourRenderingIndex,
  29331. inputChan,
  29332. sourceNodes.getUnchecked(i),
  29333. sourceOutputChans.getUnchecked(i)))
  29334. {
  29335. // we've found one of our input chans that can be re-used..
  29336. reusableInputIndex = i;
  29337. bufIndex = sourceBufIndex;
  29338. break;
  29339. }
  29340. }
  29341. if (reusableInputIndex < 0)
  29342. {
  29343. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29344. bufIndex = getFreeBuffer (false);
  29345. jassert (bufIndex != 0);
  29346. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29347. sourceOutputChans.getUnchecked (0));
  29348. if (srcIndex < 0)
  29349. {
  29350. // if not found, this is probably a feedback loop
  29351. renderingOps.add (new ClearChannelOp (bufIndex));
  29352. }
  29353. else
  29354. {
  29355. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29356. }
  29357. reusableInputIndex = 0;
  29358. }
  29359. for (int j = 0; j < sourceNodes.size(); ++j)
  29360. {
  29361. if (j != reusableInputIndex)
  29362. {
  29363. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29364. sourceOutputChans.getUnchecked(j));
  29365. if (srcIndex >= 0)
  29366. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29367. }
  29368. }
  29369. }
  29370. jassert (bufIndex >= 0);
  29371. audioChannelsToUse.add (bufIndex);
  29372. if (inputChan < numOuts)
  29373. markBufferAsContaining (bufIndex, node->id, inputChan);
  29374. }
  29375. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29376. {
  29377. const int bufIndex = getFreeBuffer (false);
  29378. jassert (bufIndex != 0);
  29379. audioChannelsToUse.add (bufIndex);
  29380. markBufferAsContaining (bufIndex, node->id, outputChan);
  29381. }
  29382. // Now the same thing for midi..
  29383. Array <int> midiSourceNodes;
  29384. for (int i = graph.getNumConnections(); --i >= 0;)
  29385. {
  29386. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29387. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29388. midiSourceNodes.add (c->sourceNodeId);
  29389. }
  29390. if (midiSourceNodes.size() == 0)
  29391. {
  29392. // No midi inputs..
  29393. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29394. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29395. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29396. }
  29397. else if (midiSourceNodes.size() == 1)
  29398. {
  29399. // One midi input..
  29400. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29401. AudioProcessorGraph::midiChannelIndex);
  29402. if (midiBufferToUse >= 0)
  29403. {
  29404. if (isBufferNeededLater (ourRenderingIndex,
  29405. AudioProcessorGraph::midiChannelIndex,
  29406. midiSourceNodes.getUnchecked(0),
  29407. AudioProcessorGraph::midiChannelIndex))
  29408. {
  29409. // can't mess up this channel because it's needed later by another node, so we
  29410. // need to use a copy of it..
  29411. const int newFreeBuffer = getFreeBuffer (true);
  29412. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29413. midiBufferToUse = newFreeBuffer;
  29414. }
  29415. }
  29416. else
  29417. {
  29418. // probably a feedback loop, so just use an empty one..
  29419. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29420. }
  29421. }
  29422. else
  29423. {
  29424. // More than one midi input being mixed..
  29425. int reusableInputIndex = -1;
  29426. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29427. {
  29428. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29429. AudioProcessorGraph::midiChannelIndex);
  29430. if (sourceBufIndex >= 0
  29431. && ! isBufferNeededLater (ourRenderingIndex,
  29432. AudioProcessorGraph::midiChannelIndex,
  29433. midiSourceNodes.getUnchecked(i),
  29434. AudioProcessorGraph::midiChannelIndex))
  29435. {
  29436. // we've found one of our input buffers that can be re-used..
  29437. reusableInputIndex = i;
  29438. midiBufferToUse = sourceBufIndex;
  29439. break;
  29440. }
  29441. }
  29442. if (reusableInputIndex < 0)
  29443. {
  29444. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29445. midiBufferToUse = getFreeBuffer (true);
  29446. jassert (midiBufferToUse >= 0);
  29447. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29448. AudioProcessorGraph::midiChannelIndex);
  29449. if (srcIndex >= 0)
  29450. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29451. else
  29452. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29453. reusableInputIndex = 0;
  29454. }
  29455. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29456. {
  29457. if (j != reusableInputIndex)
  29458. {
  29459. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29460. AudioProcessorGraph::midiChannelIndex);
  29461. if (srcIndex >= 0)
  29462. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29463. }
  29464. }
  29465. }
  29466. if (node->getProcessor()->producesMidi())
  29467. markBufferAsContaining (midiBufferToUse, node->id,
  29468. AudioProcessorGraph::midiChannelIndex);
  29469. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29470. totalChans, midiBufferToUse));
  29471. }
  29472. int getFreeBuffer (const bool forMidi)
  29473. {
  29474. if (forMidi)
  29475. {
  29476. for (int i = 1; i < midiNodeIds.size(); ++i)
  29477. if (midiNodeIds.getUnchecked(i) < 0)
  29478. return i;
  29479. midiNodeIds.add (-1);
  29480. return midiNodeIds.size() - 1;
  29481. }
  29482. else
  29483. {
  29484. for (int i = 1; i < nodeIds.size(); ++i)
  29485. if (nodeIds.getUnchecked(i) < 0)
  29486. return i;
  29487. nodeIds.add (-1);
  29488. channels.add (0);
  29489. return nodeIds.size() - 1;
  29490. }
  29491. }
  29492. int getReadOnlyEmptyBuffer() const
  29493. {
  29494. return 0;
  29495. }
  29496. int getBufferContaining (const int nodeId, const int outputChannel) const
  29497. {
  29498. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29499. {
  29500. for (int i = midiNodeIds.size(); --i >= 0;)
  29501. if (midiNodeIds.getUnchecked(i) == nodeId)
  29502. return i;
  29503. }
  29504. else
  29505. {
  29506. for (int i = nodeIds.size(); --i >= 0;)
  29507. if (nodeIds.getUnchecked(i) == nodeId
  29508. && channels.getUnchecked(i) == outputChannel)
  29509. return i;
  29510. }
  29511. return -1;
  29512. }
  29513. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29514. {
  29515. int i;
  29516. for (i = 0; i < nodeIds.size(); ++i)
  29517. {
  29518. if (nodeIds.getUnchecked(i) >= 0
  29519. && ! isBufferNeededLater (stepIndex, -1,
  29520. nodeIds.getUnchecked(i),
  29521. channels.getUnchecked(i)))
  29522. {
  29523. nodeIds.set (i, -1);
  29524. }
  29525. }
  29526. for (i = 0; i < midiNodeIds.size(); ++i)
  29527. {
  29528. if (midiNodeIds.getUnchecked(i) >= 0
  29529. && ! isBufferNeededLater (stepIndex, -1,
  29530. midiNodeIds.getUnchecked(i),
  29531. AudioProcessorGraph::midiChannelIndex))
  29532. {
  29533. midiNodeIds.set (i, -1);
  29534. }
  29535. }
  29536. }
  29537. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29538. int inputChannelOfIndexToIgnore,
  29539. const int nodeId,
  29540. const int outputChanIndex) const
  29541. {
  29542. while (stepIndexToSearchFrom < orderedNodes.size())
  29543. {
  29544. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29545. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29546. {
  29547. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29548. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29549. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29550. return true;
  29551. }
  29552. else
  29553. {
  29554. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29555. if (i != inputChannelOfIndexToIgnore
  29556. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29557. node->id, i) != 0)
  29558. return true;
  29559. }
  29560. inputChannelOfIndexToIgnore = -1;
  29561. ++stepIndexToSearchFrom;
  29562. }
  29563. return false;
  29564. }
  29565. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29566. {
  29567. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29568. {
  29569. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29570. midiNodeIds.set (bufferNum, nodeId);
  29571. }
  29572. else
  29573. {
  29574. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29575. nodeIds.set (bufferNum, nodeId);
  29576. channels.set (bufferNum, outputIndex);
  29577. }
  29578. }
  29579. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29580. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29581. };
  29582. }
  29583. void AudioProcessorGraph::clearRenderingSequence()
  29584. {
  29585. const ScopedLock sl (renderLock);
  29586. for (int i = renderingOps.size(); --i >= 0;)
  29587. {
  29588. GraphRenderingOps::AudioGraphRenderingOp* const r
  29589. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29590. renderingOps.remove (i);
  29591. delete r;
  29592. }
  29593. }
  29594. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29595. const uint32 possibleDestinationId,
  29596. const int recursionCheck) const
  29597. {
  29598. if (recursionCheck > 0)
  29599. {
  29600. for (int i = connections.size(); --i >= 0;)
  29601. {
  29602. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29603. if (c->destNodeId == possibleDestinationId
  29604. && (c->sourceNodeId == possibleInputId
  29605. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29606. return true;
  29607. }
  29608. }
  29609. return false;
  29610. }
  29611. void AudioProcessorGraph::buildRenderingSequence()
  29612. {
  29613. Array<void*> newRenderingOps;
  29614. int numRenderingBuffersNeeded = 2;
  29615. int numMidiBuffersNeeded = 1;
  29616. {
  29617. MessageManagerLock mml;
  29618. Array<void*> orderedNodes;
  29619. int i;
  29620. for (i = 0; i < nodes.size(); ++i)
  29621. {
  29622. Node* const node = nodes.getUnchecked(i);
  29623. node->prepare (getSampleRate(), getBlockSize(), this);
  29624. int j = 0;
  29625. for (; j < orderedNodes.size(); ++j)
  29626. if (isAnInputTo (node->id,
  29627. ((Node*) orderedNodes.getUnchecked (j))->id,
  29628. nodes.size() + 1))
  29629. break;
  29630. orderedNodes.insert (j, node);
  29631. }
  29632. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29633. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29634. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29635. }
  29636. Array<void*> oldRenderingOps (renderingOps);
  29637. {
  29638. // swap over to the new rendering sequence..
  29639. const ScopedLock sl (renderLock);
  29640. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29641. renderingBuffers.clear();
  29642. for (int i = midiBuffers.size(); --i >= 0;)
  29643. midiBuffers.getUnchecked(i)->clear();
  29644. while (midiBuffers.size() < numMidiBuffersNeeded)
  29645. midiBuffers.add (new MidiBuffer());
  29646. renderingOps = newRenderingOps;
  29647. }
  29648. for (int i = oldRenderingOps.size(); --i >= 0;)
  29649. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29650. }
  29651. void AudioProcessorGraph::handleAsyncUpdate()
  29652. {
  29653. buildRenderingSequence();
  29654. }
  29655. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29656. {
  29657. currentAudioInputBuffer = 0;
  29658. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29659. currentMidiInputBuffer = 0;
  29660. currentMidiOutputBuffer.clear();
  29661. clearRenderingSequence();
  29662. buildRenderingSequence();
  29663. }
  29664. void AudioProcessorGraph::releaseResources()
  29665. {
  29666. for (int i = 0; i < nodes.size(); ++i)
  29667. nodes.getUnchecked(i)->unprepare();
  29668. renderingBuffers.setSize (1, 1);
  29669. midiBuffers.clear();
  29670. currentAudioInputBuffer = 0;
  29671. currentAudioOutputBuffer.setSize (1, 1);
  29672. currentMidiInputBuffer = 0;
  29673. currentMidiOutputBuffer.clear();
  29674. }
  29675. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29676. {
  29677. const int numSamples = buffer.getNumSamples();
  29678. const ScopedLock sl (renderLock);
  29679. currentAudioInputBuffer = &buffer;
  29680. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29681. currentAudioOutputBuffer.clear();
  29682. currentMidiInputBuffer = &midiMessages;
  29683. currentMidiOutputBuffer.clear();
  29684. int i;
  29685. for (i = 0; i < renderingOps.size(); ++i)
  29686. {
  29687. GraphRenderingOps::AudioGraphRenderingOp* const op
  29688. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29689. op->perform (renderingBuffers, midiBuffers, numSamples);
  29690. }
  29691. for (i = 0; i < buffer.getNumChannels(); ++i)
  29692. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29693. midiMessages.clear();
  29694. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29695. }
  29696. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29697. {
  29698. return "Input " + String (channelIndex + 1);
  29699. }
  29700. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29701. {
  29702. return "Output " + String (channelIndex + 1);
  29703. }
  29704. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29705. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29706. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29707. bool AudioProcessorGraph::producesMidi() const { return true; }
  29708. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29709. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29710. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29711. : type (type_),
  29712. graph (0)
  29713. {
  29714. }
  29715. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29716. {
  29717. }
  29718. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29719. {
  29720. switch (type)
  29721. {
  29722. case audioOutputNode: return "Audio Output";
  29723. case audioInputNode: return "Audio Input";
  29724. case midiOutputNode: return "Midi Output";
  29725. case midiInputNode: return "Midi Input";
  29726. default: break;
  29727. }
  29728. return String::empty;
  29729. }
  29730. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29731. {
  29732. d.name = getName();
  29733. d.uid = d.name.hashCode();
  29734. d.category = "I/O devices";
  29735. d.pluginFormatName = "Internal";
  29736. d.manufacturerName = "Raw Material Software";
  29737. d.version = "1.0";
  29738. d.isInstrument = false;
  29739. d.numInputChannels = getNumInputChannels();
  29740. if (type == audioOutputNode && graph != 0)
  29741. d.numInputChannels = graph->getNumInputChannels();
  29742. d.numOutputChannels = getNumOutputChannels();
  29743. if (type == audioInputNode && graph != 0)
  29744. d.numOutputChannels = graph->getNumOutputChannels();
  29745. }
  29746. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29747. {
  29748. jassert (graph != 0);
  29749. }
  29750. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29751. {
  29752. }
  29753. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29754. MidiBuffer& midiMessages)
  29755. {
  29756. jassert (graph != 0);
  29757. switch (type)
  29758. {
  29759. case audioOutputNode:
  29760. {
  29761. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29762. buffer.getNumChannels()); --i >= 0;)
  29763. {
  29764. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29765. }
  29766. break;
  29767. }
  29768. case audioInputNode:
  29769. {
  29770. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29771. buffer.getNumChannels()); --i >= 0;)
  29772. {
  29773. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29774. }
  29775. break;
  29776. }
  29777. case midiOutputNode:
  29778. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29779. break;
  29780. case midiInputNode:
  29781. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29782. break;
  29783. default:
  29784. break;
  29785. }
  29786. }
  29787. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29788. {
  29789. return type == midiOutputNode;
  29790. }
  29791. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29792. {
  29793. return type == midiInputNode;
  29794. }
  29795. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29796. {
  29797. switch (type)
  29798. {
  29799. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29800. case midiOutputNode: return "Midi Output";
  29801. default: break;
  29802. }
  29803. return String::empty;
  29804. }
  29805. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29806. {
  29807. switch (type)
  29808. {
  29809. case audioInputNode: return "Input " + String (channelIndex + 1);
  29810. case midiInputNode: return "Midi Input";
  29811. default: break;
  29812. }
  29813. return String::empty;
  29814. }
  29815. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29816. {
  29817. return type == audioInputNode || type == audioOutputNode;
  29818. }
  29819. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29820. {
  29821. return isInputChannelStereoPair (index);
  29822. }
  29823. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29824. {
  29825. return type == audioInputNode || type == midiInputNode;
  29826. }
  29827. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29828. {
  29829. return type == audioOutputNode || type == midiOutputNode;
  29830. }
  29831. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29832. {
  29833. return 0;
  29834. }
  29835. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29836. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29837. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29838. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29839. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29840. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29841. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29842. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29843. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29844. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29845. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29846. {
  29847. }
  29848. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29849. {
  29850. }
  29851. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29852. {
  29853. graph = newGraph;
  29854. if (graph != 0)
  29855. {
  29856. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29857. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29858. getSampleRate(),
  29859. getBlockSize());
  29860. updateHostDisplay();
  29861. }
  29862. }
  29863. END_JUCE_NAMESPACE
  29864. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29865. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29866. BEGIN_JUCE_NAMESPACE
  29867. AudioProcessorPlayer::AudioProcessorPlayer()
  29868. : processor (0),
  29869. sampleRate (0),
  29870. blockSize (0),
  29871. isPrepared (false),
  29872. numInputChans (0),
  29873. numOutputChans (0),
  29874. tempBuffer (1, 1)
  29875. {
  29876. }
  29877. AudioProcessorPlayer::~AudioProcessorPlayer()
  29878. {
  29879. setProcessor (0);
  29880. }
  29881. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29882. {
  29883. if (processor != processorToPlay)
  29884. {
  29885. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29886. {
  29887. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29888. sampleRate, blockSize);
  29889. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29890. }
  29891. AudioProcessor* oldOne;
  29892. {
  29893. const ScopedLock sl (lock);
  29894. oldOne = isPrepared ? processor : 0;
  29895. processor = processorToPlay;
  29896. isPrepared = true;
  29897. }
  29898. if (oldOne != 0)
  29899. oldOne->releaseResources();
  29900. }
  29901. }
  29902. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29903. const int numInputChannels,
  29904. float** const outputChannelData,
  29905. const int numOutputChannels,
  29906. const int numSamples)
  29907. {
  29908. // these should have been prepared by audioDeviceAboutToStart()...
  29909. jassert (sampleRate > 0 && blockSize > 0);
  29910. incomingMidi.clear();
  29911. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29912. int i, totalNumChans = 0;
  29913. if (numInputChannels > numOutputChannels)
  29914. {
  29915. // if there aren't enough output channels for the number of
  29916. // inputs, we need to create some temporary extra ones (can't
  29917. // use the input data in case it gets written to)
  29918. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29919. false, false, true);
  29920. for (i = 0; i < numOutputChannels; ++i)
  29921. {
  29922. channels[totalNumChans] = outputChannelData[i];
  29923. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29924. ++totalNumChans;
  29925. }
  29926. for (i = numOutputChannels; i < numInputChannels; ++i)
  29927. {
  29928. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29929. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29930. ++totalNumChans;
  29931. }
  29932. }
  29933. else
  29934. {
  29935. for (i = 0; i < numInputChannels; ++i)
  29936. {
  29937. channels[totalNumChans] = outputChannelData[i];
  29938. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29939. ++totalNumChans;
  29940. }
  29941. for (i = numInputChannels; i < numOutputChannels; ++i)
  29942. {
  29943. channels[totalNumChans] = outputChannelData[i];
  29944. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29945. ++totalNumChans;
  29946. }
  29947. }
  29948. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29949. const ScopedLock sl (lock);
  29950. if (processor != 0)
  29951. {
  29952. const ScopedLock sl (processor->getCallbackLock());
  29953. if (processor->isSuspended())
  29954. {
  29955. for (i = 0; i < numOutputChannels; ++i)
  29956. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29957. }
  29958. else
  29959. {
  29960. processor->processBlock (buffer, incomingMidi);
  29961. }
  29962. }
  29963. }
  29964. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29965. {
  29966. const ScopedLock sl (lock);
  29967. sampleRate = device->getCurrentSampleRate();
  29968. blockSize = device->getCurrentBufferSizeSamples();
  29969. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29970. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29971. messageCollector.reset (sampleRate);
  29972. zeromem (channels, sizeof (channels));
  29973. if (processor != 0)
  29974. {
  29975. if (isPrepared)
  29976. processor->releaseResources();
  29977. AudioProcessor* const oldProcessor = processor;
  29978. setProcessor (0);
  29979. setProcessor (oldProcessor);
  29980. }
  29981. }
  29982. void AudioProcessorPlayer::audioDeviceStopped()
  29983. {
  29984. const ScopedLock sl (lock);
  29985. if (processor != 0 && isPrepared)
  29986. processor->releaseResources();
  29987. sampleRate = 0.0;
  29988. blockSize = 0;
  29989. isPrepared = false;
  29990. tempBuffer.setSize (1, 1);
  29991. }
  29992. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29993. {
  29994. messageCollector.addMessageToQueue (message);
  29995. }
  29996. END_JUCE_NAMESPACE
  29997. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29998. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29999. BEGIN_JUCE_NAMESPACE
  30000. class ProcessorParameterPropertyComp : public PropertyComponent,
  30001. public AudioProcessorListener,
  30002. public AsyncUpdater
  30003. {
  30004. public:
  30005. ProcessorParameterPropertyComp (const String& name,
  30006. AudioProcessor* const owner_,
  30007. const int index_)
  30008. : PropertyComponent (name),
  30009. owner (owner_),
  30010. index (index_)
  30011. {
  30012. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  30013. owner_->addListener (this);
  30014. }
  30015. ~ProcessorParameterPropertyComp()
  30016. {
  30017. owner->removeListener (this);
  30018. deleteAllChildren();
  30019. }
  30020. void refresh()
  30021. {
  30022. slider->setValue (owner->getParameter (index), false);
  30023. }
  30024. void audioProcessorChanged (AudioProcessor*) {}
  30025. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30026. {
  30027. if (parameterIndex == index)
  30028. triggerAsyncUpdate();
  30029. }
  30030. void handleAsyncUpdate()
  30031. {
  30032. refresh();
  30033. }
  30034. juce_UseDebuggingNewOperator
  30035. private:
  30036. AudioProcessor* const owner;
  30037. const int index;
  30038. Slider* slider;
  30039. class ParamSlider : public Slider
  30040. {
  30041. public:
  30042. ParamSlider (AudioProcessor* const owner_, const int index_)
  30043. : Slider (String::empty),
  30044. owner (owner_),
  30045. index (index_)
  30046. {
  30047. setRange (0.0, 1.0, 0.0);
  30048. setSliderStyle (Slider::LinearBar);
  30049. setTextBoxIsEditable (false);
  30050. setScrollWheelEnabled (false);
  30051. }
  30052. ~ParamSlider()
  30053. {
  30054. }
  30055. void valueChanged()
  30056. {
  30057. const float newVal = (float) getValue();
  30058. if (owner->getParameter (index) != newVal)
  30059. owner->setParameter (index, newVal);
  30060. }
  30061. const String getTextFromValue (double /*value*/)
  30062. {
  30063. return owner->getParameterText (index);
  30064. }
  30065. juce_UseDebuggingNewOperator
  30066. private:
  30067. AudioProcessor* const owner;
  30068. const int index;
  30069. ParamSlider (const ParamSlider&);
  30070. ParamSlider& operator= (const ParamSlider&);
  30071. };
  30072. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30073. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30074. };
  30075. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30076. : AudioProcessorEditor (owner_)
  30077. {
  30078. setOpaque (true);
  30079. addAndMakeVisible (panel = new PropertyPanel());
  30080. Array <PropertyComponent*> params;
  30081. const int numParams = owner_->getNumParameters();
  30082. int totalHeight = 0;
  30083. for (int i = 0; i < numParams; ++i)
  30084. {
  30085. String name (owner_->getParameterName (i));
  30086. if (name.trim().isEmpty())
  30087. name = "Unnamed";
  30088. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  30089. params.add (pc);
  30090. totalHeight += pc->getPreferredHeight();
  30091. }
  30092. panel->addProperties (params);
  30093. setSize (400, jlimit (25, 400, totalHeight));
  30094. }
  30095. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30096. {
  30097. deleteAllChildren();
  30098. }
  30099. void GenericAudioProcessorEditor::paint (Graphics& g)
  30100. {
  30101. g.fillAll (Colours::white);
  30102. }
  30103. void GenericAudioProcessorEditor::resized()
  30104. {
  30105. panel->setSize (getWidth(), getHeight());
  30106. }
  30107. END_JUCE_NAMESPACE
  30108. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30109. /*** Start of inlined file: juce_Sampler.cpp ***/
  30110. BEGIN_JUCE_NAMESPACE
  30111. SamplerSound::SamplerSound (const String& name_,
  30112. AudioFormatReader& source,
  30113. const BigInteger& midiNotes_,
  30114. const int midiNoteForNormalPitch,
  30115. const double attackTimeSecs,
  30116. const double releaseTimeSecs,
  30117. const double maxSampleLengthSeconds)
  30118. : name (name_),
  30119. midiNotes (midiNotes_),
  30120. midiRootNote (midiNoteForNormalPitch)
  30121. {
  30122. sourceSampleRate = source.sampleRate;
  30123. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30124. {
  30125. length = 0;
  30126. attackSamples = 0;
  30127. releaseSamples = 0;
  30128. }
  30129. else
  30130. {
  30131. length = jmin ((int) source.lengthInSamples,
  30132. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30133. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30134. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30135. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30136. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30137. }
  30138. }
  30139. SamplerSound::~SamplerSound()
  30140. {
  30141. }
  30142. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30143. {
  30144. return midiNotes [midiNoteNumber];
  30145. }
  30146. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30147. {
  30148. return true;
  30149. }
  30150. SamplerVoice::SamplerVoice()
  30151. : pitchRatio (0.0),
  30152. sourceSamplePosition (0.0),
  30153. lgain (0.0f),
  30154. rgain (0.0f),
  30155. isInAttack (false),
  30156. isInRelease (false)
  30157. {
  30158. }
  30159. SamplerVoice::~SamplerVoice()
  30160. {
  30161. }
  30162. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30163. {
  30164. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30165. }
  30166. void SamplerVoice::startNote (const int midiNoteNumber,
  30167. const float velocity,
  30168. SynthesiserSound* s,
  30169. const int /*currentPitchWheelPosition*/)
  30170. {
  30171. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30172. jassert (sound != 0); // this object can only play SamplerSounds!
  30173. if (sound != 0)
  30174. {
  30175. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30176. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30177. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30178. sourceSamplePosition = 0.0;
  30179. lgain = velocity;
  30180. rgain = velocity;
  30181. isInAttack = (sound->attackSamples > 0);
  30182. isInRelease = false;
  30183. if (isInAttack)
  30184. {
  30185. attackReleaseLevel = 0.0f;
  30186. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30187. }
  30188. else
  30189. {
  30190. attackReleaseLevel = 1.0f;
  30191. attackDelta = 0.0f;
  30192. }
  30193. if (sound->releaseSamples > 0)
  30194. {
  30195. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30196. }
  30197. else
  30198. {
  30199. releaseDelta = 0.0f;
  30200. }
  30201. }
  30202. }
  30203. void SamplerVoice::stopNote (const bool allowTailOff)
  30204. {
  30205. if (allowTailOff)
  30206. {
  30207. isInAttack = false;
  30208. isInRelease = true;
  30209. }
  30210. else
  30211. {
  30212. clearCurrentNote();
  30213. }
  30214. }
  30215. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30216. {
  30217. }
  30218. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30219. const int /*newValue*/)
  30220. {
  30221. }
  30222. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30223. {
  30224. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30225. if (playingSound != 0)
  30226. {
  30227. const float* const inL = playingSound->data->getSampleData (0, 0);
  30228. const float* const inR = playingSound->data->getNumChannels() > 1
  30229. ? playingSound->data->getSampleData (1, 0) : 0;
  30230. float* outL = outputBuffer.getSampleData (0, startSample);
  30231. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30232. while (--numSamples >= 0)
  30233. {
  30234. const int pos = (int) sourceSamplePosition;
  30235. const float alpha = (float) (sourceSamplePosition - pos);
  30236. const float invAlpha = 1.0f - alpha;
  30237. // just using a very simple linear interpolation here..
  30238. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30239. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30240. : l;
  30241. l *= lgain;
  30242. r *= rgain;
  30243. if (isInAttack)
  30244. {
  30245. l *= attackReleaseLevel;
  30246. r *= attackReleaseLevel;
  30247. attackReleaseLevel += attackDelta;
  30248. if (attackReleaseLevel >= 1.0f)
  30249. {
  30250. attackReleaseLevel = 1.0f;
  30251. isInAttack = false;
  30252. }
  30253. }
  30254. else if (isInRelease)
  30255. {
  30256. l *= attackReleaseLevel;
  30257. r *= attackReleaseLevel;
  30258. attackReleaseLevel += releaseDelta;
  30259. if (attackReleaseLevel <= 0.0f)
  30260. {
  30261. stopNote (false);
  30262. break;
  30263. }
  30264. }
  30265. if (outR != 0)
  30266. {
  30267. *outL++ += l;
  30268. *outR++ += r;
  30269. }
  30270. else
  30271. {
  30272. *outL++ += (l + r) * 0.5f;
  30273. }
  30274. sourceSamplePosition += pitchRatio;
  30275. if (sourceSamplePosition > playingSound->length)
  30276. {
  30277. stopNote (false);
  30278. break;
  30279. }
  30280. }
  30281. }
  30282. }
  30283. END_JUCE_NAMESPACE
  30284. /*** End of inlined file: juce_Sampler.cpp ***/
  30285. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30286. BEGIN_JUCE_NAMESPACE
  30287. SynthesiserSound::SynthesiserSound()
  30288. {
  30289. }
  30290. SynthesiserSound::~SynthesiserSound()
  30291. {
  30292. }
  30293. SynthesiserVoice::SynthesiserVoice()
  30294. : currentSampleRate (44100.0),
  30295. currentlyPlayingNote (-1),
  30296. noteOnTime (0),
  30297. currentlyPlayingSound (0)
  30298. {
  30299. }
  30300. SynthesiserVoice::~SynthesiserVoice()
  30301. {
  30302. }
  30303. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30304. {
  30305. return currentlyPlayingSound != 0
  30306. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30307. }
  30308. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30309. {
  30310. currentSampleRate = newRate;
  30311. }
  30312. void SynthesiserVoice::clearCurrentNote()
  30313. {
  30314. currentlyPlayingNote = -1;
  30315. currentlyPlayingSound = 0;
  30316. }
  30317. Synthesiser::Synthesiser()
  30318. : sampleRate (0),
  30319. lastNoteOnCounter (0),
  30320. shouldStealNotes (true)
  30321. {
  30322. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30323. lastPitchWheelValues[i] = 0x2000;
  30324. }
  30325. Synthesiser::~Synthesiser()
  30326. {
  30327. }
  30328. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30329. {
  30330. const ScopedLock sl (lock);
  30331. return voices [index];
  30332. }
  30333. void Synthesiser::clearVoices()
  30334. {
  30335. const ScopedLock sl (lock);
  30336. voices.clear();
  30337. }
  30338. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30339. {
  30340. const ScopedLock sl (lock);
  30341. voices.add (newVoice);
  30342. }
  30343. void Synthesiser::removeVoice (const int index)
  30344. {
  30345. const ScopedLock sl (lock);
  30346. voices.remove (index);
  30347. }
  30348. void Synthesiser::clearSounds()
  30349. {
  30350. const ScopedLock sl (lock);
  30351. sounds.clear();
  30352. }
  30353. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30354. {
  30355. const ScopedLock sl (lock);
  30356. sounds.add (newSound);
  30357. }
  30358. void Synthesiser::removeSound (const int index)
  30359. {
  30360. const ScopedLock sl (lock);
  30361. sounds.remove (index);
  30362. }
  30363. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30364. {
  30365. shouldStealNotes = shouldStealNotes_;
  30366. }
  30367. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30368. {
  30369. if (sampleRate != newRate)
  30370. {
  30371. const ScopedLock sl (lock);
  30372. allNotesOff (0, false);
  30373. sampleRate = newRate;
  30374. for (int i = voices.size(); --i >= 0;)
  30375. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30376. }
  30377. }
  30378. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30379. const MidiBuffer& midiData,
  30380. int startSample,
  30381. int numSamples)
  30382. {
  30383. // must set the sample rate before using this!
  30384. jassert (sampleRate != 0);
  30385. const ScopedLock sl (lock);
  30386. MidiBuffer::Iterator midiIterator (midiData);
  30387. midiIterator.setNextSamplePosition (startSample);
  30388. MidiMessage m (0xf4, 0.0);
  30389. while (numSamples > 0)
  30390. {
  30391. int midiEventPos;
  30392. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30393. && midiEventPos < startSample + numSamples;
  30394. const int numThisTime = useEvent ? midiEventPos - startSample
  30395. : numSamples;
  30396. if (numThisTime > 0)
  30397. {
  30398. for (int i = voices.size(); --i >= 0;)
  30399. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30400. }
  30401. if (useEvent)
  30402. {
  30403. if (m.isNoteOn())
  30404. {
  30405. const int channel = m.getChannel();
  30406. noteOn (channel,
  30407. m.getNoteNumber(),
  30408. m.getFloatVelocity());
  30409. }
  30410. else if (m.isNoteOff())
  30411. {
  30412. noteOff (m.getChannel(),
  30413. m.getNoteNumber(),
  30414. true);
  30415. }
  30416. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30417. {
  30418. allNotesOff (m.getChannel(), true);
  30419. }
  30420. else if (m.isPitchWheel())
  30421. {
  30422. const int channel = m.getChannel();
  30423. const int wheelPos = m.getPitchWheelValue();
  30424. lastPitchWheelValues [channel - 1] = wheelPos;
  30425. handlePitchWheel (channel, wheelPos);
  30426. }
  30427. else if (m.isController())
  30428. {
  30429. handleController (m.getChannel(),
  30430. m.getControllerNumber(),
  30431. m.getControllerValue());
  30432. }
  30433. }
  30434. startSample += numThisTime;
  30435. numSamples -= numThisTime;
  30436. }
  30437. }
  30438. void Synthesiser::noteOn (const int midiChannel,
  30439. const int midiNoteNumber,
  30440. const float velocity)
  30441. {
  30442. const ScopedLock sl (lock);
  30443. for (int i = sounds.size(); --i >= 0;)
  30444. {
  30445. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30446. if (sound->appliesToNote (midiNoteNumber)
  30447. && sound->appliesToChannel (midiChannel))
  30448. {
  30449. startVoice (findFreeVoice (sound, shouldStealNotes),
  30450. sound, midiChannel, midiNoteNumber, velocity);
  30451. }
  30452. }
  30453. }
  30454. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30455. SynthesiserSound* const sound,
  30456. const int midiChannel,
  30457. const int midiNoteNumber,
  30458. const float velocity)
  30459. {
  30460. if (voice != 0 && sound != 0)
  30461. {
  30462. if (voice->currentlyPlayingSound != 0)
  30463. voice->stopNote (false);
  30464. voice->startNote (midiNoteNumber,
  30465. velocity,
  30466. sound,
  30467. lastPitchWheelValues [midiChannel - 1]);
  30468. voice->currentlyPlayingNote = midiNoteNumber;
  30469. voice->noteOnTime = ++lastNoteOnCounter;
  30470. voice->currentlyPlayingSound = sound;
  30471. }
  30472. }
  30473. void Synthesiser::noteOff (const int midiChannel,
  30474. const int midiNoteNumber,
  30475. const bool allowTailOff)
  30476. {
  30477. const ScopedLock sl (lock);
  30478. for (int i = voices.size(); --i >= 0;)
  30479. {
  30480. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30481. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30482. {
  30483. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30484. if (sound != 0
  30485. && sound->appliesToNote (midiNoteNumber)
  30486. && sound->appliesToChannel (midiChannel))
  30487. {
  30488. voice->stopNote (allowTailOff);
  30489. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30490. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30491. }
  30492. }
  30493. }
  30494. }
  30495. void Synthesiser::allNotesOff (const int midiChannel,
  30496. const bool allowTailOff)
  30497. {
  30498. const ScopedLock sl (lock);
  30499. for (int i = voices.size(); --i >= 0;)
  30500. {
  30501. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30502. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30503. voice->stopNote (allowTailOff);
  30504. }
  30505. }
  30506. void Synthesiser::handlePitchWheel (const int midiChannel,
  30507. const int wheelValue)
  30508. {
  30509. const ScopedLock sl (lock);
  30510. for (int i = voices.size(); --i >= 0;)
  30511. {
  30512. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30513. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30514. {
  30515. voice->pitchWheelMoved (wheelValue);
  30516. }
  30517. }
  30518. }
  30519. void Synthesiser::handleController (const int midiChannel,
  30520. const int controllerNumber,
  30521. const int controllerValue)
  30522. {
  30523. const ScopedLock sl (lock);
  30524. for (int i = voices.size(); --i >= 0;)
  30525. {
  30526. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30527. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30528. voice->controllerMoved (controllerNumber, controllerValue);
  30529. }
  30530. }
  30531. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30532. const bool stealIfNoneAvailable) const
  30533. {
  30534. const ScopedLock sl (lock);
  30535. for (int i = voices.size(); --i >= 0;)
  30536. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30537. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30538. return voices.getUnchecked (i);
  30539. if (stealIfNoneAvailable)
  30540. {
  30541. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30542. SynthesiserVoice* oldest = 0;
  30543. for (int i = voices.size(); --i >= 0;)
  30544. {
  30545. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30546. if (voice->canPlaySound (soundToPlay)
  30547. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30548. oldest = voice;
  30549. }
  30550. jassert (oldest != 0);
  30551. return oldest;
  30552. }
  30553. return 0;
  30554. }
  30555. END_JUCE_NAMESPACE
  30556. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30557. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30558. BEGIN_JUCE_NAMESPACE
  30559. ActionBroadcaster::ActionBroadcaster() throw()
  30560. {
  30561. // are you trying to create this object before or after juce has been intialised??
  30562. jassert (MessageManager::instance != 0);
  30563. }
  30564. ActionBroadcaster::~ActionBroadcaster()
  30565. {
  30566. // all event-based objects must be deleted BEFORE juce is shut down!
  30567. jassert (MessageManager::instance != 0);
  30568. }
  30569. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30570. {
  30571. actionListenerList.addActionListener (listener);
  30572. }
  30573. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30574. {
  30575. jassert (actionListenerList.isValidMessageListener());
  30576. if (actionListenerList.isValidMessageListener())
  30577. actionListenerList.removeActionListener (listener);
  30578. }
  30579. void ActionBroadcaster::removeAllActionListeners()
  30580. {
  30581. actionListenerList.removeAllActionListeners();
  30582. }
  30583. void ActionBroadcaster::sendActionMessage (const String& message) const
  30584. {
  30585. actionListenerList.sendActionMessage (message);
  30586. }
  30587. END_JUCE_NAMESPACE
  30588. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30589. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30590. BEGIN_JUCE_NAMESPACE
  30591. // special message of our own with a string in it
  30592. class ActionMessage : public Message
  30593. {
  30594. public:
  30595. const String message;
  30596. ActionMessage (const String& messageText, void* const listener_) throw()
  30597. : message (messageText)
  30598. {
  30599. pointerParameter = listener_;
  30600. }
  30601. ~ActionMessage() throw()
  30602. {
  30603. }
  30604. private:
  30605. ActionMessage (const ActionMessage&);
  30606. ActionMessage& operator= (const ActionMessage&);
  30607. };
  30608. ActionListenerList::ActionListenerList()
  30609. {
  30610. }
  30611. ActionListenerList::~ActionListenerList()
  30612. {
  30613. }
  30614. void ActionListenerList::addActionListener (ActionListener* const listener)
  30615. {
  30616. const ScopedLock sl (actionListenerLock_);
  30617. jassert (listener != 0);
  30618. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30619. if (listener != 0)
  30620. actionListeners_.add (listener);
  30621. }
  30622. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30623. {
  30624. const ScopedLock sl (actionListenerLock_);
  30625. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30626. actionListeners_.removeValue (listener);
  30627. }
  30628. void ActionListenerList::removeAllActionListeners()
  30629. {
  30630. const ScopedLock sl (actionListenerLock_);
  30631. actionListeners_.clear();
  30632. }
  30633. void ActionListenerList::sendActionMessage (const String& message) const
  30634. {
  30635. const ScopedLock sl (actionListenerLock_);
  30636. for (int i = actionListeners_.size(); --i >= 0;)
  30637. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30638. }
  30639. void ActionListenerList::handleMessage (const Message& message)
  30640. {
  30641. const ActionMessage& am = (const ActionMessage&) message;
  30642. if (actionListeners_.contains (am.pointerParameter))
  30643. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30644. }
  30645. END_JUCE_NAMESPACE
  30646. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30647. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30648. BEGIN_JUCE_NAMESPACE
  30649. AsyncUpdater::AsyncUpdater() throw()
  30650. : asyncMessagePending (false)
  30651. {
  30652. internalAsyncHandler.owner = this;
  30653. }
  30654. AsyncUpdater::~AsyncUpdater()
  30655. {
  30656. }
  30657. void AsyncUpdater::triggerAsyncUpdate()
  30658. {
  30659. if (! asyncMessagePending)
  30660. {
  30661. asyncMessagePending = true;
  30662. internalAsyncHandler.postMessage (new Message());
  30663. }
  30664. }
  30665. void AsyncUpdater::cancelPendingUpdate() throw()
  30666. {
  30667. asyncMessagePending = false;
  30668. }
  30669. void AsyncUpdater::handleUpdateNowIfNeeded()
  30670. {
  30671. if (asyncMessagePending)
  30672. {
  30673. asyncMessagePending = false;
  30674. handleAsyncUpdate();
  30675. }
  30676. }
  30677. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30678. {
  30679. owner->handleUpdateNowIfNeeded();
  30680. }
  30681. END_JUCE_NAMESPACE
  30682. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30683. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30684. BEGIN_JUCE_NAMESPACE
  30685. ChangeBroadcaster::ChangeBroadcaster() throw()
  30686. {
  30687. // are you trying to create this object before or after juce has been intialised??
  30688. jassert (MessageManager::instance != 0);
  30689. }
  30690. ChangeBroadcaster::~ChangeBroadcaster()
  30691. {
  30692. // all event-based objects must be deleted BEFORE juce is shut down!
  30693. jassert (MessageManager::instance != 0);
  30694. }
  30695. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30696. {
  30697. changeListenerList.addChangeListener (listener);
  30698. }
  30699. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30700. {
  30701. jassert (changeListenerList.isValidMessageListener());
  30702. if (changeListenerList.isValidMessageListener())
  30703. changeListenerList.removeChangeListener (listener);
  30704. }
  30705. void ChangeBroadcaster::removeAllChangeListeners()
  30706. {
  30707. changeListenerList.removeAllChangeListeners();
  30708. }
  30709. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30710. {
  30711. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30712. }
  30713. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30714. {
  30715. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30716. }
  30717. void ChangeBroadcaster::dispatchPendingMessages()
  30718. {
  30719. changeListenerList.dispatchPendingMessages();
  30720. }
  30721. END_JUCE_NAMESPACE
  30722. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30723. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30724. BEGIN_JUCE_NAMESPACE
  30725. ChangeListenerList::ChangeListenerList()
  30726. : lastChangedObject (0),
  30727. messagePending (false)
  30728. {
  30729. }
  30730. ChangeListenerList::~ChangeListenerList()
  30731. {
  30732. }
  30733. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30734. {
  30735. const ScopedLock sl (lock);
  30736. jassert (listener != 0);
  30737. if (listener != 0)
  30738. listeners.add (listener);
  30739. }
  30740. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30741. {
  30742. const ScopedLock sl (lock);
  30743. listeners.removeValue (listener);
  30744. }
  30745. void ChangeListenerList::removeAllChangeListeners()
  30746. {
  30747. const ScopedLock sl (lock);
  30748. listeners.clear();
  30749. }
  30750. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30751. {
  30752. const ScopedLock sl (lock);
  30753. if ((! messagePending) && (listeners.size() > 0))
  30754. {
  30755. lastChangedObject = objectThatHasChanged;
  30756. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30757. messagePending = true;
  30758. }
  30759. }
  30760. void ChangeListenerList::handleMessage (const Message& message)
  30761. {
  30762. sendSynchronousChangeMessage (message.pointerParameter);
  30763. }
  30764. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30765. {
  30766. const ScopedLock sl (lock);
  30767. messagePending = false;
  30768. for (int i = listeners.size(); --i >= 0;)
  30769. {
  30770. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30771. {
  30772. const ScopedUnlock tempUnlocker (lock);
  30773. l->changeListenerCallback (objectThatHasChanged);
  30774. }
  30775. i = jmin (i, listeners.size());
  30776. }
  30777. }
  30778. void ChangeListenerList::dispatchPendingMessages()
  30779. {
  30780. if (messagePending)
  30781. sendSynchronousChangeMessage (lastChangedObject);
  30782. }
  30783. END_JUCE_NAMESPACE
  30784. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30785. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30786. BEGIN_JUCE_NAMESPACE
  30787. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30788. const uint32 magicMessageHeaderNumber)
  30789. : Thread ("Juce IPC connection"),
  30790. callbackConnectionState (false),
  30791. useMessageThread (callbacksOnMessageThread),
  30792. magicMessageHeader (magicMessageHeaderNumber),
  30793. pipeReceiveMessageTimeout (-1)
  30794. {
  30795. }
  30796. InterprocessConnection::~InterprocessConnection()
  30797. {
  30798. callbackConnectionState = false;
  30799. disconnect();
  30800. }
  30801. bool InterprocessConnection::connectToSocket (const String& hostName,
  30802. const int portNumber,
  30803. const int timeOutMillisecs)
  30804. {
  30805. disconnect();
  30806. const ScopedLock sl (pipeAndSocketLock);
  30807. socket = new StreamingSocket();
  30808. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30809. {
  30810. connectionMadeInt();
  30811. startThread();
  30812. return true;
  30813. }
  30814. else
  30815. {
  30816. socket = 0;
  30817. return false;
  30818. }
  30819. }
  30820. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30821. const int pipeReceiveMessageTimeoutMs)
  30822. {
  30823. disconnect();
  30824. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30825. if (newPipe->openExisting (pipeName))
  30826. {
  30827. const ScopedLock sl (pipeAndSocketLock);
  30828. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30829. initialiseWithPipe (newPipe.release());
  30830. return true;
  30831. }
  30832. return false;
  30833. }
  30834. bool InterprocessConnection::createPipe (const String& pipeName,
  30835. const int pipeReceiveMessageTimeoutMs)
  30836. {
  30837. disconnect();
  30838. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30839. if (newPipe->createNewPipe (pipeName))
  30840. {
  30841. const ScopedLock sl (pipeAndSocketLock);
  30842. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30843. initialiseWithPipe (newPipe.release());
  30844. return true;
  30845. }
  30846. return false;
  30847. }
  30848. void InterprocessConnection::disconnect()
  30849. {
  30850. if (socket != 0)
  30851. socket->close();
  30852. if (pipe != 0)
  30853. {
  30854. pipe->cancelPendingReads();
  30855. pipe->close();
  30856. }
  30857. stopThread (4000);
  30858. {
  30859. const ScopedLock sl (pipeAndSocketLock);
  30860. socket = 0;
  30861. pipe = 0;
  30862. }
  30863. connectionLostInt();
  30864. }
  30865. bool InterprocessConnection::isConnected() const
  30866. {
  30867. const ScopedLock sl (pipeAndSocketLock);
  30868. return ((socket != 0 && socket->isConnected())
  30869. || (pipe != 0 && pipe->isOpen()))
  30870. && isThreadRunning();
  30871. }
  30872. const String InterprocessConnection::getConnectedHostName() const
  30873. {
  30874. if (pipe != 0)
  30875. {
  30876. return "localhost";
  30877. }
  30878. else if (socket != 0)
  30879. {
  30880. if (! socket->isLocal())
  30881. return socket->getHostName();
  30882. return "localhost";
  30883. }
  30884. return String::empty;
  30885. }
  30886. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30887. {
  30888. uint32 messageHeader[2];
  30889. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30890. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30891. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30892. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30893. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30894. size_t bytesWritten = 0;
  30895. const ScopedLock sl (pipeAndSocketLock);
  30896. if (socket != 0)
  30897. {
  30898. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30899. }
  30900. else if (pipe != 0)
  30901. {
  30902. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30903. }
  30904. if (bytesWritten < 0)
  30905. {
  30906. // error..
  30907. return false;
  30908. }
  30909. return (bytesWritten == messageData.getSize());
  30910. }
  30911. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30912. {
  30913. jassert (socket == 0);
  30914. socket = socket_;
  30915. connectionMadeInt();
  30916. startThread();
  30917. }
  30918. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30919. {
  30920. jassert (pipe == 0);
  30921. pipe = pipe_;
  30922. connectionMadeInt();
  30923. startThread();
  30924. }
  30925. const int messageMagicNumber = 0xb734128b;
  30926. void InterprocessConnection::handleMessage (const Message& message)
  30927. {
  30928. if (message.intParameter1 == messageMagicNumber)
  30929. {
  30930. switch (message.intParameter2)
  30931. {
  30932. case 0:
  30933. {
  30934. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30935. messageReceived (*data);
  30936. break;
  30937. }
  30938. case 1:
  30939. connectionMade();
  30940. break;
  30941. case 2:
  30942. connectionLost();
  30943. break;
  30944. }
  30945. }
  30946. }
  30947. void InterprocessConnection::connectionMadeInt()
  30948. {
  30949. if (! callbackConnectionState)
  30950. {
  30951. callbackConnectionState = true;
  30952. if (useMessageThread)
  30953. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30954. else
  30955. connectionMade();
  30956. }
  30957. }
  30958. void InterprocessConnection::connectionLostInt()
  30959. {
  30960. if (callbackConnectionState)
  30961. {
  30962. callbackConnectionState = false;
  30963. if (useMessageThread)
  30964. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30965. else
  30966. connectionLost();
  30967. }
  30968. }
  30969. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30970. {
  30971. jassert (callbackConnectionState);
  30972. if (useMessageThread)
  30973. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30974. else
  30975. messageReceived (data);
  30976. }
  30977. bool InterprocessConnection::readNextMessageInt()
  30978. {
  30979. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30980. uint32 messageHeader[2];
  30981. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30982. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30983. if (bytes == sizeof (messageHeader)
  30984. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30985. {
  30986. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30987. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30988. {
  30989. MemoryBlock messageData (bytesInMessage, true);
  30990. int bytesRead = 0;
  30991. while (bytesInMessage > 0)
  30992. {
  30993. if (threadShouldExit())
  30994. return false;
  30995. const int numThisTime = jmin (bytesInMessage, 65536);
  30996. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30997. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30998. if (bytesIn <= 0)
  30999. break;
  31000. bytesRead += bytesIn;
  31001. bytesInMessage -= bytesIn;
  31002. }
  31003. if (bytesRead >= 0)
  31004. deliverDataInt (messageData);
  31005. }
  31006. }
  31007. else if (bytes < 0)
  31008. {
  31009. {
  31010. const ScopedLock sl (pipeAndSocketLock);
  31011. socket = 0;
  31012. }
  31013. connectionLostInt();
  31014. return false;
  31015. }
  31016. return true;
  31017. }
  31018. void InterprocessConnection::run()
  31019. {
  31020. while (! threadShouldExit())
  31021. {
  31022. if (socket != 0)
  31023. {
  31024. const int ready = socket->waitUntilReady (true, 0);
  31025. if (ready < 0)
  31026. {
  31027. {
  31028. const ScopedLock sl (pipeAndSocketLock);
  31029. socket = 0;
  31030. }
  31031. connectionLostInt();
  31032. break;
  31033. }
  31034. else if (ready > 0)
  31035. {
  31036. if (! readNextMessageInt())
  31037. break;
  31038. }
  31039. else
  31040. {
  31041. Thread::sleep (2);
  31042. }
  31043. }
  31044. else if (pipe != 0)
  31045. {
  31046. if (! pipe->isOpen())
  31047. {
  31048. {
  31049. const ScopedLock sl (pipeAndSocketLock);
  31050. pipe = 0;
  31051. }
  31052. connectionLostInt();
  31053. break;
  31054. }
  31055. else
  31056. {
  31057. if (! readNextMessageInt())
  31058. break;
  31059. }
  31060. }
  31061. else
  31062. {
  31063. break;
  31064. }
  31065. }
  31066. }
  31067. END_JUCE_NAMESPACE
  31068. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31069. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31070. BEGIN_JUCE_NAMESPACE
  31071. InterprocessConnectionServer::InterprocessConnectionServer()
  31072. : Thread ("Juce IPC server")
  31073. {
  31074. }
  31075. InterprocessConnectionServer::~InterprocessConnectionServer()
  31076. {
  31077. stop();
  31078. }
  31079. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31080. {
  31081. stop();
  31082. socket = new StreamingSocket();
  31083. if (socket->createListener (portNumber))
  31084. {
  31085. startThread();
  31086. return true;
  31087. }
  31088. socket = 0;
  31089. return false;
  31090. }
  31091. void InterprocessConnectionServer::stop()
  31092. {
  31093. signalThreadShouldExit();
  31094. if (socket != 0)
  31095. socket->close();
  31096. stopThread (4000);
  31097. socket = 0;
  31098. }
  31099. void InterprocessConnectionServer::run()
  31100. {
  31101. while ((! threadShouldExit()) && socket != 0)
  31102. {
  31103. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31104. if (clientSocket != 0)
  31105. {
  31106. InterprocessConnection* newConnection = createConnectionObject();
  31107. if (newConnection != 0)
  31108. newConnection->initialiseWithSocket (clientSocket.release());
  31109. }
  31110. }
  31111. }
  31112. END_JUCE_NAMESPACE
  31113. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31114. /*** Start of inlined file: juce_Message.cpp ***/
  31115. BEGIN_JUCE_NAMESPACE
  31116. Message::Message() throw()
  31117. : intParameter1 (0),
  31118. intParameter2 (0),
  31119. intParameter3 (0),
  31120. pointerParameter (0)
  31121. {
  31122. }
  31123. Message::Message (const int intParameter1_,
  31124. const int intParameter2_,
  31125. const int intParameter3_,
  31126. void* const pointerParameter_) throw()
  31127. : intParameter1 (intParameter1_),
  31128. intParameter2 (intParameter2_),
  31129. intParameter3 (intParameter3_),
  31130. pointerParameter (pointerParameter_)
  31131. {
  31132. }
  31133. Message::~Message() throw()
  31134. {
  31135. }
  31136. END_JUCE_NAMESPACE
  31137. /*** End of inlined file: juce_Message.cpp ***/
  31138. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31139. BEGIN_JUCE_NAMESPACE
  31140. MessageListener::MessageListener() throw()
  31141. {
  31142. // are you trying to create a messagelistener before or after juce has been intialised??
  31143. jassert (MessageManager::instance != 0);
  31144. if (MessageManager::instance != 0)
  31145. MessageManager::instance->messageListeners.add (this);
  31146. }
  31147. MessageListener::~MessageListener()
  31148. {
  31149. if (MessageManager::instance != 0)
  31150. MessageManager::instance->messageListeners.removeValue (this);
  31151. }
  31152. void MessageListener::postMessage (Message* const message) const throw()
  31153. {
  31154. message->messageRecipient = const_cast <MessageListener*> (this);
  31155. if (MessageManager::instance == 0)
  31156. MessageManager::getInstance();
  31157. MessageManager::instance->postMessageToQueue (message);
  31158. }
  31159. bool MessageListener::isValidMessageListener() const throw()
  31160. {
  31161. return (MessageManager::instance != 0)
  31162. && MessageManager::instance->messageListeners.contains (this);
  31163. }
  31164. END_JUCE_NAMESPACE
  31165. /*** End of inlined file: juce_MessageListener.cpp ***/
  31166. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31167. BEGIN_JUCE_NAMESPACE
  31168. // platform-specific functions..
  31169. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31170. bool juce_postMessageToSystemQueue (Message* message);
  31171. MessageManager* MessageManager::instance = 0;
  31172. static const int quitMessageId = 0xfffff321;
  31173. MessageManager::MessageManager() throw()
  31174. : quitMessagePosted (false),
  31175. quitMessageReceived (false),
  31176. threadWithLock (0)
  31177. {
  31178. messageThreadId = Thread::getCurrentThreadId();
  31179. }
  31180. MessageManager::~MessageManager() throw()
  31181. {
  31182. broadcastListeners = 0;
  31183. doPlatformSpecificShutdown();
  31184. // If you hit this assertion, then you've probably leaked a Component or some other
  31185. // kind of MessageListener object...
  31186. jassert (messageListeners.size() == 0);
  31187. jassert (instance == this);
  31188. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31189. }
  31190. MessageManager* MessageManager::getInstance() throw()
  31191. {
  31192. if (instance == 0)
  31193. {
  31194. instance = new MessageManager();
  31195. doPlatformSpecificInitialisation();
  31196. }
  31197. return instance;
  31198. }
  31199. void MessageManager::postMessageToQueue (Message* const message)
  31200. {
  31201. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31202. delete message;
  31203. }
  31204. CallbackMessage::CallbackMessage() throw() {}
  31205. CallbackMessage::~CallbackMessage() throw() {}
  31206. void CallbackMessage::post()
  31207. {
  31208. if (MessageManager::instance != 0)
  31209. MessageManager::instance->postCallbackMessage (this);
  31210. }
  31211. void MessageManager::postCallbackMessage (Message* const message)
  31212. {
  31213. message->messageRecipient = 0;
  31214. postMessageToQueue (message);
  31215. }
  31216. // not for public use..
  31217. void MessageManager::deliverMessage (Message* const message)
  31218. {
  31219. const ScopedPointer <Message> messageDeleter (message);
  31220. MessageListener* const recipient = message->messageRecipient;
  31221. JUCE_TRY
  31222. {
  31223. if (messageListeners.contains (recipient))
  31224. {
  31225. recipient->handleMessage (*message);
  31226. }
  31227. else if (recipient == 0)
  31228. {
  31229. if (message->intParameter1 == quitMessageId)
  31230. {
  31231. quitMessageReceived = true;
  31232. }
  31233. else
  31234. {
  31235. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31236. if (cm != 0)
  31237. cm->messageCallback();
  31238. }
  31239. }
  31240. }
  31241. JUCE_CATCH_EXCEPTION
  31242. }
  31243. #if ! (JUCE_MAC || JUCE_IOS)
  31244. void MessageManager::runDispatchLoop()
  31245. {
  31246. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31247. runDispatchLoopUntil (-1);
  31248. }
  31249. void MessageManager::stopDispatchLoop()
  31250. {
  31251. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31252. m->messageRecipient = 0;
  31253. postMessageToQueue (m);
  31254. quitMessagePosted = true;
  31255. }
  31256. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31257. {
  31258. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31259. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31260. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31261. && ! quitMessageReceived)
  31262. {
  31263. JUCE_TRY
  31264. {
  31265. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31266. {
  31267. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31268. if (msToWait > 0)
  31269. Thread::sleep (jmin (5, msToWait));
  31270. }
  31271. }
  31272. JUCE_CATCH_EXCEPTION
  31273. }
  31274. return ! quitMessageReceived;
  31275. }
  31276. #endif
  31277. void MessageManager::deliverBroadcastMessage (const String& value)
  31278. {
  31279. if (broadcastListeners != 0)
  31280. broadcastListeners->sendActionMessage (value);
  31281. }
  31282. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31283. {
  31284. if (broadcastListeners == 0)
  31285. broadcastListeners = new ActionListenerList();
  31286. broadcastListeners->addActionListener (listener);
  31287. }
  31288. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31289. {
  31290. if (broadcastListeners != 0)
  31291. broadcastListeners->removeActionListener (listener);
  31292. }
  31293. bool MessageManager::isThisTheMessageThread() const throw()
  31294. {
  31295. return Thread::getCurrentThreadId() == messageThreadId;
  31296. }
  31297. void MessageManager::setCurrentThreadAsMessageThread()
  31298. {
  31299. if (messageThreadId != Thread::getCurrentThreadId())
  31300. {
  31301. messageThreadId = Thread::getCurrentThreadId();
  31302. // This is needed on windows to make sure the message window is created by this thread
  31303. doPlatformSpecificShutdown();
  31304. doPlatformSpecificInitialisation();
  31305. }
  31306. }
  31307. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31308. {
  31309. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31310. return thisThread == messageThreadId || thisThread == threadWithLock;
  31311. }
  31312. /* The only safe way to lock the message thread while another thread does
  31313. some work is by posting a special message, whose purpose is to tie up the event
  31314. loop until the other thread has finished its business.
  31315. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31316. get locked before making an event callback, because if the same OS lock gets indirectly
  31317. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31318. in Cocoa).
  31319. */
  31320. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31321. {
  31322. public:
  31323. SharedEvents() {}
  31324. ~SharedEvents() {}
  31325. /* This class just holds a couple of events to communicate between the BlockingMessage
  31326. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31327. this shared data must be kept in a separate, ref-counted container. */
  31328. WaitableEvent lockedEvent, releaseEvent;
  31329. private:
  31330. SharedEvents (const SharedEvents&);
  31331. SharedEvents& operator= (const SharedEvents&);
  31332. };
  31333. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31334. {
  31335. public:
  31336. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31337. ~BlockingMessage() throw() {}
  31338. void messageCallback()
  31339. {
  31340. events->lockedEvent.signal();
  31341. events->releaseEvent.wait();
  31342. }
  31343. juce_UseDebuggingNewOperator
  31344. private:
  31345. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31346. BlockingMessage (const BlockingMessage&);
  31347. BlockingMessage& operator= (const BlockingMessage&);
  31348. };
  31349. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31350. : sharedEvents (0),
  31351. locked (false)
  31352. {
  31353. init (threadToCheck, 0);
  31354. }
  31355. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31356. : sharedEvents (0),
  31357. locked (false)
  31358. {
  31359. init (0, jobToCheckForExitSignal);
  31360. }
  31361. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31362. {
  31363. if (MessageManager::instance != 0)
  31364. {
  31365. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31366. {
  31367. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31368. }
  31369. else
  31370. {
  31371. if (threadToCheck == 0 && job == 0)
  31372. {
  31373. MessageManager::instance->lockingLock.enter();
  31374. }
  31375. else
  31376. {
  31377. while (! MessageManager::instance->lockingLock.tryEnter())
  31378. {
  31379. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31380. || (job != 0 && job->shouldExit()))
  31381. return;
  31382. Thread::sleep (1);
  31383. }
  31384. }
  31385. sharedEvents = new SharedEvents();
  31386. sharedEvents->incReferenceCount();
  31387. (new BlockingMessage (sharedEvents))->post();
  31388. while (! sharedEvents->lockedEvent.wait (50))
  31389. {
  31390. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31391. || (job != 0 && job->shouldExit()))
  31392. {
  31393. sharedEvents->releaseEvent.signal();
  31394. sharedEvents->decReferenceCount();
  31395. sharedEvents = 0;
  31396. MessageManager::instance->lockingLock.exit();
  31397. return;
  31398. }
  31399. }
  31400. jassert (MessageManager::instance->threadWithLock == 0);
  31401. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31402. locked = true;
  31403. }
  31404. }
  31405. }
  31406. MessageManagerLock::~MessageManagerLock() throw()
  31407. {
  31408. if (sharedEvents != 0)
  31409. {
  31410. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31411. sharedEvents->releaseEvent.signal();
  31412. sharedEvents->decReferenceCount();
  31413. if (MessageManager::instance != 0)
  31414. {
  31415. MessageManager::instance->threadWithLock = 0;
  31416. MessageManager::instance->lockingLock.exit();
  31417. }
  31418. }
  31419. }
  31420. END_JUCE_NAMESPACE
  31421. /*** End of inlined file: juce_MessageManager.cpp ***/
  31422. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31423. BEGIN_JUCE_NAMESPACE
  31424. class MultiTimer::MultiTimerCallback : public Timer
  31425. {
  31426. public:
  31427. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31428. : timerId (timerId_),
  31429. owner (owner_)
  31430. {
  31431. }
  31432. ~MultiTimerCallback()
  31433. {
  31434. }
  31435. void timerCallback()
  31436. {
  31437. owner.timerCallback (timerId);
  31438. }
  31439. const int timerId;
  31440. private:
  31441. MultiTimer& owner;
  31442. };
  31443. MultiTimer::MultiTimer() throw()
  31444. {
  31445. }
  31446. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31447. {
  31448. }
  31449. MultiTimer::~MultiTimer()
  31450. {
  31451. const ScopedLock sl (timerListLock);
  31452. timers.clear();
  31453. }
  31454. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31455. {
  31456. const ScopedLock sl (timerListLock);
  31457. for (int i = timers.size(); --i >= 0;)
  31458. {
  31459. MultiTimerCallback* const t = timers.getUnchecked(i);
  31460. if (t->timerId == timerId)
  31461. {
  31462. t->startTimer (intervalInMilliseconds);
  31463. return;
  31464. }
  31465. }
  31466. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31467. timers.add (newTimer);
  31468. newTimer->startTimer (intervalInMilliseconds);
  31469. }
  31470. void MultiTimer::stopTimer (const int timerId) throw()
  31471. {
  31472. const ScopedLock sl (timerListLock);
  31473. for (int i = timers.size(); --i >= 0;)
  31474. {
  31475. MultiTimerCallback* const t = timers.getUnchecked(i);
  31476. if (t->timerId == timerId)
  31477. t->stopTimer();
  31478. }
  31479. }
  31480. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31481. {
  31482. const ScopedLock sl (timerListLock);
  31483. for (int i = timers.size(); --i >= 0;)
  31484. {
  31485. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31486. if (t->timerId == timerId)
  31487. return t->isTimerRunning();
  31488. }
  31489. return false;
  31490. }
  31491. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31492. {
  31493. const ScopedLock sl (timerListLock);
  31494. for (int i = timers.size(); --i >= 0;)
  31495. {
  31496. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31497. if (t->timerId == timerId)
  31498. return t->getTimerInterval();
  31499. }
  31500. return 0;
  31501. }
  31502. END_JUCE_NAMESPACE
  31503. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31504. /*** Start of inlined file: juce_Timer.cpp ***/
  31505. BEGIN_JUCE_NAMESPACE
  31506. class InternalTimerThread : private Thread,
  31507. private MessageListener,
  31508. private DeletedAtShutdown,
  31509. private AsyncUpdater
  31510. {
  31511. public:
  31512. InternalTimerThread()
  31513. : Thread ("Juce Timer"),
  31514. firstTimer (0),
  31515. callbackNeeded (0)
  31516. {
  31517. triggerAsyncUpdate();
  31518. }
  31519. ~InternalTimerThread() throw()
  31520. {
  31521. stopThread (4000);
  31522. jassert (instance == this || instance == 0);
  31523. if (instance == this)
  31524. instance = 0;
  31525. }
  31526. void run()
  31527. {
  31528. uint32 lastTime = Time::getMillisecondCounter();
  31529. while (! threadShouldExit())
  31530. {
  31531. const uint32 now = Time::getMillisecondCounter();
  31532. if (now <= lastTime)
  31533. {
  31534. wait (2);
  31535. continue;
  31536. }
  31537. const int elapsed = now - lastTime;
  31538. lastTime = now;
  31539. int timeUntilFirstTimer = 1000;
  31540. {
  31541. const ScopedLock sl (lock);
  31542. decrementAllCounters (elapsed);
  31543. if (firstTimer != 0)
  31544. timeUntilFirstTimer = firstTimer->countdownMs;
  31545. }
  31546. if (timeUntilFirstTimer <= 0)
  31547. {
  31548. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31549. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31550. but if it fails it means the message-thread changed the value from under us so at least
  31551. some processing is happenening and we can just loop around and try again
  31552. */
  31553. if (callbackNeeded.compareAndSetBool (1, 0))
  31554. {
  31555. postMessage (new Message());
  31556. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31557. when the app has a modal loop), so this is how long to wait before assuming the
  31558. message has been lost and trying again.
  31559. */
  31560. const uint32 messageDeliveryTimeout = now + 2000;
  31561. while (callbackNeeded.get() != 0)
  31562. {
  31563. wait (4);
  31564. if (threadShouldExit())
  31565. return;
  31566. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31567. break;
  31568. }
  31569. }
  31570. }
  31571. else
  31572. {
  31573. // don't wait for too long because running this loop also helps keep the
  31574. // Time::getApproximateMillisecondTimer value stay up-to-date
  31575. wait (jlimit (1, 50, timeUntilFirstTimer));
  31576. }
  31577. }
  31578. }
  31579. void callTimers()
  31580. {
  31581. const ScopedLock sl (lock);
  31582. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31583. {
  31584. Timer* const t = firstTimer;
  31585. t->countdownMs = t->periodMs;
  31586. removeTimer (t);
  31587. addTimer (t);
  31588. const ScopedUnlock ul (lock);
  31589. JUCE_TRY
  31590. {
  31591. t->timerCallback();
  31592. }
  31593. JUCE_CATCH_EXCEPTION
  31594. }
  31595. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31596. before the boolean is set. This set should never fail since if it was false in the first place,
  31597. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31598. get a message then the value is true and the other thread can only set it to true again and
  31599. we will get another callback to set it to false.
  31600. */
  31601. callbackNeeded.set (0);
  31602. }
  31603. void handleMessage (const Message&)
  31604. {
  31605. callTimers();
  31606. }
  31607. void callTimersSynchronously()
  31608. {
  31609. if (! isThreadRunning())
  31610. {
  31611. // (This is relied on by some plugins in cases where the MM has
  31612. // had to restart and the async callback never started)
  31613. cancelPendingUpdate();
  31614. triggerAsyncUpdate();
  31615. }
  31616. callTimers();
  31617. }
  31618. static void callAnyTimersSynchronously()
  31619. {
  31620. if (InternalTimerThread::instance != 0)
  31621. InternalTimerThread::instance->callTimersSynchronously();
  31622. }
  31623. static inline void add (Timer* const tim) throw()
  31624. {
  31625. if (instance == 0)
  31626. instance = new InternalTimerThread();
  31627. const ScopedLock sl (instance->lock);
  31628. instance->addTimer (tim);
  31629. }
  31630. static inline void remove (Timer* const tim) throw()
  31631. {
  31632. if (instance != 0)
  31633. {
  31634. const ScopedLock sl (instance->lock);
  31635. instance->removeTimer (tim);
  31636. }
  31637. }
  31638. static inline void resetCounter (Timer* const tim,
  31639. const int newCounter) throw()
  31640. {
  31641. if (instance != 0)
  31642. {
  31643. tim->countdownMs = newCounter;
  31644. tim->periodMs = newCounter;
  31645. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31646. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31647. {
  31648. const ScopedLock sl (instance->lock);
  31649. instance->removeTimer (tim);
  31650. instance->addTimer (tim);
  31651. }
  31652. }
  31653. }
  31654. private:
  31655. friend class Timer;
  31656. static InternalTimerThread* instance;
  31657. static CriticalSection lock;
  31658. Timer* volatile firstTimer;
  31659. Atomic <int> callbackNeeded;
  31660. void addTimer (Timer* const t) throw()
  31661. {
  31662. #if JUCE_DEBUG
  31663. Timer* tt = firstTimer;
  31664. while (tt != 0)
  31665. {
  31666. // trying to add a timer that's already here - shouldn't get to this point,
  31667. // so if you get this assertion, let me know!
  31668. jassert (tt != t);
  31669. tt = tt->next;
  31670. }
  31671. jassert (t->previous == 0 && t->next == 0);
  31672. #endif
  31673. Timer* i = firstTimer;
  31674. if (i == 0 || i->countdownMs > t->countdownMs)
  31675. {
  31676. t->next = firstTimer;
  31677. firstTimer = t;
  31678. }
  31679. else
  31680. {
  31681. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31682. i = i->next;
  31683. jassert (i != 0);
  31684. t->next = i->next;
  31685. t->previous = i;
  31686. i->next = t;
  31687. }
  31688. if (t->next != 0)
  31689. t->next->previous = t;
  31690. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31691. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31692. notify();
  31693. }
  31694. void removeTimer (Timer* const t) throw()
  31695. {
  31696. #if JUCE_DEBUG
  31697. Timer* tt = firstTimer;
  31698. bool found = false;
  31699. while (tt != 0)
  31700. {
  31701. if (tt == t)
  31702. {
  31703. found = true;
  31704. break;
  31705. }
  31706. tt = tt->next;
  31707. }
  31708. // trying to remove a timer that's not here - shouldn't get to this point,
  31709. // so if you get this assertion, let me know!
  31710. jassert (found);
  31711. #endif
  31712. if (t->previous != 0)
  31713. {
  31714. jassert (firstTimer != t);
  31715. t->previous->next = t->next;
  31716. }
  31717. else
  31718. {
  31719. jassert (firstTimer == t);
  31720. firstTimer = t->next;
  31721. }
  31722. if (t->next != 0)
  31723. t->next->previous = t->previous;
  31724. t->next = 0;
  31725. t->previous = 0;
  31726. }
  31727. void decrementAllCounters (const int numMillisecs) const
  31728. {
  31729. Timer* t = firstTimer;
  31730. while (t != 0)
  31731. {
  31732. t->countdownMs -= numMillisecs;
  31733. t = t->next;
  31734. }
  31735. }
  31736. void handleAsyncUpdate()
  31737. {
  31738. startThread (7);
  31739. }
  31740. InternalTimerThread (const InternalTimerThread&);
  31741. InternalTimerThread& operator= (const InternalTimerThread&);
  31742. };
  31743. InternalTimerThread* InternalTimerThread::instance = 0;
  31744. CriticalSection InternalTimerThread::lock;
  31745. void juce_callAnyTimersSynchronously()
  31746. {
  31747. InternalTimerThread::callAnyTimersSynchronously();
  31748. }
  31749. #if JUCE_DEBUG
  31750. static SortedSet <Timer*> activeTimers;
  31751. #endif
  31752. Timer::Timer() throw()
  31753. : countdownMs (0),
  31754. periodMs (0),
  31755. previous (0),
  31756. next (0)
  31757. {
  31758. #if JUCE_DEBUG
  31759. activeTimers.add (this);
  31760. #endif
  31761. }
  31762. Timer::Timer (const Timer&) throw()
  31763. : countdownMs (0),
  31764. periodMs (0),
  31765. previous (0),
  31766. next (0)
  31767. {
  31768. #if JUCE_DEBUG
  31769. activeTimers.add (this);
  31770. #endif
  31771. }
  31772. Timer::~Timer()
  31773. {
  31774. stopTimer();
  31775. #if JUCE_DEBUG
  31776. activeTimers.removeValue (this);
  31777. #endif
  31778. }
  31779. void Timer::startTimer (const int interval) throw()
  31780. {
  31781. const ScopedLock sl (InternalTimerThread::lock);
  31782. #if JUCE_DEBUG
  31783. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31784. jassert (activeTimers.contains (this));
  31785. #endif
  31786. if (periodMs == 0)
  31787. {
  31788. countdownMs = interval;
  31789. periodMs = jmax (1, interval);
  31790. InternalTimerThread::add (this);
  31791. }
  31792. else
  31793. {
  31794. InternalTimerThread::resetCounter (this, interval);
  31795. }
  31796. }
  31797. void Timer::stopTimer() throw()
  31798. {
  31799. const ScopedLock sl (InternalTimerThread::lock);
  31800. #if JUCE_DEBUG
  31801. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31802. jassert (activeTimers.contains (this));
  31803. #endif
  31804. if (periodMs > 0)
  31805. {
  31806. InternalTimerThread::remove (this);
  31807. periodMs = 0;
  31808. }
  31809. }
  31810. END_JUCE_NAMESPACE
  31811. /*** End of inlined file: juce_Timer.cpp ***/
  31812. #endif
  31813. #if JUCE_BUILD_GUI
  31814. /*** Start of inlined file: juce_Component.cpp ***/
  31815. BEGIN_JUCE_NAMESPACE
  31816. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31817. enum ComponentMessageNumbers
  31818. {
  31819. customCommandMessage = 0x7fff0001,
  31820. exitModalStateMessage = 0x7fff0002
  31821. };
  31822. static uint32 nextComponentUID = 0;
  31823. Component* Component::currentlyFocusedComponent = 0;
  31824. Component::Component()
  31825. : parentComponent_ (0),
  31826. componentUID (++nextComponentUID),
  31827. numDeepMouseListeners (0),
  31828. lookAndFeel_ (0),
  31829. effect_ (0),
  31830. bufferedImage_ (0),
  31831. mouseListeners_ (0),
  31832. keyListeners_ (0),
  31833. componentFlags_ (0)
  31834. {
  31835. }
  31836. Component::Component (const String& name)
  31837. : componentName_ (name),
  31838. parentComponent_ (0),
  31839. componentUID (++nextComponentUID),
  31840. numDeepMouseListeners (0),
  31841. lookAndFeel_ (0),
  31842. effect_ (0),
  31843. bufferedImage_ (0),
  31844. mouseListeners_ (0),
  31845. keyListeners_ (0),
  31846. componentFlags_ (0)
  31847. {
  31848. }
  31849. Component::~Component()
  31850. {
  31851. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31852. if (parentComponent_ != 0)
  31853. {
  31854. parentComponent_->removeChildComponent (this);
  31855. }
  31856. else if ((currentlyFocusedComponent == this)
  31857. || isParentOf (currentlyFocusedComponent))
  31858. {
  31859. giveAwayFocus();
  31860. }
  31861. if (flags.hasHeavyweightPeerFlag)
  31862. removeFromDesktop();
  31863. for (int i = childComponentList_.size(); --i >= 0;)
  31864. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31865. delete mouseListeners_;
  31866. delete keyListeners_;
  31867. }
  31868. void Component::setName (const String& name)
  31869. {
  31870. // if component methods are being called from threads other than the message
  31871. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31872. checkMessageManagerIsLocked
  31873. if (componentName_ != name)
  31874. {
  31875. componentName_ = name;
  31876. if (flags.hasHeavyweightPeerFlag)
  31877. {
  31878. ComponentPeer* const peer = getPeer();
  31879. jassert (peer != 0);
  31880. if (peer != 0)
  31881. peer->setTitle (name);
  31882. }
  31883. BailOutChecker checker (this);
  31884. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31885. }
  31886. }
  31887. void Component::setVisible (bool shouldBeVisible)
  31888. {
  31889. if (flags.visibleFlag != shouldBeVisible)
  31890. {
  31891. // if component methods are being called from threads other than the message
  31892. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31893. checkMessageManagerIsLocked
  31894. SafePointer<Component> safePointer (this);
  31895. flags.visibleFlag = shouldBeVisible;
  31896. internalRepaint (0, 0, getWidth(), getHeight());
  31897. sendFakeMouseMove();
  31898. if (! shouldBeVisible)
  31899. {
  31900. if (currentlyFocusedComponent == this
  31901. || isParentOf (currentlyFocusedComponent))
  31902. {
  31903. if (parentComponent_ != 0)
  31904. parentComponent_->grabKeyboardFocus();
  31905. else
  31906. giveAwayFocus();
  31907. }
  31908. }
  31909. if (safePointer != 0)
  31910. {
  31911. sendVisibilityChangeMessage();
  31912. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31913. {
  31914. ComponentPeer* const peer = getPeer();
  31915. jassert (peer != 0);
  31916. if (peer != 0)
  31917. {
  31918. peer->setVisible (shouldBeVisible);
  31919. internalHierarchyChanged();
  31920. }
  31921. }
  31922. }
  31923. }
  31924. }
  31925. void Component::visibilityChanged()
  31926. {
  31927. }
  31928. void Component::sendVisibilityChangeMessage()
  31929. {
  31930. BailOutChecker checker (this);
  31931. visibilityChanged();
  31932. if (! checker.shouldBailOut())
  31933. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31934. }
  31935. bool Component::isShowing() const
  31936. {
  31937. if (flags.visibleFlag)
  31938. {
  31939. if (parentComponent_ != 0)
  31940. {
  31941. return parentComponent_->isShowing();
  31942. }
  31943. else
  31944. {
  31945. const ComponentPeer* const peer = getPeer();
  31946. return peer != 0 && ! peer->isMinimised();
  31947. }
  31948. }
  31949. return false;
  31950. }
  31951. class FadeOutProxyComponent : public Component,
  31952. public Timer
  31953. {
  31954. public:
  31955. FadeOutProxyComponent (Component* comp,
  31956. const int fadeLengthMs,
  31957. const int deltaXToMove,
  31958. const int deltaYToMove,
  31959. const float scaleFactorAtEnd)
  31960. : lastTime (0),
  31961. alpha (1.0f),
  31962. scale (1.0f)
  31963. {
  31964. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31965. setBounds (comp->getBounds());
  31966. comp->getParentComponent()->addAndMakeVisible (this);
  31967. toBehind (comp);
  31968. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31969. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31970. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31971. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31972. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31973. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31974. setInterceptsMouseClicks (false, false);
  31975. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31976. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31977. }
  31978. ~FadeOutProxyComponent()
  31979. {
  31980. }
  31981. void paint (Graphics& g)
  31982. {
  31983. g.setOpacity (alpha);
  31984. g.drawImage (image,
  31985. 0, 0, getWidth(), getHeight(),
  31986. 0, 0, image.getWidth(), image.getHeight());
  31987. }
  31988. void timerCallback()
  31989. {
  31990. const uint32 now = Time::getMillisecondCounter();
  31991. if (lastTime == 0)
  31992. lastTime = now;
  31993. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31994. lastTime = now;
  31995. alpha += alphaChangePerMs * msPassed;
  31996. if (alpha > 0)
  31997. {
  31998. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31999. {
  32000. centreX += xChangePerMs * msPassed;
  32001. centreY += yChangePerMs * msPassed;
  32002. scale += scaleChangePerMs * msPassed;
  32003. const int w = roundToInt (image.getWidth() * scale);
  32004. const int h = roundToInt (image.getHeight() * scale);
  32005. setBounds (roundToInt (centreX) - w / 2,
  32006. roundToInt (centreY) - h / 2,
  32007. w, h);
  32008. }
  32009. repaint();
  32010. }
  32011. else
  32012. {
  32013. delete this;
  32014. }
  32015. }
  32016. juce_UseDebuggingNewOperator
  32017. private:
  32018. Image image;
  32019. uint32 lastTime;
  32020. float alpha, alphaChangePerMs;
  32021. float centreX, xChangePerMs;
  32022. float centreY, yChangePerMs;
  32023. float scale, scaleChangePerMs;
  32024. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32025. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32026. };
  32027. void Component::fadeOutComponent (const int millisecondsToFade,
  32028. const int deltaXToMove,
  32029. const int deltaYToMove,
  32030. const float scaleFactorAtEnd)
  32031. {
  32032. //xxx won't work for comps without parents
  32033. if (isShowing() && millisecondsToFade > 0)
  32034. new FadeOutProxyComponent (this, millisecondsToFade,
  32035. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32036. setVisible (false);
  32037. }
  32038. bool Component::isValidComponent() const
  32039. {
  32040. return (this != 0) && isValidMessageListener();
  32041. }
  32042. void* Component::getWindowHandle() const
  32043. {
  32044. const ComponentPeer* const peer = getPeer();
  32045. if (peer != 0)
  32046. return peer->getNativeHandle();
  32047. return 0;
  32048. }
  32049. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32050. {
  32051. // if component methods are being called from threads other than the message
  32052. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32053. checkMessageManagerIsLocked
  32054. if (isOpaque())
  32055. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32056. else
  32057. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32058. int currentStyleFlags = 0;
  32059. // don't use getPeer(), so that we only get the peer that's specifically
  32060. // for this comp, and not for one of its parents.
  32061. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32062. if (peer != 0)
  32063. currentStyleFlags = peer->getStyleFlags();
  32064. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32065. {
  32066. SafePointer<Component> safePointer (this);
  32067. #if JUCE_LINUX
  32068. // it's wise to give the component a non-zero size before
  32069. // putting it on the desktop, as X windows get confused by this, and
  32070. // a (1, 1) minimum size is enforced here.
  32071. setSize (jmax (1, getWidth()),
  32072. jmax (1, getHeight()));
  32073. #endif
  32074. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32075. bool wasFullscreen = false;
  32076. bool wasMinimised = false;
  32077. ComponentBoundsConstrainer* currentConstainer = 0;
  32078. Rectangle<int> oldNonFullScreenBounds;
  32079. if (peer != 0)
  32080. {
  32081. wasFullscreen = peer->isFullScreen();
  32082. wasMinimised = peer->isMinimised();
  32083. currentConstainer = peer->getConstrainer();
  32084. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32085. removeFromDesktop();
  32086. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32087. }
  32088. if (parentComponent_ != 0)
  32089. parentComponent_->removeChildComponent (this);
  32090. if (safePointer != 0)
  32091. {
  32092. flags.hasHeavyweightPeerFlag = true;
  32093. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32094. Desktop::getInstance().addDesktopComponent (this);
  32095. bounds_.setPosition (topLeft);
  32096. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32097. peer->setVisible (isVisible());
  32098. if (wasFullscreen)
  32099. {
  32100. peer->setFullScreen (true);
  32101. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32102. }
  32103. if (wasMinimised)
  32104. peer->setMinimised (true);
  32105. if (isAlwaysOnTop())
  32106. peer->setAlwaysOnTop (true);
  32107. peer->setConstrainer (currentConstainer);
  32108. repaint();
  32109. }
  32110. internalHierarchyChanged();
  32111. }
  32112. }
  32113. void Component::removeFromDesktop()
  32114. {
  32115. // if component methods are being called from threads other than the message
  32116. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32117. checkMessageManagerIsLocked
  32118. if (flags.hasHeavyweightPeerFlag)
  32119. {
  32120. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32121. flags.hasHeavyweightPeerFlag = false;
  32122. jassert (peer != 0);
  32123. delete peer;
  32124. Desktop::getInstance().removeDesktopComponent (this);
  32125. }
  32126. }
  32127. bool Component::isOnDesktop() const throw()
  32128. {
  32129. return flags.hasHeavyweightPeerFlag;
  32130. }
  32131. void Component::userTriedToCloseWindow()
  32132. {
  32133. /* This means that the user's trying to get rid of your window with the 'close window' system
  32134. menu option (on windows) or possibly the task manager - you should really handle this
  32135. and delete or hide your component in an appropriate way.
  32136. If you want to ignore the event and don't want to trigger this assertion, just override
  32137. this method and do nothing.
  32138. */
  32139. jassertfalse;
  32140. }
  32141. void Component::minimisationStateChanged (bool)
  32142. {
  32143. }
  32144. void Component::setOpaque (const bool shouldBeOpaque)
  32145. {
  32146. if (shouldBeOpaque != flags.opaqueFlag)
  32147. {
  32148. flags.opaqueFlag = shouldBeOpaque;
  32149. if (flags.hasHeavyweightPeerFlag)
  32150. {
  32151. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32152. if (peer != 0)
  32153. {
  32154. // to make it recreate the heavyweight window
  32155. addToDesktop (peer->getStyleFlags());
  32156. }
  32157. }
  32158. repaint();
  32159. }
  32160. }
  32161. bool Component::isOpaque() const throw()
  32162. {
  32163. return flags.opaqueFlag;
  32164. }
  32165. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32166. {
  32167. if (shouldBeBuffered != flags.bufferToImageFlag)
  32168. {
  32169. bufferedImage_ = Image::null;
  32170. flags.bufferToImageFlag = shouldBeBuffered;
  32171. }
  32172. }
  32173. void Component::toFront (const bool setAsForeground)
  32174. {
  32175. // if component methods are being called from threads other than the message
  32176. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32177. checkMessageManagerIsLocked
  32178. if (flags.hasHeavyweightPeerFlag)
  32179. {
  32180. ComponentPeer* const peer = getPeer();
  32181. if (peer != 0)
  32182. {
  32183. peer->toFront (setAsForeground);
  32184. if (setAsForeground && ! hasKeyboardFocus (true))
  32185. grabKeyboardFocus();
  32186. }
  32187. }
  32188. else if (parentComponent_ != 0)
  32189. {
  32190. Array<Component*>& childList = parentComponent_->childComponentList_;
  32191. if (childList.getLast() != this)
  32192. {
  32193. const int index = childList.indexOf (this);
  32194. if (index >= 0)
  32195. {
  32196. int insertIndex = -1;
  32197. if (! flags.alwaysOnTopFlag)
  32198. {
  32199. insertIndex = childList.size() - 1;
  32200. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32201. --insertIndex;
  32202. }
  32203. if (index != insertIndex)
  32204. {
  32205. childList.move (index, insertIndex);
  32206. sendFakeMouseMove();
  32207. repaintParent();
  32208. }
  32209. }
  32210. }
  32211. if (setAsForeground)
  32212. {
  32213. internalBroughtToFront();
  32214. grabKeyboardFocus();
  32215. }
  32216. }
  32217. }
  32218. void Component::toBehind (Component* const other)
  32219. {
  32220. if (other != 0 && other != this)
  32221. {
  32222. // the two components must belong to the same parent..
  32223. jassert (parentComponent_ == other->parentComponent_);
  32224. if (parentComponent_ != 0)
  32225. {
  32226. Array<Component*>& childList = parentComponent_->childComponentList_;
  32227. const int index = childList.indexOf (this);
  32228. if (index >= 0 && childList [index + 1] != other)
  32229. {
  32230. int otherIndex = childList.indexOf (other);
  32231. if (otherIndex >= 0)
  32232. {
  32233. if (index < otherIndex)
  32234. --otherIndex;
  32235. childList.move (index, otherIndex);
  32236. sendFakeMouseMove();
  32237. repaintParent();
  32238. }
  32239. }
  32240. }
  32241. else if (isOnDesktop())
  32242. {
  32243. jassert (other->isOnDesktop());
  32244. if (other->isOnDesktop())
  32245. {
  32246. ComponentPeer* const us = getPeer();
  32247. ComponentPeer* const them = other->getPeer();
  32248. jassert (us != 0 && them != 0);
  32249. if (us != 0 && them != 0)
  32250. us->toBehind (them);
  32251. }
  32252. }
  32253. }
  32254. }
  32255. void Component::toBack()
  32256. {
  32257. Array<Component*>& childList = parentComponent_->childComponentList_;
  32258. if (isOnDesktop())
  32259. {
  32260. jassertfalse; //xxx need to add this to native window
  32261. }
  32262. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32263. {
  32264. const int index = childList.indexOf (this);
  32265. if (index > 0)
  32266. {
  32267. int insertIndex = 0;
  32268. if (flags.alwaysOnTopFlag)
  32269. {
  32270. while (insertIndex < childList.size()
  32271. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32272. {
  32273. ++insertIndex;
  32274. }
  32275. }
  32276. if (index != insertIndex)
  32277. {
  32278. childList.move (index, insertIndex);
  32279. sendFakeMouseMove();
  32280. repaintParent();
  32281. }
  32282. }
  32283. }
  32284. }
  32285. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32286. {
  32287. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32288. {
  32289. flags.alwaysOnTopFlag = shouldStayOnTop;
  32290. if (isOnDesktop())
  32291. {
  32292. ComponentPeer* const peer = getPeer();
  32293. jassert (peer != 0);
  32294. if (peer != 0)
  32295. {
  32296. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32297. {
  32298. // some kinds of peer can't change their always-on-top status, so
  32299. // for these, we'll need to create a new window
  32300. const int oldFlags = peer->getStyleFlags();
  32301. removeFromDesktop();
  32302. addToDesktop (oldFlags);
  32303. }
  32304. }
  32305. }
  32306. if (shouldStayOnTop)
  32307. toFront (false);
  32308. internalHierarchyChanged();
  32309. }
  32310. }
  32311. bool Component::isAlwaysOnTop() const throw()
  32312. {
  32313. return flags.alwaysOnTopFlag;
  32314. }
  32315. int Component::proportionOfWidth (const float proportion) const throw()
  32316. {
  32317. return roundToInt (proportion * bounds_.getWidth());
  32318. }
  32319. int Component::proportionOfHeight (const float proportion) const throw()
  32320. {
  32321. return roundToInt (proportion * bounds_.getHeight());
  32322. }
  32323. int Component::getParentWidth() const throw()
  32324. {
  32325. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32326. : getParentMonitorArea().getWidth();
  32327. }
  32328. int Component::getParentHeight() const throw()
  32329. {
  32330. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32331. : getParentMonitorArea().getHeight();
  32332. }
  32333. int Component::getScreenX() const
  32334. {
  32335. return getScreenPosition().getX();
  32336. }
  32337. int Component::getScreenY() const
  32338. {
  32339. return getScreenPosition().getY();
  32340. }
  32341. const Point<int> Component::getScreenPosition() const
  32342. {
  32343. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32344. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32345. : getPosition());
  32346. }
  32347. const Rectangle<int> Component::getScreenBounds() const
  32348. {
  32349. return bounds_.withPosition (getScreenPosition());
  32350. }
  32351. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32352. {
  32353. const Component* c = this;
  32354. Point<int> p (relativePosition);
  32355. do
  32356. {
  32357. if (c->flags.hasHeavyweightPeerFlag)
  32358. return c->getPeer()->relativePositionToGlobal (p);
  32359. p += c->getPosition();
  32360. c = c->parentComponent_;
  32361. }
  32362. while (c != 0);
  32363. return p;
  32364. }
  32365. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32366. {
  32367. if (flags.hasHeavyweightPeerFlag)
  32368. {
  32369. return getPeer()->globalPositionToRelative (screenPosition);
  32370. }
  32371. else
  32372. {
  32373. if (parentComponent_ != 0)
  32374. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32375. return screenPosition - getPosition();
  32376. }
  32377. }
  32378. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32379. {
  32380. Point<int> p (positionRelativeToThis);
  32381. if (targetComponent != 0)
  32382. {
  32383. const Component* c = this;
  32384. do
  32385. {
  32386. if (c == targetComponent)
  32387. return p;
  32388. if (c->flags.hasHeavyweightPeerFlag)
  32389. {
  32390. p = c->getPeer()->relativePositionToGlobal (p);
  32391. break;
  32392. }
  32393. p += c->getPosition();
  32394. c = c->parentComponent_;
  32395. }
  32396. while (c != 0);
  32397. p = targetComponent->globalPositionToRelative (p);
  32398. }
  32399. return p;
  32400. }
  32401. void Component::setBounds (const int x, const int y, int w, int h)
  32402. {
  32403. // if component methods are being called from threads other than the message
  32404. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32405. checkMessageManagerIsLocked
  32406. if (w < 0) w = 0;
  32407. if (h < 0) h = 0;
  32408. const bool wasResized = (getWidth() != w || getHeight() != h);
  32409. const bool wasMoved = (getX() != x || getY() != y);
  32410. #if JUCE_DEBUG
  32411. // It's a very bad idea to try to resize a window during its paint() method!
  32412. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32413. #endif
  32414. if (wasMoved || wasResized)
  32415. {
  32416. if (flags.visibleFlag)
  32417. {
  32418. // send a fake mouse move to trigger enter/exit messages if needed..
  32419. sendFakeMouseMove();
  32420. if (! flags.hasHeavyweightPeerFlag)
  32421. repaintParent();
  32422. }
  32423. bounds_.setBounds (x, y, w, h);
  32424. if (wasResized)
  32425. repaint();
  32426. else if (! flags.hasHeavyweightPeerFlag)
  32427. repaintParent();
  32428. if (flags.hasHeavyweightPeerFlag)
  32429. {
  32430. ComponentPeer* const peer = getPeer();
  32431. if (peer != 0)
  32432. {
  32433. if (wasMoved && wasResized)
  32434. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32435. else if (wasMoved)
  32436. peer->setPosition (getX(), getY());
  32437. else if (wasResized)
  32438. peer->setSize (getWidth(), getHeight());
  32439. }
  32440. }
  32441. sendMovedResizedMessages (wasMoved, wasResized);
  32442. }
  32443. }
  32444. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32445. {
  32446. JUCE_TRY
  32447. {
  32448. if (wasMoved)
  32449. moved();
  32450. if (wasResized)
  32451. {
  32452. resized();
  32453. for (int i = childComponentList_.size(); --i >= 0;)
  32454. {
  32455. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32456. i = jmin (i, childComponentList_.size());
  32457. }
  32458. }
  32459. BailOutChecker checker (this);
  32460. if (parentComponent_ != 0)
  32461. parentComponent_->childBoundsChanged (this);
  32462. if (! checker.shouldBailOut())
  32463. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32464. *this, wasMoved, wasResized);
  32465. }
  32466. JUCE_CATCH_EXCEPTION
  32467. }
  32468. void Component::setSize (const int w, const int h)
  32469. {
  32470. setBounds (getX(), getY(), w, h);
  32471. }
  32472. void Component::setTopLeftPosition (const int x, const int y)
  32473. {
  32474. setBounds (x, y, getWidth(), getHeight());
  32475. }
  32476. void Component::setTopRightPosition (const int x, const int y)
  32477. {
  32478. setTopLeftPosition (x - getWidth(), y);
  32479. }
  32480. void Component::setBounds (const Rectangle<int>& r)
  32481. {
  32482. setBounds (r.getX(),
  32483. r.getY(),
  32484. r.getWidth(),
  32485. r.getHeight());
  32486. }
  32487. void Component::setBoundsRelative (const float x, const float y,
  32488. const float w, const float h)
  32489. {
  32490. const int pw = getParentWidth();
  32491. const int ph = getParentHeight();
  32492. setBounds (roundToInt (x * pw),
  32493. roundToInt (y * ph),
  32494. roundToInt (w * pw),
  32495. roundToInt (h * ph));
  32496. }
  32497. void Component::setCentrePosition (const int x, const int y)
  32498. {
  32499. setTopLeftPosition (x - getWidth() / 2,
  32500. y - getHeight() / 2);
  32501. }
  32502. void Component::setCentreRelative (const float x, const float y)
  32503. {
  32504. setCentrePosition (roundToInt (getParentWidth() * x),
  32505. roundToInt (getParentHeight() * y));
  32506. }
  32507. void Component::centreWithSize (const int width, const int height)
  32508. {
  32509. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32510. setBounds (parentArea.getCentreX() - width / 2,
  32511. parentArea.getCentreY() - height / 2,
  32512. width, height);
  32513. }
  32514. void Component::setBoundsInset (const BorderSize& borders)
  32515. {
  32516. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32517. }
  32518. void Component::setBoundsToFit (int x, int y, int width, int height,
  32519. const Justification& justification,
  32520. const bool onlyReduceInSize)
  32521. {
  32522. // it's no good calling this method unless both the component and
  32523. // target rectangle have a finite size.
  32524. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32525. if (getWidth() > 0 && getHeight() > 0
  32526. && width > 0 && height > 0)
  32527. {
  32528. int newW, newH;
  32529. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32530. {
  32531. newW = getWidth();
  32532. newH = getHeight();
  32533. }
  32534. else
  32535. {
  32536. const double imageRatio = getHeight() / (double) getWidth();
  32537. const double targetRatio = height / (double) width;
  32538. if (imageRatio <= targetRatio)
  32539. {
  32540. newW = width;
  32541. newH = jmin (height, roundToInt (newW * imageRatio));
  32542. }
  32543. else
  32544. {
  32545. newH = height;
  32546. newW = jmin (width, roundToInt (newH / imageRatio));
  32547. }
  32548. }
  32549. if (newW > 0 && newH > 0)
  32550. {
  32551. int newX, newY;
  32552. justification.applyToRectangle (newX, newY, newW, newH,
  32553. x, y, width, height);
  32554. setBounds (newX, newY, newW, newH);
  32555. }
  32556. }
  32557. }
  32558. bool Component::hitTest (int x, int y)
  32559. {
  32560. if (! flags.ignoresMouseClicksFlag)
  32561. return true;
  32562. if (flags.allowChildMouseClicksFlag)
  32563. {
  32564. for (int i = getNumChildComponents(); --i >= 0;)
  32565. {
  32566. Component* const c = getChildComponent (i);
  32567. if (c->isVisible()
  32568. && c->bounds_.contains (x, y)
  32569. && c->hitTest (x - c->getX(),
  32570. y - c->getY()))
  32571. {
  32572. return true;
  32573. }
  32574. }
  32575. }
  32576. return false;
  32577. }
  32578. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32579. const bool allowClicksOnChildComponents) throw()
  32580. {
  32581. flags.ignoresMouseClicksFlag = ! allowClicks;
  32582. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32583. }
  32584. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32585. bool& allowsClicksOnChildComponents) const throw()
  32586. {
  32587. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32588. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32589. }
  32590. bool Component::contains (const int x, const int y)
  32591. {
  32592. if (((unsigned int) x) < (unsigned int) getWidth()
  32593. && ((unsigned int) y) < (unsigned int) getHeight()
  32594. && hitTest (x, y))
  32595. {
  32596. if (parentComponent_ != 0)
  32597. {
  32598. return parentComponent_->contains (x + getX(),
  32599. y + getY());
  32600. }
  32601. else if (flags.hasHeavyweightPeerFlag)
  32602. {
  32603. const ComponentPeer* const peer = getPeer();
  32604. if (peer != 0)
  32605. return peer->contains (Point<int> (x, y), true);
  32606. }
  32607. }
  32608. return false;
  32609. }
  32610. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32611. {
  32612. if (! contains (x, y))
  32613. return false;
  32614. Component* p = this;
  32615. while (p->parentComponent_ != 0)
  32616. {
  32617. x += p->getX();
  32618. y += p->getY();
  32619. p = p->parentComponent_;
  32620. }
  32621. const Component* const c = p->getComponentAt (x, y);
  32622. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32623. }
  32624. Component* Component::getComponentAt (const Point<int>& position)
  32625. {
  32626. return getComponentAt (position.getX(), position.getY());
  32627. }
  32628. Component* Component::getComponentAt (const int x, const int y)
  32629. {
  32630. if (flags.visibleFlag
  32631. && ((unsigned int) x) < (unsigned int) getWidth()
  32632. && ((unsigned int) y) < (unsigned int) getHeight()
  32633. && hitTest (x, y))
  32634. {
  32635. for (int i = childComponentList_.size(); --i >= 0;)
  32636. {
  32637. Component* const child = childComponentList_.getUnchecked(i);
  32638. Component* const c = child->getComponentAt (x - child->getX(),
  32639. y - child->getY());
  32640. if (c != 0)
  32641. return c;
  32642. }
  32643. return this;
  32644. }
  32645. return 0;
  32646. }
  32647. void Component::addChildComponent (Component* const child, int zOrder)
  32648. {
  32649. // if component methods are being called from threads other than the message
  32650. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32651. checkMessageManagerIsLocked
  32652. if (child != 0 && child->parentComponent_ != this)
  32653. {
  32654. if (child->parentComponent_ != 0)
  32655. child->parentComponent_->removeChildComponent (child);
  32656. else
  32657. child->removeFromDesktop();
  32658. child->parentComponent_ = this;
  32659. if (child->isVisible())
  32660. child->repaintParent();
  32661. if (! child->isAlwaysOnTop())
  32662. {
  32663. if (zOrder < 0 || zOrder > childComponentList_.size())
  32664. zOrder = childComponentList_.size();
  32665. while (zOrder > 0)
  32666. {
  32667. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32668. break;
  32669. --zOrder;
  32670. }
  32671. }
  32672. childComponentList_.insert (zOrder, child);
  32673. child->internalHierarchyChanged();
  32674. internalChildrenChanged();
  32675. }
  32676. }
  32677. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32678. {
  32679. if (child != 0)
  32680. {
  32681. child->setVisible (true);
  32682. addChildComponent (child, zOrder);
  32683. }
  32684. }
  32685. void Component::removeChildComponent (Component* const child)
  32686. {
  32687. removeChildComponent (childComponentList_.indexOf (child));
  32688. }
  32689. Component* Component::removeChildComponent (const int index)
  32690. {
  32691. // if component methods are being called from threads other than the message
  32692. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32693. checkMessageManagerIsLocked
  32694. Component* const child = childComponentList_ [index];
  32695. if (child != 0)
  32696. {
  32697. sendFakeMouseMove();
  32698. child->repaintParent();
  32699. childComponentList_.remove (index);
  32700. child->parentComponent_ = 0;
  32701. JUCE_TRY
  32702. {
  32703. if ((currentlyFocusedComponent == child)
  32704. || child->isParentOf (currentlyFocusedComponent))
  32705. {
  32706. // get rid first to force the grabKeyboardFocus to change to us.
  32707. giveAwayFocus();
  32708. grabKeyboardFocus();
  32709. }
  32710. }
  32711. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32712. catch (const std::exception& e)
  32713. {
  32714. currentlyFocusedComponent = 0;
  32715. Desktop::getInstance().triggerFocusCallback();
  32716. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32717. }
  32718. catch (...)
  32719. {
  32720. currentlyFocusedComponent = 0;
  32721. Desktop::getInstance().triggerFocusCallback();
  32722. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32723. }
  32724. #endif
  32725. child->internalHierarchyChanged();
  32726. internalChildrenChanged();
  32727. }
  32728. return child;
  32729. }
  32730. void Component::removeAllChildren()
  32731. {
  32732. while (childComponentList_.size() > 0)
  32733. removeChildComponent (childComponentList_.size() - 1);
  32734. }
  32735. void Component::deleteAllChildren()
  32736. {
  32737. while (childComponentList_.size() > 0)
  32738. delete (removeChildComponent (childComponentList_.size() - 1));
  32739. }
  32740. int Component::getNumChildComponents() const throw()
  32741. {
  32742. return childComponentList_.size();
  32743. }
  32744. Component* Component::getChildComponent (const int index) const throw()
  32745. {
  32746. return childComponentList_ [index];
  32747. }
  32748. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32749. {
  32750. return childComponentList_.indexOf (const_cast <Component*> (child));
  32751. }
  32752. Component* Component::getTopLevelComponent() const throw()
  32753. {
  32754. const Component* comp = this;
  32755. while (comp->parentComponent_ != 0)
  32756. comp = comp->parentComponent_;
  32757. return const_cast <Component*> (comp);
  32758. }
  32759. bool Component::isParentOf (const Component* possibleChild) const throw()
  32760. {
  32761. if (! possibleChild->isValidComponent())
  32762. {
  32763. jassert (possibleChild == 0);
  32764. return false;
  32765. }
  32766. while (possibleChild != 0)
  32767. {
  32768. possibleChild = possibleChild->parentComponent_;
  32769. if (possibleChild == this)
  32770. return true;
  32771. }
  32772. return false;
  32773. }
  32774. void Component::parentHierarchyChanged()
  32775. {
  32776. }
  32777. void Component::childrenChanged()
  32778. {
  32779. }
  32780. void Component::internalChildrenChanged()
  32781. {
  32782. if (componentListeners.isEmpty())
  32783. {
  32784. childrenChanged();
  32785. }
  32786. else
  32787. {
  32788. BailOutChecker checker (this);
  32789. childrenChanged();
  32790. if (! checker.shouldBailOut())
  32791. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32792. }
  32793. }
  32794. void Component::internalHierarchyChanged()
  32795. {
  32796. BailOutChecker checker (this);
  32797. parentHierarchyChanged();
  32798. if (checker.shouldBailOut())
  32799. return;
  32800. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32801. if (checker.shouldBailOut())
  32802. return;
  32803. for (int i = childComponentList_.size(); --i >= 0;)
  32804. {
  32805. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32806. if (checker.shouldBailOut())
  32807. {
  32808. // you really shouldn't delete the parent component during a callback telling you
  32809. // that it's changed..
  32810. jassertfalse;
  32811. return;
  32812. }
  32813. i = jmin (i, childComponentList_.size());
  32814. }
  32815. }
  32816. void* Component::runModalLoopCallback (void* userData)
  32817. {
  32818. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32819. }
  32820. int Component::runModalLoop()
  32821. {
  32822. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32823. {
  32824. // use a callback so this can be called from non-gui threads
  32825. return (int) (pointer_sized_int) MessageManager::getInstance()
  32826. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32827. }
  32828. if (! isCurrentlyModal())
  32829. enterModalState (true);
  32830. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32831. }
  32832. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32833. {
  32834. // if component methods are being called from threads other than the message
  32835. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32836. checkMessageManagerIsLocked
  32837. // Check for an attempt to make a component modal when it already is!
  32838. // This can cause nasty problems..
  32839. jassert (! flags.currentlyModalFlag);
  32840. if (! isCurrentlyModal())
  32841. {
  32842. ModalComponentManager::getInstance()->startModal (this, callback);
  32843. flags.currentlyModalFlag = true;
  32844. setVisible (true);
  32845. if (takeKeyboardFocus_)
  32846. grabKeyboardFocus();
  32847. }
  32848. }
  32849. void Component::exitModalState (const int returnValue)
  32850. {
  32851. if (isCurrentlyModal())
  32852. {
  32853. if (MessageManager::getInstance()->isThisTheMessageThread())
  32854. {
  32855. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32856. flags.currentlyModalFlag = false;
  32857. bringModalComponentToFront();
  32858. }
  32859. else
  32860. {
  32861. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32862. }
  32863. }
  32864. }
  32865. bool Component::isCurrentlyModal() const throw()
  32866. {
  32867. return flags.currentlyModalFlag
  32868. && getCurrentlyModalComponent() == this;
  32869. }
  32870. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32871. {
  32872. Component* const mc = getCurrentlyModalComponent();
  32873. return mc != 0
  32874. && mc != this
  32875. && (! mc->isParentOf (this))
  32876. && ! mc->canModalEventBeSentToComponent (this);
  32877. }
  32878. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32879. {
  32880. return ModalComponentManager::getInstance()->getNumModalComponents();
  32881. }
  32882. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32883. {
  32884. return ModalComponentManager::getInstance()->getModalComponent (index);
  32885. }
  32886. void Component::bringModalComponentToFront()
  32887. {
  32888. ComponentPeer* lastOne = 0;
  32889. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32890. {
  32891. Component* const c = getCurrentlyModalComponent (i);
  32892. if (c == 0)
  32893. break;
  32894. ComponentPeer* peer = c->getPeer();
  32895. if (peer != 0 && peer != lastOne)
  32896. {
  32897. if (lastOne == 0)
  32898. {
  32899. peer->toFront (true);
  32900. peer->grabFocus();
  32901. }
  32902. else
  32903. peer->toBehind (lastOne);
  32904. lastOne = peer;
  32905. }
  32906. }
  32907. }
  32908. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32909. {
  32910. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32911. }
  32912. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32913. {
  32914. return flags.bringToFrontOnClickFlag;
  32915. }
  32916. void Component::setMouseCursor (const MouseCursor& cursor)
  32917. {
  32918. if (cursor_ != cursor)
  32919. {
  32920. cursor_ = cursor;
  32921. if (flags.visibleFlag)
  32922. updateMouseCursor();
  32923. }
  32924. }
  32925. const MouseCursor Component::getMouseCursor()
  32926. {
  32927. return cursor_;
  32928. }
  32929. void Component::updateMouseCursor() const
  32930. {
  32931. sendFakeMouseMove();
  32932. }
  32933. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32934. {
  32935. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32936. }
  32937. void Component::repaintParent()
  32938. {
  32939. if (flags.visibleFlag)
  32940. internalRepaint (0, 0, getWidth(), getHeight());
  32941. }
  32942. void Component::repaint()
  32943. {
  32944. repaint (0, 0, getWidth(), getHeight());
  32945. }
  32946. void Component::repaint (const int x, const int y,
  32947. const int w, const int h)
  32948. {
  32949. bufferedImage_ = Image::null;
  32950. if (flags.visibleFlag)
  32951. internalRepaint (x, y, w, h);
  32952. }
  32953. void Component::repaint (const Rectangle<int>& area)
  32954. {
  32955. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32956. }
  32957. void Component::internalRepaint (int x, int y, int w, int h)
  32958. {
  32959. // if component methods are being called from threads other than the message
  32960. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32961. checkMessageManagerIsLocked
  32962. if (x < 0)
  32963. {
  32964. w += x;
  32965. x = 0;
  32966. }
  32967. if (x + w > getWidth())
  32968. w = getWidth() - x;
  32969. if (w > 0)
  32970. {
  32971. if (y < 0)
  32972. {
  32973. h += y;
  32974. y = 0;
  32975. }
  32976. if (y + h > getHeight())
  32977. h = getHeight() - y;
  32978. if (h > 0)
  32979. {
  32980. if (parentComponent_ != 0)
  32981. {
  32982. x += getX();
  32983. y += getY();
  32984. if (parentComponent_->flags.visibleFlag)
  32985. parentComponent_->internalRepaint (x, y, w, h);
  32986. }
  32987. else if (flags.hasHeavyweightPeerFlag)
  32988. {
  32989. ComponentPeer* const peer = getPeer();
  32990. if (peer != 0)
  32991. peer->repaint (Rectangle<int> (x, y, w, h));
  32992. }
  32993. }
  32994. }
  32995. }
  32996. void Component::renderComponent (Graphics& g)
  32997. {
  32998. const Rectangle<int> clipBounds (g.getClipBounds());
  32999. g.saveState();
  33000. clipObscuredRegions (g, clipBounds, 0, 0);
  33001. if (! g.isClipEmpty())
  33002. {
  33003. if (flags.bufferToImageFlag)
  33004. {
  33005. if (bufferedImage_.isNull())
  33006. {
  33007. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33008. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33009. Graphics imG (bufferedImage_);
  33010. paint (imG);
  33011. }
  33012. g.setColour (Colours::black);
  33013. g.drawImageAt (bufferedImage_, 0, 0);
  33014. }
  33015. else
  33016. {
  33017. paint (g);
  33018. }
  33019. }
  33020. g.restoreState();
  33021. for (int i = 0; i < childComponentList_.size(); ++i)
  33022. {
  33023. Component* const child = childComponentList_.getUnchecked (i);
  33024. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33025. {
  33026. g.saveState();
  33027. if (g.reduceClipRegion (child->getX(), child->getY(),
  33028. child->getWidth(), child->getHeight()))
  33029. {
  33030. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33031. {
  33032. const Component* const sibling = childComponentList_.getUnchecked (j);
  33033. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33034. g.excludeClipRegion (sibling->getBounds());
  33035. }
  33036. if (! g.isClipEmpty())
  33037. {
  33038. g.setOrigin (child->getX(), child->getY());
  33039. child->paintEntireComponent (g);
  33040. }
  33041. }
  33042. g.restoreState();
  33043. }
  33044. }
  33045. g.saveState();
  33046. paintOverChildren (g);
  33047. g.restoreState();
  33048. }
  33049. void Component::paintEntireComponent (Graphics& g)
  33050. {
  33051. jassert (! g.isClipEmpty());
  33052. #if JUCE_DEBUG
  33053. flags.isInsidePaintCall = true;
  33054. #endif
  33055. if (effect_ != 0)
  33056. {
  33057. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33058. getWidth(), getHeight(),
  33059. ! flags.opaqueFlag, Image::NativeImage);
  33060. {
  33061. Graphics g2 (effectImage);
  33062. renderComponent (g2);
  33063. }
  33064. effect_->applyEffect (effectImage, g);
  33065. }
  33066. else
  33067. {
  33068. renderComponent (g);
  33069. }
  33070. #if JUCE_DEBUG
  33071. flags.isInsidePaintCall = false;
  33072. #endif
  33073. }
  33074. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33075. const bool clipImageToComponentBounds)
  33076. {
  33077. Rectangle<int> r (areaToGrab);
  33078. if (clipImageToComponentBounds)
  33079. r = r.getIntersection (getLocalBounds());
  33080. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33081. jmax (1, r.getWidth()),
  33082. jmax (1, r.getHeight()),
  33083. true);
  33084. Graphics imageContext (componentImage);
  33085. imageContext.setOrigin (-r.getX(), -r.getY());
  33086. paintEntireComponent (imageContext);
  33087. return componentImage;
  33088. }
  33089. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33090. {
  33091. if (effect_ != effect)
  33092. {
  33093. effect_ = effect;
  33094. repaint();
  33095. }
  33096. }
  33097. LookAndFeel& Component::getLookAndFeel() const throw()
  33098. {
  33099. const Component* c = this;
  33100. do
  33101. {
  33102. if (c->lookAndFeel_ != 0)
  33103. return *(c->lookAndFeel_);
  33104. c = c->parentComponent_;
  33105. }
  33106. while (c != 0);
  33107. return LookAndFeel::getDefaultLookAndFeel();
  33108. }
  33109. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33110. {
  33111. if (lookAndFeel_ != newLookAndFeel)
  33112. {
  33113. lookAndFeel_ = newLookAndFeel;
  33114. sendLookAndFeelChange();
  33115. }
  33116. }
  33117. void Component::lookAndFeelChanged()
  33118. {
  33119. }
  33120. void Component::sendLookAndFeelChange()
  33121. {
  33122. repaint();
  33123. lookAndFeelChanged();
  33124. // (it's not a great idea to do anything that would delete this component
  33125. // during the lookAndFeelChanged() callback)
  33126. jassert (isValidComponent());
  33127. SafePointer<Component> safePointer (this);
  33128. for (int i = childComponentList_.size(); --i >= 0;)
  33129. {
  33130. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33131. if (safePointer == 0)
  33132. return;
  33133. i = jmin (i, childComponentList_.size());
  33134. }
  33135. }
  33136. static const Identifier getColourPropertyId (const int colourId)
  33137. {
  33138. String s;
  33139. s.preallocateStorage (18);
  33140. s << "jcclr_" << String::toHexString (colourId);
  33141. return s;
  33142. }
  33143. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33144. {
  33145. var* v = properties.getItem (getColourPropertyId (colourId));
  33146. if (v != 0)
  33147. return Colour ((int) *v);
  33148. if (inheritFromParent && parentComponent_ != 0)
  33149. return parentComponent_->findColour (colourId, true);
  33150. return getLookAndFeel().findColour (colourId);
  33151. }
  33152. bool Component::isColourSpecified (const int colourId) const
  33153. {
  33154. return properties.contains (getColourPropertyId (colourId));
  33155. }
  33156. void Component::removeColour (const int colourId)
  33157. {
  33158. if (properties.remove (getColourPropertyId (colourId)))
  33159. colourChanged();
  33160. }
  33161. void Component::setColour (const int colourId, const Colour& colour)
  33162. {
  33163. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33164. colourChanged();
  33165. }
  33166. void Component::copyAllExplicitColoursTo (Component& target) const
  33167. {
  33168. bool changed = false;
  33169. for (int i = properties.size(); --i >= 0;)
  33170. {
  33171. const Identifier name (properties.getName(i));
  33172. if (name.toString().startsWith ("jcclr_"))
  33173. if (target.properties.set (name, properties [name]))
  33174. changed = true;
  33175. }
  33176. if (changed)
  33177. target.colourChanged();
  33178. }
  33179. void Component::colourChanged()
  33180. {
  33181. }
  33182. const Rectangle<int> Component::getLocalBounds() const throw()
  33183. {
  33184. return Rectangle<int> (getWidth(), getHeight());
  33185. }
  33186. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33187. {
  33188. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33189. : Desktop::getInstance().getMainMonitorArea();
  33190. }
  33191. const Rectangle<int> Component::getUnclippedArea() const
  33192. {
  33193. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33194. Component* p = parentComponent_;
  33195. int px = getX();
  33196. int py = getY();
  33197. while (p != 0)
  33198. {
  33199. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33200. return Rectangle<int>();
  33201. px += p->getX();
  33202. py += p->getY();
  33203. p = p->parentComponent_;
  33204. }
  33205. return Rectangle<int> (x, y, w, h);
  33206. }
  33207. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33208. const int deltaX, const int deltaY) const
  33209. {
  33210. for (int i = childComponentList_.size(); --i >= 0;)
  33211. {
  33212. const Component* const c = childComponentList_.getUnchecked(i);
  33213. if (c->isVisible())
  33214. {
  33215. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33216. if (! newClip.isEmpty())
  33217. {
  33218. if (c->isOpaque())
  33219. {
  33220. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33221. }
  33222. else
  33223. {
  33224. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33225. c->getX() + deltaX,
  33226. c->getY() + deltaY);
  33227. }
  33228. }
  33229. }
  33230. }
  33231. }
  33232. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33233. {
  33234. result.clear();
  33235. const Rectangle<int> unclipped (getUnclippedArea());
  33236. if (! unclipped.isEmpty())
  33237. {
  33238. result.add (unclipped);
  33239. if (includeSiblings)
  33240. {
  33241. const Component* const c = getTopLevelComponent();
  33242. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33243. c->getLocalBounds(), this);
  33244. }
  33245. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33246. result.consolidate();
  33247. }
  33248. }
  33249. void Component::subtractObscuredRegions (RectangleList& result,
  33250. const Point<int>& delta,
  33251. const Rectangle<int>& clipRect,
  33252. const Component* const compToAvoid) const
  33253. {
  33254. for (int i = childComponentList_.size(); --i >= 0;)
  33255. {
  33256. const Component* const c = childComponentList_.getUnchecked(i);
  33257. if (c != compToAvoid && c->isVisible())
  33258. {
  33259. if (c->isOpaque())
  33260. {
  33261. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33262. childBounds.translate (delta.getX(), delta.getY());
  33263. result.subtract (childBounds);
  33264. }
  33265. else
  33266. {
  33267. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33268. newClip.translate (-c->getX(), -c->getY());
  33269. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33270. newClip, compToAvoid);
  33271. }
  33272. }
  33273. }
  33274. }
  33275. void Component::mouseEnter (const MouseEvent&)
  33276. {
  33277. // base class does nothing
  33278. }
  33279. void Component::mouseExit (const MouseEvent&)
  33280. {
  33281. // base class does nothing
  33282. }
  33283. void Component::mouseDown (const MouseEvent&)
  33284. {
  33285. // base class does nothing
  33286. }
  33287. void Component::mouseUp (const MouseEvent&)
  33288. {
  33289. // base class does nothing
  33290. }
  33291. void Component::mouseDrag (const MouseEvent&)
  33292. {
  33293. // base class does nothing
  33294. }
  33295. void Component::mouseMove (const MouseEvent&)
  33296. {
  33297. // base class does nothing
  33298. }
  33299. void Component::mouseDoubleClick (const MouseEvent&)
  33300. {
  33301. // base class does nothing
  33302. }
  33303. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33304. {
  33305. // the base class just passes this event up to its parent..
  33306. if (parentComponent_ != 0)
  33307. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33308. wheelIncrementX, wheelIncrementY);
  33309. }
  33310. void Component::resized()
  33311. {
  33312. // base class does nothing
  33313. }
  33314. void Component::moved()
  33315. {
  33316. // base class does nothing
  33317. }
  33318. void Component::childBoundsChanged (Component*)
  33319. {
  33320. // base class does nothing
  33321. }
  33322. void Component::parentSizeChanged()
  33323. {
  33324. // base class does nothing
  33325. }
  33326. void Component::addComponentListener (ComponentListener* const newListener)
  33327. {
  33328. jassert (isValidComponent());
  33329. componentListeners.add (newListener);
  33330. }
  33331. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33332. {
  33333. jassert (isValidComponent());
  33334. componentListeners.remove (listenerToRemove);
  33335. }
  33336. void Component::inputAttemptWhenModal()
  33337. {
  33338. bringModalComponentToFront();
  33339. getLookAndFeel().playAlertSound();
  33340. }
  33341. bool Component::canModalEventBeSentToComponent (const Component*)
  33342. {
  33343. return false;
  33344. }
  33345. void Component::internalModalInputAttempt()
  33346. {
  33347. Component* const current = getCurrentlyModalComponent();
  33348. if (current != 0)
  33349. current->inputAttemptWhenModal();
  33350. }
  33351. void Component::paint (Graphics&)
  33352. {
  33353. // all painting is done in the subclasses
  33354. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33355. }
  33356. void Component::paintOverChildren (Graphics&)
  33357. {
  33358. // all painting is done in the subclasses
  33359. }
  33360. void Component::handleMessage (const Message& message)
  33361. {
  33362. if (message.intParameter1 == exitModalStateMessage)
  33363. {
  33364. exitModalState (message.intParameter2);
  33365. }
  33366. else if (message.intParameter1 == customCommandMessage)
  33367. {
  33368. handleCommandMessage (message.intParameter2);
  33369. }
  33370. }
  33371. void Component::postCommandMessage (const int commandId)
  33372. {
  33373. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33374. }
  33375. void Component::handleCommandMessage (int)
  33376. {
  33377. // used by subclasses
  33378. }
  33379. void Component::addMouseListener (MouseListener* const newListener,
  33380. const bool wantsEventsForAllNestedChildComponents)
  33381. {
  33382. // if component methods are being called from threads other than the message
  33383. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33384. checkMessageManagerIsLocked
  33385. if (mouseListeners_ == 0)
  33386. mouseListeners_ = new Array<MouseListener*>();
  33387. if (! mouseListeners_->contains (newListener))
  33388. {
  33389. if (wantsEventsForAllNestedChildComponents)
  33390. {
  33391. mouseListeners_->insert (0, newListener);
  33392. ++numDeepMouseListeners;
  33393. }
  33394. else
  33395. {
  33396. mouseListeners_->add (newListener);
  33397. }
  33398. }
  33399. }
  33400. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33401. {
  33402. // if component methods are being called from threads other than the message
  33403. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33404. checkMessageManagerIsLocked
  33405. if (mouseListeners_ != 0)
  33406. {
  33407. const int index = mouseListeners_->indexOf (listenerToRemove);
  33408. if (index >= 0)
  33409. {
  33410. if (index < numDeepMouseListeners)
  33411. --numDeepMouseListeners;
  33412. mouseListeners_->remove (index);
  33413. }
  33414. }
  33415. }
  33416. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33417. {
  33418. if (isCurrentlyBlockedByAnotherModalComponent())
  33419. {
  33420. // if something else is modal, always just show a normal mouse cursor
  33421. source.showMouseCursor (MouseCursor::NormalCursor);
  33422. return;
  33423. }
  33424. if (! flags.mouseInsideFlag)
  33425. {
  33426. flags.mouseInsideFlag = true;
  33427. flags.mouseOverFlag = true;
  33428. flags.draggingFlag = false;
  33429. BailOutChecker checker (this);
  33430. if (flags.repaintOnMouseActivityFlag)
  33431. repaint();
  33432. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33433. this, this, time, relativePos,
  33434. time, 0, false);
  33435. mouseEnter (me);
  33436. if (checker.shouldBailOut())
  33437. return;
  33438. Desktop::getInstance().resetTimer();
  33439. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33440. if (checker.shouldBailOut())
  33441. return;
  33442. if (mouseListeners_ != 0)
  33443. {
  33444. for (int i = mouseListeners_->size(); --i >= 0;)
  33445. {
  33446. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33447. if (checker.shouldBailOut())
  33448. return;
  33449. i = jmin (i, mouseListeners_->size());
  33450. }
  33451. }
  33452. Component* p = parentComponent_;
  33453. while (p != 0)
  33454. {
  33455. if (p->numDeepMouseListeners > 0)
  33456. {
  33457. BailOutChecker checker2 (this, p);
  33458. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33459. {
  33460. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33461. if (checker2.shouldBailOut())
  33462. return;
  33463. i = jmin (i, p->numDeepMouseListeners);
  33464. }
  33465. }
  33466. p = p->parentComponent_;
  33467. }
  33468. }
  33469. }
  33470. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33471. {
  33472. BailOutChecker checker (this);
  33473. if (flags.draggingFlag)
  33474. {
  33475. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33476. if (checker.shouldBailOut())
  33477. return;
  33478. }
  33479. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33480. {
  33481. flags.mouseInsideFlag = false;
  33482. flags.mouseOverFlag = false;
  33483. flags.draggingFlag = false;
  33484. if (flags.repaintOnMouseActivityFlag)
  33485. repaint();
  33486. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33487. this, this, time, relativePos,
  33488. time, 0, false);
  33489. mouseExit (me);
  33490. if (checker.shouldBailOut())
  33491. return;
  33492. Desktop::getInstance().resetTimer();
  33493. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33494. if (checker.shouldBailOut())
  33495. return;
  33496. if (mouseListeners_ != 0)
  33497. {
  33498. for (int i = mouseListeners_->size(); --i >= 0;)
  33499. {
  33500. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33501. if (checker.shouldBailOut())
  33502. return;
  33503. i = jmin (i, mouseListeners_->size());
  33504. }
  33505. }
  33506. Component* p = parentComponent_;
  33507. while (p != 0)
  33508. {
  33509. if (p->numDeepMouseListeners > 0)
  33510. {
  33511. BailOutChecker checker2 (this, p);
  33512. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33513. {
  33514. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33515. if (checker2.shouldBailOut())
  33516. return;
  33517. i = jmin (i, p->numDeepMouseListeners);
  33518. }
  33519. }
  33520. p = p->parentComponent_;
  33521. }
  33522. }
  33523. }
  33524. class InternalDragRepeater : public Timer
  33525. {
  33526. public:
  33527. InternalDragRepeater()
  33528. {}
  33529. ~InternalDragRepeater()
  33530. {
  33531. clearSingletonInstance();
  33532. }
  33533. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33534. void timerCallback()
  33535. {
  33536. Desktop& desktop = Desktop::getInstance();
  33537. int numMiceDown = 0;
  33538. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33539. {
  33540. MouseInputSource* const source = desktop.getMouseSource(i);
  33541. if (source->isDragging())
  33542. {
  33543. source->triggerFakeMove();
  33544. ++numMiceDown;
  33545. }
  33546. }
  33547. if (numMiceDown == 0)
  33548. deleteInstance();
  33549. }
  33550. juce_UseDebuggingNewOperator
  33551. private:
  33552. InternalDragRepeater (const InternalDragRepeater&);
  33553. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33554. };
  33555. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33556. void Component::beginDragAutoRepeat (const int interval)
  33557. {
  33558. if (interval > 0)
  33559. {
  33560. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33561. InternalDragRepeater::getInstance()->startTimer (interval);
  33562. }
  33563. else
  33564. {
  33565. InternalDragRepeater::deleteInstance();
  33566. }
  33567. }
  33568. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33569. {
  33570. Desktop& desktop = Desktop::getInstance();
  33571. BailOutChecker checker (this);
  33572. if (isCurrentlyBlockedByAnotherModalComponent())
  33573. {
  33574. internalModalInputAttempt();
  33575. if (checker.shouldBailOut())
  33576. return;
  33577. // If processing the input attempt has exited the modal loop, we'll allow the event
  33578. // to be delivered..
  33579. if (isCurrentlyBlockedByAnotherModalComponent())
  33580. {
  33581. // allow blocked mouse-events to go to global listeners..
  33582. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33583. this, this, time, relativePos, time,
  33584. source.getNumberOfMultipleClicks(), false);
  33585. desktop.resetTimer();
  33586. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33587. return;
  33588. }
  33589. }
  33590. {
  33591. Component* c = this;
  33592. while (c != 0)
  33593. {
  33594. if (c->isBroughtToFrontOnMouseClick())
  33595. {
  33596. c->toFront (true);
  33597. if (checker.shouldBailOut())
  33598. return;
  33599. }
  33600. c = c->parentComponent_;
  33601. }
  33602. }
  33603. if (! flags.dontFocusOnMouseClickFlag)
  33604. {
  33605. grabFocusInternal (focusChangedByMouseClick);
  33606. if (checker.shouldBailOut())
  33607. return;
  33608. }
  33609. flags.draggingFlag = true;
  33610. flags.mouseOverFlag = true;
  33611. if (flags.repaintOnMouseActivityFlag)
  33612. repaint();
  33613. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33614. this, this, time, relativePos, time,
  33615. source.getNumberOfMultipleClicks(), false);
  33616. mouseDown (me);
  33617. if (checker.shouldBailOut())
  33618. return;
  33619. desktop.resetTimer();
  33620. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33621. if (checker.shouldBailOut())
  33622. return;
  33623. if (mouseListeners_ != 0)
  33624. {
  33625. for (int i = mouseListeners_->size(); --i >= 0;)
  33626. {
  33627. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33628. if (checker.shouldBailOut())
  33629. return;
  33630. i = jmin (i, mouseListeners_->size());
  33631. }
  33632. }
  33633. Component* p = parentComponent_;
  33634. while (p != 0)
  33635. {
  33636. if (p->numDeepMouseListeners > 0)
  33637. {
  33638. BailOutChecker checker2 (this, p);
  33639. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33640. {
  33641. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33642. if (checker2.shouldBailOut())
  33643. return;
  33644. i = jmin (i, p->numDeepMouseListeners);
  33645. }
  33646. }
  33647. p = p->parentComponent_;
  33648. }
  33649. }
  33650. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33651. {
  33652. if (flags.draggingFlag)
  33653. {
  33654. Desktop& desktop = Desktop::getInstance();
  33655. flags.draggingFlag = false;
  33656. BailOutChecker checker (this);
  33657. if (flags.repaintOnMouseActivityFlag)
  33658. repaint();
  33659. const MouseEvent me (source, relativePos,
  33660. oldModifiers, this, this, time,
  33661. globalPositionToRelative (source.getLastMouseDownPosition()),
  33662. source.getLastMouseDownTime(),
  33663. source.getNumberOfMultipleClicks(),
  33664. source.hasMouseMovedSignificantlySincePressed());
  33665. mouseUp (me);
  33666. if (checker.shouldBailOut())
  33667. return;
  33668. desktop.resetTimer();
  33669. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33670. if (checker.shouldBailOut())
  33671. return;
  33672. if (mouseListeners_ != 0)
  33673. {
  33674. for (int i = mouseListeners_->size(); --i >= 0;)
  33675. {
  33676. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33677. if (checker.shouldBailOut())
  33678. return;
  33679. i = jmin (i, mouseListeners_->size());
  33680. }
  33681. }
  33682. {
  33683. Component* p = parentComponent_;
  33684. while (p != 0)
  33685. {
  33686. if (p->numDeepMouseListeners > 0)
  33687. {
  33688. BailOutChecker checker2 (this, p);
  33689. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33690. {
  33691. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33692. if (checker2.shouldBailOut())
  33693. return;
  33694. i = jmin (i, p->numDeepMouseListeners);
  33695. }
  33696. }
  33697. p = p->parentComponent_;
  33698. }
  33699. }
  33700. // check for double-click
  33701. if (me.getNumberOfClicks() >= 2)
  33702. {
  33703. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33704. mouseDoubleClick (me);
  33705. if (checker.shouldBailOut())
  33706. return;
  33707. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33708. if (checker.shouldBailOut())
  33709. return;
  33710. for (int i = numListeners; --i >= 0;)
  33711. {
  33712. if (checker.shouldBailOut())
  33713. return;
  33714. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33715. if (ml != 0)
  33716. ml->mouseDoubleClick (me);
  33717. }
  33718. if (checker.shouldBailOut())
  33719. return;
  33720. Component* p = parentComponent_;
  33721. while (p != 0)
  33722. {
  33723. if (p->numDeepMouseListeners > 0)
  33724. {
  33725. BailOutChecker checker2 (this, p);
  33726. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33727. {
  33728. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33729. if (checker2.shouldBailOut())
  33730. return;
  33731. i = jmin (i, p->numDeepMouseListeners);
  33732. }
  33733. }
  33734. p = p->parentComponent_;
  33735. }
  33736. }
  33737. }
  33738. }
  33739. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33740. {
  33741. if (flags.draggingFlag)
  33742. {
  33743. Desktop& desktop = Desktop::getInstance();
  33744. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33745. BailOutChecker checker (this);
  33746. const MouseEvent me (source, relativePos,
  33747. source.getCurrentModifiers(), this, this, time,
  33748. globalPositionToRelative (source.getLastMouseDownPosition()),
  33749. source.getLastMouseDownTime(),
  33750. source.getNumberOfMultipleClicks(),
  33751. source.hasMouseMovedSignificantlySincePressed());
  33752. mouseDrag (me);
  33753. if (checker.shouldBailOut())
  33754. return;
  33755. desktop.resetTimer();
  33756. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33757. if (checker.shouldBailOut())
  33758. return;
  33759. if (mouseListeners_ != 0)
  33760. {
  33761. for (int i = mouseListeners_->size(); --i >= 0;)
  33762. {
  33763. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33764. if (checker.shouldBailOut())
  33765. return;
  33766. i = jmin (i, mouseListeners_->size());
  33767. }
  33768. }
  33769. Component* p = parentComponent_;
  33770. while (p != 0)
  33771. {
  33772. if (p->numDeepMouseListeners > 0)
  33773. {
  33774. BailOutChecker checker2 (this, p);
  33775. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33776. {
  33777. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33778. if (checker2.shouldBailOut())
  33779. return;
  33780. i = jmin (i, p->numDeepMouseListeners);
  33781. }
  33782. }
  33783. p = p->parentComponent_;
  33784. }
  33785. }
  33786. }
  33787. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33788. {
  33789. Desktop& desktop = Desktop::getInstance();
  33790. BailOutChecker checker (this);
  33791. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33792. this, this, time, relativePos,
  33793. time, 0, false);
  33794. if (isCurrentlyBlockedByAnotherModalComponent())
  33795. {
  33796. // allow blocked mouse-events to go to global listeners..
  33797. desktop.sendMouseMove();
  33798. }
  33799. else
  33800. {
  33801. flags.mouseOverFlag = true;
  33802. mouseMove (me);
  33803. if (checker.shouldBailOut())
  33804. return;
  33805. desktop.resetTimer();
  33806. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33807. if (checker.shouldBailOut())
  33808. return;
  33809. if (mouseListeners_ != 0)
  33810. {
  33811. for (int i = mouseListeners_->size(); --i >= 0;)
  33812. {
  33813. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33814. if (checker.shouldBailOut())
  33815. return;
  33816. i = jmin (i, mouseListeners_->size());
  33817. }
  33818. }
  33819. Component* p = parentComponent_;
  33820. while (p != 0)
  33821. {
  33822. if (p->numDeepMouseListeners > 0)
  33823. {
  33824. BailOutChecker checker2 (this, p);
  33825. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33826. {
  33827. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33828. if (checker2.shouldBailOut())
  33829. return;
  33830. i = jmin (i, p->numDeepMouseListeners);
  33831. }
  33832. }
  33833. p = p->parentComponent_;
  33834. }
  33835. }
  33836. }
  33837. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33838. const Time& time, const float amountX, const float amountY)
  33839. {
  33840. Desktop& desktop = Desktop::getInstance();
  33841. BailOutChecker checker (this);
  33842. const float wheelIncrementX = amountX / 256.0f;
  33843. const float wheelIncrementY = amountY / 256.0f;
  33844. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33845. this, this, time, relativePos, time, 0, false);
  33846. if (isCurrentlyBlockedByAnotherModalComponent())
  33847. {
  33848. // allow blocked mouse-events to go to global listeners..
  33849. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33850. }
  33851. else
  33852. {
  33853. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33854. if (checker.shouldBailOut())
  33855. return;
  33856. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33857. if (checker.shouldBailOut())
  33858. return;
  33859. if (mouseListeners_ != 0)
  33860. {
  33861. for (int i = mouseListeners_->size(); --i >= 0;)
  33862. {
  33863. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33864. if (checker.shouldBailOut())
  33865. return;
  33866. i = jmin (i, mouseListeners_->size());
  33867. }
  33868. }
  33869. Component* p = parentComponent_;
  33870. while (p != 0)
  33871. {
  33872. if (p->numDeepMouseListeners > 0)
  33873. {
  33874. BailOutChecker checker2 (this, p);
  33875. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33876. {
  33877. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33878. if (checker2.shouldBailOut())
  33879. return;
  33880. i = jmin (i, p->numDeepMouseListeners);
  33881. }
  33882. }
  33883. p = p->parentComponent_;
  33884. }
  33885. }
  33886. }
  33887. void Component::sendFakeMouseMove() const
  33888. {
  33889. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33890. }
  33891. void Component::broughtToFront()
  33892. {
  33893. }
  33894. void Component::internalBroughtToFront()
  33895. {
  33896. if (! isValidComponent())
  33897. return;
  33898. if (flags.hasHeavyweightPeerFlag)
  33899. Desktop::getInstance().componentBroughtToFront (this);
  33900. BailOutChecker checker (this);
  33901. broughtToFront();
  33902. if (checker.shouldBailOut())
  33903. return;
  33904. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33905. if (checker.shouldBailOut())
  33906. return;
  33907. // When brought to the front and there's a modal component blocking this one,
  33908. // we need to bring the modal one to the front instead..
  33909. Component* const cm = getCurrentlyModalComponent();
  33910. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33911. bringModalComponentToFront();
  33912. }
  33913. void Component::focusGained (FocusChangeType)
  33914. {
  33915. // base class does nothing
  33916. }
  33917. void Component::internalFocusGain (const FocusChangeType cause)
  33918. {
  33919. SafePointer<Component> safePointer (this);
  33920. focusGained (cause);
  33921. if (safePointer != 0)
  33922. internalChildFocusChange (cause);
  33923. }
  33924. void Component::focusLost (FocusChangeType)
  33925. {
  33926. // base class does nothing
  33927. }
  33928. void Component::internalFocusLoss (const FocusChangeType cause)
  33929. {
  33930. SafePointer<Component> safePointer (this);
  33931. focusLost (focusChangedDirectly);
  33932. if (safePointer != 0)
  33933. internalChildFocusChange (cause);
  33934. }
  33935. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33936. {
  33937. // base class does nothing
  33938. }
  33939. void Component::internalChildFocusChange (FocusChangeType cause)
  33940. {
  33941. const bool childIsNowFocused = hasKeyboardFocus (true);
  33942. if (flags.childCompFocusedFlag != childIsNowFocused)
  33943. {
  33944. flags.childCompFocusedFlag = childIsNowFocused;
  33945. SafePointer<Component> safePointer (this);
  33946. focusOfChildComponentChanged (cause);
  33947. if (safePointer == 0)
  33948. return;
  33949. }
  33950. if (parentComponent_ != 0)
  33951. parentComponent_->internalChildFocusChange (cause);
  33952. }
  33953. bool Component::isEnabled() const throw()
  33954. {
  33955. return (! flags.isDisabledFlag)
  33956. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33957. }
  33958. void Component::setEnabled (const bool shouldBeEnabled)
  33959. {
  33960. if (flags.isDisabledFlag == shouldBeEnabled)
  33961. {
  33962. flags.isDisabledFlag = ! shouldBeEnabled;
  33963. // if any parent components are disabled, setting our flag won't make a difference,
  33964. // so no need to send a change message
  33965. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33966. sendEnablementChangeMessage();
  33967. }
  33968. }
  33969. void Component::sendEnablementChangeMessage()
  33970. {
  33971. SafePointer<Component> safePointer (this);
  33972. enablementChanged();
  33973. if (safePointer == 0)
  33974. return;
  33975. for (int i = getNumChildComponents(); --i >= 0;)
  33976. {
  33977. Component* const c = getChildComponent (i);
  33978. if (c != 0)
  33979. {
  33980. c->sendEnablementChangeMessage();
  33981. if (safePointer == 0)
  33982. return;
  33983. }
  33984. }
  33985. }
  33986. void Component::enablementChanged()
  33987. {
  33988. }
  33989. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33990. {
  33991. flags.wantsFocusFlag = wantsFocus;
  33992. }
  33993. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33994. {
  33995. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33996. }
  33997. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33998. {
  33999. return ! flags.dontFocusOnMouseClickFlag;
  34000. }
  34001. bool Component::getWantsKeyboardFocus() const throw()
  34002. {
  34003. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34004. }
  34005. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34006. {
  34007. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34008. }
  34009. bool Component::isFocusContainer() const throw()
  34010. {
  34011. return flags.isFocusContainerFlag;
  34012. }
  34013. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34014. int Component::getExplicitFocusOrder() const
  34015. {
  34016. return properties [juce_explicitFocusOrderId];
  34017. }
  34018. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34019. {
  34020. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34021. }
  34022. KeyboardFocusTraverser* Component::createFocusTraverser()
  34023. {
  34024. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34025. return new KeyboardFocusTraverser();
  34026. return parentComponent_->createFocusTraverser();
  34027. }
  34028. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34029. {
  34030. // give the focus to this component
  34031. if (currentlyFocusedComponent != this)
  34032. {
  34033. JUCE_TRY
  34034. {
  34035. // get the focus onto our desktop window
  34036. ComponentPeer* const peer = getPeer();
  34037. if (peer != 0)
  34038. {
  34039. SafePointer<Component> safePointer (this);
  34040. peer->grabFocus();
  34041. if (peer->isFocused() && currentlyFocusedComponent != this)
  34042. {
  34043. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34044. currentlyFocusedComponent = this;
  34045. Desktop::getInstance().triggerFocusCallback();
  34046. // call this after setting currentlyFocusedComponent so that the one that's
  34047. // losing it has a chance to see where focus is going
  34048. if (componentLosingFocus != 0)
  34049. componentLosingFocus->internalFocusLoss (cause);
  34050. if (currentlyFocusedComponent == this)
  34051. {
  34052. focusGained (cause);
  34053. if (safePointer != 0)
  34054. internalChildFocusChange (cause);
  34055. }
  34056. }
  34057. }
  34058. }
  34059. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34060. catch (const std::exception& e)
  34061. {
  34062. currentlyFocusedComponent = 0;
  34063. Desktop::getInstance().triggerFocusCallback();
  34064. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34065. }
  34066. catch (...)
  34067. {
  34068. currentlyFocusedComponent = 0;
  34069. Desktop::getInstance().triggerFocusCallback();
  34070. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34071. }
  34072. #endif
  34073. }
  34074. }
  34075. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34076. {
  34077. if (isShowing())
  34078. {
  34079. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34080. {
  34081. takeKeyboardFocus (cause);
  34082. }
  34083. else
  34084. {
  34085. if (isParentOf (currentlyFocusedComponent)
  34086. && currentlyFocusedComponent->isShowing())
  34087. {
  34088. // do nothing if the focused component is actually a child of ours..
  34089. }
  34090. else
  34091. {
  34092. // find the default child component..
  34093. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34094. if (traverser != 0)
  34095. {
  34096. Component* const defaultComp = traverser->getDefaultComponent (this);
  34097. traverser = 0;
  34098. if (defaultComp != 0)
  34099. {
  34100. defaultComp->grabFocusInternal (cause, false);
  34101. return;
  34102. }
  34103. }
  34104. if (canTryParent && parentComponent_ != 0)
  34105. {
  34106. // if no children want it and we're allowed to try our parent comp,
  34107. // then pass up to parent, which will try our siblings.
  34108. parentComponent_->grabFocusInternal (cause, true);
  34109. }
  34110. }
  34111. }
  34112. }
  34113. }
  34114. void Component::grabKeyboardFocus()
  34115. {
  34116. // if component methods are being called from threads other than the message
  34117. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34118. checkMessageManagerIsLocked
  34119. grabFocusInternal (focusChangedDirectly);
  34120. }
  34121. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34122. {
  34123. // if component methods are being called from threads other than the message
  34124. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34125. checkMessageManagerIsLocked
  34126. if (parentComponent_ != 0)
  34127. {
  34128. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34129. if (traverser != 0)
  34130. {
  34131. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34132. : traverser->getPreviousComponent (this);
  34133. traverser = 0;
  34134. if (nextComp != 0)
  34135. {
  34136. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34137. {
  34138. SafePointer<Component> nextCompPointer (nextComp);
  34139. internalModalInputAttempt();
  34140. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34141. return;
  34142. }
  34143. nextComp->grabFocusInternal (focusChangedByTabKey);
  34144. return;
  34145. }
  34146. }
  34147. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34148. }
  34149. }
  34150. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34151. {
  34152. return (currentlyFocusedComponent == this)
  34153. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34154. }
  34155. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34156. {
  34157. return currentlyFocusedComponent;
  34158. }
  34159. void Component::giveAwayFocus()
  34160. {
  34161. // use a copy so we can clear the value before the call
  34162. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34163. currentlyFocusedComponent = 0;
  34164. Desktop::getInstance().triggerFocusCallback();
  34165. if (componentLosingFocus != 0)
  34166. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34167. }
  34168. bool Component::isMouseOver() const throw()
  34169. {
  34170. return flags.mouseOverFlag;
  34171. }
  34172. bool Component::isMouseButtonDown() const throw()
  34173. {
  34174. return flags.draggingFlag;
  34175. }
  34176. bool Component::isMouseOverOrDragging() const throw()
  34177. {
  34178. return flags.mouseOverFlag || flags.draggingFlag;
  34179. }
  34180. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34181. {
  34182. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34183. }
  34184. const Point<int> Component::getMouseXYRelative() const
  34185. {
  34186. return globalPositionToRelative (Desktop::getMousePosition());
  34187. }
  34188. const Rectangle<int> Component::getParentMonitorArea() const
  34189. {
  34190. return Desktop::getInstance()
  34191. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34192. }
  34193. void Component::addKeyListener (KeyListener* const newListener)
  34194. {
  34195. if (keyListeners_ == 0)
  34196. keyListeners_ = new Array <KeyListener*>();
  34197. keyListeners_->addIfNotAlreadyThere (newListener);
  34198. }
  34199. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34200. {
  34201. if (keyListeners_ != 0)
  34202. keyListeners_->removeValue (listenerToRemove);
  34203. }
  34204. bool Component::keyPressed (const KeyPress&)
  34205. {
  34206. return false;
  34207. }
  34208. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34209. {
  34210. return false;
  34211. }
  34212. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34213. {
  34214. if (parentComponent_ != 0)
  34215. parentComponent_->modifierKeysChanged (modifiers);
  34216. }
  34217. void Component::internalModifierKeysChanged()
  34218. {
  34219. sendFakeMouseMove();
  34220. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34221. }
  34222. ComponentPeer* Component::getPeer() const
  34223. {
  34224. if (flags.hasHeavyweightPeerFlag)
  34225. return ComponentPeer::getPeerFor (this);
  34226. else if (parentComponent_ != 0)
  34227. return parentComponent_->getPeer();
  34228. else
  34229. return 0;
  34230. }
  34231. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34232. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34233. {
  34234. jassert (component1 != 0);
  34235. }
  34236. bool Component::BailOutChecker::shouldBailOut() const throw()
  34237. {
  34238. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34239. }
  34240. END_JUCE_NAMESPACE
  34241. /*** End of inlined file: juce_Component.cpp ***/
  34242. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34243. BEGIN_JUCE_NAMESPACE
  34244. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34245. void ComponentListener::componentBroughtToFront (Component&) {}
  34246. void ComponentListener::componentVisibilityChanged (Component&) {}
  34247. void ComponentListener::componentChildrenChanged (Component&) {}
  34248. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34249. void ComponentListener::componentNameChanged (Component&) {}
  34250. void ComponentListener::componentBeingDeleted (Component&) {}
  34251. END_JUCE_NAMESPACE
  34252. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34253. /*** Start of inlined file: juce_Desktop.cpp ***/
  34254. BEGIN_JUCE_NAMESPACE
  34255. Desktop::Desktop()
  34256. : mouseClickCounter (0),
  34257. kioskModeComponent (0)
  34258. {
  34259. createMouseInputSources();
  34260. refreshMonitorSizes();
  34261. }
  34262. Desktop::~Desktop()
  34263. {
  34264. jassert (instance == this);
  34265. instance = 0;
  34266. // doh! If you don't delete all your windows before exiting, you're going to
  34267. // be leaking memory!
  34268. jassert (desktopComponents.size() == 0);
  34269. }
  34270. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34271. {
  34272. if (instance == 0)
  34273. instance = new Desktop();
  34274. return *instance;
  34275. }
  34276. Desktop* Desktop::instance = 0;
  34277. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34278. const bool clipToWorkArea);
  34279. void Desktop::refreshMonitorSizes()
  34280. {
  34281. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34282. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34283. monitorCoordsClipped.clear();
  34284. monitorCoordsUnclipped.clear();
  34285. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34286. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34287. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34288. if (oldClipped != monitorCoordsClipped
  34289. || oldUnclipped != monitorCoordsUnclipped)
  34290. {
  34291. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34292. {
  34293. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34294. if (p != 0)
  34295. p->handleScreenSizeChange();
  34296. }
  34297. }
  34298. }
  34299. int Desktop::getNumDisplayMonitors() const throw()
  34300. {
  34301. return monitorCoordsClipped.size();
  34302. }
  34303. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34304. {
  34305. return clippedToWorkArea ? monitorCoordsClipped [index]
  34306. : monitorCoordsUnclipped [index];
  34307. }
  34308. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34309. {
  34310. RectangleList rl;
  34311. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34312. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34313. return rl;
  34314. }
  34315. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34316. {
  34317. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34318. }
  34319. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34320. {
  34321. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34322. double bestDistance = 1.0e10;
  34323. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34324. {
  34325. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34326. if (rect.contains (position))
  34327. return rect;
  34328. const double distance = rect.getCentre().getDistanceFrom (position);
  34329. if (distance < bestDistance)
  34330. {
  34331. bestDistance = distance;
  34332. best = rect;
  34333. }
  34334. }
  34335. return best;
  34336. }
  34337. int Desktop::getNumComponents() const throw()
  34338. {
  34339. return desktopComponents.size();
  34340. }
  34341. Component* Desktop::getComponent (const int index) const throw()
  34342. {
  34343. return desktopComponents [index];
  34344. }
  34345. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34346. {
  34347. for (int i = desktopComponents.size(); --i >= 0;)
  34348. {
  34349. Component* const c = desktopComponents.getUnchecked(i);
  34350. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34351. if (c->contains (relative.getX(), relative.getY()))
  34352. return c->getComponentAt (relative.getX(), relative.getY());
  34353. }
  34354. return 0;
  34355. }
  34356. void Desktop::addDesktopComponent (Component* const c)
  34357. {
  34358. jassert (c != 0);
  34359. jassert (! desktopComponents.contains (c));
  34360. desktopComponents.addIfNotAlreadyThere (c);
  34361. }
  34362. void Desktop::removeDesktopComponent (Component* const c)
  34363. {
  34364. desktopComponents.removeValue (c);
  34365. }
  34366. void Desktop::componentBroughtToFront (Component* const c)
  34367. {
  34368. const int index = desktopComponents.indexOf (c);
  34369. jassert (index >= 0);
  34370. if (index >= 0)
  34371. {
  34372. int newIndex = -1;
  34373. if (! c->isAlwaysOnTop())
  34374. {
  34375. newIndex = desktopComponents.size();
  34376. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34377. --newIndex;
  34378. --newIndex;
  34379. }
  34380. desktopComponents.move (index, newIndex);
  34381. }
  34382. }
  34383. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34384. {
  34385. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34386. }
  34387. int Desktop::getMouseButtonClickCounter() throw()
  34388. {
  34389. return getInstance().mouseClickCounter;
  34390. }
  34391. void Desktop::incrementMouseClickCounter() throw()
  34392. {
  34393. ++mouseClickCounter;
  34394. }
  34395. int Desktop::getNumDraggingMouseSources() const throw()
  34396. {
  34397. int num = 0;
  34398. for (int i = mouseSources.size(); --i >= 0;)
  34399. if (mouseSources.getUnchecked(i)->isDragging())
  34400. ++num;
  34401. return num;
  34402. }
  34403. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34404. {
  34405. int num = 0;
  34406. for (int i = mouseSources.size(); --i >= 0;)
  34407. {
  34408. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34409. if (mi->isDragging())
  34410. {
  34411. if (index == num)
  34412. return mi;
  34413. ++num;
  34414. }
  34415. }
  34416. return 0;
  34417. }
  34418. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34419. {
  34420. focusListeners.add (listener);
  34421. }
  34422. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34423. {
  34424. focusListeners.remove (listener);
  34425. }
  34426. void Desktop::triggerFocusCallback()
  34427. {
  34428. triggerAsyncUpdate();
  34429. }
  34430. void Desktop::handleAsyncUpdate()
  34431. {
  34432. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34433. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34434. }
  34435. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34436. {
  34437. mouseListeners.add (listener);
  34438. resetTimer();
  34439. }
  34440. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34441. {
  34442. mouseListeners.remove (listener);
  34443. resetTimer();
  34444. }
  34445. void Desktop::timerCallback()
  34446. {
  34447. if (lastFakeMouseMove != getMousePosition())
  34448. sendMouseMove();
  34449. }
  34450. void Desktop::sendMouseMove()
  34451. {
  34452. if (! mouseListeners.isEmpty())
  34453. {
  34454. startTimer (20);
  34455. lastFakeMouseMove = getMousePosition();
  34456. Component* const target = findComponentAt (lastFakeMouseMove);
  34457. if (target != 0)
  34458. {
  34459. Component::BailOutChecker checker (target);
  34460. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34461. const Time now (Time::getCurrentTime());
  34462. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34463. target, target, now, pos, now, 0, false);
  34464. if (me.mods.isAnyMouseButtonDown())
  34465. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34466. else
  34467. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34468. }
  34469. }
  34470. }
  34471. void Desktop::resetTimer()
  34472. {
  34473. if (mouseListeners.size() == 0)
  34474. stopTimer();
  34475. else
  34476. startTimer (100);
  34477. lastFakeMouseMove = getMousePosition();
  34478. }
  34479. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34480. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34481. {
  34482. if (kioskModeComponent != componentToUse)
  34483. {
  34484. // agh! Don't delete a component without first stopping it being the kiosk comp
  34485. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34486. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34487. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34488. if (kioskModeComponent->isValidComponent())
  34489. {
  34490. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34491. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34492. }
  34493. kioskModeComponent = componentToUse;
  34494. if (kioskModeComponent != 0)
  34495. {
  34496. jassert (kioskModeComponent->isValidComponent());
  34497. // Only components that are already on the desktop can be put into kiosk mode!
  34498. jassert (kioskModeComponent->isOnDesktop());
  34499. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34500. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34501. }
  34502. }
  34503. }
  34504. END_JUCE_NAMESPACE
  34505. /*** End of inlined file: juce_Desktop.cpp ***/
  34506. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34507. BEGIN_JUCE_NAMESPACE
  34508. class ModalComponentManager::ModalItem : public ComponentListener
  34509. {
  34510. public:
  34511. ModalItem (Component* const comp, Callback* const callback)
  34512. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34513. {
  34514. if (callback != 0)
  34515. callbacks.add (callback);
  34516. jassert (comp != 0);
  34517. component->addComponentListener (this);
  34518. }
  34519. ~ModalItem()
  34520. {
  34521. if (! isDeleted)
  34522. component->removeComponentListener (this);
  34523. }
  34524. void componentBeingDeleted (Component&)
  34525. {
  34526. isDeleted = true;
  34527. cancel();
  34528. }
  34529. void componentVisibilityChanged (Component&)
  34530. {
  34531. if (! component->isShowing())
  34532. cancel();
  34533. }
  34534. void componentParentHierarchyChanged (Component&)
  34535. {
  34536. if (! component->isShowing())
  34537. cancel();
  34538. }
  34539. void cancel()
  34540. {
  34541. if (isActive)
  34542. {
  34543. isActive = false;
  34544. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34545. }
  34546. }
  34547. Component* component;
  34548. OwnedArray<Callback> callbacks;
  34549. int returnValue;
  34550. bool isActive, isDeleted;
  34551. private:
  34552. ModalItem (const ModalItem&);
  34553. ModalItem& operator= (const ModalItem&);
  34554. };
  34555. ModalComponentManager::ModalComponentManager()
  34556. {
  34557. }
  34558. ModalComponentManager::~ModalComponentManager()
  34559. {
  34560. clearSingletonInstance();
  34561. }
  34562. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34563. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34564. {
  34565. if (component != 0)
  34566. stack.add (new ModalItem (component, callback));
  34567. }
  34568. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34569. {
  34570. if (callback != 0)
  34571. {
  34572. ScopedPointer<Callback> callbackDeleter (callback);
  34573. for (int i = stack.size(); --i >= 0;)
  34574. {
  34575. ModalItem* const item = stack.getUnchecked(i);
  34576. if (item->component == component)
  34577. {
  34578. item->callbacks.add (callback);
  34579. callbackDeleter.release();
  34580. break;
  34581. }
  34582. }
  34583. }
  34584. }
  34585. void ModalComponentManager::endModal (Component* component)
  34586. {
  34587. for (int i = stack.size(); --i >= 0;)
  34588. {
  34589. ModalItem* const item = stack.getUnchecked(i);
  34590. if (item->component == component)
  34591. item->cancel();
  34592. }
  34593. }
  34594. void ModalComponentManager::endModal (Component* component, int returnValue)
  34595. {
  34596. for (int i = stack.size(); --i >= 0;)
  34597. {
  34598. ModalItem* const item = stack.getUnchecked(i);
  34599. if (item->component == component)
  34600. {
  34601. item->returnValue = returnValue;
  34602. item->cancel();
  34603. }
  34604. }
  34605. }
  34606. int ModalComponentManager::getNumModalComponents() const
  34607. {
  34608. int n = 0;
  34609. for (int i = 0; i < stack.size(); ++i)
  34610. if (stack.getUnchecked(i)->isActive)
  34611. ++n;
  34612. return n;
  34613. }
  34614. Component* ModalComponentManager::getModalComponent (const int index) const
  34615. {
  34616. int n = 0;
  34617. for (int i = stack.size(); --i >= 0;)
  34618. {
  34619. const ModalItem* const item = stack.getUnchecked(i);
  34620. if (item->isActive)
  34621. if (n++ == index)
  34622. return item->component;
  34623. }
  34624. return 0;
  34625. }
  34626. bool ModalComponentManager::isModal (Component* const comp) const
  34627. {
  34628. for (int i = stack.size(); --i >= 0;)
  34629. {
  34630. const ModalItem* const item = stack.getUnchecked(i);
  34631. if (item->isActive && item->component == comp)
  34632. return true;
  34633. }
  34634. return false;
  34635. }
  34636. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34637. {
  34638. return comp == getModalComponent (0);
  34639. }
  34640. void ModalComponentManager::handleAsyncUpdate()
  34641. {
  34642. for (int i = stack.size(); --i >= 0;)
  34643. {
  34644. const ModalItem* const item = stack.getUnchecked(i);
  34645. if (! item->isActive)
  34646. {
  34647. for (int j = item->callbacks.size(); --j >= 0;)
  34648. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34649. stack.remove (i);
  34650. }
  34651. }
  34652. }
  34653. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34654. {
  34655. public:
  34656. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34657. ~ReturnValueRetriever() {}
  34658. void modalStateFinished (int returnValue)
  34659. {
  34660. finished = true;
  34661. value = returnValue;
  34662. }
  34663. private:
  34664. int& value;
  34665. bool& finished;
  34666. ReturnValueRetriever (const ReturnValueRetriever&);
  34667. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34668. };
  34669. int ModalComponentManager::runEventLoopForCurrentComponent()
  34670. {
  34671. // This can only be run from the message thread!
  34672. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34673. Component* currentlyModal = getModalComponent (0);
  34674. if (currentlyModal == 0)
  34675. return 0;
  34676. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34677. int returnValue = 0;
  34678. bool finished = false;
  34679. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34680. JUCE_TRY
  34681. {
  34682. while (! finished)
  34683. {
  34684. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34685. break;
  34686. }
  34687. }
  34688. JUCE_CATCH_EXCEPTION
  34689. if (prevFocused != 0)
  34690. prevFocused->grabKeyboardFocus();
  34691. return returnValue;
  34692. }
  34693. END_JUCE_NAMESPACE
  34694. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34695. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34696. BEGIN_JUCE_NAMESPACE
  34697. ArrowButton::ArrowButton (const String& name,
  34698. float arrowDirectionInRadians,
  34699. const Colour& arrowColour)
  34700. : Button (name),
  34701. colour (arrowColour)
  34702. {
  34703. path.lineTo (0.0f, 1.0f);
  34704. path.lineTo (1.0f, 0.5f);
  34705. path.closeSubPath();
  34706. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34707. 0.5f, 0.5f));
  34708. setComponentEffect (&shadow);
  34709. buttonStateChanged();
  34710. }
  34711. ArrowButton::~ArrowButton()
  34712. {
  34713. }
  34714. void ArrowButton::paintButton (Graphics& g,
  34715. bool /*isMouseOverButton*/,
  34716. bool /*isButtonDown*/)
  34717. {
  34718. g.setColour (colour);
  34719. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34720. (float) offset,
  34721. (float) (getWidth() - 3),
  34722. (float) (getHeight() - 3),
  34723. false));
  34724. }
  34725. void ArrowButton::buttonStateChanged()
  34726. {
  34727. offset = (isDown()) ? 1 : 0;
  34728. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34729. 0.3f, -1, 0);
  34730. }
  34731. END_JUCE_NAMESPACE
  34732. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34733. /*** Start of inlined file: juce_Button.cpp ***/
  34734. BEGIN_JUCE_NAMESPACE
  34735. class Button::RepeatTimer : public Timer
  34736. {
  34737. public:
  34738. RepeatTimer (Button& owner_) : owner (owner_) {}
  34739. void timerCallback() { owner.repeatTimerCallback(); }
  34740. juce_UseDebuggingNewOperator
  34741. private:
  34742. Button& owner;
  34743. RepeatTimer (const RepeatTimer&);
  34744. RepeatTimer& operator= (const RepeatTimer&);
  34745. };
  34746. Button::Button (const String& name)
  34747. : Component (name),
  34748. text (name),
  34749. buttonPressTime (0),
  34750. lastTimeCallbackTime (0),
  34751. commandManagerToUse (0),
  34752. autoRepeatDelay (-1),
  34753. autoRepeatSpeed (0),
  34754. autoRepeatMinimumDelay (-1),
  34755. radioGroupId (0),
  34756. commandID (0),
  34757. connectedEdgeFlags (0),
  34758. buttonState (buttonNormal),
  34759. lastToggleState (false),
  34760. clickTogglesState (false),
  34761. needsToRelease (false),
  34762. needsRepainting (false),
  34763. isKeyDown (false),
  34764. triggerOnMouseDown (false),
  34765. generateTooltip (false)
  34766. {
  34767. setWantsKeyboardFocus (true);
  34768. isOn.addListener (this);
  34769. }
  34770. Button::~Button()
  34771. {
  34772. isOn.removeListener (this);
  34773. if (commandManagerToUse != 0)
  34774. commandManagerToUse->removeListener (this);
  34775. repeatTimer = 0;
  34776. clearShortcuts();
  34777. }
  34778. void Button::setButtonText (const String& newText)
  34779. {
  34780. if (text != newText)
  34781. {
  34782. text = newText;
  34783. repaint();
  34784. }
  34785. }
  34786. void Button::setTooltip (const String& newTooltip)
  34787. {
  34788. SettableTooltipClient::setTooltip (newTooltip);
  34789. generateTooltip = false;
  34790. }
  34791. const String Button::getTooltip()
  34792. {
  34793. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34794. {
  34795. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34796. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34797. for (int i = 0; i < keyPresses.size(); ++i)
  34798. {
  34799. const String key (keyPresses.getReference(i).getTextDescription());
  34800. tt << " [";
  34801. if (key.length() == 1)
  34802. tt << TRANS("shortcut") << ": '" << key << "']";
  34803. else
  34804. tt << key << ']';
  34805. }
  34806. return tt;
  34807. }
  34808. return SettableTooltipClient::getTooltip();
  34809. }
  34810. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34811. {
  34812. if (connectedEdgeFlags != connectedEdgeFlags_)
  34813. {
  34814. connectedEdgeFlags = connectedEdgeFlags_;
  34815. repaint();
  34816. }
  34817. }
  34818. void Button::setToggleState (const bool shouldBeOn,
  34819. const bool sendChangeNotification)
  34820. {
  34821. if (shouldBeOn != lastToggleState)
  34822. {
  34823. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34824. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34825. lastToggleState = shouldBeOn;
  34826. repaint();
  34827. if (sendChangeNotification)
  34828. {
  34829. Component::SafePointer<Component> deletionWatcher (this);
  34830. sendClickMessage (ModifierKeys());
  34831. if (deletionWatcher == 0)
  34832. return;
  34833. }
  34834. if (lastToggleState)
  34835. turnOffOtherButtonsInGroup (sendChangeNotification);
  34836. }
  34837. }
  34838. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34839. {
  34840. clickTogglesState = shouldToggle;
  34841. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34842. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34843. // it is that this button represents, and the button will update its state to reflect this
  34844. // in the applicationCommandListChanged() method.
  34845. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34846. }
  34847. bool Button::getClickingTogglesState() const throw()
  34848. {
  34849. return clickTogglesState;
  34850. }
  34851. void Button::valueChanged (Value& value)
  34852. {
  34853. if (value.refersToSameSourceAs (isOn))
  34854. setToggleState (isOn.getValue(), true);
  34855. }
  34856. void Button::setRadioGroupId (const int newGroupId)
  34857. {
  34858. if (radioGroupId != newGroupId)
  34859. {
  34860. radioGroupId = newGroupId;
  34861. if (lastToggleState)
  34862. turnOffOtherButtonsInGroup (true);
  34863. }
  34864. }
  34865. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34866. {
  34867. Component* const p = getParentComponent();
  34868. if (p != 0 && radioGroupId != 0)
  34869. {
  34870. Component::SafePointer<Component> deletionWatcher (this);
  34871. for (int i = p->getNumChildComponents(); --i >= 0;)
  34872. {
  34873. Component* const c = p->getChildComponent (i);
  34874. if (c != this)
  34875. {
  34876. Button* const b = dynamic_cast <Button*> (c);
  34877. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34878. {
  34879. b->setToggleState (false, sendChangeNotification);
  34880. if (deletionWatcher == 0)
  34881. return;
  34882. }
  34883. }
  34884. }
  34885. }
  34886. }
  34887. void Button::enablementChanged()
  34888. {
  34889. updateState (0);
  34890. repaint();
  34891. }
  34892. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34893. {
  34894. ButtonState state = buttonNormal;
  34895. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34896. {
  34897. Point<int> mousePos;
  34898. if (e == 0)
  34899. mousePos = getMouseXYRelative();
  34900. else
  34901. mousePos = e->getEventRelativeTo (this).getPosition();
  34902. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34903. const bool down = isMouseButtonDown();
  34904. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34905. state = buttonDown;
  34906. else if (over)
  34907. state = buttonOver;
  34908. }
  34909. setState (state);
  34910. return state;
  34911. }
  34912. void Button::setState (const ButtonState newState)
  34913. {
  34914. if (buttonState != newState)
  34915. {
  34916. buttonState = newState;
  34917. repaint();
  34918. if (buttonState == buttonDown)
  34919. {
  34920. buttonPressTime = Time::getApproximateMillisecondCounter();
  34921. lastTimeCallbackTime = buttonPressTime;
  34922. }
  34923. sendStateMessage();
  34924. }
  34925. }
  34926. bool Button::isDown() const throw()
  34927. {
  34928. return buttonState == buttonDown;
  34929. }
  34930. bool Button::isOver() const throw()
  34931. {
  34932. return buttonState != buttonNormal;
  34933. }
  34934. void Button::buttonStateChanged()
  34935. {
  34936. }
  34937. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34938. {
  34939. const uint32 now = Time::getApproximateMillisecondCounter();
  34940. return now > buttonPressTime ? now - buttonPressTime : 0;
  34941. }
  34942. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34943. {
  34944. triggerOnMouseDown = isTriggeredOnMouseDown;
  34945. }
  34946. void Button::clicked()
  34947. {
  34948. }
  34949. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34950. {
  34951. clicked();
  34952. }
  34953. static const int clickMessageId = 0x2f3f4f99;
  34954. void Button::triggerClick()
  34955. {
  34956. postCommandMessage (clickMessageId);
  34957. }
  34958. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34959. {
  34960. if (clickTogglesState)
  34961. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34962. sendClickMessage (modifiers);
  34963. }
  34964. void Button::flashButtonState()
  34965. {
  34966. if (isEnabled())
  34967. {
  34968. needsToRelease = true;
  34969. setState (buttonDown);
  34970. getRepeatTimer().startTimer (100);
  34971. }
  34972. }
  34973. void Button::handleCommandMessage (int commandId)
  34974. {
  34975. if (commandId == clickMessageId)
  34976. {
  34977. if (isEnabled())
  34978. {
  34979. flashButtonState();
  34980. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34981. }
  34982. }
  34983. else
  34984. {
  34985. Component::handleCommandMessage (commandId);
  34986. }
  34987. }
  34988. void Button::addButtonListener (Listener* const newListener)
  34989. {
  34990. buttonListeners.add (newListener);
  34991. }
  34992. void Button::removeButtonListener (Listener* const listener)
  34993. {
  34994. buttonListeners.remove (listener);
  34995. }
  34996. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34997. {
  34998. Component::BailOutChecker checker (this);
  34999. if (commandManagerToUse != 0 && commandID != 0)
  35000. {
  35001. ApplicationCommandTarget::InvocationInfo info (commandID);
  35002. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35003. info.originatingComponent = this;
  35004. commandManagerToUse->invoke (info, true);
  35005. }
  35006. clicked (modifiers);
  35007. if (! checker.shouldBailOut())
  35008. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35009. }
  35010. void Button::sendStateMessage()
  35011. {
  35012. Component::BailOutChecker checker (this);
  35013. buttonStateChanged();
  35014. if (! checker.shouldBailOut())
  35015. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35016. }
  35017. void Button::paint (Graphics& g)
  35018. {
  35019. if (needsToRelease && isEnabled())
  35020. {
  35021. needsToRelease = false;
  35022. needsRepainting = true;
  35023. }
  35024. paintButton (g, isOver(), isDown());
  35025. }
  35026. void Button::mouseEnter (const MouseEvent& e)
  35027. {
  35028. updateState (&e);
  35029. }
  35030. void Button::mouseExit (const MouseEvent& e)
  35031. {
  35032. updateState (&e);
  35033. }
  35034. void Button::mouseDown (const MouseEvent& e)
  35035. {
  35036. updateState (&e);
  35037. if (isDown())
  35038. {
  35039. if (autoRepeatDelay >= 0)
  35040. getRepeatTimer().startTimer (autoRepeatDelay);
  35041. if (triggerOnMouseDown)
  35042. internalClickCallback (e.mods);
  35043. }
  35044. }
  35045. void Button::mouseUp (const MouseEvent& e)
  35046. {
  35047. const bool wasDown = isDown();
  35048. updateState (&e);
  35049. if (wasDown && isOver() && ! triggerOnMouseDown)
  35050. internalClickCallback (e.mods);
  35051. }
  35052. void Button::mouseDrag (const MouseEvent& e)
  35053. {
  35054. const ButtonState oldState = buttonState;
  35055. updateState (&e);
  35056. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35057. getRepeatTimer().startTimer (autoRepeatSpeed);
  35058. }
  35059. void Button::focusGained (FocusChangeType)
  35060. {
  35061. updateState (0);
  35062. repaint();
  35063. }
  35064. void Button::focusLost (FocusChangeType)
  35065. {
  35066. updateState (0);
  35067. repaint();
  35068. }
  35069. void Button::setVisible (bool shouldBeVisible)
  35070. {
  35071. if (shouldBeVisible != isVisible())
  35072. {
  35073. Component::setVisible (shouldBeVisible);
  35074. if (! shouldBeVisible)
  35075. needsToRelease = false;
  35076. updateState (0);
  35077. }
  35078. else
  35079. {
  35080. Component::setVisible (shouldBeVisible);
  35081. }
  35082. }
  35083. void Button::parentHierarchyChanged()
  35084. {
  35085. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35086. if (newKeySource != keySource.getComponent())
  35087. {
  35088. if (keySource != 0)
  35089. keySource->removeKeyListener (this);
  35090. keySource = newKeySource;
  35091. if (keySource != 0)
  35092. keySource->addKeyListener (this);
  35093. }
  35094. }
  35095. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35096. const int commandID_,
  35097. const bool generateTooltip_)
  35098. {
  35099. commandID = commandID_;
  35100. generateTooltip = generateTooltip_;
  35101. if (commandManagerToUse != commandManagerToUse_)
  35102. {
  35103. if (commandManagerToUse != 0)
  35104. commandManagerToUse->removeListener (this);
  35105. commandManagerToUse = commandManagerToUse_;
  35106. if (commandManagerToUse != 0)
  35107. commandManagerToUse->addListener (this);
  35108. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35109. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35110. // it is that this button represents, and the button will update its state to reflect this
  35111. // in the applicationCommandListChanged() method.
  35112. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35113. }
  35114. if (commandManagerToUse != 0)
  35115. applicationCommandListChanged();
  35116. else
  35117. setEnabled (true);
  35118. }
  35119. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35120. {
  35121. if (info.commandID == commandID
  35122. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35123. {
  35124. flashButtonState();
  35125. }
  35126. }
  35127. void Button::applicationCommandListChanged()
  35128. {
  35129. if (commandManagerToUse != 0)
  35130. {
  35131. ApplicationCommandInfo info (0);
  35132. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35133. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35134. if (target != 0)
  35135. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35136. }
  35137. }
  35138. void Button::addShortcut (const KeyPress& key)
  35139. {
  35140. if (key.isValid())
  35141. {
  35142. jassert (! isRegisteredForShortcut (key)); // already registered!
  35143. shortcuts.add (key);
  35144. parentHierarchyChanged();
  35145. }
  35146. }
  35147. void Button::clearShortcuts()
  35148. {
  35149. shortcuts.clear();
  35150. parentHierarchyChanged();
  35151. }
  35152. bool Button::isShortcutPressed() const
  35153. {
  35154. if (! isCurrentlyBlockedByAnotherModalComponent())
  35155. {
  35156. for (int i = shortcuts.size(); --i >= 0;)
  35157. if (shortcuts.getReference(i).isCurrentlyDown())
  35158. return true;
  35159. }
  35160. return false;
  35161. }
  35162. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35163. {
  35164. for (int i = shortcuts.size(); --i >= 0;)
  35165. if (key == shortcuts.getReference(i))
  35166. return true;
  35167. return false;
  35168. }
  35169. bool Button::keyStateChanged (const bool, Component*)
  35170. {
  35171. if (! isEnabled())
  35172. return false;
  35173. const bool wasDown = isKeyDown;
  35174. isKeyDown = isShortcutPressed();
  35175. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35176. getRepeatTimer().startTimer (autoRepeatDelay);
  35177. updateState (0);
  35178. if (isEnabled() && wasDown && ! isKeyDown)
  35179. {
  35180. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35181. // (return immediately - this button may now have been deleted)
  35182. return true;
  35183. }
  35184. return wasDown || isKeyDown;
  35185. }
  35186. bool Button::keyPressed (const KeyPress&, Component*)
  35187. {
  35188. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35189. return isShortcutPressed();
  35190. }
  35191. bool Button::keyPressed (const KeyPress& key)
  35192. {
  35193. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35194. {
  35195. triggerClick();
  35196. return true;
  35197. }
  35198. return false;
  35199. }
  35200. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35201. const int repeatMillisecs,
  35202. const int minimumDelayInMillisecs) throw()
  35203. {
  35204. autoRepeatDelay = initialDelayMillisecs;
  35205. autoRepeatSpeed = repeatMillisecs;
  35206. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35207. }
  35208. void Button::repeatTimerCallback()
  35209. {
  35210. if (needsRepainting)
  35211. {
  35212. getRepeatTimer().stopTimer();
  35213. updateState (0);
  35214. needsRepainting = false;
  35215. }
  35216. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35217. {
  35218. int repeatSpeed = autoRepeatSpeed;
  35219. if (autoRepeatMinimumDelay >= 0)
  35220. {
  35221. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35222. timeHeldDown *= timeHeldDown;
  35223. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35224. }
  35225. repeatSpeed = jmax (1, repeatSpeed);
  35226. getRepeatTimer().startTimer (repeatSpeed);
  35227. const uint32 now = Time::getApproximateMillisecondCounter();
  35228. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35229. lastTimeCallbackTime = now;
  35230. Component::SafePointer<Component> deletionWatcher (this);
  35231. for (int i = numTimesToCallback; --i >= 0;)
  35232. {
  35233. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35234. if (deletionWatcher == 0 || ! isDown())
  35235. return;
  35236. }
  35237. }
  35238. else if (! needsToRelease)
  35239. {
  35240. getRepeatTimer().stopTimer();
  35241. }
  35242. }
  35243. Button::RepeatTimer& Button::getRepeatTimer()
  35244. {
  35245. if (repeatTimer == 0)
  35246. repeatTimer = new RepeatTimer (*this);
  35247. return *repeatTimer;
  35248. }
  35249. END_JUCE_NAMESPACE
  35250. /*** End of inlined file: juce_Button.cpp ***/
  35251. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35252. BEGIN_JUCE_NAMESPACE
  35253. DrawableButton::DrawableButton (const String& name,
  35254. const DrawableButton::ButtonStyle buttonStyle)
  35255. : Button (name),
  35256. style (buttonStyle),
  35257. edgeIndent (3)
  35258. {
  35259. if (buttonStyle == ImageOnButtonBackground)
  35260. {
  35261. backgroundOff = Colour (0xffbbbbff);
  35262. backgroundOn = Colour (0xff3333ff);
  35263. }
  35264. else
  35265. {
  35266. backgroundOff = Colours::transparentBlack;
  35267. backgroundOn = Colour (0xaabbbbff);
  35268. }
  35269. }
  35270. DrawableButton::~DrawableButton()
  35271. {
  35272. deleteImages();
  35273. }
  35274. void DrawableButton::deleteImages()
  35275. {
  35276. }
  35277. void DrawableButton::setImages (const Drawable* normal,
  35278. const Drawable* over,
  35279. const Drawable* down,
  35280. const Drawable* disabled,
  35281. const Drawable* normalOn,
  35282. const Drawable* overOn,
  35283. const Drawable* downOn,
  35284. const Drawable* disabledOn)
  35285. {
  35286. deleteImages();
  35287. jassert (normal != 0); // you really need to give it at least a normal image..
  35288. if (normal != 0)
  35289. normalImage = normal->createCopy();
  35290. if (over != 0)
  35291. overImage = over->createCopy();
  35292. if (down != 0)
  35293. downImage = down->createCopy();
  35294. if (disabled != 0)
  35295. disabledImage = disabled->createCopy();
  35296. if (normalOn != 0)
  35297. normalImageOn = normalOn->createCopy();
  35298. if (overOn != 0)
  35299. overImageOn = overOn->createCopy();
  35300. if (downOn != 0)
  35301. downImageOn = downOn->createCopy();
  35302. if (disabledOn != 0)
  35303. disabledImageOn = disabledOn->createCopy();
  35304. repaint();
  35305. }
  35306. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35307. {
  35308. if (style != newStyle)
  35309. {
  35310. style = newStyle;
  35311. repaint();
  35312. }
  35313. }
  35314. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35315. const Colour& toggledOnColour)
  35316. {
  35317. if (backgroundOff != toggledOffColour
  35318. || backgroundOn != toggledOnColour)
  35319. {
  35320. backgroundOff = toggledOffColour;
  35321. backgroundOn = toggledOnColour;
  35322. repaint();
  35323. }
  35324. }
  35325. const Colour& DrawableButton::getBackgroundColour() const throw()
  35326. {
  35327. return getToggleState() ? backgroundOn
  35328. : backgroundOff;
  35329. }
  35330. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35331. {
  35332. edgeIndent = numPixelsIndent;
  35333. repaint();
  35334. }
  35335. void DrawableButton::paintButton (Graphics& g,
  35336. bool isMouseOverButton,
  35337. bool isButtonDown)
  35338. {
  35339. Rectangle<int> imageSpace;
  35340. if (style == ImageOnButtonBackground)
  35341. {
  35342. const int insetX = getWidth() / 4;
  35343. const int insetY = getHeight() / 4;
  35344. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35345. getLookAndFeel().drawButtonBackground (g, *this,
  35346. getBackgroundColour(),
  35347. isMouseOverButton,
  35348. isButtonDown);
  35349. }
  35350. else
  35351. {
  35352. g.fillAll (getBackgroundColour());
  35353. const int textH = (style == ImageAboveTextLabel)
  35354. ? jmin (16, proportionOfHeight (0.25f))
  35355. : 0;
  35356. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35357. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35358. imageSpace.setBounds (indentX, indentY,
  35359. getWidth() - indentX * 2,
  35360. getHeight() - indentY * 2 - textH);
  35361. if (textH > 0)
  35362. {
  35363. g.setFont ((float) textH);
  35364. g.setColour (getLookAndFeel().findColour (DrawableButton::textColourId)
  35365. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35366. g.drawFittedText (getButtonText(),
  35367. 2, getHeight() - textH - 1,
  35368. getWidth() - 4, textH,
  35369. Justification::centred, 1);
  35370. }
  35371. }
  35372. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35373. g.setOpacity (1.0f);
  35374. const Drawable* imageToDraw = 0;
  35375. if (isEnabled())
  35376. {
  35377. imageToDraw = getCurrentImage();
  35378. }
  35379. else
  35380. {
  35381. imageToDraw = getToggleState() ? disabledImageOn
  35382. : disabledImage;
  35383. if (imageToDraw == 0)
  35384. {
  35385. g.setOpacity (0.4f);
  35386. imageToDraw = getNormalImage();
  35387. }
  35388. }
  35389. if (imageToDraw != 0)
  35390. {
  35391. if (style == ImageRaw)
  35392. {
  35393. imageToDraw->draw (g, 1.0f);
  35394. }
  35395. else
  35396. {
  35397. imageToDraw->drawWithin (g,
  35398. imageSpace.getX(),
  35399. imageSpace.getY(),
  35400. imageSpace.getWidth(),
  35401. imageSpace.getHeight(),
  35402. RectanglePlacement::centred,
  35403. 1.0f);
  35404. }
  35405. }
  35406. }
  35407. const Drawable* DrawableButton::getCurrentImage() const throw()
  35408. {
  35409. if (isDown())
  35410. return getDownImage();
  35411. if (isOver())
  35412. return getOverImage();
  35413. return getNormalImage();
  35414. }
  35415. const Drawable* DrawableButton::getNormalImage() const throw()
  35416. {
  35417. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35418. : normalImage;
  35419. }
  35420. const Drawable* DrawableButton::getOverImage() const throw()
  35421. {
  35422. const Drawable* d = normalImage;
  35423. if (getToggleState())
  35424. {
  35425. if (overImageOn != 0)
  35426. d = overImageOn;
  35427. else if (normalImageOn != 0)
  35428. d = normalImageOn;
  35429. else if (overImage != 0)
  35430. d = overImage;
  35431. }
  35432. else
  35433. {
  35434. if (overImage != 0)
  35435. d = overImage;
  35436. }
  35437. return d;
  35438. }
  35439. const Drawable* DrawableButton::getDownImage() const throw()
  35440. {
  35441. const Drawable* d = normalImage;
  35442. if (getToggleState())
  35443. {
  35444. if (downImageOn != 0)
  35445. d = downImageOn;
  35446. else if (overImageOn != 0)
  35447. d = overImageOn;
  35448. else if (normalImageOn != 0)
  35449. d = normalImageOn;
  35450. else if (downImage != 0)
  35451. d = downImage;
  35452. else
  35453. d = getOverImage();
  35454. }
  35455. else
  35456. {
  35457. if (downImage != 0)
  35458. d = downImage;
  35459. else
  35460. d = getOverImage();
  35461. }
  35462. return d;
  35463. }
  35464. END_JUCE_NAMESPACE
  35465. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35466. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35467. BEGIN_JUCE_NAMESPACE
  35468. HyperlinkButton::HyperlinkButton (const String& linkText,
  35469. const URL& linkURL)
  35470. : Button (linkText),
  35471. url (linkURL),
  35472. font (14.0f, Font::underlined),
  35473. resizeFont (true),
  35474. justification (Justification::centred)
  35475. {
  35476. setMouseCursor (MouseCursor::PointingHandCursor);
  35477. setTooltip (linkURL.toString (false));
  35478. }
  35479. HyperlinkButton::~HyperlinkButton()
  35480. {
  35481. }
  35482. void HyperlinkButton::setFont (const Font& newFont,
  35483. const bool resizeToMatchComponentHeight,
  35484. const Justification& justificationType)
  35485. {
  35486. font = newFont;
  35487. resizeFont = resizeToMatchComponentHeight;
  35488. justification = justificationType;
  35489. repaint();
  35490. }
  35491. void HyperlinkButton::setURL (const URL& newURL) throw()
  35492. {
  35493. url = newURL;
  35494. setTooltip (newURL.toString (false));
  35495. }
  35496. const Font HyperlinkButton::getFontToUse() const
  35497. {
  35498. Font f (font);
  35499. if (resizeFont)
  35500. f.setHeight (getHeight() * 0.7f);
  35501. return f;
  35502. }
  35503. void HyperlinkButton::changeWidthToFitText()
  35504. {
  35505. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35506. }
  35507. void HyperlinkButton::colourChanged()
  35508. {
  35509. repaint();
  35510. }
  35511. void HyperlinkButton::clicked()
  35512. {
  35513. if (url.isWellFormed())
  35514. url.launchInDefaultBrowser();
  35515. }
  35516. void HyperlinkButton::paintButton (Graphics& g,
  35517. bool isMouseOverButton,
  35518. bool isButtonDown)
  35519. {
  35520. const Colour textColour (findColour (textColourId));
  35521. if (isEnabled())
  35522. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35523. : textColour);
  35524. else
  35525. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35526. g.setFont (getFontToUse());
  35527. g.drawText (getButtonText(),
  35528. 2, 0, getWidth() - 2, getHeight(),
  35529. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35530. true);
  35531. }
  35532. END_JUCE_NAMESPACE
  35533. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35534. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35535. BEGIN_JUCE_NAMESPACE
  35536. ImageButton::ImageButton (const String& text_)
  35537. : Button (text_),
  35538. scaleImageToFit (true),
  35539. preserveProportions (true),
  35540. alphaThreshold (0),
  35541. imageX (0),
  35542. imageY (0),
  35543. imageW (0),
  35544. imageH (0),
  35545. normalImage (0),
  35546. overImage (0),
  35547. downImage (0)
  35548. {
  35549. }
  35550. ImageButton::~ImageButton()
  35551. {
  35552. }
  35553. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35554. const bool rescaleImagesWhenButtonSizeChanges,
  35555. const bool preserveImageProportions,
  35556. const Image& normalImage_,
  35557. const float imageOpacityWhenNormal,
  35558. const Colour& overlayColourWhenNormal,
  35559. const Image& overImage_,
  35560. const float imageOpacityWhenOver,
  35561. const Colour& overlayColourWhenOver,
  35562. const Image& downImage_,
  35563. const float imageOpacityWhenDown,
  35564. const Colour& overlayColourWhenDown,
  35565. const float hitTestAlphaThreshold)
  35566. {
  35567. normalImage = normalImage_;
  35568. overImage = overImage_;
  35569. downImage = downImage_;
  35570. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35571. {
  35572. imageW = normalImage.getWidth();
  35573. imageH = normalImage.getHeight();
  35574. setSize (imageW, imageH);
  35575. }
  35576. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35577. preserveProportions = preserveImageProportions;
  35578. normalOpacity = imageOpacityWhenNormal;
  35579. normalOverlay = overlayColourWhenNormal;
  35580. overOpacity = imageOpacityWhenOver;
  35581. overOverlay = overlayColourWhenOver;
  35582. downOpacity = imageOpacityWhenDown;
  35583. downOverlay = overlayColourWhenDown;
  35584. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35585. repaint();
  35586. }
  35587. const Image ImageButton::getCurrentImage() const
  35588. {
  35589. if (isDown() || getToggleState())
  35590. return getDownImage();
  35591. if (isOver())
  35592. return getOverImage();
  35593. return getNormalImage();
  35594. }
  35595. const Image ImageButton::getNormalImage() const
  35596. {
  35597. return normalImage;
  35598. }
  35599. const Image ImageButton::getOverImage() const
  35600. {
  35601. return overImage.isValid() ? overImage
  35602. : normalImage;
  35603. }
  35604. const Image ImageButton::getDownImage() const
  35605. {
  35606. return downImage.isValid() ? downImage
  35607. : getOverImage();
  35608. }
  35609. void ImageButton::paintButton (Graphics& g,
  35610. bool isMouseOverButton,
  35611. bool isButtonDown)
  35612. {
  35613. if (! isEnabled())
  35614. {
  35615. isMouseOverButton = false;
  35616. isButtonDown = false;
  35617. }
  35618. Image im (getCurrentImage());
  35619. if (im.isValid())
  35620. {
  35621. const int iw = im.getWidth();
  35622. const int ih = im.getHeight();
  35623. imageW = getWidth();
  35624. imageH = getHeight();
  35625. imageX = (imageW - iw) >> 1;
  35626. imageY = (imageH - ih) >> 1;
  35627. if (scaleImageToFit)
  35628. {
  35629. if (preserveProportions)
  35630. {
  35631. int newW, newH;
  35632. const float imRatio = ih / (float)iw;
  35633. const float destRatio = imageH / (float)imageW;
  35634. if (imRatio > destRatio)
  35635. {
  35636. newW = roundToInt (imageH / imRatio);
  35637. newH = imageH;
  35638. }
  35639. else
  35640. {
  35641. newW = imageW;
  35642. newH = roundToInt (imageW * imRatio);
  35643. }
  35644. imageX = (imageW - newW) / 2;
  35645. imageY = (imageH - newH) / 2;
  35646. imageW = newW;
  35647. imageH = newH;
  35648. }
  35649. else
  35650. {
  35651. imageX = 0;
  35652. imageY = 0;
  35653. }
  35654. }
  35655. if (! scaleImageToFit)
  35656. {
  35657. imageW = iw;
  35658. imageH = ih;
  35659. }
  35660. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35661. isButtonDown ? downOverlay
  35662. : (isMouseOverButton ? overOverlay
  35663. : normalOverlay),
  35664. isButtonDown ? downOpacity
  35665. : (isMouseOverButton ? overOpacity
  35666. : normalOpacity),
  35667. *this);
  35668. }
  35669. }
  35670. bool ImageButton::hitTest (int x, int y)
  35671. {
  35672. if (alphaThreshold == 0)
  35673. return true;
  35674. Image im (getCurrentImage());
  35675. return im.isNull() || (imageW > 0 && imageH > 0
  35676. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35677. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35678. }
  35679. END_JUCE_NAMESPACE
  35680. /*** End of inlined file: juce_ImageButton.cpp ***/
  35681. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35682. BEGIN_JUCE_NAMESPACE
  35683. ShapeButton::ShapeButton (const String& text_,
  35684. const Colour& normalColour_,
  35685. const Colour& overColour_,
  35686. const Colour& downColour_)
  35687. : Button (text_),
  35688. normalColour (normalColour_),
  35689. overColour (overColour_),
  35690. downColour (downColour_),
  35691. maintainShapeProportions (false),
  35692. outlineWidth (0.0f)
  35693. {
  35694. }
  35695. ShapeButton::~ShapeButton()
  35696. {
  35697. }
  35698. void ShapeButton::setColours (const Colour& newNormalColour,
  35699. const Colour& newOverColour,
  35700. const Colour& newDownColour)
  35701. {
  35702. normalColour = newNormalColour;
  35703. overColour = newOverColour;
  35704. downColour = newDownColour;
  35705. }
  35706. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35707. const float newOutlineWidth)
  35708. {
  35709. outlineColour = newOutlineColour;
  35710. outlineWidth = newOutlineWidth;
  35711. }
  35712. void ShapeButton::setShape (const Path& newShape,
  35713. const bool resizeNowToFitThisShape,
  35714. const bool maintainShapeProportions_,
  35715. const bool hasShadow)
  35716. {
  35717. shape = newShape;
  35718. maintainShapeProportions = maintainShapeProportions_;
  35719. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35720. setComponentEffect ((hasShadow) ? &shadow : 0);
  35721. if (resizeNowToFitThisShape)
  35722. {
  35723. Rectangle<float> bounds (shape.getBounds());
  35724. if (hasShadow)
  35725. bounds.expand (4.0f, 4.0f);
  35726. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35727. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35728. 1 + (int) (bounds.getHeight() + outlineWidth));
  35729. }
  35730. }
  35731. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35732. {
  35733. if (! isEnabled())
  35734. {
  35735. isMouseOverButton = false;
  35736. isButtonDown = false;
  35737. }
  35738. g.setColour ((isButtonDown) ? downColour
  35739. : (isMouseOverButton) ? overColour
  35740. : normalColour);
  35741. int w = getWidth();
  35742. int h = getHeight();
  35743. if (getComponentEffect() != 0)
  35744. {
  35745. w -= 4;
  35746. h -= 4;
  35747. }
  35748. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35749. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35750. w - offset - outlineWidth,
  35751. h - offset - outlineWidth,
  35752. maintainShapeProportions));
  35753. g.fillPath (shape, trans);
  35754. if (outlineWidth > 0.0f)
  35755. {
  35756. g.setColour (outlineColour);
  35757. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35758. }
  35759. }
  35760. END_JUCE_NAMESPACE
  35761. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35762. /*** Start of inlined file: juce_TextButton.cpp ***/
  35763. BEGIN_JUCE_NAMESPACE
  35764. TextButton::TextButton (const String& name,
  35765. const String& toolTip)
  35766. : Button (name)
  35767. {
  35768. setTooltip (toolTip);
  35769. }
  35770. TextButton::~TextButton()
  35771. {
  35772. }
  35773. void TextButton::paintButton (Graphics& g,
  35774. bool isMouseOverButton,
  35775. bool isButtonDown)
  35776. {
  35777. getLookAndFeel().drawButtonBackground (g, *this,
  35778. findColour (getToggleState() ? buttonOnColourId
  35779. : buttonColourId),
  35780. isMouseOverButton,
  35781. isButtonDown);
  35782. getLookAndFeel().drawButtonText (g, *this,
  35783. isMouseOverButton,
  35784. isButtonDown);
  35785. }
  35786. void TextButton::colourChanged()
  35787. {
  35788. repaint();
  35789. }
  35790. const Font TextButton::getFont()
  35791. {
  35792. return Font (jmin (15.0f, getHeight() * 0.6f));
  35793. }
  35794. void TextButton::changeWidthToFitText (const int newHeight)
  35795. {
  35796. if (newHeight >= 0)
  35797. setSize (jmax (1, getWidth()), newHeight);
  35798. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35799. getHeight());
  35800. }
  35801. END_JUCE_NAMESPACE
  35802. /*** End of inlined file: juce_TextButton.cpp ***/
  35803. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35804. BEGIN_JUCE_NAMESPACE
  35805. ToggleButton::ToggleButton (const String& buttonText)
  35806. : Button (buttonText)
  35807. {
  35808. setClickingTogglesState (true);
  35809. }
  35810. ToggleButton::~ToggleButton()
  35811. {
  35812. }
  35813. void ToggleButton::paintButton (Graphics& g,
  35814. bool isMouseOverButton,
  35815. bool isButtonDown)
  35816. {
  35817. getLookAndFeel().drawToggleButton (g, *this,
  35818. isMouseOverButton,
  35819. isButtonDown);
  35820. }
  35821. void ToggleButton::changeWidthToFitText()
  35822. {
  35823. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35824. }
  35825. void ToggleButton::colourChanged()
  35826. {
  35827. repaint();
  35828. }
  35829. END_JUCE_NAMESPACE
  35830. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35831. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35832. BEGIN_JUCE_NAMESPACE
  35833. ToolbarButton::ToolbarButton (const int itemId_,
  35834. const String& buttonText,
  35835. Drawable* const normalImage_,
  35836. Drawable* const toggledOnImage_)
  35837. : ToolbarItemComponent (itemId_, buttonText, true),
  35838. normalImage (normalImage_),
  35839. toggledOnImage (toggledOnImage_)
  35840. {
  35841. jassert (normalImage_ != 0);
  35842. }
  35843. ToolbarButton::~ToolbarButton()
  35844. {
  35845. }
  35846. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35847. bool /*isToolbarVertical*/,
  35848. int& preferredSize,
  35849. int& minSize, int& maxSize)
  35850. {
  35851. preferredSize = minSize = maxSize = toolbarDepth;
  35852. return true;
  35853. }
  35854. void ToolbarButton::paintButtonArea (Graphics& g,
  35855. int width, int height,
  35856. bool /*isMouseOver*/,
  35857. bool /*isMouseDown*/)
  35858. {
  35859. Drawable* d = normalImage;
  35860. if (getToggleState() && toggledOnImage != 0)
  35861. d = toggledOnImage;
  35862. if (! isEnabled())
  35863. {
  35864. Image im (Image::ARGB, width, height, true);
  35865. {
  35866. Graphics g2 (im);
  35867. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35868. }
  35869. im.desaturate();
  35870. g.drawImageAt (im, 0, 0);
  35871. }
  35872. else
  35873. {
  35874. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35875. }
  35876. }
  35877. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35878. {
  35879. }
  35880. END_JUCE_NAMESPACE
  35881. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35882. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35883. BEGIN_JUCE_NAMESPACE
  35884. class CodeDocumentLine
  35885. {
  35886. public:
  35887. CodeDocumentLine (const juce_wchar* const line_,
  35888. const int lineLength_,
  35889. const int numNewLineChars,
  35890. const int lineStartInFile_)
  35891. : line (line_, lineLength_),
  35892. lineStartInFile (lineStartInFile_),
  35893. lineLength (lineLength_),
  35894. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35895. {
  35896. }
  35897. ~CodeDocumentLine()
  35898. {
  35899. }
  35900. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35901. {
  35902. const juce_wchar* const t = text;
  35903. int pos = 0;
  35904. while (t [pos] != 0)
  35905. {
  35906. const int startOfLine = pos;
  35907. int numNewLineChars = 0;
  35908. while (t[pos] != 0)
  35909. {
  35910. if (t[pos] == '\r')
  35911. {
  35912. ++numNewLineChars;
  35913. ++pos;
  35914. if (t[pos] == '\n')
  35915. {
  35916. ++numNewLineChars;
  35917. ++pos;
  35918. }
  35919. break;
  35920. }
  35921. if (t[pos] == '\n')
  35922. {
  35923. ++numNewLineChars;
  35924. ++pos;
  35925. break;
  35926. }
  35927. ++pos;
  35928. }
  35929. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35930. numNewLineChars, startOfLine));
  35931. }
  35932. jassert (pos == text.length());
  35933. }
  35934. bool endsWithLineBreak() const throw()
  35935. {
  35936. return lineLengthWithoutNewLines != lineLength;
  35937. }
  35938. void updateLength() throw()
  35939. {
  35940. lineLengthWithoutNewLines = lineLength = line.length();
  35941. while (lineLengthWithoutNewLines > 0
  35942. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35943. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35944. {
  35945. --lineLengthWithoutNewLines;
  35946. }
  35947. }
  35948. String line;
  35949. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35950. };
  35951. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35952. : document (document_),
  35953. currentLine (document_->lines[0]),
  35954. line (0),
  35955. position (0)
  35956. {
  35957. }
  35958. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35959. : document (other.document),
  35960. currentLine (other.currentLine),
  35961. line (other.line),
  35962. position (other.position)
  35963. {
  35964. }
  35965. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35966. {
  35967. document = other.document;
  35968. currentLine = other.currentLine;
  35969. line = other.line;
  35970. position = other.position;
  35971. return *this;
  35972. }
  35973. CodeDocument::Iterator::~Iterator() throw()
  35974. {
  35975. }
  35976. juce_wchar CodeDocument::Iterator::nextChar()
  35977. {
  35978. if (currentLine == 0)
  35979. return 0;
  35980. jassert (currentLine == document->lines.getUnchecked (line));
  35981. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35982. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35983. {
  35984. ++line;
  35985. currentLine = document->lines [line];
  35986. }
  35987. return result;
  35988. }
  35989. void CodeDocument::Iterator::skip()
  35990. {
  35991. if (currentLine != 0)
  35992. {
  35993. jassert (currentLine == document->lines.getUnchecked (line));
  35994. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35995. {
  35996. ++line;
  35997. currentLine = document->lines [line];
  35998. }
  35999. }
  36000. }
  36001. void CodeDocument::Iterator::skipToEndOfLine()
  36002. {
  36003. if (currentLine != 0)
  36004. {
  36005. jassert (currentLine == document->lines.getUnchecked (line));
  36006. ++line;
  36007. currentLine = document->lines [line];
  36008. if (currentLine != 0)
  36009. position = currentLine->lineStartInFile;
  36010. else
  36011. position = document->getNumCharacters();
  36012. }
  36013. }
  36014. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36015. {
  36016. if (currentLine == 0)
  36017. return 0;
  36018. jassert (currentLine == document->lines.getUnchecked (line));
  36019. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36020. }
  36021. void CodeDocument::Iterator::skipWhitespace()
  36022. {
  36023. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36024. skip();
  36025. }
  36026. bool CodeDocument::Iterator::isEOF() const throw()
  36027. {
  36028. return currentLine == 0;
  36029. }
  36030. CodeDocument::Position::Position() throw()
  36031. : owner (0), characterPos (0), line (0),
  36032. indexInLine (0), positionMaintained (false)
  36033. {
  36034. }
  36035. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36036. const int line_, const int indexInLine_) throw()
  36037. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36038. characterPos (0), line (line_),
  36039. indexInLine (indexInLine_), positionMaintained (false)
  36040. {
  36041. setLineAndIndex (line_, indexInLine_);
  36042. }
  36043. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36044. const int characterPos_) throw()
  36045. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36046. positionMaintained (false)
  36047. {
  36048. setPosition (characterPos_);
  36049. }
  36050. CodeDocument::Position::Position (const Position& other) throw()
  36051. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36052. indexInLine (other.indexInLine), positionMaintained (false)
  36053. {
  36054. jassert (*this == other);
  36055. }
  36056. CodeDocument::Position::~Position()
  36057. {
  36058. setPositionMaintained (false);
  36059. }
  36060. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36061. {
  36062. if (this != &other)
  36063. {
  36064. const bool wasPositionMaintained = positionMaintained;
  36065. if (owner != other.owner)
  36066. setPositionMaintained (false);
  36067. owner = other.owner;
  36068. line = other.line;
  36069. indexInLine = other.indexInLine;
  36070. characterPos = other.characterPos;
  36071. setPositionMaintained (wasPositionMaintained);
  36072. jassert (*this == other);
  36073. }
  36074. return *this;
  36075. }
  36076. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36077. {
  36078. jassert ((characterPos == other.characterPos)
  36079. == (line == other.line && indexInLine == other.indexInLine));
  36080. return characterPos == other.characterPos
  36081. && line == other.line
  36082. && indexInLine == other.indexInLine
  36083. && owner == other.owner;
  36084. }
  36085. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36086. {
  36087. return ! operator== (other);
  36088. }
  36089. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36090. {
  36091. jassert (owner != 0);
  36092. if (owner->lines.size() == 0)
  36093. {
  36094. line = 0;
  36095. indexInLine = 0;
  36096. characterPos = 0;
  36097. }
  36098. else
  36099. {
  36100. if (newLine >= owner->lines.size())
  36101. {
  36102. line = owner->lines.size() - 1;
  36103. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36104. jassert (l != 0);
  36105. indexInLine = l->lineLengthWithoutNewLines;
  36106. characterPos = l->lineStartInFile + indexInLine;
  36107. }
  36108. else
  36109. {
  36110. line = jmax (0, newLine);
  36111. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36112. jassert (l != 0);
  36113. if (l->lineLengthWithoutNewLines > 0)
  36114. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36115. else
  36116. indexInLine = 0;
  36117. characterPos = l->lineStartInFile + indexInLine;
  36118. }
  36119. }
  36120. }
  36121. void CodeDocument::Position::setPosition (const int newPosition)
  36122. {
  36123. jassert (owner != 0);
  36124. line = 0;
  36125. indexInLine = 0;
  36126. characterPos = 0;
  36127. if (newPosition > 0)
  36128. {
  36129. int lineStart = 0;
  36130. int lineEnd = owner->lines.size();
  36131. for (;;)
  36132. {
  36133. if (lineEnd - lineStart < 4)
  36134. {
  36135. for (int i = lineStart; i < lineEnd; ++i)
  36136. {
  36137. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36138. int index = newPosition - l->lineStartInFile;
  36139. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36140. {
  36141. line = i;
  36142. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36143. characterPos = l->lineStartInFile + indexInLine;
  36144. }
  36145. }
  36146. break;
  36147. }
  36148. else
  36149. {
  36150. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36151. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36152. if (newPosition >= mid->lineStartInFile)
  36153. lineStart = midIndex;
  36154. else
  36155. lineEnd = midIndex;
  36156. }
  36157. }
  36158. }
  36159. }
  36160. void CodeDocument::Position::moveBy (int characterDelta)
  36161. {
  36162. jassert (owner != 0);
  36163. if (characterDelta == 1)
  36164. {
  36165. setPosition (getPosition());
  36166. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36167. if (line < owner->lines.size())
  36168. {
  36169. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36170. if (indexInLine + characterDelta < l->lineLength
  36171. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36172. ++characterDelta;
  36173. }
  36174. }
  36175. setPosition (characterPos + characterDelta);
  36176. }
  36177. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36178. {
  36179. CodeDocument::Position p (*this);
  36180. p.moveBy (characterDelta);
  36181. return p;
  36182. }
  36183. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36184. {
  36185. CodeDocument::Position p (*this);
  36186. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36187. return p;
  36188. }
  36189. const juce_wchar CodeDocument::Position::getCharacter() const
  36190. {
  36191. const CodeDocumentLine* const l = owner->lines [line];
  36192. return l == 0 ? 0 : l->line [getIndexInLine()];
  36193. }
  36194. const String CodeDocument::Position::getLineText() const
  36195. {
  36196. const CodeDocumentLine* const l = owner->lines [line];
  36197. return l == 0 ? String::empty : l->line;
  36198. }
  36199. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36200. {
  36201. if (isMaintained != positionMaintained)
  36202. {
  36203. positionMaintained = isMaintained;
  36204. if (owner != 0)
  36205. {
  36206. if (isMaintained)
  36207. {
  36208. jassert (! owner->positionsToMaintain.contains (this));
  36209. owner->positionsToMaintain.add (this);
  36210. }
  36211. else
  36212. {
  36213. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36214. jassert (owner->positionsToMaintain.contains (this));
  36215. owner->positionsToMaintain.removeValue (this);
  36216. }
  36217. }
  36218. }
  36219. }
  36220. CodeDocument::CodeDocument()
  36221. : undoManager (std::numeric_limits<int>::max(), 10000),
  36222. currentActionIndex (0),
  36223. indexOfSavedState (-1),
  36224. maximumLineLength (-1),
  36225. newLineChars ("\r\n")
  36226. {
  36227. }
  36228. CodeDocument::~CodeDocument()
  36229. {
  36230. }
  36231. const String CodeDocument::getAllContent() const
  36232. {
  36233. return getTextBetween (Position (this, 0),
  36234. Position (this, lines.size(), 0));
  36235. }
  36236. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36237. {
  36238. if (end.getPosition() <= start.getPosition())
  36239. return String::empty;
  36240. const int startLine = start.getLineNumber();
  36241. const int endLine = end.getLineNumber();
  36242. if (startLine == endLine)
  36243. {
  36244. CodeDocumentLine* const line = lines [startLine];
  36245. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36246. }
  36247. String result;
  36248. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36249. String::Concatenator concatenator (result);
  36250. const int maxLine = jmin (lines.size() - 1, endLine);
  36251. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36252. {
  36253. const CodeDocumentLine* line = lines.getUnchecked(i);
  36254. int len = line->lineLength;
  36255. if (i == startLine)
  36256. {
  36257. const int index = start.getIndexInLine();
  36258. concatenator.append (line->line.substring (index, len));
  36259. }
  36260. else if (i == endLine)
  36261. {
  36262. len = end.getIndexInLine();
  36263. concatenator.append (line->line.substring (0, len));
  36264. }
  36265. else
  36266. {
  36267. concatenator.append (line->line);
  36268. }
  36269. }
  36270. return result;
  36271. }
  36272. int CodeDocument::getNumCharacters() const throw()
  36273. {
  36274. const CodeDocumentLine* const lastLine = lines.getLast();
  36275. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36276. }
  36277. const String CodeDocument::getLine (const int lineIndex) const throw()
  36278. {
  36279. const CodeDocumentLine* const line = lines [lineIndex];
  36280. return (line == 0) ? String::empty : line->line;
  36281. }
  36282. int CodeDocument::getMaximumLineLength() throw()
  36283. {
  36284. if (maximumLineLength < 0)
  36285. {
  36286. maximumLineLength = 0;
  36287. for (int i = lines.size(); --i >= 0;)
  36288. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36289. }
  36290. return maximumLineLength;
  36291. }
  36292. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36293. {
  36294. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36295. }
  36296. void CodeDocument::insertText (const Position& position, const String& text)
  36297. {
  36298. insert (text, position.getPosition(), true);
  36299. }
  36300. void CodeDocument::replaceAllContent (const String& newContent)
  36301. {
  36302. remove (0, getNumCharacters(), true);
  36303. insert (newContent, 0, true);
  36304. }
  36305. bool CodeDocument::loadFromStream (InputStream& stream)
  36306. {
  36307. replaceAllContent (stream.readEntireStreamAsString());
  36308. setSavePoint();
  36309. clearUndoHistory();
  36310. return true;
  36311. }
  36312. bool CodeDocument::writeToStream (OutputStream& stream)
  36313. {
  36314. for (int i = 0; i < lines.size(); ++i)
  36315. {
  36316. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36317. const char* utf8 = temp.toUTF8();
  36318. if (! stream.write (utf8, (int) strlen (utf8)))
  36319. return false;
  36320. }
  36321. return true;
  36322. }
  36323. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36324. {
  36325. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36326. newLineChars = newLine;
  36327. }
  36328. void CodeDocument::newTransaction()
  36329. {
  36330. undoManager.beginNewTransaction (String::empty);
  36331. }
  36332. void CodeDocument::undo()
  36333. {
  36334. newTransaction();
  36335. undoManager.undo();
  36336. }
  36337. void CodeDocument::redo()
  36338. {
  36339. undoManager.redo();
  36340. }
  36341. void CodeDocument::clearUndoHistory()
  36342. {
  36343. undoManager.clearUndoHistory();
  36344. }
  36345. void CodeDocument::setSavePoint() throw()
  36346. {
  36347. indexOfSavedState = currentActionIndex;
  36348. }
  36349. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36350. {
  36351. return currentActionIndex != indexOfSavedState;
  36352. }
  36353. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36354. {
  36355. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36356. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36357. }
  36358. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36359. {
  36360. Position p (position);
  36361. const int maxDistance = 256;
  36362. int i = 0;
  36363. while (i < maxDistance
  36364. && CharacterFunctions::isWhitespace (p.getCharacter())
  36365. && (i == 0 || (p.getCharacter() != '\n'
  36366. && p.getCharacter() != '\r')))
  36367. {
  36368. ++i;
  36369. p.moveBy (1);
  36370. }
  36371. if (i == 0)
  36372. {
  36373. const int type = getCodeCharacterCategory (p.getCharacter());
  36374. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36375. {
  36376. ++i;
  36377. p.moveBy (1);
  36378. }
  36379. while (i < maxDistance
  36380. && CharacterFunctions::isWhitespace (p.getCharacter())
  36381. && (i == 0 || (p.getCharacter() != '\n'
  36382. && p.getCharacter() != '\r')))
  36383. {
  36384. ++i;
  36385. p.moveBy (1);
  36386. }
  36387. }
  36388. return p;
  36389. }
  36390. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36391. {
  36392. Position p (position);
  36393. const int maxDistance = 256;
  36394. int i = 0;
  36395. bool stoppedAtLineStart = false;
  36396. while (i < maxDistance)
  36397. {
  36398. const juce_wchar c = p.movedBy (-1).getCharacter();
  36399. if (c == '\r' || c == '\n')
  36400. {
  36401. stoppedAtLineStart = true;
  36402. if (i > 0)
  36403. break;
  36404. }
  36405. if (! CharacterFunctions::isWhitespace (c))
  36406. break;
  36407. p.moveBy (-1);
  36408. ++i;
  36409. }
  36410. if (i < maxDistance && ! stoppedAtLineStart)
  36411. {
  36412. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36413. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36414. {
  36415. p.moveBy (-1);
  36416. ++i;
  36417. }
  36418. }
  36419. return p;
  36420. }
  36421. void CodeDocument::checkLastLineStatus()
  36422. {
  36423. while (lines.size() > 0
  36424. && lines.getLast()->lineLength == 0
  36425. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36426. {
  36427. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36428. lines.removeLast();
  36429. }
  36430. const CodeDocumentLine* const lastLine = lines.getLast();
  36431. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36432. {
  36433. // check that there's an empty line at the end if the preceding one ends in a newline..
  36434. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36435. }
  36436. }
  36437. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36438. {
  36439. listeners.add (listener);
  36440. }
  36441. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36442. {
  36443. listeners.remove (listener);
  36444. }
  36445. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36446. {
  36447. Position startPos (this, startLine, 0);
  36448. Position endPos (this, endLine, 0);
  36449. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36450. }
  36451. class CodeDocumentInsertAction : public UndoableAction
  36452. {
  36453. CodeDocument& owner;
  36454. const String text;
  36455. int insertPos;
  36456. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36457. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36458. public:
  36459. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36460. : owner (owner_),
  36461. text (text_),
  36462. insertPos (insertPos_)
  36463. {
  36464. }
  36465. ~CodeDocumentInsertAction() {}
  36466. bool perform()
  36467. {
  36468. owner.currentActionIndex++;
  36469. owner.insert (text, insertPos, false);
  36470. return true;
  36471. }
  36472. bool undo()
  36473. {
  36474. owner.currentActionIndex--;
  36475. owner.remove (insertPos, insertPos + text.length(), false);
  36476. return true;
  36477. }
  36478. int getSizeInUnits() { return text.length() + 32; }
  36479. };
  36480. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36481. {
  36482. if (text.isEmpty())
  36483. return;
  36484. if (undoable)
  36485. {
  36486. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36487. }
  36488. else
  36489. {
  36490. Position pos (this, insertPos);
  36491. const int firstAffectedLine = pos.getLineNumber();
  36492. int lastAffectedLine = firstAffectedLine + 1;
  36493. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36494. String textInsideOriginalLine (text);
  36495. if (firstLine != 0)
  36496. {
  36497. const int index = pos.getIndexInLine();
  36498. textInsideOriginalLine = firstLine->line.substring (0, index)
  36499. + textInsideOriginalLine
  36500. + firstLine->line.substring (index);
  36501. }
  36502. maximumLineLength = -1;
  36503. Array <CodeDocumentLine*> newLines;
  36504. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36505. jassert (newLines.size() > 0);
  36506. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36507. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36508. lines.set (firstAffectedLine, newFirstLine);
  36509. if (newLines.size() > 1)
  36510. {
  36511. for (int i = 1; i < newLines.size(); ++i)
  36512. {
  36513. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36514. lines.insert (firstAffectedLine + i, l);
  36515. }
  36516. lastAffectedLine = lines.size();
  36517. }
  36518. int i, lineStart = newFirstLine->lineStartInFile;
  36519. for (i = firstAffectedLine; i < lines.size(); ++i)
  36520. {
  36521. CodeDocumentLine* const l = lines.getUnchecked (i);
  36522. l->lineStartInFile = lineStart;
  36523. lineStart += l->lineLength;
  36524. }
  36525. checkLastLineStatus();
  36526. const int newTextLength = text.length();
  36527. for (i = 0; i < positionsToMaintain.size(); ++i)
  36528. {
  36529. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36530. if (p->getPosition() >= insertPos)
  36531. p->setPosition (p->getPosition() + newTextLength);
  36532. }
  36533. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36534. }
  36535. }
  36536. class CodeDocumentDeleteAction : public UndoableAction
  36537. {
  36538. CodeDocument& owner;
  36539. int startPos, endPos;
  36540. String removedText;
  36541. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36542. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36543. public:
  36544. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36545. : owner (owner_),
  36546. startPos (startPos_),
  36547. endPos (endPos_)
  36548. {
  36549. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36550. CodeDocument::Position (&owner, endPos));
  36551. }
  36552. ~CodeDocumentDeleteAction() {}
  36553. bool perform()
  36554. {
  36555. owner.currentActionIndex++;
  36556. owner.remove (startPos, endPos, false);
  36557. return true;
  36558. }
  36559. bool undo()
  36560. {
  36561. owner.currentActionIndex--;
  36562. owner.insert (removedText, startPos, false);
  36563. return true;
  36564. }
  36565. int getSizeInUnits() { return removedText.length() + 32; }
  36566. };
  36567. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36568. {
  36569. if (endPos <= startPos)
  36570. return;
  36571. if (undoable)
  36572. {
  36573. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36574. }
  36575. else
  36576. {
  36577. Position startPosition (this, startPos);
  36578. Position endPosition (this, endPos);
  36579. maximumLineLength = -1;
  36580. const int firstAffectedLine = startPosition.getLineNumber();
  36581. const int endLine = endPosition.getLineNumber();
  36582. int lastAffectedLine = firstAffectedLine + 1;
  36583. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36584. if (firstAffectedLine == endLine)
  36585. {
  36586. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36587. + firstLine->line.substring (endPosition.getIndexInLine());
  36588. firstLine->updateLength();
  36589. }
  36590. else
  36591. {
  36592. lastAffectedLine = lines.size();
  36593. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36594. jassert (lastLine != 0);
  36595. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36596. + lastLine->line.substring (endPosition.getIndexInLine());
  36597. firstLine->updateLength();
  36598. int numLinesToRemove = endLine - firstAffectedLine;
  36599. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36600. }
  36601. int i;
  36602. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36603. {
  36604. CodeDocumentLine* const l = lines.getUnchecked (i);
  36605. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36606. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36607. }
  36608. checkLastLineStatus();
  36609. const int totalChars = getNumCharacters();
  36610. for (i = 0; i < positionsToMaintain.size(); ++i)
  36611. {
  36612. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36613. if (p->getPosition() > startPosition.getPosition())
  36614. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36615. if (p->getPosition() > totalChars)
  36616. p->setPosition (totalChars);
  36617. }
  36618. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36619. }
  36620. }
  36621. END_JUCE_NAMESPACE
  36622. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36623. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36624. BEGIN_JUCE_NAMESPACE
  36625. class CodeEditorComponent::CaretComponent : public Component,
  36626. public Timer
  36627. {
  36628. public:
  36629. CaretComponent (CodeEditorComponent& owner_)
  36630. : owner (owner_)
  36631. {
  36632. setAlwaysOnTop (true);
  36633. setInterceptsMouseClicks (false, false);
  36634. }
  36635. ~CaretComponent()
  36636. {
  36637. }
  36638. void paint (Graphics& g)
  36639. {
  36640. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36641. }
  36642. void timerCallback()
  36643. {
  36644. setVisible (shouldBeShown() && ! isVisible());
  36645. }
  36646. void updatePosition()
  36647. {
  36648. startTimer (400);
  36649. setVisible (shouldBeShown());
  36650. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36651. }
  36652. private:
  36653. CodeEditorComponent& owner;
  36654. CaretComponent (const CaretComponent&);
  36655. CaretComponent& operator= (const CaretComponent&);
  36656. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36657. };
  36658. class CodeEditorComponent::CodeEditorLine
  36659. {
  36660. public:
  36661. CodeEditorLine() throw()
  36662. : highlightColumnStart (0), highlightColumnEnd (0)
  36663. {
  36664. }
  36665. ~CodeEditorLine() throw()
  36666. {
  36667. }
  36668. bool update (CodeDocument& document, int lineNum,
  36669. CodeDocument::Iterator& source,
  36670. CodeTokeniser* analyser, const int spacesPerTab,
  36671. const CodeDocument::Position& selectionStart,
  36672. const CodeDocument::Position& selectionEnd)
  36673. {
  36674. Array <SyntaxToken> newTokens;
  36675. newTokens.ensureStorageAllocated (8);
  36676. if (analyser == 0)
  36677. {
  36678. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36679. }
  36680. else if (lineNum < document.getNumLines())
  36681. {
  36682. const CodeDocument::Position pos (&document, lineNum, 0);
  36683. createTokens (pos.getPosition(), pos.getLineText(),
  36684. source, analyser, newTokens);
  36685. }
  36686. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36687. int newHighlightStart = 0;
  36688. int newHighlightEnd = 0;
  36689. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36690. {
  36691. const String line (document.getLine (lineNum));
  36692. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36693. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36694. line, spacesPerTab);
  36695. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36696. line, spacesPerTab);
  36697. }
  36698. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36699. {
  36700. highlightColumnStart = newHighlightStart;
  36701. highlightColumnEnd = newHighlightEnd;
  36702. }
  36703. else
  36704. {
  36705. if (tokens.size() == newTokens.size())
  36706. {
  36707. bool allTheSame = true;
  36708. for (int i = newTokens.size(); --i >= 0;)
  36709. {
  36710. if (tokens.getReference(i) != newTokens.getReference(i))
  36711. {
  36712. allTheSame = false;
  36713. break;
  36714. }
  36715. }
  36716. if (allTheSame)
  36717. return false;
  36718. }
  36719. }
  36720. tokens.swapWithArray (newTokens);
  36721. return true;
  36722. }
  36723. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36724. float x, const int y, const int baselineOffset, const int lineHeight,
  36725. const Colour& highlightColour) const
  36726. {
  36727. if (highlightColumnStart < highlightColumnEnd)
  36728. {
  36729. g.setColour (highlightColour);
  36730. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36731. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36732. }
  36733. int lastType = std::numeric_limits<int>::min();
  36734. for (int i = 0; i < tokens.size(); ++i)
  36735. {
  36736. SyntaxToken& token = tokens.getReference(i);
  36737. if (lastType != token.tokenType)
  36738. {
  36739. lastType = token.tokenType;
  36740. g.setColour (owner.getColourForTokenType (lastType));
  36741. }
  36742. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36743. if (i < tokens.size() - 1)
  36744. {
  36745. if (token.width < 0)
  36746. token.width = font.getStringWidthFloat (token.text);
  36747. x += token.width;
  36748. }
  36749. }
  36750. }
  36751. private:
  36752. struct SyntaxToken
  36753. {
  36754. String text;
  36755. int tokenType;
  36756. float width;
  36757. SyntaxToken (const String& text_, const int type) throw()
  36758. : text (text_), tokenType (type), width (-1.0f)
  36759. {
  36760. }
  36761. bool operator!= (const SyntaxToken& other) const throw()
  36762. {
  36763. return text != other.text || tokenType != other.tokenType;
  36764. }
  36765. };
  36766. Array <SyntaxToken> tokens;
  36767. int highlightColumnStart, highlightColumnEnd;
  36768. static void createTokens (int startPosition, const String& lineText,
  36769. CodeDocument::Iterator& source,
  36770. CodeTokeniser* analyser,
  36771. Array <SyntaxToken>& newTokens)
  36772. {
  36773. CodeDocument::Iterator lastIterator (source);
  36774. const int lineLength = lineText.length();
  36775. for (;;)
  36776. {
  36777. int tokenType = analyser->readNextToken (source);
  36778. int tokenStart = lastIterator.getPosition();
  36779. int tokenEnd = source.getPosition();
  36780. if (tokenEnd <= tokenStart)
  36781. break;
  36782. tokenEnd -= startPosition;
  36783. if (tokenEnd > 0)
  36784. {
  36785. tokenStart -= startPosition;
  36786. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36787. tokenType));
  36788. if (tokenEnd >= lineLength)
  36789. break;
  36790. }
  36791. lastIterator = source;
  36792. }
  36793. source = lastIterator;
  36794. }
  36795. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36796. {
  36797. int x = 0;
  36798. for (int i = 0; i < tokens.size(); ++i)
  36799. {
  36800. SyntaxToken& t = tokens.getReference(i);
  36801. for (;;)
  36802. {
  36803. int tabPos = t.text.indexOfChar ('\t');
  36804. if (tabPos < 0)
  36805. break;
  36806. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36807. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36808. }
  36809. x += t.text.length();
  36810. }
  36811. }
  36812. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36813. {
  36814. jassert (index <= line.length());
  36815. int col = 0;
  36816. for (int i = 0; i < index; ++i)
  36817. {
  36818. if (line[i] != '\t')
  36819. ++col;
  36820. else
  36821. col += spacesPerTab - (col % spacesPerTab);
  36822. }
  36823. return col;
  36824. }
  36825. };
  36826. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36827. CodeTokeniser* const codeTokeniser_)
  36828. : document (document_),
  36829. firstLineOnScreen (0),
  36830. gutter (5),
  36831. spacesPerTab (4),
  36832. lineHeight (0),
  36833. linesOnScreen (0),
  36834. columnsOnScreen (0),
  36835. scrollbarThickness (16),
  36836. columnToTryToMaintain (-1),
  36837. useSpacesForTabs (false),
  36838. xOffset (0),
  36839. codeTokeniser (codeTokeniser_)
  36840. {
  36841. caretPos = CodeDocument::Position (&document_, 0, 0);
  36842. caretPos.setPositionMaintained (true);
  36843. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36844. selectionStart.setPositionMaintained (true);
  36845. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36846. selectionEnd.setPositionMaintained (true);
  36847. setOpaque (true);
  36848. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36849. setWantsKeyboardFocus (true);
  36850. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36851. verticalScrollBar->setSingleStepSize (1.0);
  36852. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36853. horizontalScrollBar->setSingleStepSize (1.0);
  36854. addAndMakeVisible (caret = new CaretComponent (*this));
  36855. Font f (12.0f);
  36856. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36857. setFont (f);
  36858. resetToDefaultColours();
  36859. verticalScrollBar->addListener (this);
  36860. horizontalScrollBar->addListener (this);
  36861. document.addListener (this);
  36862. }
  36863. CodeEditorComponent::~CodeEditorComponent()
  36864. {
  36865. document.removeListener (this);
  36866. deleteAllChildren();
  36867. }
  36868. void CodeEditorComponent::loadContent (const String& newContent)
  36869. {
  36870. clearCachedIterators (0);
  36871. document.replaceAllContent (newContent);
  36872. document.clearUndoHistory();
  36873. document.setSavePoint();
  36874. caretPos.setPosition (0);
  36875. selectionStart.setPosition (0);
  36876. selectionEnd.setPosition (0);
  36877. scrollToLine (0);
  36878. }
  36879. bool CodeEditorComponent::isTextInputActive() const
  36880. {
  36881. return true;
  36882. }
  36883. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36884. const CodeDocument::Position& affectedTextEnd)
  36885. {
  36886. clearCachedIterators (affectedTextStart.getLineNumber());
  36887. triggerAsyncUpdate();
  36888. caret->updatePosition();
  36889. columnToTryToMaintain = -1;
  36890. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36891. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36892. deselectAll();
  36893. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36894. || caretPos.getPosition() < affectedTextStart.getPosition())
  36895. moveCaretTo (affectedTextStart, false);
  36896. updateScrollBars();
  36897. }
  36898. void CodeEditorComponent::resized()
  36899. {
  36900. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36901. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36902. lines.clear();
  36903. rebuildLineTokens();
  36904. caret->updatePosition();
  36905. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36906. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36907. updateScrollBars();
  36908. }
  36909. void CodeEditorComponent::paint (Graphics& g)
  36910. {
  36911. handleUpdateNowIfNeeded();
  36912. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36913. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36914. g.setFont (font);
  36915. const int baselineOffset = (int) font.getAscent();
  36916. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36917. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36918. const Rectangle<int> clip (g.getClipBounds());
  36919. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36920. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36921. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36922. {
  36923. lines.getUnchecked(j)->draw (*this, g, font,
  36924. (float) (gutter - xOffset * charWidth),
  36925. lineHeight * j, baselineOffset, lineHeight,
  36926. highlightColour);
  36927. }
  36928. }
  36929. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36930. {
  36931. if (scrollbarThickness != thickness)
  36932. {
  36933. scrollbarThickness = thickness;
  36934. resized();
  36935. }
  36936. }
  36937. void CodeEditorComponent::handleAsyncUpdate()
  36938. {
  36939. rebuildLineTokens();
  36940. }
  36941. void CodeEditorComponent::rebuildLineTokens()
  36942. {
  36943. cancelPendingUpdate();
  36944. const int numNeeded = linesOnScreen + 1;
  36945. int minLineToRepaint = numNeeded;
  36946. int maxLineToRepaint = 0;
  36947. if (numNeeded != lines.size())
  36948. {
  36949. lines.clear();
  36950. for (int i = numNeeded; --i >= 0;)
  36951. lines.add (new CodeEditorLine());
  36952. minLineToRepaint = 0;
  36953. maxLineToRepaint = numNeeded;
  36954. }
  36955. jassert (numNeeded == lines.size());
  36956. CodeDocument::Iterator source (&document);
  36957. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36958. for (int i = 0; i < numNeeded; ++i)
  36959. {
  36960. CodeEditorLine* const line = lines.getUnchecked(i);
  36961. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36962. selectionStart, selectionEnd))
  36963. {
  36964. minLineToRepaint = jmin (minLineToRepaint, i);
  36965. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36966. }
  36967. }
  36968. if (minLineToRepaint <= maxLineToRepaint)
  36969. {
  36970. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36971. verticalScrollBar->getX() - gutter,
  36972. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36973. }
  36974. }
  36975. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36976. {
  36977. caretPos = newPos;
  36978. columnToTryToMaintain = -1;
  36979. if (highlighting)
  36980. {
  36981. if (dragType == notDragging)
  36982. {
  36983. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36984. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36985. dragType = draggingSelectionStart;
  36986. else
  36987. dragType = draggingSelectionEnd;
  36988. }
  36989. if (dragType == draggingSelectionStart)
  36990. {
  36991. selectionStart = caretPos;
  36992. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36993. {
  36994. const CodeDocument::Position temp (selectionStart);
  36995. selectionStart = selectionEnd;
  36996. selectionEnd = temp;
  36997. dragType = draggingSelectionEnd;
  36998. }
  36999. }
  37000. else
  37001. {
  37002. selectionEnd = caretPos;
  37003. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37004. {
  37005. const CodeDocument::Position temp (selectionStart);
  37006. selectionStart = selectionEnd;
  37007. selectionEnd = temp;
  37008. dragType = draggingSelectionStart;
  37009. }
  37010. }
  37011. triggerAsyncUpdate();
  37012. }
  37013. else
  37014. {
  37015. deselectAll();
  37016. }
  37017. caret->updatePosition();
  37018. scrollToKeepCaretOnScreen();
  37019. updateScrollBars();
  37020. }
  37021. void CodeEditorComponent::deselectAll()
  37022. {
  37023. if (selectionStart != selectionEnd)
  37024. triggerAsyncUpdate();
  37025. selectionStart = caretPos;
  37026. selectionEnd = caretPos;
  37027. }
  37028. void CodeEditorComponent::updateScrollBars()
  37029. {
  37030. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37031. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37032. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37033. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37034. }
  37035. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37036. {
  37037. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37038. newFirstLineOnScreen);
  37039. if (newFirstLineOnScreen != firstLineOnScreen)
  37040. {
  37041. firstLineOnScreen = newFirstLineOnScreen;
  37042. caret->updatePosition();
  37043. updateCachedIterators (firstLineOnScreen);
  37044. triggerAsyncUpdate();
  37045. }
  37046. }
  37047. void CodeEditorComponent::scrollToColumnInternal (double column)
  37048. {
  37049. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37050. if (xOffset != newOffset)
  37051. {
  37052. xOffset = newOffset;
  37053. caret->updatePosition();
  37054. repaint();
  37055. }
  37056. }
  37057. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37058. {
  37059. scrollToLineInternal (newFirstLineOnScreen);
  37060. updateScrollBars();
  37061. }
  37062. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37063. {
  37064. scrollToColumnInternal (newFirstColumnOnScreen);
  37065. updateScrollBars();
  37066. }
  37067. void CodeEditorComponent::scrollBy (int deltaLines)
  37068. {
  37069. scrollToLine (firstLineOnScreen + deltaLines);
  37070. }
  37071. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37072. {
  37073. if (caretPos.getLineNumber() < firstLineOnScreen)
  37074. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37075. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37076. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37077. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37078. if (column >= xOffset + columnsOnScreen - 1)
  37079. scrollToColumn (column + 1 - columnsOnScreen);
  37080. else if (column < xOffset)
  37081. scrollToColumn (column);
  37082. }
  37083. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37084. {
  37085. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37086. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37087. roundToInt (charWidth),
  37088. lineHeight);
  37089. }
  37090. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37091. {
  37092. const int line = y / lineHeight + firstLineOnScreen;
  37093. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37094. const int index = columnToIndex (line, column);
  37095. return CodeDocument::Position (&document, line, index);
  37096. }
  37097. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37098. {
  37099. document.deleteSection (selectionStart, selectionEnd);
  37100. if (newText.isNotEmpty())
  37101. document.insertText (caretPos, newText);
  37102. scrollToKeepCaretOnScreen();
  37103. }
  37104. void CodeEditorComponent::insertTabAtCaret()
  37105. {
  37106. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37107. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37108. {
  37109. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37110. }
  37111. if (useSpacesForTabs)
  37112. {
  37113. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37114. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37115. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37116. }
  37117. else
  37118. {
  37119. insertTextAtCaret ("\t");
  37120. }
  37121. }
  37122. void CodeEditorComponent::cut()
  37123. {
  37124. insertTextAtCaret (String::empty);
  37125. }
  37126. void CodeEditorComponent::copy()
  37127. {
  37128. newTransaction();
  37129. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37130. if (selection.isNotEmpty())
  37131. SystemClipboard::copyTextToClipboard (selection);
  37132. }
  37133. void CodeEditorComponent::copyThenCut()
  37134. {
  37135. copy();
  37136. cut();
  37137. newTransaction();
  37138. }
  37139. void CodeEditorComponent::paste()
  37140. {
  37141. newTransaction();
  37142. const String clip (SystemClipboard::getTextFromClipboard());
  37143. if (clip.isNotEmpty())
  37144. insertTextAtCaret (clip);
  37145. newTransaction();
  37146. }
  37147. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37148. {
  37149. newTransaction();
  37150. if (moveInWholeWordSteps)
  37151. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37152. else
  37153. moveCaretTo (caretPos.movedBy (-1), selecting);
  37154. }
  37155. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37156. {
  37157. newTransaction();
  37158. if (moveInWholeWordSteps)
  37159. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37160. else
  37161. moveCaretTo (caretPos.movedBy (1), selecting);
  37162. }
  37163. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37164. {
  37165. CodeDocument::Position pos (caretPos);
  37166. const int newLineNum = pos.getLineNumber() + delta;
  37167. if (columnToTryToMaintain < 0)
  37168. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37169. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37170. const int colToMaintain = columnToTryToMaintain;
  37171. moveCaretTo (pos, selecting);
  37172. columnToTryToMaintain = colToMaintain;
  37173. }
  37174. void CodeEditorComponent::cursorDown (const bool selecting)
  37175. {
  37176. newTransaction();
  37177. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37178. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37179. else
  37180. moveLineDelta (1, selecting);
  37181. }
  37182. void CodeEditorComponent::cursorUp (const bool selecting)
  37183. {
  37184. newTransaction();
  37185. if (caretPos.getLineNumber() == 0)
  37186. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37187. else
  37188. moveLineDelta (-1, selecting);
  37189. }
  37190. void CodeEditorComponent::pageDown (const bool selecting)
  37191. {
  37192. newTransaction();
  37193. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37194. moveLineDelta (linesOnScreen, selecting);
  37195. }
  37196. void CodeEditorComponent::pageUp (const bool selecting)
  37197. {
  37198. newTransaction();
  37199. scrollBy (-linesOnScreen);
  37200. moveLineDelta (-linesOnScreen, selecting);
  37201. }
  37202. void CodeEditorComponent::scrollUp()
  37203. {
  37204. newTransaction();
  37205. scrollBy (1);
  37206. if (caretPos.getLineNumber() < firstLineOnScreen)
  37207. moveLineDelta (1, false);
  37208. }
  37209. void CodeEditorComponent::scrollDown()
  37210. {
  37211. newTransaction();
  37212. scrollBy (-1);
  37213. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37214. moveLineDelta (-1, false);
  37215. }
  37216. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37217. {
  37218. newTransaction();
  37219. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37220. }
  37221. static int findFirstNonWhitespaceChar (const String& line) throw()
  37222. {
  37223. const int len = line.length();
  37224. for (int i = 0; i < len; ++i)
  37225. if (! CharacterFunctions::isWhitespace (line [i]))
  37226. return i;
  37227. return 0;
  37228. }
  37229. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37230. {
  37231. newTransaction();
  37232. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37233. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37234. index = 0;
  37235. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37236. }
  37237. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37238. {
  37239. newTransaction();
  37240. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37241. }
  37242. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37243. {
  37244. newTransaction();
  37245. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37246. }
  37247. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37248. {
  37249. if (moveInWholeWordSteps)
  37250. {
  37251. cut(); // in case something is already highlighted
  37252. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37253. }
  37254. else
  37255. {
  37256. if (selectionStart == selectionEnd)
  37257. selectionStart.moveBy (-1);
  37258. }
  37259. cut();
  37260. }
  37261. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37262. {
  37263. if (moveInWholeWordSteps)
  37264. {
  37265. cut(); // in case something is already highlighted
  37266. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37267. }
  37268. else
  37269. {
  37270. if (selectionStart == selectionEnd)
  37271. selectionEnd.moveBy (1);
  37272. else
  37273. newTransaction();
  37274. }
  37275. cut();
  37276. }
  37277. void CodeEditorComponent::selectAll()
  37278. {
  37279. newTransaction();
  37280. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37281. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37282. }
  37283. void CodeEditorComponent::undo()
  37284. {
  37285. document.undo();
  37286. scrollToKeepCaretOnScreen();
  37287. }
  37288. void CodeEditorComponent::redo()
  37289. {
  37290. document.redo();
  37291. scrollToKeepCaretOnScreen();
  37292. }
  37293. void CodeEditorComponent::newTransaction()
  37294. {
  37295. document.newTransaction();
  37296. startTimer (600);
  37297. }
  37298. void CodeEditorComponent::timerCallback()
  37299. {
  37300. newTransaction();
  37301. }
  37302. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37303. {
  37304. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37305. }
  37306. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37307. {
  37308. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37309. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37310. }
  37311. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37312. {
  37313. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37314. CodeDocument::Position (&document, range.getEnd()));
  37315. }
  37316. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37317. {
  37318. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37319. const bool shiftDown = key.getModifiers().isShiftDown();
  37320. if (key.isKeyCode (KeyPress::leftKey))
  37321. {
  37322. cursorLeft (moveInWholeWordSteps, shiftDown);
  37323. }
  37324. else if (key.isKeyCode (KeyPress::rightKey))
  37325. {
  37326. cursorRight (moveInWholeWordSteps, shiftDown);
  37327. }
  37328. else if (key.isKeyCode (KeyPress::upKey))
  37329. {
  37330. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37331. scrollDown();
  37332. #if JUCE_MAC
  37333. else if (key.getModifiers().isCommandDown())
  37334. goToStartOfDocument (shiftDown);
  37335. #endif
  37336. else
  37337. cursorUp (shiftDown);
  37338. }
  37339. else if (key.isKeyCode (KeyPress::downKey))
  37340. {
  37341. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37342. scrollUp();
  37343. #if JUCE_MAC
  37344. else if (key.getModifiers().isCommandDown())
  37345. goToEndOfDocument (shiftDown);
  37346. #endif
  37347. else
  37348. cursorDown (shiftDown);
  37349. }
  37350. else if (key.isKeyCode (KeyPress::pageDownKey))
  37351. {
  37352. pageDown (shiftDown);
  37353. }
  37354. else if (key.isKeyCode (KeyPress::pageUpKey))
  37355. {
  37356. pageUp (shiftDown);
  37357. }
  37358. else if (key.isKeyCode (KeyPress::homeKey))
  37359. {
  37360. if (moveInWholeWordSteps)
  37361. goToStartOfDocument (shiftDown);
  37362. else
  37363. goToStartOfLine (shiftDown);
  37364. }
  37365. else if (key.isKeyCode (KeyPress::endKey))
  37366. {
  37367. if (moveInWholeWordSteps)
  37368. goToEndOfDocument (shiftDown);
  37369. else
  37370. goToEndOfLine (shiftDown);
  37371. }
  37372. else if (key.isKeyCode (KeyPress::backspaceKey))
  37373. {
  37374. backspace (moveInWholeWordSteps);
  37375. }
  37376. else if (key.isKeyCode (KeyPress::deleteKey))
  37377. {
  37378. deleteForward (moveInWholeWordSteps);
  37379. }
  37380. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37381. {
  37382. copy();
  37383. }
  37384. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37385. {
  37386. copyThenCut();
  37387. }
  37388. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37389. {
  37390. paste();
  37391. }
  37392. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37393. {
  37394. undo();
  37395. }
  37396. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37397. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37398. {
  37399. redo();
  37400. }
  37401. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37402. {
  37403. selectAll();
  37404. }
  37405. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37406. {
  37407. insertTabAtCaret();
  37408. }
  37409. else if (key == KeyPress::returnKey)
  37410. {
  37411. newTransaction();
  37412. insertTextAtCaret (document.getNewLineCharacters());
  37413. }
  37414. else if (key.isKeyCode (KeyPress::escapeKey))
  37415. {
  37416. newTransaction();
  37417. }
  37418. else if (key.getTextCharacter() >= ' ')
  37419. {
  37420. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37421. }
  37422. else
  37423. {
  37424. return false;
  37425. }
  37426. return true;
  37427. }
  37428. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37429. {
  37430. newTransaction();
  37431. dragType = notDragging;
  37432. if (! e.mods.isPopupMenu())
  37433. {
  37434. beginDragAutoRepeat (100);
  37435. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37436. }
  37437. else
  37438. {
  37439. /*PopupMenu m;
  37440. addPopupMenuItems (m, &e);
  37441. const int result = m.show();
  37442. if (result != 0)
  37443. performPopupMenuAction (result);
  37444. */
  37445. }
  37446. }
  37447. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37448. {
  37449. if (! e.mods.isPopupMenu())
  37450. moveCaretTo (getPositionAt (e.x, e.y), true);
  37451. }
  37452. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37453. {
  37454. newTransaction();
  37455. beginDragAutoRepeat (0);
  37456. dragType = notDragging;
  37457. }
  37458. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37459. {
  37460. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37461. CodeDocument::Position tokenEnd (tokenStart);
  37462. if (e.getNumberOfClicks() > 2)
  37463. {
  37464. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37465. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37466. }
  37467. else
  37468. {
  37469. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37470. tokenEnd.moveBy (1);
  37471. tokenStart = tokenEnd;
  37472. while (tokenStart.getIndexInLine() > 0
  37473. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37474. tokenStart.moveBy (-1);
  37475. }
  37476. moveCaretTo (tokenEnd, false);
  37477. moveCaretTo (tokenStart, true);
  37478. }
  37479. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37480. {
  37481. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37482. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37483. {
  37484. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37485. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37486. }
  37487. else
  37488. {
  37489. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37490. }
  37491. }
  37492. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37493. {
  37494. if (scrollBarThatHasMoved == verticalScrollBar)
  37495. scrollToLineInternal ((int) newRangeStart);
  37496. else
  37497. scrollToColumnInternal (newRangeStart);
  37498. }
  37499. void CodeEditorComponent::focusGained (FocusChangeType)
  37500. {
  37501. caret->updatePosition();
  37502. }
  37503. void CodeEditorComponent::focusLost (FocusChangeType)
  37504. {
  37505. caret->updatePosition();
  37506. }
  37507. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37508. {
  37509. useSpacesForTabs = insertSpaces;
  37510. if (spacesPerTab != numSpaces)
  37511. {
  37512. spacesPerTab = numSpaces;
  37513. triggerAsyncUpdate();
  37514. }
  37515. }
  37516. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37517. {
  37518. const String line (document.getLine (lineNum));
  37519. jassert (index <= line.length());
  37520. int col = 0;
  37521. for (int i = 0; i < index; ++i)
  37522. {
  37523. if (line[i] != '\t')
  37524. ++col;
  37525. else
  37526. col += getTabSize() - (col % getTabSize());
  37527. }
  37528. return col;
  37529. }
  37530. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37531. {
  37532. const String line (document.getLine (lineNum));
  37533. const int lineLength = line.length();
  37534. int i, col = 0;
  37535. for (i = 0; i < lineLength; ++i)
  37536. {
  37537. if (line[i] != '\t')
  37538. ++col;
  37539. else
  37540. col += getTabSize() - (col % getTabSize());
  37541. if (col > column)
  37542. break;
  37543. }
  37544. return i;
  37545. }
  37546. void CodeEditorComponent::setFont (const Font& newFont)
  37547. {
  37548. font = newFont;
  37549. charWidth = font.getStringWidthFloat ("0");
  37550. lineHeight = roundToInt (font.getHeight());
  37551. resized();
  37552. }
  37553. void CodeEditorComponent::resetToDefaultColours()
  37554. {
  37555. coloursForTokenCategories.clear();
  37556. if (codeTokeniser != 0)
  37557. {
  37558. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37559. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37560. }
  37561. }
  37562. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37563. {
  37564. jassert (tokenType < 256);
  37565. while (coloursForTokenCategories.size() < tokenType)
  37566. coloursForTokenCategories.add (Colours::black);
  37567. coloursForTokenCategories.set (tokenType, colour);
  37568. repaint();
  37569. }
  37570. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37571. {
  37572. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37573. return findColour (CodeEditorComponent::defaultTextColourId);
  37574. return coloursForTokenCategories.getReference (tokenType);
  37575. }
  37576. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37577. {
  37578. int i;
  37579. for (i = cachedIterators.size(); --i >= 0;)
  37580. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37581. break;
  37582. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37583. }
  37584. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37585. {
  37586. const int maxNumCachedPositions = 5000;
  37587. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37588. if (cachedIterators.size() == 0)
  37589. cachedIterators.add (new CodeDocument::Iterator (&document));
  37590. if (codeTokeniser == 0)
  37591. return;
  37592. for (;;)
  37593. {
  37594. CodeDocument::Iterator* last = cachedIterators.getLast();
  37595. if (last->getLine() >= maxLineNum)
  37596. break;
  37597. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37598. cachedIterators.add (t);
  37599. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37600. for (;;)
  37601. {
  37602. codeTokeniser->readNextToken (*t);
  37603. if (t->getLine() >= targetLine)
  37604. break;
  37605. if (t->isEOF())
  37606. return;
  37607. }
  37608. }
  37609. }
  37610. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37611. {
  37612. if (codeTokeniser == 0)
  37613. return;
  37614. for (int i = cachedIterators.size(); --i >= 0;)
  37615. {
  37616. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37617. if (t->getPosition() <= position)
  37618. {
  37619. source = *t;
  37620. break;
  37621. }
  37622. }
  37623. while (source.getPosition() < position)
  37624. {
  37625. const CodeDocument::Iterator original (source);
  37626. codeTokeniser->readNextToken (source);
  37627. if (source.getPosition() > position || source.isEOF())
  37628. {
  37629. source = original;
  37630. break;
  37631. }
  37632. }
  37633. }
  37634. END_JUCE_NAMESPACE
  37635. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37636. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37637. BEGIN_JUCE_NAMESPACE
  37638. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37639. {
  37640. }
  37641. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37642. {
  37643. }
  37644. namespace CppTokeniser
  37645. {
  37646. static bool isIdentifierStart (const juce_wchar c) throw()
  37647. {
  37648. return CharacterFunctions::isLetter (c)
  37649. || c == '_' || c == '@';
  37650. }
  37651. static bool isIdentifierBody (const juce_wchar c) throw()
  37652. {
  37653. return CharacterFunctions::isLetterOrDigit (c)
  37654. || c == '_' || c == '@';
  37655. }
  37656. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37657. {
  37658. static const juce_wchar* const keywords2Char[] =
  37659. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37660. static const juce_wchar* const keywords3Char[] =
  37661. { 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 };
  37662. static const juce_wchar* const keywords4Char[] =
  37663. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37664. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37665. static const juce_wchar* const keywords5Char[] =
  37666. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37667. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37668. static const juce_wchar* const keywords6Char[] =
  37669. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37670. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37671. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37672. static const juce_wchar* const keywordsOther[] =
  37673. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37674. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37675. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37676. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37677. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37678. const juce_wchar* const* k;
  37679. switch (tokenLength)
  37680. {
  37681. case 2: k = keywords2Char; break;
  37682. case 3: k = keywords3Char; break;
  37683. case 4: k = keywords4Char; break;
  37684. case 5: k = keywords5Char; break;
  37685. case 6: k = keywords6Char; break;
  37686. default:
  37687. if (tokenLength < 2 || tokenLength > 16)
  37688. return false;
  37689. k = keywordsOther;
  37690. break;
  37691. }
  37692. int i = 0;
  37693. while (k[i] != 0)
  37694. {
  37695. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37696. return true;
  37697. ++i;
  37698. }
  37699. return false;
  37700. }
  37701. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37702. {
  37703. int tokenLength = 0;
  37704. juce_wchar possibleIdentifier [19];
  37705. while (isIdentifierBody (source.peekNextChar()))
  37706. {
  37707. const juce_wchar c = source.nextChar();
  37708. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37709. possibleIdentifier [tokenLength] = c;
  37710. ++tokenLength;
  37711. }
  37712. if (tokenLength > 1 && tokenLength <= 16)
  37713. {
  37714. possibleIdentifier [tokenLength] = 0;
  37715. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37716. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37717. }
  37718. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37719. }
  37720. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37721. {
  37722. const juce_wchar c = source.peekNextChar();
  37723. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37724. source.skip();
  37725. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37726. return false;
  37727. return true;
  37728. }
  37729. static bool isHexDigit (const juce_wchar c) throw()
  37730. {
  37731. return (c >= '0' && c <= '9')
  37732. || (c >= 'a' && c <= 'f')
  37733. || (c >= 'A' && c <= 'F');
  37734. }
  37735. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37736. {
  37737. if (source.nextChar() != '0')
  37738. return false;
  37739. juce_wchar c = source.nextChar();
  37740. if (c != 'x' && c != 'X')
  37741. return false;
  37742. int numDigits = 0;
  37743. while (isHexDigit (source.peekNextChar()))
  37744. {
  37745. ++numDigits;
  37746. source.skip();
  37747. }
  37748. if (numDigits == 0)
  37749. return false;
  37750. return skipNumberSuffix (source);
  37751. }
  37752. static bool isOctalDigit (const juce_wchar c) throw()
  37753. {
  37754. return c >= '0' && c <= '7';
  37755. }
  37756. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37757. {
  37758. if (source.nextChar() != '0')
  37759. return false;
  37760. if (! isOctalDigit (source.nextChar()))
  37761. return false;
  37762. while (isOctalDigit (source.peekNextChar()))
  37763. source.skip();
  37764. return skipNumberSuffix (source);
  37765. }
  37766. static bool isDecimalDigit (const juce_wchar c) throw()
  37767. {
  37768. return c >= '0' && c <= '9';
  37769. }
  37770. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37771. {
  37772. int numChars = 0;
  37773. while (isDecimalDigit (source.peekNextChar()))
  37774. {
  37775. ++numChars;
  37776. source.skip();
  37777. }
  37778. if (numChars == 0)
  37779. return false;
  37780. return skipNumberSuffix (source);
  37781. }
  37782. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37783. {
  37784. int numDigits = 0;
  37785. while (isDecimalDigit (source.peekNextChar()))
  37786. {
  37787. source.skip();
  37788. ++numDigits;
  37789. }
  37790. const bool hasPoint = (source.peekNextChar() == '.');
  37791. if (hasPoint)
  37792. {
  37793. source.skip();
  37794. while (isDecimalDigit (source.peekNextChar()))
  37795. {
  37796. source.skip();
  37797. ++numDigits;
  37798. }
  37799. }
  37800. if (numDigits == 0)
  37801. return false;
  37802. juce_wchar c = source.peekNextChar();
  37803. const bool hasExponent = (c == 'e' || c == 'E');
  37804. if (hasExponent)
  37805. {
  37806. source.skip();
  37807. c = source.peekNextChar();
  37808. if (c == '+' || c == '-')
  37809. source.skip();
  37810. int numExpDigits = 0;
  37811. while (isDecimalDigit (source.peekNextChar()))
  37812. {
  37813. source.skip();
  37814. ++numExpDigits;
  37815. }
  37816. if (numExpDigits == 0)
  37817. return false;
  37818. }
  37819. c = source.peekNextChar();
  37820. if (c == 'f' || c == 'F')
  37821. source.skip();
  37822. else if (! (hasExponent || hasPoint))
  37823. return false;
  37824. return true;
  37825. }
  37826. static int parseNumber (CodeDocument::Iterator& source)
  37827. {
  37828. const CodeDocument::Iterator original (source);
  37829. if (parseFloatLiteral (source))
  37830. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37831. source = original;
  37832. if (parseHexLiteral (source))
  37833. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37834. source = original;
  37835. if (parseOctalLiteral (source))
  37836. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37837. source = original;
  37838. if (parseDecimalLiteral (source))
  37839. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37840. source = original;
  37841. source.skip();
  37842. return CPlusPlusCodeTokeniser::tokenType_error;
  37843. }
  37844. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37845. {
  37846. const juce_wchar quote = source.nextChar();
  37847. for (;;)
  37848. {
  37849. const juce_wchar c = source.nextChar();
  37850. if (c == quote || c == 0)
  37851. break;
  37852. if (c == '\\')
  37853. source.skip();
  37854. }
  37855. }
  37856. static void skipComment (CodeDocument::Iterator& source) throw()
  37857. {
  37858. bool lastWasStar = false;
  37859. for (;;)
  37860. {
  37861. const juce_wchar c = source.nextChar();
  37862. if (c == 0 || (c == '/' && lastWasStar))
  37863. break;
  37864. lastWasStar = (c == '*');
  37865. }
  37866. }
  37867. }
  37868. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37869. {
  37870. int result = tokenType_error;
  37871. source.skipWhitespace();
  37872. juce_wchar firstChar = source.peekNextChar();
  37873. switch (firstChar)
  37874. {
  37875. case 0:
  37876. source.skip();
  37877. break;
  37878. case '0':
  37879. case '1':
  37880. case '2':
  37881. case '3':
  37882. case '4':
  37883. case '5':
  37884. case '6':
  37885. case '7':
  37886. case '8':
  37887. case '9':
  37888. result = CppTokeniser::parseNumber (source);
  37889. break;
  37890. case '.':
  37891. result = CppTokeniser::parseNumber (source);
  37892. if (result == tokenType_error)
  37893. result = tokenType_punctuation;
  37894. break;
  37895. case ',':
  37896. case ';':
  37897. case ':':
  37898. source.skip();
  37899. result = tokenType_punctuation;
  37900. break;
  37901. case '(':
  37902. case ')':
  37903. case '{':
  37904. case '}':
  37905. case '[':
  37906. case ']':
  37907. source.skip();
  37908. result = tokenType_bracket;
  37909. break;
  37910. case '"':
  37911. case '\'':
  37912. CppTokeniser::skipQuotedString (source);
  37913. result = tokenType_stringLiteral;
  37914. break;
  37915. case '+':
  37916. result = tokenType_operator;
  37917. source.skip();
  37918. if (source.peekNextChar() == '+')
  37919. source.skip();
  37920. else if (source.peekNextChar() == '=')
  37921. source.skip();
  37922. break;
  37923. case '-':
  37924. source.skip();
  37925. result = CppTokeniser::parseNumber (source);
  37926. if (result == tokenType_error)
  37927. {
  37928. result = tokenType_operator;
  37929. if (source.peekNextChar() == '-')
  37930. source.skip();
  37931. else if (source.peekNextChar() == '=')
  37932. source.skip();
  37933. }
  37934. break;
  37935. case '*':
  37936. case '%':
  37937. case '=':
  37938. case '!':
  37939. result = tokenType_operator;
  37940. source.skip();
  37941. if (source.peekNextChar() == '=')
  37942. source.skip();
  37943. break;
  37944. case '/':
  37945. result = tokenType_operator;
  37946. source.skip();
  37947. if (source.peekNextChar() == '=')
  37948. {
  37949. source.skip();
  37950. }
  37951. else if (source.peekNextChar() == '/')
  37952. {
  37953. result = tokenType_comment;
  37954. source.skipToEndOfLine();
  37955. }
  37956. else if (source.peekNextChar() == '*')
  37957. {
  37958. source.skip();
  37959. result = tokenType_comment;
  37960. CppTokeniser::skipComment (source);
  37961. }
  37962. break;
  37963. case '?':
  37964. case '~':
  37965. source.skip();
  37966. result = tokenType_operator;
  37967. break;
  37968. case '<':
  37969. source.skip();
  37970. result = tokenType_operator;
  37971. if (source.peekNextChar() == '=')
  37972. {
  37973. source.skip();
  37974. }
  37975. else if (source.peekNextChar() == '<')
  37976. {
  37977. source.skip();
  37978. if (source.peekNextChar() == '=')
  37979. source.skip();
  37980. }
  37981. break;
  37982. case '>':
  37983. source.skip();
  37984. result = tokenType_operator;
  37985. if (source.peekNextChar() == '=')
  37986. {
  37987. source.skip();
  37988. }
  37989. else if (source.peekNextChar() == '<')
  37990. {
  37991. source.skip();
  37992. if (source.peekNextChar() == '=')
  37993. source.skip();
  37994. }
  37995. break;
  37996. case '|':
  37997. source.skip();
  37998. result = tokenType_operator;
  37999. if (source.peekNextChar() == '=')
  38000. {
  38001. source.skip();
  38002. }
  38003. else if (source.peekNextChar() == '|')
  38004. {
  38005. source.skip();
  38006. if (source.peekNextChar() == '=')
  38007. source.skip();
  38008. }
  38009. break;
  38010. case '&':
  38011. source.skip();
  38012. result = tokenType_operator;
  38013. if (source.peekNextChar() == '=')
  38014. {
  38015. source.skip();
  38016. }
  38017. else if (source.peekNextChar() == '&')
  38018. {
  38019. source.skip();
  38020. if (source.peekNextChar() == '=')
  38021. source.skip();
  38022. }
  38023. break;
  38024. case '^':
  38025. source.skip();
  38026. result = tokenType_operator;
  38027. if (source.peekNextChar() == '=')
  38028. {
  38029. source.skip();
  38030. }
  38031. else if (source.peekNextChar() == '^')
  38032. {
  38033. source.skip();
  38034. if (source.peekNextChar() == '=')
  38035. source.skip();
  38036. }
  38037. break;
  38038. case '#':
  38039. result = tokenType_preprocessor;
  38040. source.skipToEndOfLine();
  38041. break;
  38042. default:
  38043. if (CppTokeniser::isIdentifierStart (firstChar))
  38044. result = CppTokeniser::parseIdentifier (source);
  38045. else
  38046. source.skip();
  38047. break;
  38048. }
  38049. return result;
  38050. }
  38051. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38052. {
  38053. const char* const types[] =
  38054. {
  38055. "Error",
  38056. "Comment",
  38057. "C++ keyword",
  38058. "Identifier",
  38059. "Integer literal",
  38060. "Float literal",
  38061. "String literal",
  38062. "Operator",
  38063. "Bracket",
  38064. "Punctuation",
  38065. "Preprocessor line",
  38066. 0
  38067. };
  38068. return StringArray (types);
  38069. }
  38070. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38071. {
  38072. const uint32 colours[] =
  38073. {
  38074. 0xffcc0000, // error
  38075. 0xff00aa00, // comment
  38076. 0xff0000cc, // keyword
  38077. 0xff000000, // identifier
  38078. 0xff880000, // int literal
  38079. 0xff885500, // float literal
  38080. 0xff990099, // string literal
  38081. 0xff225500, // operator
  38082. 0xff000055, // bracket
  38083. 0xff004400, // punctuation
  38084. 0xff660000 // preprocessor
  38085. };
  38086. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38087. return Colour (colours [tokenType]);
  38088. return Colours::black;
  38089. }
  38090. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38091. {
  38092. return CppTokeniser::isReservedKeyword (token, token.length());
  38093. }
  38094. END_JUCE_NAMESPACE
  38095. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38096. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38097. BEGIN_JUCE_NAMESPACE
  38098. ComboBox::ComboBox (const String& name)
  38099. : Component (name),
  38100. lastCurrentId (0),
  38101. isButtonDown (false),
  38102. separatorPending (false),
  38103. menuActive (false),
  38104. label (0)
  38105. {
  38106. noChoicesMessage = TRANS("(no choices)");
  38107. setRepaintsOnMouseActivity (true);
  38108. lookAndFeelChanged();
  38109. currentId.addListener (this);
  38110. }
  38111. ComboBox::~ComboBox()
  38112. {
  38113. currentId.removeListener (this);
  38114. if (menuActive)
  38115. PopupMenu::dismissAllActiveMenus();
  38116. label = 0;
  38117. deleteAllChildren();
  38118. }
  38119. void ComboBox::setEditableText (const bool isEditable)
  38120. {
  38121. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38122. {
  38123. label->setEditable (isEditable, isEditable, false);
  38124. setWantsKeyboardFocus (! isEditable);
  38125. resized();
  38126. }
  38127. }
  38128. bool ComboBox::isTextEditable() const throw()
  38129. {
  38130. return label->isEditable();
  38131. }
  38132. void ComboBox::setJustificationType (const Justification& justification)
  38133. {
  38134. label->setJustificationType (justification);
  38135. }
  38136. const Justification ComboBox::getJustificationType() const throw()
  38137. {
  38138. return label->getJustificationType();
  38139. }
  38140. void ComboBox::setTooltip (const String& newTooltip)
  38141. {
  38142. SettableTooltipClient::setTooltip (newTooltip);
  38143. label->setTooltip (newTooltip);
  38144. }
  38145. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38146. {
  38147. // you can't add empty strings to the list..
  38148. jassert (newItemText.isNotEmpty());
  38149. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38150. jassert (newItemId != 0);
  38151. // you shouldn't use duplicate item IDs!
  38152. jassert (getItemForId (newItemId) == 0);
  38153. if (newItemText.isNotEmpty() && newItemId != 0)
  38154. {
  38155. if (separatorPending)
  38156. {
  38157. separatorPending = false;
  38158. ItemInfo* const item = new ItemInfo();
  38159. item->itemId = 0;
  38160. item->isEnabled = false;
  38161. item->isHeading = false;
  38162. items.add (item);
  38163. }
  38164. ItemInfo* const item = new ItemInfo();
  38165. item->name = newItemText;
  38166. item->itemId = newItemId;
  38167. item->isEnabled = true;
  38168. item->isHeading = false;
  38169. items.add (item);
  38170. }
  38171. }
  38172. void ComboBox::addSeparator()
  38173. {
  38174. separatorPending = (items.size() > 0);
  38175. }
  38176. void ComboBox::addSectionHeading (const String& headingName)
  38177. {
  38178. // you can't add empty strings to the list..
  38179. jassert (headingName.isNotEmpty());
  38180. if (headingName.isNotEmpty())
  38181. {
  38182. if (separatorPending)
  38183. {
  38184. separatorPending = false;
  38185. ItemInfo* const item = new ItemInfo();
  38186. item->itemId = 0;
  38187. item->isEnabled = false;
  38188. item->isHeading = false;
  38189. items.add (item);
  38190. }
  38191. ItemInfo* const item = new ItemInfo();
  38192. item->name = headingName;
  38193. item->itemId = 0;
  38194. item->isEnabled = true;
  38195. item->isHeading = true;
  38196. items.add (item);
  38197. }
  38198. }
  38199. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38200. {
  38201. ItemInfo* const item = getItemForId (itemId);
  38202. if (item != 0)
  38203. item->isEnabled = shouldBeEnabled;
  38204. }
  38205. void ComboBox::changeItemText (const int itemId, const String& newText)
  38206. {
  38207. ItemInfo* const item = getItemForId (itemId);
  38208. jassert (item != 0);
  38209. if (item != 0)
  38210. item->name = newText;
  38211. }
  38212. void ComboBox::clear (const bool dontSendChangeMessage)
  38213. {
  38214. items.clear();
  38215. separatorPending = false;
  38216. if (! label->isEditable())
  38217. setSelectedItemIndex (-1, dontSendChangeMessage);
  38218. }
  38219. bool ComboBox::ItemInfo::isSeparator() const throw()
  38220. {
  38221. return name.isEmpty();
  38222. }
  38223. bool ComboBox::ItemInfo::isRealItem() const throw()
  38224. {
  38225. return ! (isHeading || name.isEmpty());
  38226. }
  38227. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38228. {
  38229. if (itemId != 0)
  38230. {
  38231. for (int i = items.size(); --i >= 0;)
  38232. if (items.getUnchecked(i)->itemId == itemId)
  38233. return items.getUnchecked(i);
  38234. }
  38235. return 0;
  38236. }
  38237. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38238. {
  38239. int n = 0;
  38240. for (int i = 0; i < items.size(); ++i)
  38241. {
  38242. ItemInfo* const item = items.getUnchecked(i);
  38243. if (item->isRealItem())
  38244. if (n++ == index)
  38245. return item;
  38246. }
  38247. return 0;
  38248. }
  38249. int ComboBox::getNumItems() const throw()
  38250. {
  38251. int n = 0;
  38252. for (int i = items.size(); --i >= 0;)
  38253. if (items.getUnchecked(i)->isRealItem())
  38254. ++n;
  38255. return n;
  38256. }
  38257. const String ComboBox::getItemText (const int index) const
  38258. {
  38259. const ItemInfo* const item = getItemForIndex (index);
  38260. if (item != 0)
  38261. return item->name;
  38262. return String::empty;
  38263. }
  38264. int ComboBox::getItemId (const int index) const throw()
  38265. {
  38266. const ItemInfo* const item = getItemForIndex (index);
  38267. return (item != 0) ? item->itemId : 0;
  38268. }
  38269. int ComboBox::indexOfItemId (const int itemId) const throw()
  38270. {
  38271. int n = 0;
  38272. for (int i = 0; i < items.size(); ++i)
  38273. {
  38274. const ItemInfo* const item = items.getUnchecked(i);
  38275. if (item->isRealItem())
  38276. {
  38277. if (item->itemId == itemId)
  38278. return n;
  38279. ++n;
  38280. }
  38281. }
  38282. return -1;
  38283. }
  38284. int ComboBox::getSelectedItemIndex() const
  38285. {
  38286. int index = indexOfItemId (currentId.getValue());
  38287. if (getText() != getItemText (index))
  38288. index = -1;
  38289. return index;
  38290. }
  38291. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38292. {
  38293. setSelectedId (getItemId (index), dontSendChangeMessage);
  38294. }
  38295. int ComboBox::getSelectedId() const throw()
  38296. {
  38297. const ItemInfo* const item = getItemForId (currentId.getValue());
  38298. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38299. }
  38300. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38301. {
  38302. const ItemInfo* const item = getItemForId (newItemId);
  38303. const String newItemText (item != 0 ? item->name : String::empty);
  38304. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38305. {
  38306. if (! dontSendChangeMessage)
  38307. triggerAsyncUpdate();
  38308. label->setText (newItemText, false);
  38309. lastCurrentId = newItemId;
  38310. currentId = newItemId;
  38311. repaint(); // for the benefit of the 'none selected' text
  38312. }
  38313. }
  38314. void ComboBox::valueChanged (Value&)
  38315. {
  38316. if (lastCurrentId != (int) currentId.getValue())
  38317. setSelectedId (currentId.getValue(), false);
  38318. }
  38319. const String ComboBox::getText() const
  38320. {
  38321. return label->getText();
  38322. }
  38323. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38324. {
  38325. for (int i = items.size(); --i >= 0;)
  38326. {
  38327. const ItemInfo* const item = items.getUnchecked(i);
  38328. if (item->isRealItem()
  38329. && item->name == newText)
  38330. {
  38331. setSelectedId (item->itemId, dontSendChangeMessage);
  38332. return;
  38333. }
  38334. }
  38335. lastCurrentId = 0;
  38336. currentId = 0;
  38337. if (label->getText() != newText)
  38338. {
  38339. label->setText (newText, false);
  38340. if (! dontSendChangeMessage)
  38341. triggerAsyncUpdate();
  38342. }
  38343. repaint();
  38344. }
  38345. void ComboBox::showEditor()
  38346. {
  38347. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38348. label->showEditor();
  38349. }
  38350. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38351. {
  38352. if (textWhenNothingSelected != newMessage)
  38353. {
  38354. textWhenNothingSelected = newMessage;
  38355. repaint();
  38356. }
  38357. }
  38358. const String ComboBox::getTextWhenNothingSelected() const
  38359. {
  38360. return textWhenNothingSelected;
  38361. }
  38362. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38363. {
  38364. noChoicesMessage = newMessage;
  38365. }
  38366. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38367. {
  38368. return noChoicesMessage;
  38369. }
  38370. void ComboBox::paint (Graphics& g)
  38371. {
  38372. getLookAndFeel().drawComboBox (g,
  38373. getWidth(),
  38374. getHeight(),
  38375. isButtonDown,
  38376. label->getRight(),
  38377. 0,
  38378. getWidth() - label->getRight(),
  38379. getHeight(),
  38380. *this);
  38381. if (textWhenNothingSelected.isNotEmpty()
  38382. && label->getText().isEmpty()
  38383. && ! label->isBeingEdited())
  38384. {
  38385. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38386. g.setFont (label->getFont());
  38387. g.drawFittedText (textWhenNothingSelected,
  38388. label->getX() + 2, label->getY() + 1,
  38389. label->getWidth() - 4, label->getHeight() - 2,
  38390. label->getJustificationType(),
  38391. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38392. }
  38393. }
  38394. void ComboBox::resized()
  38395. {
  38396. if (getHeight() > 0 && getWidth() > 0)
  38397. getLookAndFeel().positionComboBoxText (*this, *label);
  38398. }
  38399. void ComboBox::enablementChanged()
  38400. {
  38401. repaint();
  38402. }
  38403. void ComboBox::lookAndFeelChanged()
  38404. {
  38405. repaint();
  38406. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38407. if (label != 0)
  38408. {
  38409. newLabel->setEditable (label->isEditable());
  38410. newLabel->setJustificationType (label->getJustificationType());
  38411. newLabel->setTooltip (label->getTooltip());
  38412. newLabel->setText (label->getText(), false);
  38413. }
  38414. label = newLabel;
  38415. addAndMakeVisible (newLabel);
  38416. newLabel->addListener (this);
  38417. newLabel->addMouseListener (this, false);
  38418. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38419. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38420. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38421. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38422. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38423. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38424. resized();
  38425. }
  38426. void ComboBox::colourChanged()
  38427. {
  38428. lookAndFeelChanged();
  38429. }
  38430. bool ComboBox::keyPressed (const KeyPress& key)
  38431. {
  38432. bool used = false;
  38433. if (key.isKeyCode (KeyPress::upKey)
  38434. || key.isKeyCode (KeyPress::leftKey))
  38435. {
  38436. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38437. used = true;
  38438. }
  38439. else if (key.isKeyCode (KeyPress::downKey)
  38440. || key.isKeyCode (KeyPress::rightKey))
  38441. {
  38442. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38443. used = true;
  38444. }
  38445. else if (key.isKeyCode (KeyPress::returnKey))
  38446. {
  38447. showPopup();
  38448. used = true;
  38449. }
  38450. return used;
  38451. }
  38452. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38453. {
  38454. // only forward key events that aren't used by this component
  38455. return isKeyDown
  38456. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38457. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38458. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38459. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38460. }
  38461. void ComboBox::focusGained (FocusChangeType)
  38462. {
  38463. repaint();
  38464. }
  38465. void ComboBox::focusLost (FocusChangeType)
  38466. {
  38467. repaint();
  38468. }
  38469. void ComboBox::labelTextChanged (Label*)
  38470. {
  38471. triggerAsyncUpdate();
  38472. }
  38473. class ComboBox::Callback : public ModalComponentManager::Callback
  38474. {
  38475. public:
  38476. Callback (ComboBox* const box_)
  38477. : box (box_)
  38478. {
  38479. }
  38480. void modalStateFinished (int returnValue)
  38481. {
  38482. if (box != 0)
  38483. {
  38484. box->menuActive = false;
  38485. if (returnValue != 0)
  38486. box->setSelectedId (returnValue);
  38487. }
  38488. }
  38489. private:
  38490. Component::SafePointer<ComboBox> box;
  38491. Callback (const Callback&);
  38492. Callback& operator= (const Callback&);
  38493. };
  38494. void ComboBox::showPopup()
  38495. {
  38496. if (! menuActive)
  38497. {
  38498. const int selectedId = getSelectedId();
  38499. PopupMenu menu;
  38500. menu.setLookAndFeel (&getLookAndFeel());
  38501. for (int i = 0; i < items.size(); ++i)
  38502. {
  38503. const ItemInfo* const item = items.getUnchecked(i);
  38504. if (item->isSeparator())
  38505. menu.addSeparator();
  38506. else if (item->isHeading)
  38507. menu.addSectionHeader (item->name);
  38508. else
  38509. menu.addItem (item->itemId, item->name,
  38510. item->isEnabled, item->itemId == selectedId);
  38511. }
  38512. if (items.size() == 0)
  38513. menu.addItem (1, noChoicesMessage, false);
  38514. menuActive = true;
  38515. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38516. new Callback (this));
  38517. }
  38518. }
  38519. void ComboBox::mouseDown (const MouseEvent& e)
  38520. {
  38521. beginDragAutoRepeat (300);
  38522. isButtonDown = isEnabled();
  38523. if (isButtonDown
  38524. && (e.eventComponent == this || ! label->isEditable()))
  38525. {
  38526. showPopup();
  38527. }
  38528. }
  38529. void ComboBox::mouseDrag (const MouseEvent& e)
  38530. {
  38531. beginDragAutoRepeat (50);
  38532. if (isButtonDown && ! e.mouseWasClicked())
  38533. showPopup();
  38534. }
  38535. void ComboBox::mouseUp (const MouseEvent& e2)
  38536. {
  38537. if (isButtonDown)
  38538. {
  38539. isButtonDown = false;
  38540. repaint();
  38541. const MouseEvent e (e2.getEventRelativeTo (this));
  38542. if (reallyContains (e.x, e.y, true)
  38543. && (e2.eventComponent == this || ! label->isEditable()))
  38544. {
  38545. showPopup();
  38546. }
  38547. }
  38548. }
  38549. void ComboBox::addListener (Listener* const listener)
  38550. {
  38551. listeners.add (listener);
  38552. }
  38553. void ComboBox::removeListener (Listener* const listener)
  38554. {
  38555. listeners.remove (listener);
  38556. }
  38557. void ComboBox::handleAsyncUpdate()
  38558. {
  38559. Component::BailOutChecker checker (this);
  38560. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38561. }
  38562. END_JUCE_NAMESPACE
  38563. /*** End of inlined file: juce_ComboBox.cpp ***/
  38564. /*** Start of inlined file: juce_Label.cpp ***/
  38565. BEGIN_JUCE_NAMESPACE
  38566. Label::Label (const String& componentName,
  38567. const String& labelText)
  38568. : Component (componentName),
  38569. textValue (labelText),
  38570. lastTextValue (labelText),
  38571. font (15.0f),
  38572. justification (Justification::centredLeft),
  38573. ownerComponent (0),
  38574. horizontalBorderSize (5),
  38575. verticalBorderSize (1),
  38576. minimumHorizontalScale (0.7f),
  38577. editSingleClick (false),
  38578. editDoubleClick (false),
  38579. lossOfFocusDiscardsChanges (false)
  38580. {
  38581. setColour (TextEditor::textColourId, Colours::black);
  38582. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38583. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38584. textValue.addListener (this);
  38585. }
  38586. Label::~Label()
  38587. {
  38588. textValue.removeListener (this);
  38589. if (ownerComponent != 0)
  38590. ownerComponent->removeComponentListener (this);
  38591. editor = 0;
  38592. }
  38593. void Label::setText (const String& newText,
  38594. const bool broadcastChangeMessage)
  38595. {
  38596. hideEditor (true);
  38597. if (lastTextValue != newText)
  38598. {
  38599. lastTextValue = newText;
  38600. textValue = newText;
  38601. repaint();
  38602. textWasChanged();
  38603. if (ownerComponent != 0)
  38604. componentMovedOrResized (*ownerComponent, true, true);
  38605. if (broadcastChangeMessage)
  38606. callChangeListeners();
  38607. }
  38608. }
  38609. const String Label::getText (const bool returnActiveEditorContents) const
  38610. {
  38611. return (returnActiveEditorContents && isBeingEdited())
  38612. ? editor->getText()
  38613. : textValue.toString();
  38614. }
  38615. void Label::valueChanged (Value&)
  38616. {
  38617. if (lastTextValue != textValue.toString())
  38618. setText (textValue.toString(), true);
  38619. }
  38620. void Label::setFont (const Font& newFont)
  38621. {
  38622. if (font != newFont)
  38623. {
  38624. font = newFont;
  38625. repaint();
  38626. }
  38627. }
  38628. const Font& Label::getFont() const throw()
  38629. {
  38630. return font;
  38631. }
  38632. void Label::setEditable (const bool editOnSingleClick,
  38633. const bool editOnDoubleClick,
  38634. const bool lossOfFocusDiscardsChanges_)
  38635. {
  38636. editSingleClick = editOnSingleClick;
  38637. editDoubleClick = editOnDoubleClick;
  38638. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38639. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38640. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38641. }
  38642. void Label::setJustificationType (const Justification& newJustification)
  38643. {
  38644. if (justification != newJustification)
  38645. {
  38646. justification = newJustification;
  38647. repaint();
  38648. }
  38649. }
  38650. void Label::setBorderSize (int h, int v)
  38651. {
  38652. if (horizontalBorderSize != h || verticalBorderSize != v)
  38653. {
  38654. horizontalBorderSize = h;
  38655. verticalBorderSize = v;
  38656. repaint();
  38657. }
  38658. }
  38659. Component* Label::getAttachedComponent() const
  38660. {
  38661. return static_cast<Component*> (ownerComponent);
  38662. }
  38663. void Label::attachToComponent (Component* owner,
  38664. const bool onLeft)
  38665. {
  38666. if (ownerComponent != 0)
  38667. ownerComponent->removeComponentListener (this);
  38668. ownerComponent = owner;
  38669. leftOfOwnerComp = onLeft;
  38670. if (ownerComponent != 0)
  38671. {
  38672. setVisible (owner->isVisible());
  38673. ownerComponent->addComponentListener (this);
  38674. componentParentHierarchyChanged (*ownerComponent);
  38675. componentMovedOrResized (*ownerComponent, true, true);
  38676. }
  38677. }
  38678. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38679. {
  38680. if (leftOfOwnerComp)
  38681. {
  38682. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38683. component.getHeight());
  38684. setTopRightPosition (component.getX(), component.getY());
  38685. }
  38686. else
  38687. {
  38688. setSize (component.getWidth(),
  38689. 8 + roundToInt (getFont().getHeight()));
  38690. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38691. }
  38692. }
  38693. void Label::componentParentHierarchyChanged (Component& component)
  38694. {
  38695. if (component.getParentComponent() != 0)
  38696. component.getParentComponent()->addChildComponent (this);
  38697. }
  38698. void Label::componentVisibilityChanged (Component& component)
  38699. {
  38700. setVisible (component.isVisible());
  38701. }
  38702. void Label::textWasEdited()
  38703. {
  38704. }
  38705. void Label::textWasChanged()
  38706. {
  38707. }
  38708. void Label::showEditor()
  38709. {
  38710. if (editor == 0)
  38711. {
  38712. addAndMakeVisible (editor = createEditorComponent());
  38713. editor->setText (getText(), false);
  38714. editor->addListener (this);
  38715. editor->grabKeyboardFocus();
  38716. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38717. editor->addListener (this);
  38718. resized();
  38719. repaint();
  38720. editorShown (editor);
  38721. enterModalState (false);
  38722. editor->grabKeyboardFocus();
  38723. }
  38724. }
  38725. void Label::editorShown (TextEditor* /*editorComponent*/)
  38726. {
  38727. }
  38728. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38729. {
  38730. }
  38731. bool Label::updateFromTextEditorContents()
  38732. {
  38733. jassert (editor != 0);
  38734. const String newText (editor->getText());
  38735. if (textValue.toString() != newText)
  38736. {
  38737. lastTextValue = newText;
  38738. textValue = newText;
  38739. repaint();
  38740. textWasChanged();
  38741. if (ownerComponent != 0)
  38742. componentMovedOrResized (*ownerComponent, true, true);
  38743. return true;
  38744. }
  38745. return false;
  38746. }
  38747. void Label::hideEditor (const bool discardCurrentEditorContents)
  38748. {
  38749. if (editor != 0)
  38750. {
  38751. Component::SafePointer<Component> deletionChecker (this);
  38752. editorAboutToBeHidden (editor);
  38753. const bool changed = (! discardCurrentEditorContents)
  38754. && updateFromTextEditorContents();
  38755. editor = 0;
  38756. repaint();
  38757. if (changed)
  38758. textWasEdited();
  38759. if (deletionChecker != 0)
  38760. exitModalState (0);
  38761. if (changed && deletionChecker != 0)
  38762. callChangeListeners();
  38763. }
  38764. }
  38765. void Label::inputAttemptWhenModal()
  38766. {
  38767. if (editor != 0)
  38768. {
  38769. if (lossOfFocusDiscardsChanges)
  38770. textEditorEscapeKeyPressed (*editor);
  38771. else
  38772. textEditorReturnKeyPressed (*editor);
  38773. }
  38774. }
  38775. bool Label::isBeingEdited() const throw()
  38776. {
  38777. return editor != 0;
  38778. }
  38779. TextEditor* Label::createEditorComponent()
  38780. {
  38781. TextEditor* const ed = new TextEditor (getName());
  38782. ed->setFont (font);
  38783. // copy these colours from our own settings..
  38784. const int cols[] = { TextEditor::backgroundColourId,
  38785. TextEditor::textColourId,
  38786. TextEditor::highlightColourId,
  38787. TextEditor::highlightedTextColourId,
  38788. TextEditor::caretColourId,
  38789. TextEditor::outlineColourId,
  38790. TextEditor::focusedOutlineColourId,
  38791. TextEditor::shadowColourId };
  38792. for (int i = 0; i < numElementsInArray (cols); ++i)
  38793. ed->setColour (cols[i], findColour (cols[i]));
  38794. return ed;
  38795. }
  38796. void Label::paint (Graphics& g)
  38797. {
  38798. getLookAndFeel().drawLabel (g, *this);
  38799. }
  38800. void Label::mouseUp (const MouseEvent& e)
  38801. {
  38802. if (editSingleClick
  38803. && e.mouseWasClicked()
  38804. && contains (e.x, e.y)
  38805. && ! e.mods.isPopupMenu())
  38806. {
  38807. showEditor();
  38808. }
  38809. }
  38810. void Label::mouseDoubleClick (const MouseEvent& e)
  38811. {
  38812. if (editDoubleClick && ! e.mods.isPopupMenu())
  38813. showEditor();
  38814. }
  38815. void Label::resized()
  38816. {
  38817. if (editor != 0)
  38818. editor->setBoundsInset (BorderSize (0));
  38819. }
  38820. void Label::focusGained (FocusChangeType cause)
  38821. {
  38822. if (editSingleClick && cause == focusChangedByTabKey)
  38823. showEditor();
  38824. }
  38825. void Label::enablementChanged()
  38826. {
  38827. repaint();
  38828. }
  38829. void Label::colourChanged()
  38830. {
  38831. repaint();
  38832. }
  38833. void Label::setMinimumHorizontalScale (const float newScale)
  38834. {
  38835. if (minimumHorizontalScale != newScale)
  38836. {
  38837. minimumHorizontalScale = newScale;
  38838. repaint();
  38839. }
  38840. }
  38841. // We'll use a custom focus traverser here to make sure focus goes from the
  38842. // text editor to another component rather than back to the label itself.
  38843. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38844. {
  38845. public:
  38846. LabelKeyboardFocusTraverser() {}
  38847. Component* getNextComponent (Component* current)
  38848. {
  38849. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38850. ? current->getParentComponent() : current);
  38851. }
  38852. Component* getPreviousComponent (Component* current)
  38853. {
  38854. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38855. ? current->getParentComponent() : current);
  38856. }
  38857. };
  38858. KeyboardFocusTraverser* Label::createFocusTraverser()
  38859. {
  38860. return new LabelKeyboardFocusTraverser();
  38861. }
  38862. void Label::addListener (Listener* const listener)
  38863. {
  38864. listeners.add (listener);
  38865. }
  38866. void Label::removeListener (Listener* const listener)
  38867. {
  38868. listeners.remove (listener);
  38869. }
  38870. void Label::callChangeListeners()
  38871. {
  38872. Component::BailOutChecker checker (this);
  38873. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38874. }
  38875. void Label::textEditorTextChanged (TextEditor& ed)
  38876. {
  38877. if (editor != 0)
  38878. {
  38879. jassert (&ed == editor);
  38880. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38881. {
  38882. if (lossOfFocusDiscardsChanges)
  38883. textEditorEscapeKeyPressed (ed);
  38884. else
  38885. textEditorReturnKeyPressed (ed);
  38886. }
  38887. }
  38888. }
  38889. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38890. {
  38891. if (editor != 0)
  38892. {
  38893. jassert (&ed == editor);
  38894. (void) ed;
  38895. const bool changed = updateFromTextEditorContents();
  38896. hideEditor (true);
  38897. if (changed)
  38898. {
  38899. Component::SafePointer<Component> deletionChecker (this);
  38900. textWasEdited();
  38901. if (deletionChecker != 0)
  38902. callChangeListeners();
  38903. }
  38904. }
  38905. }
  38906. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38907. {
  38908. if (editor != 0)
  38909. {
  38910. jassert (&ed == editor);
  38911. (void) ed;
  38912. editor->setText (textValue.toString(), false);
  38913. hideEditor (true);
  38914. }
  38915. }
  38916. void Label::textEditorFocusLost (TextEditor& ed)
  38917. {
  38918. textEditorTextChanged (ed);
  38919. }
  38920. END_JUCE_NAMESPACE
  38921. /*** End of inlined file: juce_Label.cpp ***/
  38922. /*** Start of inlined file: juce_ListBox.cpp ***/
  38923. BEGIN_JUCE_NAMESPACE
  38924. class ListBoxRowComponent : public Component,
  38925. public TooltipClient
  38926. {
  38927. public:
  38928. ListBoxRowComponent (ListBox& owner_)
  38929. : owner (owner_),
  38930. row (-1),
  38931. selected (false),
  38932. isDragging (false)
  38933. {
  38934. }
  38935. ~ListBoxRowComponent()
  38936. {
  38937. deleteAllChildren();
  38938. }
  38939. void paint (Graphics& g)
  38940. {
  38941. if (owner.getModel() != 0)
  38942. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38943. }
  38944. void update (const int row_, const bool selected_)
  38945. {
  38946. if (row != row_ || selected != selected_)
  38947. {
  38948. repaint();
  38949. row = row_;
  38950. selected = selected_;
  38951. }
  38952. if (owner.getModel() != 0)
  38953. {
  38954. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38955. if (customComp != 0)
  38956. {
  38957. addAndMakeVisible (customComp);
  38958. customComp->setBounds (getLocalBounds());
  38959. for (int i = getNumChildComponents(); --i >= 0;)
  38960. if (getChildComponent (i) != customComp)
  38961. delete getChildComponent (i);
  38962. }
  38963. else
  38964. {
  38965. deleteAllChildren();
  38966. }
  38967. }
  38968. }
  38969. void mouseDown (const MouseEvent& e)
  38970. {
  38971. isDragging = false;
  38972. selectRowOnMouseUp = false;
  38973. if (isEnabled())
  38974. {
  38975. if (! selected)
  38976. {
  38977. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38978. if (owner.getModel() != 0)
  38979. owner.getModel()->listBoxItemClicked (row, e);
  38980. }
  38981. else
  38982. {
  38983. selectRowOnMouseUp = true;
  38984. }
  38985. }
  38986. }
  38987. void mouseUp (const MouseEvent& e)
  38988. {
  38989. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38990. {
  38991. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38992. if (owner.getModel() != 0)
  38993. owner.getModel()->listBoxItemClicked (row, e);
  38994. }
  38995. }
  38996. void mouseDoubleClick (const MouseEvent& e)
  38997. {
  38998. if (owner.getModel() != 0 && isEnabled())
  38999. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39000. }
  39001. void mouseDrag (const MouseEvent& e)
  39002. {
  39003. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39004. {
  39005. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39006. if (selectedRows.size() > 0)
  39007. {
  39008. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39009. if (dragDescription.isNotEmpty())
  39010. {
  39011. isDragging = true;
  39012. owner.startDragAndDrop (e, dragDescription);
  39013. }
  39014. }
  39015. }
  39016. }
  39017. void resized()
  39018. {
  39019. if (getNumChildComponents() > 0)
  39020. getChildComponent(0)->setBounds (getLocalBounds());
  39021. }
  39022. const String getTooltip()
  39023. {
  39024. if (owner.getModel() != 0)
  39025. return owner.getModel()->getTooltipForRow (row);
  39026. return String::empty;
  39027. }
  39028. juce_UseDebuggingNewOperator
  39029. bool neededFlag;
  39030. private:
  39031. ListBox& owner;
  39032. int row;
  39033. bool selected, isDragging, selectRowOnMouseUp;
  39034. ListBoxRowComponent (const ListBoxRowComponent&);
  39035. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39036. };
  39037. class ListViewport : public Viewport
  39038. {
  39039. public:
  39040. int firstIndex, firstWholeIndex, lastWholeIndex;
  39041. bool hasUpdated;
  39042. ListViewport (ListBox& owner_)
  39043. : owner (owner_)
  39044. {
  39045. setWantsKeyboardFocus (false);
  39046. setViewedComponent (new Component());
  39047. getViewedComponent()->addMouseListener (this, false);
  39048. getViewedComponent()->setWantsKeyboardFocus (false);
  39049. }
  39050. ~ListViewport()
  39051. {
  39052. getViewedComponent()->removeMouseListener (this);
  39053. getViewedComponent()->deleteAllChildren();
  39054. }
  39055. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39056. {
  39057. return static_cast <ListBoxRowComponent*>
  39058. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39059. }
  39060. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39061. {
  39062. const int index = getIndexOfChildComponent (rowComponent);
  39063. const int num = getViewedComponent()->getNumChildComponents();
  39064. for (int i = num; --i >= 0;)
  39065. if (((firstIndex + i) % jmax (1, num)) == index)
  39066. return firstIndex + i;
  39067. return -1;
  39068. }
  39069. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39070. {
  39071. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39072. ? getComponentForRow (row) : 0;
  39073. }
  39074. void visibleAreaChanged (int, int, int, int)
  39075. {
  39076. updateVisibleArea (true);
  39077. if (owner.getModel() != 0)
  39078. owner.getModel()->listWasScrolled();
  39079. }
  39080. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39081. {
  39082. hasUpdated = false;
  39083. const int newX = getViewedComponent()->getX();
  39084. int newY = getViewedComponent()->getY();
  39085. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39086. const int newH = owner.totalItems * owner.getRowHeight();
  39087. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39088. newY = getMaximumVisibleHeight() - newH;
  39089. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39090. if (makeSureItUpdatesContent && ! hasUpdated)
  39091. updateContents();
  39092. }
  39093. void updateContents()
  39094. {
  39095. hasUpdated = true;
  39096. const int rowHeight = owner.getRowHeight();
  39097. if (rowHeight > 0)
  39098. {
  39099. const int y = getViewPositionY();
  39100. const int w = getViewedComponent()->getWidth();
  39101. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39102. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39103. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39104. jassert (numNeeded >= 0);
  39105. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39106. {
  39107. Component* const rowToRemove
  39108. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39109. delete rowToRemove;
  39110. }
  39111. firstIndex = y / rowHeight;
  39112. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39113. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39114. for (int i = 0; i < numNeeded; ++i)
  39115. {
  39116. const int row = i + firstIndex;
  39117. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39118. if (rowComp != 0)
  39119. {
  39120. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39121. rowComp->update (row, owner.isRowSelected (row));
  39122. }
  39123. }
  39124. }
  39125. if (owner.headerComponent != 0)
  39126. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39127. owner.outlineThickness,
  39128. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39129. getViewedComponent()->getWidth()),
  39130. owner.headerComponent->getHeight());
  39131. }
  39132. void paint (Graphics& g)
  39133. {
  39134. if (isOpaque())
  39135. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39136. }
  39137. bool keyPressed (const KeyPress& key)
  39138. {
  39139. if (key.isKeyCode (KeyPress::upKey)
  39140. || key.isKeyCode (KeyPress::downKey)
  39141. || key.isKeyCode (KeyPress::pageUpKey)
  39142. || key.isKeyCode (KeyPress::pageDownKey)
  39143. || key.isKeyCode (KeyPress::homeKey)
  39144. || key.isKeyCode (KeyPress::endKey))
  39145. {
  39146. // we want to avoid these keypresses going to the viewport, and instead allow
  39147. // them to pass up to our listbox..
  39148. return false;
  39149. }
  39150. return Viewport::keyPressed (key);
  39151. }
  39152. juce_UseDebuggingNewOperator
  39153. private:
  39154. ListBox& owner;
  39155. ListViewport (const ListViewport&);
  39156. ListViewport& operator= (const ListViewport&);
  39157. };
  39158. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39159. : Component (name),
  39160. model (model_),
  39161. totalItems (0),
  39162. rowHeight (22),
  39163. minimumRowWidth (0),
  39164. outlineThickness (0),
  39165. lastRowSelected (-1),
  39166. mouseMoveSelects (false),
  39167. multipleSelection (false),
  39168. hasDoneInitialUpdate (false)
  39169. {
  39170. addAndMakeVisible (viewport = new ListViewport (*this));
  39171. setWantsKeyboardFocus (true);
  39172. colourChanged();
  39173. }
  39174. ListBox::~ListBox()
  39175. {
  39176. headerComponent = 0;
  39177. viewport = 0;
  39178. }
  39179. void ListBox::setModel (ListBoxModel* const newModel)
  39180. {
  39181. if (model != newModel)
  39182. {
  39183. model = newModel;
  39184. updateContent();
  39185. }
  39186. }
  39187. void ListBox::setMultipleSelectionEnabled (bool b)
  39188. {
  39189. multipleSelection = b;
  39190. }
  39191. void ListBox::setMouseMoveSelectsRows (bool b)
  39192. {
  39193. mouseMoveSelects = b;
  39194. if (b)
  39195. addMouseListener (this, true);
  39196. }
  39197. void ListBox::paint (Graphics& g)
  39198. {
  39199. if (! hasDoneInitialUpdate)
  39200. updateContent();
  39201. g.fillAll (findColour (backgroundColourId));
  39202. }
  39203. void ListBox::paintOverChildren (Graphics& g)
  39204. {
  39205. if (outlineThickness > 0)
  39206. {
  39207. g.setColour (findColour (outlineColourId));
  39208. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39209. }
  39210. }
  39211. void ListBox::resized()
  39212. {
  39213. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39214. outlineThickness,
  39215. outlineThickness,
  39216. outlineThickness));
  39217. viewport->setSingleStepSizes (20, getRowHeight());
  39218. viewport->updateVisibleArea (false);
  39219. }
  39220. void ListBox::visibilityChanged()
  39221. {
  39222. viewport->updateVisibleArea (true);
  39223. }
  39224. Viewport* ListBox::getViewport() const throw()
  39225. {
  39226. return viewport;
  39227. }
  39228. void ListBox::updateContent()
  39229. {
  39230. hasDoneInitialUpdate = true;
  39231. totalItems = (model != 0) ? model->getNumRows() : 0;
  39232. bool selectionChanged = false;
  39233. if (selected [selected.size() - 1] >= totalItems)
  39234. {
  39235. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39236. lastRowSelected = getSelectedRow (0);
  39237. selectionChanged = true;
  39238. }
  39239. viewport->updateVisibleArea (isVisible());
  39240. viewport->resized();
  39241. if (selectionChanged && model != 0)
  39242. model->selectedRowsChanged (lastRowSelected);
  39243. }
  39244. void ListBox::selectRow (const int row,
  39245. bool dontScroll,
  39246. bool deselectOthersFirst)
  39247. {
  39248. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39249. }
  39250. void ListBox::selectRowInternal (const int row,
  39251. bool dontScroll,
  39252. bool deselectOthersFirst,
  39253. bool isMouseClick)
  39254. {
  39255. if (! multipleSelection)
  39256. deselectOthersFirst = true;
  39257. if ((! isRowSelected (row))
  39258. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39259. {
  39260. if (((unsigned int) row) < (unsigned int) totalItems)
  39261. {
  39262. if (deselectOthersFirst)
  39263. selected.clear();
  39264. selected.addRange (Range<int> (row, row + 1));
  39265. if (getHeight() == 0 || getWidth() == 0)
  39266. dontScroll = true;
  39267. viewport->hasUpdated = false;
  39268. if (row < viewport->firstWholeIndex && ! dontScroll)
  39269. {
  39270. viewport->setViewPosition (viewport->getViewPositionX(),
  39271. row * getRowHeight());
  39272. }
  39273. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39274. {
  39275. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39276. if (row >= lastRowSelected + rowsOnScreen
  39277. && rowsOnScreen < totalItems - 1
  39278. && ! isMouseClick)
  39279. {
  39280. viewport->setViewPosition (viewport->getViewPositionX(),
  39281. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39282. * getRowHeight());
  39283. }
  39284. else
  39285. {
  39286. viewport->setViewPosition (viewport->getViewPositionX(),
  39287. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39288. }
  39289. }
  39290. if (! viewport->hasUpdated)
  39291. viewport->updateContents();
  39292. lastRowSelected = row;
  39293. model->selectedRowsChanged (row);
  39294. }
  39295. else
  39296. {
  39297. if (deselectOthersFirst)
  39298. deselectAllRows();
  39299. }
  39300. }
  39301. }
  39302. void ListBox::deselectRow (const int row)
  39303. {
  39304. if (selected.contains (row))
  39305. {
  39306. selected.removeRange (Range <int> (row, row + 1));
  39307. if (row == lastRowSelected)
  39308. lastRowSelected = getSelectedRow (0);
  39309. viewport->updateContents();
  39310. model->selectedRowsChanged (lastRowSelected);
  39311. }
  39312. }
  39313. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39314. const bool sendNotificationEventToModel)
  39315. {
  39316. selected = setOfRowsToBeSelected;
  39317. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39318. if (! isRowSelected (lastRowSelected))
  39319. lastRowSelected = getSelectedRow (0);
  39320. viewport->updateContents();
  39321. if ((model != 0) && sendNotificationEventToModel)
  39322. model->selectedRowsChanged (lastRowSelected);
  39323. }
  39324. const SparseSet<int> ListBox::getSelectedRows() const
  39325. {
  39326. return selected;
  39327. }
  39328. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39329. {
  39330. if (multipleSelection && (firstRow != lastRow))
  39331. {
  39332. const int numRows = totalItems - 1;
  39333. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39334. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39335. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39336. jmax (firstRow, lastRow) + 1));
  39337. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39338. }
  39339. selectRowInternal (lastRow, false, false, true);
  39340. }
  39341. void ListBox::flipRowSelection (const int row)
  39342. {
  39343. if (isRowSelected (row))
  39344. deselectRow (row);
  39345. else
  39346. selectRowInternal (row, false, false, true);
  39347. }
  39348. void ListBox::deselectAllRows()
  39349. {
  39350. if (! selected.isEmpty())
  39351. {
  39352. selected.clear();
  39353. lastRowSelected = -1;
  39354. viewport->updateContents();
  39355. if (model != 0)
  39356. model->selectedRowsChanged (lastRowSelected);
  39357. }
  39358. }
  39359. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39360. const ModifierKeys& mods)
  39361. {
  39362. if (multipleSelection && mods.isCommandDown())
  39363. {
  39364. flipRowSelection (row);
  39365. }
  39366. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39367. {
  39368. selectRangeOfRows (lastRowSelected, row);
  39369. }
  39370. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39371. {
  39372. selectRowInternal (row, false, true, true);
  39373. }
  39374. }
  39375. int ListBox::getNumSelectedRows() const
  39376. {
  39377. return selected.size();
  39378. }
  39379. int ListBox::getSelectedRow (const int index) const
  39380. {
  39381. return (((unsigned int) index) < (unsigned int) selected.size())
  39382. ? selected [index] : -1;
  39383. }
  39384. bool ListBox::isRowSelected (const int row) const
  39385. {
  39386. return selected.contains (row);
  39387. }
  39388. int ListBox::getLastRowSelected() const
  39389. {
  39390. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39391. }
  39392. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39393. {
  39394. if (((unsigned int) x) < (unsigned int) getWidth())
  39395. {
  39396. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39397. if (((unsigned int) row) < (unsigned int) totalItems)
  39398. return row;
  39399. }
  39400. return -1;
  39401. }
  39402. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39403. {
  39404. if (((unsigned int) x) < (unsigned int) getWidth())
  39405. {
  39406. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39407. return jlimit (0, totalItems, row);
  39408. }
  39409. return -1;
  39410. }
  39411. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39412. {
  39413. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39414. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39415. }
  39416. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39417. {
  39418. return viewport->getRowNumberOfComponent (rowComponent);
  39419. }
  39420. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39421. const bool relativeToComponentTopLeft) const throw()
  39422. {
  39423. int y = viewport->getY() + rowHeight * rowNumber;
  39424. if (relativeToComponentTopLeft)
  39425. y -= viewport->getViewPositionY();
  39426. return Rectangle<int> (viewport->getX(), y,
  39427. viewport->getViewedComponent()->getWidth(), rowHeight);
  39428. }
  39429. void ListBox::setVerticalPosition (const double proportion)
  39430. {
  39431. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39432. viewport->setViewPosition (viewport->getViewPositionX(),
  39433. jmax (0, roundToInt (proportion * offscreen)));
  39434. }
  39435. double ListBox::getVerticalPosition() const
  39436. {
  39437. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39438. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39439. : 0;
  39440. }
  39441. int ListBox::getVisibleRowWidth() const throw()
  39442. {
  39443. return viewport->getViewWidth();
  39444. }
  39445. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39446. {
  39447. if (row < viewport->firstWholeIndex)
  39448. {
  39449. viewport->setViewPosition (viewport->getViewPositionX(),
  39450. row * getRowHeight());
  39451. }
  39452. else if (row >= viewport->lastWholeIndex)
  39453. {
  39454. viewport->setViewPosition (viewport->getViewPositionX(),
  39455. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39456. }
  39457. }
  39458. bool ListBox::keyPressed (const KeyPress& key)
  39459. {
  39460. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39461. const bool multiple = multipleSelection
  39462. && (lastRowSelected >= 0)
  39463. && (key.getModifiers().isShiftDown()
  39464. || key.getModifiers().isCtrlDown()
  39465. || key.getModifiers().isCommandDown());
  39466. if (key.isKeyCode (KeyPress::upKey))
  39467. {
  39468. if (multiple)
  39469. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39470. else
  39471. selectRow (jmax (0, lastRowSelected - 1));
  39472. }
  39473. else if (key.isKeyCode (KeyPress::returnKey)
  39474. && isRowSelected (lastRowSelected))
  39475. {
  39476. if (model != 0)
  39477. model->returnKeyPressed (lastRowSelected);
  39478. }
  39479. else if (key.isKeyCode (KeyPress::pageUpKey))
  39480. {
  39481. if (multiple)
  39482. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39483. else
  39484. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39485. }
  39486. else if (key.isKeyCode (KeyPress::pageDownKey))
  39487. {
  39488. if (multiple)
  39489. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39490. else
  39491. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39492. }
  39493. else if (key.isKeyCode (KeyPress::homeKey))
  39494. {
  39495. if (multiple && key.getModifiers().isShiftDown())
  39496. selectRangeOfRows (lastRowSelected, 0);
  39497. else
  39498. selectRow (0);
  39499. }
  39500. else if (key.isKeyCode (KeyPress::endKey))
  39501. {
  39502. if (multiple && key.getModifiers().isShiftDown())
  39503. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39504. else
  39505. selectRow (totalItems - 1);
  39506. }
  39507. else if (key.isKeyCode (KeyPress::downKey))
  39508. {
  39509. if (multiple)
  39510. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39511. else
  39512. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39513. }
  39514. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39515. && isRowSelected (lastRowSelected))
  39516. {
  39517. if (model != 0)
  39518. model->deleteKeyPressed (lastRowSelected);
  39519. }
  39520. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39521. {
  39522. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39523. }
  39524. else
  39525. {
  39526. return false;
  39527. }
  39528. return true;
  39529. }
  39530. bool ListBox::keyStateChanged (const bool isKeyDown)
  39531. {
  39532. return isKeyDown
  39533. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39534. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39535. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39536. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39537. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39538. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39539. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39540. }
  39541. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39542. {
  39543. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39544. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39545. }
  39546. void ListBox::mouseMove (const MouseEvent& e)
  39547. {
  39548. if (mouseMoveSelects)
  39549. {
  39550. const MouseEvent e2 (e.getEventRelativeTo (this));
  39551. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39552. }
  39553. }
  39554. void ListBox::mouseExit (const MouseEvent& e)
  39555. {
  39556. mouseMove (e);
  39557. }
  39558. void ListBox::mouseUp (const MouseEvent& e)
  39559. {
  39560. if (e.mouseWasClicked() && model != 0)
  39561. model->backgroundClicked();
  39562. }
  39563. void ListBox::setRowHeight (const int newHeight)
  39564. {
  39565. rowHeight = jmax (1, newHeight);
  39566. viewport->setSingleStepSizes (20, rowHeight);
  39567. updateContent();
  39568. }
  39569. int ListBox::getNumRowsOnScreen() const throw()
  39570. {
  39571. return viewport->getMaximumVisibleHeight() / rowHeight;
  39572. }
  39573. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39574. {
  39575. minimumRowWidth = newMinimumWidth;
  39576. updateContent();
  39577. }
  39578. int ListBox::getVisibleContentWidth() const throw()
  39579. {
  39580. return viewport->getMaximumVisibleWidth();
  39581. }
  39582. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39583. {
  39584. return viewport->getVerticalScrollBar();
  39585. }
  39586. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39587. {
  39588. return viewport->getHorizontalScrollBar();
  39589. }
  39590. void ListBox::colourChanged()
  39591. {
  39592. setOpaque (findColour (backgroundColourId).isOpaque());
  39593. viewport->setOpaque (isOpaque());
  39594. repaint();
  39595. }
  39596. void ListBox::setOutlineThickness (const int outlineThickness_)
  39597. {
  39598. outlineThickness = outlineThickness_;
  39599. resized();
  39600. }
  39601. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39602. {
  39603. if (newHeaderComponent != headerComponent)
  39604. {
  39605. headerComponent = newHeaderComponent;
  39606. addAndMakeVisible (newHeaderComponent);
  39607. ListBox::resized();
  39608. }
  39609. }
  39610. void ListBox::repaintRow (const int rowNumber) throw()
  39611. {
  39612. repaint (getRowPosition (rowNumber, true));
  39613. }
  39614. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39615. {
  39616. Rectangle<int> imageArea;
  39617. const int firstRow = getRowContainingPosition (0, 0);
  39618. int i;
  39619. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39620. {
  39621. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39622. if (rowComp != 0 && isRowSelected (firstRow + i))
  39623. {
  39624. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39625. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39626. imageArea = imageArea.getUnion (rowRect);
  39627. }
  39628. }
  39629. imageArea = imageArea.getIntersection (getLocalBounds());
  39630. imageX = imageArea.getX();
  39631. imageY = imageArea.getY();
  39632. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39633. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39634. {
  39635. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39636. if (rowComp != 0 && isRowSelected (firstRow + i))
  39637. {
  39638. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39639. Graphics g (snapshot);
  39640. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39641. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39642. rowComp->paintEntireComponent (g);
  39643. }
  39644. }
  39645. return snapshot;
  39646. }
  39647. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39648. {
  39649. DragAndDropContainer* const dragContainer
  39650. = DragAndDropContainer::findParentDragContainerFor (this);
  39651. if (dragContainer != 0)
  39652. {
  39653. int x, y;
  39654. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39655. dragImage.multiplyAllAlphas (0.6f);
  39656. MouseEvent e2 (e.getEventRelativeTo (this));
  39657. const Point<int> p (x - e2.x, y - e2.y);
  39658. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39659. }
  39660. else
  39661. {
  39662. // to be able to do a drag-and-drop operation, the listbox needs to
  39663. // be inside a component which is also a DragAndDropContainer.
  39664. jassertfalse;
  39665. }
  39666. }
  39667. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39668. {
  39669. (void) existingComponentToUpdate;
  39670. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39671. return 0;
  39672. }
  39673. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39674. {
  39675. }
  39676. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39677. {
  39678. }
  39679. void ListBoxModel::backgroundClicked()
  39680. {
  39681. }
  39682. void ListBoxModel::selectedRowsChanged (int)
  39683. {
  39684. }
  39685. void ListBoxModel::deleteKeyPressed (int)
  39686. {
  39687. }
  39688. void ListBoxModel::returnKeyPressed (int)
  39689. {
  39690. }
  39691. void ListBoxModel::listWasScrolled()
  39692. {
  39693. }
  39694. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39695. {
  39696. return String::empty;
  39697. }
  39698. const String ListBoxModel::getTooltipForRow (int)
  39699. {
  39700. return String::empty;
  39701. }
  39702. END_JUCE_NAMESPACE
  39703. /*** End of inlined file: juce_ListBox.cpp ***/
  39704. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39705. BEGIN_JUCE_NAMESPACE
  39706. ProgressBar::ProgressBar (double& progress_)
  39707. : progress (progress_),
  39708. displayPercentage (true),
  39709. lastCallbackTime (0)
  39710. {
  39711. currentValue = jlimit (0.0, 1.0, progress);
  39712. }
  39713. ProgressBar::~ProgressBar()
  39714. {
  39715. }
  39716. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39717. {
  39718. displayPercentage = shouldDisplayPercentage;
  39719. repaint();
  39720. }
  39721. void ProgressBar::setTextToDisplay (const String& text)
  39722. {
  39723. displayPercentage = false;
  39724. displayedMessage = text;
  39725. }
  39726. void ProgressBar::lookAndFeelChanged()
  39727. {
  39728. setOpaque (findColour (backgroundColourId).isOpaque());
  39729. }
  39730. void ProgressBar::colourChanged()
  39731. {
  39732. lookAndFeelChanged();
  39733. }
  39734. void ProgressBar::paint (Graphics& g)
  39735. {
  39736. String text;
  39737. if (displayPercentage)
  39738. {
  39739. if (currentValue >= 0 && currentValue <= 1.0)
  39740. text << roundToInt (currentValue * 100.0) << '%';
  39741. }
  39742. else
  39743. {
  39744. text = displayedMessage;
  39745. }
  39746. getLookAndFeel().drawProgressBar (g, *this,
  39747. getWidth(), getHeight(),
  39748. currentValue, text);
  39749. }
  39750. void ProgressBar::visibilityChanged()
  39751. {
  39752. if (isVisible())
  39753. startTimer (30);
  39754. else
  39755. stopTimer();
  39756. }
  39757. void ProgressBar::timerCallback()
  39758. {
  39759. double newProgress = progress;
  39760. const uint32 now = Time::getMillisecondCounter();
  39761. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39762. lastCallbackTime = now;
  39763. if (currentValue != newProgress
  39764. || newProgress < 0 || newProgress >= 1.0
  39765. || currentMessage != displayedMessage)
  39766. {
  39767. if (currentValue < newProgress
  39768. && newProgress >= 0 && newProgress < 1.0
  39769. && currentValue >= 0 && currentValue < 1.0)
  39770. {
  39771. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39772. newProgress);
  39773. }
  39774. currentValue = newProgress;
  39775. currentMessage = displayedMessage;
  39776. repaint();
  39777. }
  39778. }
  39779. END_JUCE_NAMESPACE
  39780. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39781. /*** Start of inlined file: juce_Slider.cpp ***/
  39782. BEGIN_JUCE_NAMESPACE
  39783. class SliderPopupDisplayComponent : public BubbleComponent
  39784. {
  39785. public:
  39786. SliderPopupDisplayComponent (Slider* const owner_)
  39787. : owner (owner_),
  39788. font (15.0f, Font::bold)
  39789. {
  39790. setAlwaysOnTop (true);
  39791. }
  39792. ~SliderPopupDisplayComponent()
  39793. {
  39794. }
  39795. void paintContent (Graphics& g, int w, int h)
  39796. {
  39797. g.setFont (font);
  39798. g.setColour (Colours::black);
  39799. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39800. }
  39801. void getContentSize (int& w, int& h)
  39802. {
  39803. w = font.getStringWidth (text) + 18;
  39804. h = (int) (font.getHeight() * 1.6f);
  39805. }
  39806. void updatePosition (const String& newText)
  39807. {
  39808. if (text != newText)
  39809. {
  39810. text = newText;
  39811. repaint();
  39812. }
  39813. BubbleComponent::setPosition (owner);
  39814. }
  39815. juce_UseDebuggingNewOperator
  39816. private:
  39817. Slider* owner;
  39818. Font font;
  39819. String text;
  39820. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39821. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39822. };
  39823. Slider::Slider (const String& name)
  39824. : Component (name),
  39825. lastCurrentValue (0),
  39826. lastValueMin (0),
  39827. lastValueMax (0),
  39828. minimum (0),
  39829. maximum (10),
  39830. interval (0),
  39831. skewFactor (1.0),
  39832. velocityModeSensitivity (1.0),
  39833. velocityModeOffset (0.0),
  39834. velocityModeThreshold (1),
  39835. rotaryStart (float_Pi * 1.2f),
  39836. rotaryEnd (float_Pi * 2.8f),
  39837. numDecimalPlaces (7),
  39838. sliderRegionStart (0),
  39839. sliderRegionSize (1),
  39840. sliderBeingDragged (-1),
  39841. pixelsForFullDragExtent (250),
  39842. style (LinearHorizontal),
  39843. textBoxPos (TextBoxLeft),
  39844. textBoxWidth (80),
  39845. textBoxHeight (20),
  39846. incDecButtonMode (incDecButtonsNotDraggable),
  39847. editableText (true),
  39848. doubleClickToValue (false),
  39849. isVelocityBased (false),
  39850. userKeyOverridesVelocity (true),
  39851. rotaryStop (true),
  39852. incDecButtonsSideBySide (false),
  39853. sendChangeOnlyOnRelease (false),
  39854. popupDisplayEnabled (false),
  39855. menuEnabled (false),
  39856. menuShown (false),
  39857. scrollWheelEnabled (true),
  39858. snapsToMousePos (true),
  39859. valueBox (0),
  39860. incButton (0),
  39861. decButton (0),
  39862. popupDisplay (0),
  39863. parentForPopupDisplay (0)
  39864. {
  39865. setWantsKeyboardFocus (false);
  39866. setRepaintsOnMouseActivity (true);
  39867. lookAndFeelChanged();
  39868. updateText();
  39869. currentValue.addListener (this);
  39870. valueMin.addListener (this);
  39871. valueMax.addListener (this);
  39872. }
  39873. Slider::~Slider()
  39874. {
  39875. currentValue.removeListener (this);
  39876. valueMin.removeListener (this);
  39877. valueMax.removeListener (this);
  39878. popupDisplay = 0;
  39879. deleteAllChildren();
  39880. }
  39881. void Slider::handleAsyncUpdate()
  39882. {
  39883. cancelPendingUpdate();
  39884. Component::BailOutChecker checker (this);
  39885. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39886. }
  39887. void Slider::sendDragStart()
  39888. {
  39889. startedDragging();
  39890. Component::BailOutChecker checker (this);
  39891. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39892. }
  39893. void Slider::sendDragEnd()
  39894. {
  39895. stoppedDragging();
  39896. sliderBeingDragged = -1;
  39897. Component::BailOutChecker checker (this);
  39898. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39899. }
  39900. void Slider::addListener (Listener* const listener)
  39901. {
  39902. listeners.add (listener);
  39903. }
  39904. void Slider::removeListener (Listener* const listener)
  39905. {
  39906. listeners.remove (listener);
  39907. }
  39908. void Slider::setSliderStyle (const SliderStyle newStyle)
  39909. {
  39910. if (style != newStyle)
  39911. {
  39912. style = newStyle;
  39913. repaint();
  39914. lookAndFeelChanged();
  39915. }
  39916. }
  39917. void Slider::setRotaryParameters (const float startAngleRadians,
  39918. const float endAngleRadians,
  39919. const bool stopAtEnd)
  39920. {
  39921. // make sure the values are sensible..
  39922. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39923. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39924. jassert (rotaryStart < rotaryEnd);
  39925. rotaryStart = startAngleRadians;
  39926. rotaryEnd = endAngleRadians;
  39927. rotaryStop = stopAtEnd;
  39928. }
  39929. void Slider::setVelocityBasedMode (const bool velBased)
  39930. {
  39931. isVelocityBased = velBased;
  39932. }
  39933. void Slider::setVelocityModeParameters (const double sensitivity,
  39934. const int threshold,
  39935. const double offset,
  39936. const bool userCanPressKeyToSwapMode)
  39937. {
  39938. jassert (threshold >= 0);
  39939. jassert (sensitivity > 0);
  39940. jassert (offset >= 0);
  39941. velocityModeSensitivity = sensitivity;
  39942. velocityModeOffset = offset;
  39943. velocityModeThreshold = threshold;
  39944. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39945. }
  39946. void Slider::setSkewFactor (const double factor)
  39947. {
  39948. skewFactor = factor;
  39949. }
  39950. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39951. {
  39952. if (maximum > minimum)
  39953. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39954. / (maximum - minimum));
  39955. }
  39956. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39957. {
  39958. jassert (distanceForFullScaleDrag > 0);
  39959. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39960. }
  39961. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39962. {
  39963. if (incDecButtonMode != mode)
  39964. {
  39965. incDecButtonMode = mode;
  39966. lookAndFeelChanged();
  39967. }
  39968. }
  39969. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39970. const bool isReadOnly,
  39971. const int textEntryBoxWidth,
  39972. const int textEntryBoxHeight)
  39973. {
  39974. if (textBoxPos != newPosition
  39975. || editableText != (! isReadOnly)
  39976. || textBoxWidth != textEntryBoxWidth
  39977. || textBoxHeight != textEntryBoxHeight)
  39978. {
  39979. textBoxPos = newPosition;
  39980. editableText = ! isReadOnly;
  39981. textBoxWidth = textEntryBoxWidth;
  39982. textBoxHeight = textEntryBoxHeight;
  39983. repaint();
  39984. lookAndFeelChanged();
  39985. }
  39986. }
  39987. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39988. {
  39989. editableText = shouldBeEditable;
  39990. if (valueBox != 0)
  39991. valueBox->setEditable (shouldBeEditable && isEnabled());
  39992. }
  39993. void Slider::showTextBox()
  39994. {
  39995. jassert (editableText); // this should probably be avoided in read-only sliders.
  39996. if (valueBox != 0)
  39997. valueBox->showEditor();
  39998. }
  39999. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40000. {
  40001. if (valueBox != 0)
  40002. {
  40003. valueBox->hideEditor (discardCurrentEditorContents);
  40004. if (discardCurrentEditorContents)
  40005. updateText();
  40006. }
  40007. }
  40008. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40009. {
  40010. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40011. }
  40012. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40013. {
  40014. snapsToMousePos = shouldSnapToMouse;
  40015. }
  40016. void Slider::setPopupDisplayEnabled (const bool enabled,
  40017. Component* const parentComponentToUse)
  40018. {
  40019. popupDisplayEnabled = enabled;
  40020. parentForPopupDisplay = parentComponentToUse;
  40021. }
  40022. void Slider::colourChanged()
  40023. {
  40024. lookAndFeelChanged();
  40025. }
  40026. void Slider::lookAndFeelChanged()
  40027. {
  40028. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40029. : getTextFromValue (currentValue.getValue()));
  40030. deleteAllChildren();
  40031. valueBox = 0;
  40032. LookAndFeel& lf = getLookAndFeel();
  40033. if (textBoxPos != NoTextBox)
  40034. {
  40035. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40036. valueBox->setWantsKeyboardFocus (false);
  40037. valueBox->setText (previousTextBoxContent, false);
  40038. valueBox->setEditable (editableText && isEnabled());
  40039. valueBox->addListener (this);
  40040. if (style == LinearBar)
  40041. valueBox->addMouseListener (this, false);
  40042. valueBox->setTooltip (getTooltip());
  40043. }
  40044. if (style == IncDecButtons)
  40045. {
  40046. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40047. incButton->addButtonListener (this);
  40048. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40049. decButton->addButtonListener (this);
  40050. if (incDecButtonMode != incDecButtonsNotDraggable)
  40051. {
  40052. incButton->addMouseListener (this, false);
  40053. decButton->addMouseListener (this, false);
  40054. }
  40055. else
  40056. {
  40057. incButton->setRepeatSpeed (300, 100, 20);
  40058. incButton->addMouseListener (decButton, false);
  40059. decButton->setRepeatSpeed (300, 100, 20);
  40060. decButton->addMouseListener (incButton, false);
  40061. }
  40062. incButton->setTooltip (getTooltip());
  40063. decButton->setTooltip (getTooltip());
  40064. }
  40065. setComponentEffect (lf.getSliderEffect());
  40066. resized();
  40067. repaint();
  40068. }
  40069. void Slider::setRange (const double newMin,
  40070. const double newMax,
  40071. const double newInt)
  40072. {
  40073. if (minimum != newMin
  40074. || maximum != newMax
  40075. || interval != newInt)
  40076. {
  40077. minimum = newMin;
  40078. maximum = newMax;
  40079. interval = newInt;
  40080. // figure out the number of DPs needed to display all values at this
  40081. // interval setting.
  40082. numDecimalPlaces = 7;
  40083. if (newInt != 0)
  40084. {
  40085. int v = abs ((int) (newInt * 10000000));
  40086. while ((v % 10) == 0)
  40087. {
  40088. --numDecimalPlaces;
  40089. v /= 10;
  40090. }
  40091. }
  40092. // keep the current values inside the new range..
  40093. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40094. {
  40095. setValue (getValue(), false, false);
  40096. }
  40097. else
  40098. {
  40099. setMinValue (getMinValue(), false, false);
  40100. setMaxValue (getMaxValue(), false, false);
  40101. }
  40102. updateText();
  40103. }
  40104. }
  40105. void Slider::triggerChangeMessage (const bool synchronous)
  40106. {
  40107. if (synchronous)
  40108. handleAsyncUpdate();
  40109. else
  40110. triggerAsyncUpdate();
  40111. valueChanged();
  40112. }
  40113. void Slider::valueChanged (Value& value)
  40114. {
  40115. if (value.refersToSameSourceAs (currentValue))
  40116. {
  40117. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40118. setValue (currentValue.getValue(), false, false);
  40119. }
  40120. else if (value.refersToSameSourceAs (valueMin))
  40121. setMinValue (valueMin.getValue(), false, false, true);
  40122. else if (value.refersToSameSourceAs (valueMax))
  40123. setMaxValue (valueMax.getValue(), false, false, true);
  40124. }
  40125. double Slider::getValue() const
  40126. {
  40127. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40128. // methods to get the two values.
  40129. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40130. return currentValue.getValue();
  40131. }
  40132. void Slider::setValue (double newValue,
  40133. const bool sendUpdateMessage,
  40134. const bool sendMessageSynchronously)
  40135. {
  40136. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40137. // methods to set the two values.
  40138. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40139. newValue = constrainedValue (newValue);
  40140. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40141. {
  40142. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40143. newValue = jlimit ((double) valueMin.getValue(),
  40144. (double) valueMax.getValue(),
  40145. newValue);
  40146. }
  40147. if (newValue != lastCurrentValue)
  40148. {
  40149. if (valueBox != 0)
  40150. valueBox->hideEditor (true);
  40151. lastCurrentValue = newValue;
  40152. currentValue = newValue;
  40153. updateText();
  40154. repaint();
  40155. if (popupDisplay != 0)
  40156. {
  40157. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40158. ->updatePosition (getTextFromValue (newValue));
  40159. popupDisplay->repaint();
  40160. }
  40161. if (sendUpdateMessage)
  40162. triggerChangeMessage (sendMessageSynchronously);
  40163. }
  40164. }
  40165. double Slider::getMinValue() const
  40166. {
  40167. // The minimum value only applies to sliders that are in two- or three-value mode.
  40168. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40169. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40170. return valueMin.getValue();
  40171. }
  40172. double Slider::getMaxValue() const
  40173. {
  40174. // The maximum value only applies to sliders that are in two- or three-value mode.
  40175. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40176. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40177. return valueMax.getValue();
  40178. }
  40179. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40180. {
  40181. // The minimum value only applies to sliders that are in two- or three-value mode.
  40182. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40183. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40184. newValue = constrainedValue (newValue);
  40185. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40186. {
  40187. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40188. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40189. newValue = jmin ((double) valueMax.getValue(), newValue);
  40190. }
  40191. else
  40192. {
  40193. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40194. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40195. newValue = jmin (lastCurrentValue, newValue);
  40196. }
  40197. if (lastValueMin != newValue)
  40198. {
  40199. lastValueMin = newValue;
  40200. valueMin = newValue;
  40201. repaint();
  40202. if (popupDisplay != 0)
  40203. {
  40204. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40205. ->updatePosition (getTextFromValue (newValue));
  40206. popupDisplay->repaint();
  40207. }
  40208. if (sendUpdateMessage)
  40209. triggerChangeMessage (sendMessageSynchronously);
  40210. }
  40211. }
  40212. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40213. {
  40214. // The maximum value only applies to sliders that are in two- or three-value mode.
  40215. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40216. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40217. newValue = constrainedValue (newValue);
  40218. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40219. {
  40220. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40221. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40222. newValue = jmax ((double) valueMin.getValue(), newValue);
  40223. }
  40224. else
  40225. {
  40226. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40227. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40228. newValue = jmax (lastCurrentValue, newValue);
  40229. }
  40230. if (lastValueMax != newValue)
  40231. {
  40232. lastValueMax = newValue;
  40233. valueMax = newValue;
  40234. repaint();
  40235. if (popupDisplay != 0)
  40236. {
  40237. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40238. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40239. popupDisplay->repaint();
  40240. }
  40241. if (sendUpdateMessage)
  40242. triggerChangeMessage (sendMessageSynchronously);
  40243. }
  40244. }
  40245. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40246. const double valueToSetOnDoubleClick)
  40247. {
  40248. doubleClickToValue = isDoubleClickEnabled;
  40249. doubleClickReturnValue = valueToSetOnDoubleClick;
  40250. }
  40251. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40252. {
  40253. isEnabled_ = doubleClickToValue;
  40254. return doubleClickReturnValue;
  40255. }
  40256. void Slider::updateText()
  40257. {
  40258. if (valueBox != 0)
  40259. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40260. }
  40261. void Slider::setTextValueSuffix (const String& suffix)
  40262. {
  40263. if (textSuffix != suffix)
  40264. {
  40265. textSuffix = suffix;
  40266. updateText();
  40267. }
  40268. }
  40269. const String Slider::getTextValueSuffix() const
  40270. {
  40271. return textSuffix;
  40272. }
  40273. const String Slider::getTextFromValue (double v)
  40274. {
  40275. if (getNumDecimalPlacesToDisplay() > 0)
  40276. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40277. else
  40278. return String (roundToInt (v)) + getTextValueSuffix();
  40279. }
  40280. double Slider::getValueFromText (const String& text)
  40281. {
  40282. String t (text.trimStart());
  40283. if (t.endsWith (textSuffix))
  40284. t = t.substring (0, t.length() - textSuffix.length());
  40285. while (t.startsWithChar ('+'))
  40286. t = t.substring (1).trimStart();
  40287. return t.initialSectionContainingOnly ("0123456789.,-")
  40288. .getDoubleValue();
  40289. }
  40290. double Slider::proportionOfLengthToValue (double proportion)
  40291. {
  40292. if (skewFactor != 1.0 && proportion > 0.0)
  40293. proportion = exp (log (proportion) / skewFactor);
  40294. return minimum + (maximum - minimum) * proportion;
  40295. }
  40296. double Slider::valueToProportionOfLength (double value)
  40297. {
  40298. const double n = (value - minimum) / (maximum - minimum);
  40299. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40300. }
  40301. double Slider::snapValue (double attemptedValue, const bool)
  40302. {
  40303. return attemptedValue;
  40304. }
  40305. void Slider::startedDragging()
  40306. {
  40307. }
  40308. void Slider::stoppedDragging()
  40309. {
  40310. }
  40311. void Slider::valueChanged()
  40312. {
  40313. }
  40314. void Slider::enablementChanged()
  40315. {
  40316. repaint();
  40317. }
  40318. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40319. {
  40320. menuEnabled = menuEnabled_;
  40321. }
  40322. void Slider::setScrollWheelEnabled (const bool enabled)
  40323. {
  40324. scrollWheelEnabled = enabled;
  40325. }
  40326. void Slider::labelTextChanged (Label* label)
  40327. {
  40328. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40329. if (newValue != (double) currentValue.getValue())
  40330. {
  40331. sendDragStart();
  40332. setValue (newValue, true, true);
  40333. sendDragEnd();
  40334. }
  40335. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40336. }
  40337. void Slider::buttonClicked (Button* button)
  40338. {
  40339. if (style == IncDecButtons)
  40340. {
  40341. sendDragStart();
  40342. if (button == incButton)
  40343. setValue (snapValue (getValue() + interval, false), true, true);
  40344. else if (button == decButton)
  40345. setValue (snapValue (getValue() - interval, false), true, true);
  40346. sendDragEnd();
  40347. }
  40348. }
  40349. double Slider::constrainedValue (double value) const
  40350. {
  40351. if (interval > 0)
  40352. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40353. if (value <= minimum || maximum <= minimum)
  40354. value = minimum;
  40355. else if (value >= maximum)
  40356. value = maximum;
  40357. return value;
  40358. }
  40359. float Slider::getLinearSliderPos (const double value)
  40360. {
  40361. double sliderPosProportional;
  40362. if (maximum > minimum)
  40363. {
  40364. if (value < minimum)
  40365. {
  40366. sliderPosProportional = 0.0;
  40367. }
  40368. else if (value > maximum)
  40369. {
  40370. sliderPosProportional = 1.0;
  40371. }
  40372. else
  40373. {
  40374. sliderPosProportional = valueToProportionOfLength (value);
  40375. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40376. }
  40377. }
  40378. else
  40379. {
  40380. sliderPosProportional = 0.5;
  40381. }
  40382. if (isVertical() || style == IncDecButtons)
  40383. sliderPosProportional = 1.0 - sliderPosProportional;
  40384. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40385. }
  40386. bool Slider::isHorizontal() const
  40387. {
  40388. return style == LinearHorizontal
  40389. || style == LinearBar
  40390. || style == TwoValueHorizontal
  40391. || style == ThreeValueHorizontal;
  40392. }
  40393. bool Slider::isVertical() const
  40394. {
  40395. return style == LinearVertical
  40396. || style == TwoValueVertical
  40397. || style == ThreeValueVertical;
  40398. }
  40399. bool Slider::incDecDragDirectionIsHorizontal() const
  40400. {
  40401. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40402. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40403. }
  40404. float Slider::getPositionOfValue (const double value)
  40405. {
  40406. if (isHorizontal() || isVertical())
  40407. {
  40408. return getLinearSliderPos (value);
  40409. }
  40410. else
  40411. {
  40412. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40413. return 0.0f;
  40414. }
  40415. }
  40416. void Slider::paint (Graphics& g)
  40417. {
  40418. if (style != IncDecButtons)
  40419. {
  40420. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40421. {
  40422. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40423. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40424. getLookAndFeel().drawRotarySlider (g,
  40425. sliderRect.getX(),
  40426. sliderRect.getY(),
  40427. sliderRect.getWidth(),
  40428. sliderRect.getHeight(),
  40429. sliderPos,
  40430. rotaryStart, rotaryEnd,
  40431. *this);
  40432. }
  40433. else
  40434. {
  40435. getLookAndFeel().drawLinearSlider (g,
  40436. sliderRect.getX(),
  40437. sliderRect.getY(),
  40438. sliderRect.getWidth(),
  40439. sliderRect.getHeight(),
  40440. getLinearSliderPos (lastCurrentValue),
  40441. getLinearSliderPos (lastValueMin),
  40442. getLinearSliderPos (lastValueMax),
  40443. style,
  40444. *this);
  40445. }
  40446. if (style == LinearBar && valueBox == 0)
  40447. {
  40448. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40449. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40450. }
  40451. }
  40452. }
  40453. void Slider::resized()
  40454. {
  40455. int minXSpace = 0;
  40456. int minYSpace = 0;
  40457. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40458. minXSpace = 30;
  40459. else
  40460. minYSpace = 15;
  40461. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40462. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40463. if (style == LinearBar)
  40464. {
  40465. if (valueBox != 0)
  40466. valueBox->setBounds (getLocalBounds());
  40467. }
  40468. else
  40469. {
  40470. if (textBoxPos == NoTextBox)
  40471. {
  40472. sliderRect = getLocalBounds();
  40473. }
  40474. else if (textBoxPos == TextBoxLeft)
  40475. {
  40476. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40477. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40478. }
  40479. else if (textBoxPos == TextBoxRight)
  40480. {
  40481. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40482. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40483. }
  40484. else if (textBoxPos == TextBoxAbove)
  40485. {
  40486. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40487. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40488. }
  40489. else if (textBoxPos == TextBoxBelow)
  40490. {
  40491. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40492. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40493. }
  40494. }
  40495. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40496. if (style == LinearBar)
  40497. {
  40498. const int barIndent = 1;
  40499. sliderRegionStart = barIndent;
  40500. sliderRegionSize = getWidth() - barIndent * 2;
  40501. sliderRect.setBounds (sliderRegionStart, barIndent,
  40502. sliderRegionSize, getHeight() - barIndent * 2);
  40503. }
  40504. else if (isHorizontal())
  40505. {
  40506. sliderRegionStart = sliderRect.getX() + indent;
  40507. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40508. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40509. sliderRegionSize, sliderRect.getHeight());
  40510. }
  40511. else if (isVertical())
  40512. {
  40513. sliderRegionStart = sliderRect.getY() + indent;
  40514. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40515. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40516. sliderRect.getWidth(), sliderRegionSize);
  40517. }
  40518. else
  40519. {
  40520. sliderRegionStart = 0;
  40521. sliderRegionSize = 100;
  40522. }
  40523. if (style == IncDecButtons)
  40524. {
  40525. Rectangle<int> buttonRect (sliderRect);
  40526. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40527. buttonRect.expand (-2, 0);
  40528. else
  40529. buttonRect.expand (0, -2);
  40530. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40531. if (incDecButtonsSideBySide)
  40532. {
  40533. decButton->setBounds (buttonRect.getX(),
  40534. buttonRect.getY(),
  40535. buttonRect.getWidth() / 2,
  40536. buttonRect.getHeight());
  40537. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40538. incButton->setBounds (buttonRect.getCentreX(),
  40539. buttonRect.getY(),
  40540. buttonRect.getWidth() / 2,
  40541. buttonRect.getHeight());
  40542. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40543. }
  40544. else
  40545. {
  40546. incButton->setBounds (buttonRect.getX(),
  40547. buttonRect.getY(),
  40548. buttonRect.getWidth(),
  40549. buttonRect.getHeight() / 2);
  40550. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40551. decButton->setBounds (buttonRect.getX(),
  40552. buttonRect.getCentreY(),
  40553. buttonRect.getWidth(),
  40554. buttonRect.getHeight() / 2);
  40555. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40556. }
  40557. }
  40558. }
  40559. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40560. {
  40561. repaint();
  40562. }
  40563. void Slider::mouseDown (const MouseEvent& e)
  40564. {
  40565. mouseWasHidden = false;
  40566. incDecDragged = false;
  40567. mouseXWhenLastDragged = e.x;
  40568. mouseYWhenLastDragged = e.y;
  40569. mouseDragStartX = e.getMouseDownX();
  40570. mouseDragStartY = e.getMouseDownY();
  40571. if (isEnabled())
  40572. {
  40573. if (e.mods.isPopupMenu() && menuEnabled)
  40574. {
  40575. menuShown = true;
  40576. PopupMenu m;
  40577. m.setLookAndFeel (&getLookAndFeel());
  40578. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40579. m.addSeparator();
  40580. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40581. {
  40582. PopupMenu rotaryMenu;
  40583. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40584. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40585. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40586. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40587. }
  40588. const int r = m.show();
  40589. if (r == 1)
  40590. {
  40591. setVelocityBasedMode (! isVelocityBased);
  40592. }
  40593. else if (r == 2)
  40594. {
  40595. setSliderStyle (Rotary);
  40596. }
  40597. else if (r == 3)
  40598. {
  40599. setSliderStyle (RotaryHorizontalDrag);
  40600. }
  40601. else if (r == 4)
  40602. {
  40603. setSliderStyle (RotaryVerticalDrag);
  40604. }
  40605. }
  40606. else if (maximum > minimum)
  40607. {
  40608. menuShown = false;
  40609. if (valueBox != 0)
  40610. valueBox->hideEditor (true);
  40611. sliderBeingDragged = 0;
  40612. if (style == TwoValueHorizontal
  40613. || style == TwoValueVertical
  40614. || style == ThreeValueHorizontal
  40615. || style == ThreeValueVertical)
  40616. {
  40617. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40618. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40619. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40620. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40621. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40622. {
  40623. if (maxPosDistance <= minPosDistance)
  40624. sliderBeingDragged = 2;
  40625. else
  40626. sliderBeingDragged = 1;
  40627. }
  40628. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40629. {
  40630. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40631. sliderBeingDragged = 1;
  40632. else if (normalPosDistance >= maxPosDistance)
  40633. sliderBeingDragged = 2;
  40634. }
  40635. }
  40636. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40637. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40638. * valueToProportionOfLength (currentValue.getValue());
  40639. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40640. : ((sliderBeingDragged == 1) ? valueMin
  40641. : currentValue)).getValue();
  40642. valueOnMouseDown = valueWhenLastDragged;
  40643. if (popupDisplayEnabled)
  40644. {
  40645. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40646. popupDisplay = popup;
  40647. if (parentForPopupDisplay != 0)
  40648. {
  40649. parentForPopupDisplay->addChildComponent (popup);
  40650. }
  40651. else
  40652. {
  40653. popup->addToDesktop (0);
  40654. }
  40655. popup->setVisible (true);
  40656. }
  40657. sendDragStart();
  40658. mouseDrag (e);
  40659. }
  40660. }
  40661. }
  40662. void Slider::mouseUp (const MouseEvent&)
  40663. {
  40664. if (isEnabled()
  40665. && (! menuShown)
  40666. && (maximum > minimum)
  40667. && (style != IncDecButtons || incDecDragged))
  40668. {
  40669. restoreMouseIfHidden();
  40670. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40671. triggerChangeMessage (false);
  40672. sendDragEnd();
  40673. popupDisplay = 0;
  40674. if (style == IncDecButtons)
  40675. {
  40676. incButton->setState (Button::buttonNormal);
  40677. decButton->setState (Button::buttonNormal);
  40678. }
  40679. }
  40680. }
  40681. void Slider::restoreMouseIfHidden()
  40682. {
  40683. if (mouseWasHidden)
  40684. {
  40685. mouseWasHidden = false;
  40686. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40687. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40688. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40689. : ((sliderBeingDragged == 1) ? getMinValue()
  40690. : (double) currentValue.getValue());
  40691. Point<int> mousePos;
  40692. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40693. {
  40694. mousePos = Desktop::getLastMouseDownPosition();
  40695. if (style == RotaryHorizontalDrag)
  40696. {
  40697. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40698. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40699. }
  40700. else
  40701. {
  40702. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40703. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40704. }
  40705. }
  40706. else
  40707. {
  40708. const int pixelPos = (int) getLinearSliderPos (pos);
  40709. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40710. isVertical() ? pixelPos : (getHeight() / 2)));
  40711. }
  40712. Desktop::setMousePosition (mousePos);
  40713. }
  40714. }
  40715. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40716. {
  40717. if (isEnabled()
  40718. && style != IncDecButtons
  40719. && style != Rotary
  40720. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40721. {
  40722. restoreMouseIfHidden();
  40723. }
  40724. }
  40725. static double smallestAngleBetween (double a1, double a2)
  40726. {
  40727. return jmin (std::abs (a1 - a2),
  40728. std::abs (a1 + double_Pi * 2.0 - a2),
  40729. std::abs (a2 + double_Pi * 2.0 - a1));
  40730. }
  40731. void Slider::mouseDrag (const MouseEvent& e)
  40732. {
  40733. if (isEnabled()
  40734. && (! menuShown)
  40735. && (maximum > minimum))
  40736. {
  40737. if (style == Rotary)
  40738. {
  40739. int dx = e.x - sliderRect.getCentreX();
  40740. int dy = e.y - sliderRect.getCentreY();
  40741. if (dx * dx + dy * dy > 25)
  40742. {
  40743. double angle = std::atan2 ((double) dx, (double) -dy);
  40744. while (angle < 0.0)
  40745. angle += double_Pi * 2.0;
  40746. if (rotaryStop && ! e.mouseWasClicked())
  40747. {
  40748. if (std::abs (angle - lastAngle) > double_Pi)
  40749. {
  40750. if (angle >= lastAngle)
  40751. angle -= double_Pi * 2.0;
  40752. else
  40753. angle += double_Pi * 2.0;
  40754. }
  40755. if (angle >= lastAngle)
  40756. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40757. else
  40758. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40759. }
  40760. else
  40761. {
  40762. while (angle < rotaryStart)
  40763. angle += double_Pi * 2.0;
  40764. if (angle > rotaryEnd)
  40765. {
  40766. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40767. angle = rotaryStart;
  40768. else
  40769. angle = rotaryEnd;
  40770. }
  40771. }
  40772. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40773. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40774. lastAngle = angle;
  40775. }
  40776. }
  40777. else
  40778. {
  40779. if (style == LinearBar && e.mouseWasClicked()
  40780. && valueBox != 0 && valueBox->isEditable())
  40781. return;
  40782. if (style == IncDecButtons && ! incDecDragged)
  40783. {
  40784. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40785. return;
  40786. incDecDragged = true;
  40787. mouseDragStartX = e.x;
  40788. mouseDragStartY = e.y;
  40789. }
  40790. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40791. : false))
  40792. || ((maximum - minimum) / sliderRegionSize < interval))
  40793. {
  40794. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40795. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40796. if (style == RotaryHorizontalDrag
  40797. || style == RotaryVerticalDrag
  40798. || style == IncDecButtons
  40799. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40800. && ! snapsToMousePos))
  40801. {
  40802. const int mouseDiff = (style == RotaryHorizontalDrag
  40803. || style == LinearHorizontal
  40804. || style == LinearBar
  40805. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40806. ? e.x - mouseDragStartX
  40807. : mouseDragStartY - e.y;
  40808. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40809. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40810. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40811. if (style == IncDecButtons)
  40812. {
  40813. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40814. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40815. }
  40816. }
  40817. else
  40818. {
  40819. if (isVertical())
  40820. scaledMousePos = 1.0 - scaledMousePos;
  40821. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40822. }
  40823. }
  40824. else
  40825. {
  40826. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40827. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40828. ? e.x - mouseXWhenLastDragged
  40829. : e.y - mouseYWhenLastDragged;
  40830. const double maxSpeed = jmax (200, sliderRegionSize);
  40831. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40832. if (speed != 0)
  40833. {
  40834. speed = 0.2 * velocityModeSensitivity
  40835. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40836. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40837. / maxSpeed))));
  40838. if (mouseDiff < 0)
  40839. speed = -speed;
  40840. if (isVertical() || style == RotaryVerticalDrag
  40841. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40842. speed = -speed;
  40843. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40844. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40845. e.source.enableUnboundedMouseMovement (true, false);
  40846. mouseWasHidden = true;
  40847. }
  40848. }
  40849. }
  40850. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40851. if (sliderBeingDragged == 0)
  40852. {
  40853. setValue (snapValue (valueWhenLastDragged, true),
  40854. ! sendChangeOnlyOnRelease, true);
  40855. }
  40856. else if (sliderBeingDragged == 1)
  40857. {
  40858. setMinValue (snapValue (valueWhenLastDragged, true),
  40859. ! sendChangeOnlyOnRelease, false, true);
  40860. if (e.mods.isShiftDown())
  40861. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40862. else
  40863. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40864. }
  40865. else
  40866. {
  40867. jassert (sliderBeingDragged == 2);
  40868. setMaxValue (snapValue (valueWhenLastDragged, true),
  40869. ! sendChangeOnlyOnRelease, false, true);
  40870. if (e.mods.isShiftDown())
  40871. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40872. else
  40873. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40874. }
  40875. mouseXWhenLastDragged = e.x;
  40876. mouseYWhenLastDragged = e.y;
  40877. }
  40878. }
  40879. void Slider::mouseDoubleClick (const MouseEvent&)
  40880. {
  40881. if (doubleClickToValue
  40882. && isEnabled()
  40883. && style != IncDecButtons
  40884. && minimum <= doubleClickReturnValue
  40885. && maximum >= doubleClickReturnValue)
  40886. {
  40887. sendDragStart();
  40888. setValue (doubleClickReturnValue, true, true);
  40889. sendDragEnd();
  40890. }
  40891. }
  40892. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40893. {
  40894. if (scrollWheelEnabled && isEnabled()
  40895. && style != TwoValueHorizontal
  40896. && style != TwoValueVertical)
  40897. {
  40898. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40899. {
  40900. if (valueBox != 0)
  40901. valueBox->hideEditor (false);
  40902. const double value = (double) currentValue.getValue();
  40903. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40904. const double currentPos = valueToProportionOfLength (value);
  40905. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40906. double delta = (newValue != value)
  40907. ? jmax (std::abs (newValue - value), interval) : 0;
  40908. if (value > newValue)
  40909. delta = -delta;
  40910. sendDragStart();
  40911. setValue (snapValue (value + delta, false), true, true);
  40912. sendDragEnd();
  40913. }
  40914. }
  40915. else
  40916. {
  40917. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40918. }
  40919. }
  40920. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40921. {
  40922. }
  40923. void SliderListener::sliderDragEnded (Slider*)
  40924. {
  40925. }
  40926. END_JUCE_NAMESPACE
  40927. /*** End of inlined file: juce_Slider.cpp ***/
  40928. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40929. BEGIN_JUCE_NAMESPACE
  40930. class DragOverlayComp : public Component
  40931. {
  40932. public:
  40933. DragOverlayComp (const Image& image_)
  40934. : image (image_)
  40935. {
  40936. image.duplicateIfShared();
  40937. image.multiplyAllAlphas (0.8f);
  40938. setAlwaysOnTop (true);
  40939. }
  40940. ~DragOverlayComp()
  40941. {
  40942. }
  40943. void paint (Graphics& g)
  40944. {
  40945. g.drawImageAt (image, 0, 0);
  40946. }
  40947. private:
  40948. Image image;
  40949. DragOverlayComp (const DragOverlayComp&);
  40950. DragOverlayComp& operator= (const DragOverlayComp&);
  40951. };
  40952. TableHeaderComponent::TableHeaderComponent()
  40953. : columnsChanged (false),
  40954. columnsResized (false),
  40955. sortChanged (false),
  40956. menuActive (true),
  40957. stretchToFit (false),
  40958. columnIdBeingResized (0),
  40959. columnIdBeingDragged (0),
  40960. columnIdUnderMouse (0),
  40961. lastDeliberateWidth (0)
  40962. {
  40963. }
  40964. TableHeaderComponent::~TableHeaderComponent()
  40965. {
  40966. dragOverlayComp = 0;
  40967. }
  40968. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40969. {
  40970. menuActive = hasMenu;
  40971. }
  40972. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40973. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40974. {
  40975. if (onlyCountVisibleColumns)
  40976. {
  40977. int num = 0;
  40978. for (int i = columns.size(); --i >= 0;)
  40979. if (columns.getUnchecked(i)->isVisible())
  40980. ++num;
  40981. return num;
  40982. }
  40983. else
  40984. {
  40985. return columns.size();
  40986. }
  40987. }
  40988. const String TableHeaderComponent::getColumnName (const int columnId) const
  40989. {
  40990. const ColumnInfo* const ci = getInfoForId (columnId);
  40991. return ci != 0 ? ci->name : String::empty;
  40992. }
  40993. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40994. {
  40995. ColumnInfo* const ci = getInfoForId (columnId);
  40996. if (ci != 0 && ci->name != newName)
  40997. {
  40998. ci->name = newName;
  40999. sendColumnsChanged();
  41000. }
  41001. }
  41002. void TableHeaderComponent::addColumn (const String& columnName,
  41003. const int columnId,
  41004. const int width,
  41005. const int minimumWidth,
  41006. const int maximumWidth,
  41007. const int propertyFlags,
  41008. const int insertIndex)
  41009. {
  41010. // can't have a duplicate or null ID!
  41011. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41012. jassert (width > 0);
  41013. ColumnInfo* const ci = new ColumnInfo();
  41014. ci->name = columnName;
  41015. ci->id = columnId;
  41016. ci->width = width;
  41017. ci->lastDeliberateWidth = width;
  41018. ci->minimumWidth = minimumWidth;
  41019. ci->maximumWidth = maximumWidth;
  41020. if (ci->maximumWidth < 0)
  41021. ci->maximumWidth = std::numeric_limits<int>::max();
  41022. jassert (ci->maximumWidth >= ci->minimumWidth);
  41023. ci->propertyFlags = propertyFlags;
  41024. columns.insert (insertIndex, ci);
  41025. sendColumnsChanged();
  41026. }
  41027. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41028. {
  41029. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41030. if (index >= 0)
  41031. {
  41032. columns.remove (index);
  41033. sortChanged = true;
  41034. sendColumnsChanged();
  41035. }
  41036. }
  41037. void TableHeaderComponent::removeAllColumns()
  41038. {
  41039. if (columns.size() > 0)
  41040. {
  41041. columns.clear();
  41042. sendColumnsChanged();
  41043. }
  41044. }
  41045. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41046. {
  41047. const int currentIndex = getIndexOfColumnId (columnId, false);
  41048. newIndex = visibleIndexToTotalIndex (newIndex);
  41049. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41050. {
  41051. columns.move (currentIndex, newIndex);
  41052. sendColumnsChanged();
  41053. }
  41054. }
  41055. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41056. {
  41057. const ColumnInfo* const ci = getInfoForId (columnId);
  41058. return ci != 0 ? ci->width : 0;
  41059. }
  41060. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41061. {
  41062. ColumnInfo* const ci = getInfoForId (columnId);
  41063. if (ci != 0 && ci->width != newWidth)
  41064. {
  41065. const int numColumns = getNumColumns (true);
  41066. ci->lastDeliberateWidth = ci->width
  41067. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41068. if (stretchToFit)
  41069. {
  41070. const int index = getIndexOfColumnId (columnId, true) + 1;
  41071. if (((unsigned int) index) < (unsigned int) numColumns)
  41072. {
  41073. const int x = getColumnPosition (index).getX();
  41074. if (lastDeliberateWidth == 0)
  41075. lastDeliberateWidth = getTotalWidth();
  41076. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41077. }
  41078. }
  41079. repaint();
  41080. columnsResized = true;
  41081. triggerAsyncUpdate();
  41082. }
  41083. }
  41084. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41085. {
  41086. int n = 0;
  41087. for (int i = 0; i < columns.size(); ++i)
  41088. {
  41089. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41090. {
  41091. if (columns.getUnchecked(i)->id == columnId)
  41092. return n;
  41093. ++n;
  41094. }
  41095. }
  41096. return -1;
  41097. }
  41098. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41099. {
  41100. if (onlyCountVisibleColumns)
  41101. index = visibleIndexToTotalIndex (index);
  41102. const ColumnInfo* const ci = columns [index];
  41103. return (ci != 0) ? ci->id : 0;
  41104. }
  41105. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41106. {
  41107. int x = 0, width = 0, n = 0;
  41108. for (int i = 0; i < columns.size(); ++i)
  41109. {
  41110. x += width;
  41111. if (columns.getUnchecked(i)->isVisible())
  41112. {
  41113. width = columns.getUnchecked(i)->width;
  41114. if (n++ == index)
  41115. break;
  41116. }
  41117. else
  41118. {
  41119. width = 0;
  41120. }
  41121. }
  41122. return Rectangle<int> (x, 0, width, getHeight());
  41123. }
  41124. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41125. {
  41126. if (xToFind >= 0)
  41127. {
  41128. int x = 0;
  41129. for (int i = 0; i < columns.size(); ++i)
  41130. {
  41131. const ColumnInfo* const ci = columns.getUnchecked(i);
  41132. if (ci->isVisible())
  41133. {
  41134. x += ci->width;
  41135. if (xToFind < x)
  41136. return ci->id;
  41137. }
  41138. }
  41139. }
  41140. return 0;
  41141. }
  41142. int TableHeaderComponent::getTotalWidth() const
  41143. {
  41144. int w = 0;
  41145. for (int i = columns.size(); --i >= 0;)
  41146. if (columns.getUnchecked(i)->isVisible())
  41147. w += columns.getUnchecked(i)->width;
  41148. return w;
  41149. }
  41150. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41151. {
  41152. stretchToFit = shouldStretchToFit;
  41153. lastDeliberateWidth = getTotalWidth();
  41154. resized();
  41155. }
  41156. bool TableHeaderComponent::isStretchToFitActive() const
  41157. {
  41158. return stretchToFit;
  41159. }
  41160. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41161. {
  41162. if (stretchToFit && getWidth() > 0
  41163. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41164. {
  41165. lastDeliberateWidth = targetTotalWidth;
  41166. resizeColumnsToFit (0, targetTotalWidth);
  41167. }
  41168. }
  41169. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41170. {
  41171. targetTotalWidth = jmax (targetTotalWidth, 0);
  41172. StretchableObjectResizer sor;
  41173. int i;
  41174. for (i = firstColumnIndex; i < columns.size(); ++i)
  41175. {
  41176. ColumnInfo* const ci = columns.getUnchecked(i);
  41177. if (ci->isVisible())
  41178. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41179. }
  41180. sor.resizeToFit (targetTotalWidth);
  41181. int visIndex = 0;
  41182. for (i = firstColumnIndex; i < columns.size(); ++i)
  41183. {
  41184. ColumnInfo* const ci = columns.getUnchecked(i);
  41185. if (ci->isVisible())
  41186. {
  41187. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41188. (int) std::floor (sor.getItemSize (visIndex++)));
  41189. if (newWidth != ci->width)
  41190. {
  41191. ci->width = newWidth;
  41192. repaint();
  41193. columnsResized = true;
  41194. triggerAsyncUpdate();
  41195. }
  41196. }
  41197. }
  41198. }
  41199. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41200. {
  41201. ColumnInfo* const ci = getInfoForId (columnId);
  41202. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41203. {
  41204. if (shouldBeVisible)
  41205. ci->propertyFlags |= visible;
  41206. else
  41207. ci->propertyFlags &= ~visible;
  41208. sendColumnsChanged();
  41209. resized();
  41210. }
  41211. }
  41212. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41213. {
  41214. const ColumnInfo* const ci = getInfoForId (columnId);
  41215. return ci != 0 && ci->isVisible();
  41216. }
  41217. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41218. {
  41219. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41220. {
  41221. for (int i = columns.size(); --i >= 0;)
  41222. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41223. ColumnInfo* const ci = getInfoForId (columnId);
  41224. if (ci != 0)
  41225. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41226. reSortTable();
  41227. }
  41228. }
  41229. int TableHeaderComponent::getSortColumnId() const
  41230. {
  41231. for (int i = columns.size(); --i >= 0;)
  41232. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41233. return columns.getUnchecked(i)->id;
  41234. return 0;
  41235. }
  41236. bool TableHeaderComponent::isSortedForwards() const
  41237. {
  41238. for (int i = columns.size(); --i >= 0;)
  41239. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41240. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41241. return true;
  41242. }
  41243. void TableHeaderComponent::reSortTable()
  41244. {
  41245. sortChanged = true;
  41246. repaint();
  41247. triggerAsyncUpdate();
  41248. }
  41249. const String TableHeaderComponent::toString() const
  41250. {
  41251. String s;
  41252. XmlElement doc ("TABLELAYOUT");
  41253. doc.setAttribute ("sortedCol", getSortColumnId());
  41254. doc.setAttribute ("sortForwards", isSortedForwards());
  41255. for (int i = 0; i < columns.size(); ++i)
  41256. {
  41257. const ColumnInfo* const ci = columns.getUnchecked (i);
  41258. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41259. e->setAttribute ("id", ci->id);
  41260. e->setAttribute ("visible", ci->isVisible());
  41261. e->setAttribute ("width", ci->width);
  41262. }
  41263. return doc.createDocument (String::empty, true, false);
  41264. }
  41265. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41266. {
  41267. XmlDocument doc (storedVersion);
  41268. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41269. int index = 0;
  41270. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41271. {
  41272. forEachXmlChildElement (*storedXml, col)
  41273. {
  41274. const int tabId = col->getIntAttribute ("id");
  41275. ColumnInfo* const ci = getInfoForId (tabId);
  41276. if (ci != 0)
  41277. {
  41278. columns.move (columns.indexOf (ci), index);
  41279. ci->width = col->getIntAttribute ("width");
  41280. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41281. }
  41282. ++index;
  41283. }
  41284. columnsResized = true;
  41285. sendColumnsChanged();
  41286. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41287. storedXml->getBoolAttribute ("sortForwards", true));
  41288. }
  41289. }
  41290. void TableHeaderComponent::addListener (Listener* const newListener)
  41291. {
  41292. listeners.addIfNotAlreadyThere (newListener);
  41293. }
  41294. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41295. {
  41296. listeners.removeValue (listenerToRemove);
  41297. }
  41298. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41299. {
  41300. const ColumnInfo* const ci = getInfoForId (columnId);
  41301. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41302. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41303. }
  41304. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41305. {
  41306. for (int i = 0; i < columns.size(); ++i)
  41307. {
  41308. const ColumnInfo* const ci = columns.getUnchecked(i);
  41309. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41310. menu.addItem (ci->id, ci->name,
  41311. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41312. isColumnVisible (ci->id));
  41313. }
  41314. }
  41315. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41316. {
  41317. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41318. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41319. }
  41320. void TableHeaderComponent::paint (Graphics& g)
  41321. {
  41322. LookAndFeel& lf = getLookAndFeel();
  41323. lf.drawTableHeaderBackground (g, *this);
  41324. const Rectangle<int> clip (g.getClipBounds());
  41325. int x = 0;
  41326. for (int i = 0; i < columns.size(); ++i)
  41327. {
  41328. const ColumnInfo* const ci = columns.getUnchecked(i);
  41329. if (ci->isVisible())
  41330. {
  41331. if (x + ci->width > clip.getX()
  41332. && (ci->id != columnIdBeingDragged
  41333. || dragOverlayComp == 0
  41334. || ! dragOverlayComp->isVisible()))
  41335. {
  41336. g.saveState();
  41337. g.setOrigin (x, 0);
  41338. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41339. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41340. ci->id == columnIdUnderMouse,
  41341. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41342. ci->propertyFlags);
  41343. g.restoreState();
  41344. }
  41345. x += ci->width;
  41346. if (x >= clip.getRight())
  41347. break;
  41348. }
  41349. }
  41350. }
  41351. void TableHeaderComponent::resized()
  41352. {
  41353. }
  41354. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41355. {
  41356. updateColumnUnderMouse (e.x, e.y);
  41357. }
  41358. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41359. {
  41360. updateColumnUnderMouse (e.x, e.y);
  41361. }
  41362. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41363. {
  41364. updateColumnUnderMouse (e.x, e.y);
  41365. }
  41366. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41367. {
  41368. repaint();
  41369. columnIdBeingResized = 0;
  41370. columnIdBeingDragged = 0;
  41371. if (columnIdUnderMouse != 0)
  41372. {
  41373. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41374. if (e.mods.isPopupMenu())
  41375. columnClicked (columnIdUnderMouse, e.mods);
  41376. }
  41377. if (menuActive && e.mods.isPopupMenu())
  41378. showColumnChooserMenu (columnIdUnderMouse);
  41379. }
  41380. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41381. {
  41382. if (columnIdBeingResized == 0
  41383. && columnIdBeingDragged == 0
  41384. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41385. {
  41386. dragOverlayComp = 0;
  41387. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41388. if (columnIdBeingResized != 0)
  41389. {
  41390. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41391. initialColumnWidth = ci->width;
  41392. }
  41393. else
  41394. {
  41395. beginDrag (e);
  41396. }
  41397. }
  41398. if (columnIdBeingResized != 0)
  41399. {
  41400. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41401. if (ci != 0)
  41402. {
  41403. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41404. initialColumnWidth + e.getDistanceFromDragStartX());
  41405. if (stretchToFit)
  41406. {
  41407. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41408. int minWidthOnRight = 0;
  41409. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41410. if (columns.getUnchecked (i)->isVisible())
  41411. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41412. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41413. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41414. }
  41415. setColumnWidth (columnIdBeingResized, w);
  41416. }
  41417. }
  41418. else if (columnIdBeingDragged != 0)
  41419. {
  41420. if (e.y >= -50 && e.y < getHeight() + 50)
  41421. {
  41422. if (dragOverlayComp != 0)
  41423. {
  41424. dragOverlayComp->setVisible (true);
  41425. dragOverlayComp->setBounds (jlimit (0,
  41426. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41427. e.x - draggingColumnOffset),
  41428. 0,
  41429. dragOverlayComp->getWidth(),
  41430. getHeight());
  41431. for (int i = columns.size(); --i >= 0;)
  41432. {
  41433. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41434. int newIndex = currentIndex;
  41435. if (newIndex > 0)
  41436. {
  41437. // if the previous column isn't draggable, we can't move our column
  41438. // past it, because that'd change the undraggable column's position..
  41439. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41440. if ((previous->propertyFlags & draggable) != 0)
  41441. {
  41442. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41443. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41444. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41445. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41446. {
  41447. --newIndex;
  41448. }
  41449. }
  41450. }
  41451. if (newIndex < columns.size() - 1)
  41452. {
  41453. // if the next column isn't draggable, we can't move our column
  41454. // past it, because that'd change the undraggable column's position..
  41455. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41456. if ((nextCol->propertyFlags & draggable) != 0)
  41457. {
  41458. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41459. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41460. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41461. > abs (dragOverlayComp->getRight() - rightOfNext))
  41462. {
  41463. ++newIndex;
  41464. }
  41465. }
  41466. }
  41467. if (newIndex != currentIndex)
  41468. moveColumn (columnIdBeingDragged, newIndex);
  41469. else
  41470. break;
  41471. }
  41472. }
  41473. }
  41474. else
  41475. {
  41476. endDrag (draggingColumnOriginalIndex);
  41477. }
  41478. }
  41479. }
  41480. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41481. {
  41482. if (columnIdBeingDragged == 0)
  41483. {
  41484. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41485. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41486. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41487. {
  41488. columnIdBeingDragged = 0;
  41489. }
  41490. else
  41491. {
  41492. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41493. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41494. const int temp = columnIdBeingDragged;
  41495. columnIdBeingDragged = 0;
  41496. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41497. columnIdBeingDragged = temp;
  41498. dragOverlayComp->setBounds (columnRect);
  41499. for (int i = listeners.size(); --i >= 0;)
  41500. {
  41501. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41502. i = jmin (i, listeners.size() - 1);
  41503. }
  41504. }
  41505. }
  41506. }
  41507. void TableHeaderComponent::endDrag (const int finalIndex)
  41508. {
  41509. if (columnIdBeingDragged != 0)
  41510. {
  41511. moveColumn (columnIdBeingDragged, finalIndex);
  41512. columnIdBeingDragged = 0;
  41513. repaint();
  41514. for (int i = listeners.size(); --i >= 0;)
  41515. {
  41516. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41517. i = jmin (i, listeners.size() - 1);
  41518. }
  41519. }
  41520. }
  41521. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41522. {
  41523. mouseDrag (e);
  41524. for (int i = columns.size(); --i >= 0;)
  41525. if (columns.getUnchecked (i)->isVisible())
  41526. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41527. columnIdBeingResized = 0;
  41528. repaint();
  41529. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41530. updateColumnUnderMouse (e.x, e.y);
  41531. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41532. columnClicked (columnIdUnderMouse, e.mods);
  41533. dragOverlayComp = 0;
  41534. }
  41535. const MouseCursor TableHeaderComponent::getMouseCursor()
  41536. {
  41537. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41538. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41539. return Component::getMouseCursor();
  41540. }
  41541. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41542. {
  41543. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41544. }
  41545. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41546. {
  41547. for (int i = columns.size(); --i >= 0;)
  41548. if (columns.getUnchecked(i)->id == id)
  41549. return columns.getUnchecked(i);
  41550. return 0;
  41551. }
  41552. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41553. {
  41554. int n = 0;
  41555. for (int i = 0; i < columns.size(); ++i)
  41556. {
  41557. if (columns.getUnchecked(i)->isVisible())
  41558. {
  41559. if (n == visibleIndex)
  41560. return i;
  41561. ++n;
  41562. }
  41563. }
  41564. return -1;
  41565. }
  41566. void TableHeaderComponent::sendColumnsChanged()
  41567. {
  41568. if (stretchToFit && lastDeliberateWidth > 0)
  41569. resizeAllColumnsToFit (lastDeliberateWidth);
  41570. repaint();
  41571. columnsChanged = true;
  41572. triggerAsyncUpdate();
  41573. }
  41574. void TableHeaderComponent::handleAsyncUpdate()
  41575. {
  41576. const bool changed = columnsChanged || sortChanged;
  41577. const bool sized = columnsResized || changed;
  41578. const bool sorted = sortChanged;
  41579. columnsChanged = false;
  41580. columnsResized = false;
  41581. sortChanged = false;
  41582. if (sorted)
  41583. {
  41584. for (int i = listeners.size(); --i >= 0;)
  41585. {
  41586. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41587. i = jmin (i, listeners.size() - 1);
  41588. }
  41589. }
  41590. if (changed)
  41591. {
  41592. for (int i = listeners.size(); --i >= 0;)
  41593. {
  41594. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41595. i = jmin (i, listeners.size() - 1);
  41596. }
  41597. }
  41598. if (sized)
  41599. {
  41600. for (int i = listeners.size(); --i >= 0;)
  41601. {
  41602. listeners.getUnchecked(i)->tableColumnsResized (this);
  41603. i = jmin (i, listeners.size() - 1);
  41604. }
  41605. }
  41606. }
  41607. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41608. {
  41609. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41610. {
  41611. const int draggableDistance = 3;
  41612. int x = 0;
  41613. for (int i = 0; i < columns.size(); ++i)
  41614. {
  41615. const ColumnInfo* const ci = columns.getUnchecked(i);
  41616. if (ci->isVisible())
  41617. {
  41618. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41619. && (ci->propertyFlags & resizable) != 0)
  41620. return ci->id;
  41621. x += ci->width;
  41622. }
  41623. }
  41624. }
  41625. return 0;
  41626. }
  41627. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41628. {
  41629. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41630. ? getColumnIdAtX (x) : 0;
  41631. if (newCol != columnIdUnderMouse)
  41632. {
  41633. columnIdUnderMouse = newCol;
  41634. repaint();
  41635. }
  41636. }
  41637. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41638. {
  41639. PopupMenu m;
  41640. addMenuItems (m, columnIdClicked);
  41641. if (m.getNumItems() > 0)
  41642. {
  41643. m.setLookAndFeel (&getLookAndFeel());
  41644. const int result = m.show();
  41645. if (result != 0)
  41646. reactToMenuItem (result, columnIdClicked);
  41647. }
  41648. }
  41649. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41650. {
  41651. }
  41652. END_JUCE_NAMESPACE
  41653. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41654. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41655. BEGIN_JUCE_NAMESPACE
  41656. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41657. class TableListRowComp : public Component,
  41658. public TooltipClient
  41659. {
  41660. public:
  41661. TableListRowComp (TableListBox& owner_)
  41662. : owner (owner_),
  41663. row (-1),
  41664. isSelected (false)
  41665. {
  41666. }
  41667. ~TableListRowComp()
  41668. {
  41669. deleteAllChildren();
  41670. }
  41671. void paint (Graphics& g)
  41672. {
  41673. TableListBoxModel* const model = owner.getModel();
  41674. if (model != 0)
  41675. {
  41676. const TableHeaderComponent* const header = owner.getHeader();
  41677. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41678. const int numColumns = header->getNumColumns (true);
  41679. for (int i = 0; i < numColumns; ++i)
  41680. {
  41681. if (! columnsWithComponents [i])
  41682. {
  41683. const int columnId = header->getColumnIdOfIndex (i, true);
  41684. Rectangle<int> columnRect (header->getColumnPosition (i));
  41685. columnRect.setSize (columnRect.getWidth(), getHeight());
  41686. g.saveState();
  41687. g.reduceClipRegion (columnRect);
  41688. g.setOrigin (columnRect.getX(), 0);
  41689. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41690. g.restoreState();
  41691. }
  41692. }
  41693. }
  41694. }
  41695. void update (const int newRow, const bool isNowSelected)
  41696. {
  41697. if (newRow != row || isNowSelected != isSelected)
  41698. {
  41699. row = newRow;
  41700. isSelected = isNowSelected;
  41701. repaint();
  41702. deleteAllChildren();
  41703. }
  41704. if (row < owner.getNumRows())
  41705. {
  41706. jassert (row >= 0);
  41707. const Identifier tagPropertyName ("_tableLastUseNum");
  41708. const int newTag = Random::getSystemRandom().nextInt();
  41709. const TableHeaderComponent* const header = owner.getHeader();
  41710. const int numColumns = header->getNumColumns (true);
  41711. columnsWithComponents.clear();
  41712. if (owner.getModel() != 0)
  41713. {
  41714. for (int i = 0; i < numColumns; ++i)
  41715. {
  41716. const int columnId = header->getColumnIdOfIndex (i, true);
  41717. Component* const newComp
  41718. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41719. findChildComponentForColumn (columnId));
  41720. if (newComp != 0)
  41721. {
  41722. addAndMakeVisible (newComp);
  41723. newComp->getProperties().set (tagPropertyName, newTag);
  41724. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41725. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41726. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41727. columnsWithComponents.setBit (i);
  41728. }
  41729. }
  41730. }
  41731. for (int i = getNumChildComponents(); --i >= 0;)
  41732. {
  41733. Component* const c = getChildComponent (i);
  41734. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41735. delete c;
  41736. }
  41737. }
  41738. else
  41739. {
  41740. columnsWithComponents.clear();
  41741. deleteAllChildren();
  41742. }
  41743. }
  41744. void resized()
  41745. {
  41746. for (int i = getNumChildComponents(); --i >= 0;)
  41747. {
  41748. Component* const c = getChildComponent (i);
  41749. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41750. if (columnId != 0)
  41751. {
  41752. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41753. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41754. }
  41755. }
  41756. }
  41757. void mouseDown (const MouseEvent& e)
  41758. {
  41759. isDragging = false;
  41760. selectRowOnMouseUp = false;
  41761. if (isEnabled())
  41762. {
  41763. if (! isSelected)
  41764. {
  41765. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41766. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41767. if (columnId != 0 && owner.getModel() != 0)
  41768. owner.getModel()->cellClicked (row, columnId, e);
  41769. }
  41770. else
  41771. {
  41772. selectRowOnMouseUp = true;
  41773. }
  41774. }
  41775. }
  41776. void mouseDrag (const MouseEvent& e)
  41777. {
  41778. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41779. {
  41780. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41781. if (selectedRows.size() > 0)
  41782. {
  41783. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41784. if (dragDescription.isNotEmpty())
  41785. {
  41786. isDragging = true;
  41787. owner.startDragAndDrop (e, dragDescription);
  41788. }
  41789. }
  41790. }
  41791. }
  41792. void mouseUp (const MouseEvent& e)
  41793. {
  41794. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41795. {
  41796. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41797. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41798. if (columnId != 0 && owner.getModel() != 0)
  41799. owner.getModel()->cellClicked (row, columnId, e);
  41800. }
  41801. }
  41802. void mouseDoubleClick (const MouseEvent& e)
  41803. {
  41804. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41805. if (columnId != 0 && owner.getModel() != 0)
  41806. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41807. }
  41808. const String getTooltip()
  41809. {
  41810. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41811. if (columnId != 0 && owner.getModel() != 0)
  41812. return owner.getModel()->getCellTooltip (row, columnId);
  41813. return String::empty;
  41814. }
  41815. Component* findChildComponentForColumn (const int columnId) const
  41816. {
  41817. for (int i = getNumChildComponents(); --i >= 0;)
  41818. {
  41819. Component* const c = getChildComponent (i);
  41820. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41821. return c;
  41822. }
  41823. return 0;
  41824. }
  41825. juce_UseDebuggingNewOperator
  41826. private:
  41827. TableListBox& owner;
  41828. int row;
  41829. bool isSelected, isDragging, selectRowOnMouseUp;
  41830. BigInteger columnsWithComponents;
  41831. TableListRowComp (const TableListRowComp&);
  41832. TableListRowComp& operator= (const TableListRowComp&);
  41833. };
  41834. class TableListBoxHeader : public TableHeaderComponent
  41835. {
  41836. public:
  41837. TableListBoxHeader (TableListBox& owner_)
  41838. : owner (owner_)
  41839. {
  41840. }
  41841. ~TableListBoxHeader()
  41842. {
  41843. }
  41844. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41845. {
  41846. if (owner.isAutoSizeMenuOptionShown())
  41847. {
  41848. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41849. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41850. menu.addSeparator();
  41851. }
  41852. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41853. }
  41854. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41855. {
  41856. if (menuReturnId == 0xf836743)
  41857. {
  41858. owner.autoSizeColumn (columnIdClicked);
  41859. }
  41860. else if (menuReturnId == 0xf836744)
  41861. {
  41862. owner.autoSizeAllColumns();
  41863. }
  41864. else
  41865. {
  41866. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41867. }
  41868. }
  41869. juce_UseDebuggingNewOperator
  41870. private:
  41871. TableListBox& owner;
  41872. TableListBoxHeader (const TableListBoxHeader&);
  41873. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41874. };
  41875. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41876. : ListBox (name, 0),
  41877. model (model_),
  41878. autoSizeOptionsShown (true)
  41879. {
  41880. ListBox::model = this;
  41881. header = new TableListBoxHeader (*this);
  41882. header->setSize (100, 28);
  41883. header->addListener (this);
  41884. setHeaderComponent (header);
  41885. }
  41886. TableListBox::~TableListBox()
  41887. {
  41888. header = 0;
  41889. }
  41890. void TableListBox::setModel (TableListBoxModel* const newModel)
  41891. {
  41892. if (model != newModel)
  41893. {
  41894. model = newModel;
  41895. updateContent();
  41896. }
  41897. }
  41898. int TableListBox::getHeaderHeight() const
  41899. {
  41900. return header->getHeight();
  41901. }
  41902. void TableListBox::setHeaderHeight (const int newHeight)
  41903. {
  41904. header->setSize (header->getWidth(), newHeight);
  41905. resized();
  41906. }
  41907. void TableListBox::autoSizeColumn (const int columnId)
  41908. {
  41909. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41910. if (width > 0)
  41911. header->setColumnWidth (columnId, width);
  41912. }
  41913. void TableListBox::autoSizeAllColumns()
  41914. {
  41915. for (int i = 0; i < header->getNumColumns (true); ++i)
  41916. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41917. }
  41918. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41919. {
  41920. autoSizeOptionsShown = shouldBeShown;
  41921. }
  41922. bool TableListBox::isAutoSizeMenuOptionShown() const
  41923. {
  41924. return autoSizeOptionsShown;
  41925. }
  41926. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41927. const int rowNumber,
  41928. const bool relativeToComponentTopLeft) const
  41929. {
  41930. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41931. if (relativeToComponentTopLeft)
  41932. headerCell.translate (header->getX(), 0);
  41933. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41934. return Rectangle<int> (headerCell.getX(), row.getY(),
  41935. headerCell.getWidth(), row.getHeight());
  41936. }
  41937. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41938. {
  41939. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41940. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41941. }
  41942. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41943. {
  41944. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41945. if (scrollbar != 0)
  41946. {
  41947. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41948. double x = scrollbar->getCurrentRangeStart();
  41949. const double w = scrollbar->getCurrentRangeSize();
  41950. if (pos.getX() < x)
  41951. x = pos.getX();
  41952. else if (pos.getRight() > x + w)
  41953. x += jmax (0.0, pos.getRight() - (x + w));
  41954. scrollbar->setCurrentRangeStart (x);
  41955. }
  41956. }
  41957. int TableListBox::getNumRows()
  41958. {
  41959. return model != 0 ? model->getNumRows() : 0;
  41960. }
  41961. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41962. {
  41963. }
  41964. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41965. {
  41966. if (existingComponentToUpdate == 0)
  41967. existingComponentToUpdate = new TableListRowComp (*this);
  41968. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41969. return existingComponentToUpdate;
  41970. }
  41971. void TableListBox::selectedRowsChanged (int row)
  41972. {
  41973. if (model != 0)
  41974. model->selectedRowsChanged (row);
  41975. }
  41976. void TableListBox::deleteKeyPressed (int row)
  41977. {
  41978. if (model != 0)
  41979. model->deleteKeyPressed (row);
  41980. }
  41981. void TableListBox::returnKeyPressed (int row)
  41982. {
  41983. if (model != 0)
  41984. model->returnKeyPressed (row);
  41985. }
  41986. void TableListBox::backgroundClicked()
  41987. {
  41988. if (model != 0)
  41989. model->backgroundClicked();
  41990. }
  41991. void TableListBox::listWasScrolled()
  41992. {
  41993. if (model != 0)
  41994. model->listWasScrolled();
  41995. }
  41996. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41997. {
  41998. setMinimumContentWidth (header->getTotalWidth());
  41999. repaint();
  42000. updateColumnComponents();
  42001. }
  42002. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42003. {
  42004. setMinimumContentWidth (header->getTotalWidth());
  42005. repaint();
  42006. updateColumnComponents();
  42007. }
  42008. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42009. {
  42010. if (model != 0)
  42011. model->sortOrderChanged (header->getSortColumnId(),
  42012. header->isSortedForwards());
  42013. }
  42014. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42015. {
  42016. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42017. repaint();
  42018. }
  42019. void TableListBox::resized()
  42020. {
  42021. ListBox::resized();
  42022. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42023. setMinimumContentWidth (header->getTotalWidth());
  42024. }
  42025. void TableListBox::updateColumnComponents() const
  42026. {
  42027. const int firstRow = getRowContainingPosition (0, 0);
  42028. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42029. {
  42030. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42031. if (rowComp != 0)
  42032. rowComp->resized();
  42033. }
  42034. }
  42035. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42036. {
  42037. }
  42038. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42039. {
  42040. }
  42041. void TableListBoxModel::backgroundClicked()
  42042. {
  42043. }
  42044. void TableListBoxModel::sortOrderChanged (int, const bool)
  42045. {
  42046. }
  42047. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42048. {
  42049. return 0;
  42050. }
  42051. void TableListBoxModel::selectedRowsChanged (int)
  42052. {
  42053. }
  42054. void TableListBoxModel::deleteKeyPressed (int)
  42055. {
  42056. }
  42057. void TableListBoxModel::returnKeyPressed (int)
  42058. {
  42059. }
  42060. void TableListBoxModel::listWasScrolled()
  42061. {
  42062. }
  42063. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42064. {
  42065. return String::empty;
  42066. }
  42067. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42068. {
  42069. return String::empty;
  42070. }
  42071. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42072. {
  42073. (void) existingComponentToUpdate;
  42074. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42075. return 0;
  42076. }
  42077. END_JUCE_NAMESPACE
  42078. /*** End of inlined file: juce_TableListBox.cpp ***/
  42079. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42080. BEGIN_JUCE_NAMESPACE
  42081. // a word or space that can't be broken down any further
  42082. struct TextAtom
  42083. {
  42084. String atomText;
  42085. float width;
  42086. uint16 numChars;
  42087. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42088. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42089. const String getText (const juce_wchar passwordCharacter) const
  42090. {
  42091. if (passwordCharacter == 0)
  42092. return atomText;
  42093. else
  42094. return String::repeatedString (String::charToString (passwordCharacter),
  42095. atomText.length());
  42096. }
  42097. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42098. {
  42099. if (passwordCharacter == 0)
  42100. return atomText.substring (0, numChars);
  42101. else if (isNewLine())
  42102. return String::empty;
  42103. else
  42104. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42105. }
  42106. };
  42107. // a run of text with a single font and colour
  42108. class TextEditor::UniformTextSection
  42109. {
  42110. public:
  42111. UniformTextSection (const String& text,
  42112. const Font& font_,
  42113. const Colour& colour_,
  42114. const juce_wchar passwordCharacter)
  42115. : font (font_),
  42116. colour (colour_)
  42117. {
  42118. initialiseAtoms (text, passwordCharacter);
  42119. }
  42120. UniformTextSection (const UniformTextSection& other)
  42121. : font (other.font),
  42122. colour (other.colour)
  42123. {
  42124. atoms.ensureStorageAllocated (other.atoms.size());
  42125. for (int i = 0; i < other.atoms.size(); ++i)
  42126. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42127. }
  42128. ~UniformTextSection()
  42129. {
  42130. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42131. }
  42132. void clear()
  42133. {
  42134. for (int i = atoms.size(); --i >= 0;)
  42135. delete getAtom(i);
  42136. atoms.clear();
  42137. }
  42138. int getNumAtoms() const
  42139. {
  42140. return atoms.size();
  42141. }
  42142. TextAtom* getAtom (const int index) const throw()
  42143. {
  42144. return atoms.getUnchecked (index);
  42145. }
  42146. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42147. {
  42148. if (other.atoms.size() > 0)
  42149. {
  42150. TextAtom* const lastAtom = atoms.getLast();
  42151. int i = 0;
  42152. if (lastAtom != 0)
  42153. {
  42154. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42155. {
  42156. TextAtom* const first = other.getAtom(0);
  42157. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42158. {
  42159. lastAtom->atomText += first->atomText;
  42160. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42161. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42162. delete first;
  42163. ++i;
  42164. }
  42165. }
  42166. }
  42167. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42168. while (i < other.atoms.size())
  42169. {
  42170. atoms.add (other.getAtom(i));
  42171. ++i;
  42172. }
  42173. }
  42174. }
  42175. UniformTextSection* split (const int indexToBreakAt,
  42176. const juce_wchar passwordCharacter)
  42177. {
  42178. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42179. font, colour,
  42180. passwordCharacter);
  42181. int index = 0;
  42182. for (int i = 0; i < atoms.size(); ++i)
  42183. {
  42184. TextAtom* const atom = getAtom(i);
  42185. const int nextIndex = index + atom->numChars;
  42186. if (index == indexToBreakAt)
  42187. {
  42188. int j;
  42189. for (j = i; j < atoms.size(); ++j)
  42190. section2->atoms.add (getAtom (j));
  42191. for (j = atoms.size(); --j >= i;)
  42192. atoms.remove (j);
  42193. break;
  42194. }
  42195. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42196. {
  42197. TextAtom* const secondAtom = new TextAtom();
  42198. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42199. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42200. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42201. section2->atoms.add (secondAtom);
  42202. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42203. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42204. atom->numChars = (uint16) (indexToBreakAt - index);
  42205. int j;
  42206. for (j = i + 1; j < atoms.size(); ++j)
  42207. section2->atoms.add (getAtom (j));
  42208. for (j = atoms.size(); --j > i;)
  42209. atoms.remove (j);
  42210. break;
  42211. }
  42212. index = nextIndex;
  42213. }
  42214. return section2;
  42215. }
  42216. void appendAllText (String::Concatenator& concatenator) const
  42217. {
  42218. for (int i = 0; i < atoms.size(); ++i)
  42219. concatenator.append (getAtom(i)->atomText);
  42220. }
  42221. void appendSubstring (String::Concatenator& concatenator,
  42222. const Range<int>& range) const
  42223. {
  42224. int index = 0;
  42225. for (int i = 0; i < atoms.size(); ++i)
  42226. {
  42227. const TextAtom* const atom = getAtom (i);
  42228. const int nextIndex = index + atom->numChars;
  42229. if (range.getStart() < nextIndex)
  42230. {
  42231. if (range.getEnd() <= index)
  42232. break;
  42233. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42234. if (! r.isEmpty())
  42235. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42236. }
  42237. index = nextIndex;
  42238. }
  42239. }
  42240. int getTotalLength() const
  42241. {
  42242. int total = 0;
  42243. for (int i = atoms.size(); --i >= 0;)
  42244. total += getAtom(i)->numChars;
  42245. return total;
  42246. }
  42247. void setFont (const Font& newFont,
  42248. const juce_wchar passwordCharacter)
  42249. {
  42250. if (font != newFont)
  42251. {
  42252. font = newFont;
  42253. for (int i = atoms.size(); --i >= 0;)
  42254. {
  42255. TextAtom* const atom = atoms.getUnchecked(i);
  42256. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42257. }
  42258. }
  42259. }
  42260. juce_UseDebuggingNewOperator
  42261. Font font;
  42262. Colour colour;
  42263. private:
  42264. Array <TextAtom*> atoms;
  42265. void initialiseAtoms (const String& textToParse,
  42266. const juce_wchar passwordCharacter)
  42267. {
  42268. int i = 0;
  42269. const int len = textToParse.length();
  42270. const juce_wchar* const text = textToParse;
  42271. while (i < len)
  42272. {
  42273. int start = i;
  42274. // create a whitespace atom unless it starts with non-ws
  42275. if (CharacterFunctions::isWhitespace (text[i])
  42276. && text[i] != '\r'
  42277. && text[i] != '\n')
  42278. {
  42279. while (i < len
  42280. && CharacterFunctions::isWhitespace (text[i])
  42281. && text[i] != '\r'
  42282. && text[i] != '\n')
  42283. {
  42284. ++i;
  42285. }
  42286. }
  42287. else
  42288. {
  42289. if (text[i] == '\r')
  42290. {
  42291. ++i;
  42292. if ((i < len) && (text[i] == '\n'))
  42293. {
  42294. ++start;
  42295. ++i;
  42296. }
  42297. }
  42298. else if (text[i] == '\n')
  42299. {
  42300. ++i;
  42301. }
  42302. else
  42303. {
  42304. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42305. ++i;
  42306. }
  42307. }
  42308. TextAtom* const atom = new TextAtom();
  42309. atom->atomText = String (text + start, i - start);
  42310. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42311. atom->numChars = (uint16) (i - start);
  42312. atoms.add (atom);
  42313. }
  42314. }
  42315. UniformTextSection& operator= (const UniformTextSection& other);
  42316. };
  42317. class TextEditor::Iterator
  42318. {
  42319. public:
  42320. Iterator (const Array <UniformTextSection*>& sections_,
  42321. const float wordWrapWidth_,
  42322. const juce_wchar passwordCharacter_)
  42323. : indexInText (0),
  42324. lineY (0),
  42325. lineHeight (0),
  42326. maxDescent (0),
  42327. atomX (0),
  42328. atomRight (0),
  42329. atom (0),
  42330. currentSection (0),
  42331. sections (sections_),
  42332. sectionIndex (0),
  42333. atomIndex (0),
  42334. wordWrapWidth (wordWrapWidth_),
  42335. passwordCharacter (passwordCharacter_)
  42336. {
  42337. jassert (wordWrapWidth_ > 0);
  42338. if (sections.size() > 0)
  42339. {
  42340. currentSection = sections.getUnchecked (sectionIndex);
  42341. if (currentSection != 0)
  42342. beginNewLine();
  42343. }
  42344. }
  42345. Iterator (const Iterator& other)
  42346. : indexInText (other.indexInText),
  42347. lineY (other.lineY),
  42348. lineHeight (other.lineHeight),
  42349. maxDescent (other.maxDescent),
  42350. atomX (other.atomX),
  42351. atomRight (other.atomRight),
  42352. atom (other.atom),
  42353. currentSection (other.currentSection),
  42354. sections (other.sections),
  42355. sectionIndex (other.sectionIndex),
  42356. atomIndex (other.atomIndex),
  42357. wordWrapWidth (other.wordWrapWidth),
  42358. passwordCharacter (other.passwordCharacter),
  42359. tempAtom (other.tempAtom)
  42360. {
  42361. }
  42362. ~Iterator()
  42363. {
  42364. }
  42365. bool next()
  42366. {
  42367. if (atom == &tempAtom)
  42368. {
  42369. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42370. if (numRemaining > 0)
  42371. {
  42372. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42373. atomX = 0;
  42374. if (tempAtom.numChars > 0)
  42375. lineY += lineHeight;
  42376. indexInText += tempAtom.numChars;
  42377. GlyphArrangement g;
  42378. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42379. int split;
  42380. for (split = 0; split < g.getNumGlyphs(); ++split)
  42381. if (shouldWrap (g.getGlyph (split).getRight()))
  42382. break;
  42383. if (split > 0 && split <= numRemaining)
  42384. {
  42385. tempAtom.numChars = (uint16) split;
  42386. tempAtom.width = g.getGlyph (split - 1).getRight();
  42387. atomRight = atomX + tempAtom.width;
  42388. return true;
  42389. }
  42390. }
  42391. }
  42392. bool forceNewLine = false;
  42393. if (sectionIndex >= sections.size())
  42394. {
  42395. moveToEndOfLastAtom();
  42396. return false;
  42397. }
  42398. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42399. {
  42400. if (atomIndex >= currentSection->getNumAtoms())
  42401. {
  42402. if (++sectionIndex >= sections.size())
  42403. {
  42404. moveToEndOfLastAtom();
  42405. return false;
  42406. }
  42407. atomIndex = 0;
  42408. currentSection = sections.getUnchecked (sectionIndex);
  42409. }
  42410. else
  42411. {
  42412. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42413. if (! lastAtom->isWhitespace())
  42414. {
  42415. // handle the case where the last atom in a section is actually part of the same
  42416. // word as the first atom of the next section...
  42417. float right = atomRight + lastAtom->width;
  42418. float lineHeight2 = lineHeight;
  42419. float maxDescent2 = maxDescent;
  42420. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42421. {
  42422. const UniformTextSection* const s = sections.getUnchecked (section);
  42423. if (s->getNumAtoms() == 0)
  42424. break;
  42425. const TextAtom* const nextAtom = s->getAtom (0);
  42426. if (nextAtom->isWhitespace())
  42427. break;
  42428. right += nextAtom->width;
  42429. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42430. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42431. if (shouldWrap (right))
  42432. {
  42433. lineHeight = lineHeight2;
  42434. maxDescent = maxDescent2;
  42435. forceNewLine = true;
  42436. break;
  42437. }
  42438. if (s->getNumAtoms() > 1)
  42439. break;
  42440. }
  42441. }
  42442. }
  42443. }
  42444. if (atom != 0)
  42445. {
  42446. atomX = atomRight;
  42447. indexInText += atom->numChars;
  42448. if (atom->isNewLine())
  42449. beginNewLine();
  42450. }
  42451. atom = currentSection->getAtom (atomIndex);
  42452. atomRight = atomX + atom->width;
  42453. ++atomIndex;
  42454. if (shouldWrap (atomRight) || forceNewLine)
  42455. {
  42456. if (atom->isWhitespace())
  42457. {
  42458. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42459. atomRight = jmin (atomRight, wordWrapWidth);
  42460. }
  42461. else
  42462. {
  42463. atomRight = atom->width;
  42464. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42465. {
  42466. tempAtom = *atom;
  42467. tempAtom.width = 0;
  42468. tempAtom.numChars = 0;
  42469. atom = &tempAtom;
  42470. if (atomX > 0)
  42471. beginNewLine();
  42472. return next();
  42473. }
  42474. beginNewLine();
  42475. return true;
  42476. }
  42477. }
  42478. return true;
  42479. }
  42480. void beginNewLine()
  42481. {
  42482. atomX = 0;
  42483. lineY += lineHeight;
  42484. int tempSectionIndex = sectionIndex;
  42485. int tempAtomIndex = atomIndex;
  42486. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42487. lineHeight = section->font.getHeight();
  42488. maxDescent = section->font.getDescent();
  42489. float x = (atom != 0) ? atom->width : 0;
  42490. while (! shouldWrap (x))
  42491. {
  42492. if (tempSectionIndex >= sections.size())
  42493. break;
  42494. bool checkSize = false;
  42495. if (tempAtomIndex >= section->getNumAtoms())
  42496. {
  42497. if (++tempSectionIndex >= sections.size())
  42498. break;
  42499. tempAtomIndex = 0;
  42500. section = sections.getUnchecked (tempSectionIndex);
  42501. checkSize = true;
  42502. }
  42503. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42504. if (nextAtom == 0)
  42505. break;
  42506. x += nextAtom->width;
  42507. if (shouldWrap (x) || nextAtom->isNewLine())
  42508. break;
  42509. if (checkSize)
  42510. {
  42511. lineHeight = jmax (lineHeight, section->font.getHeight());
  42512. maxDescent = jmax (maxDescent, section->font.getDescent());
  42513. }
  42514. ++tempAtomIndex;
  42515. }
  42516. }
  42517. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42518. {
  42519. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42520. {
  42521. if (lastSection != currentSection)
  42522. {
  42523. lastSection = currentSection;
  42524. g.setColour (currentSection->colour);
  42525. g.setFont (currentSection->font);
  42526. }
  42527. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42528. GlyphArrangement ga;
  42529. ga.addLineOfText (currentSection->font,
  42530. atom->getTrimmedText (passwordCharacter),
  42531. atomX,
  42532. (float) roundToInt (lineY + lineHeight - maxDescent));
  42533. ga.draw (g);
  42534. }
  42535. }
  42536. void drawSelection (Graphics& g,
  42537. const Range<int>& selection) const
  42538. {
  42539. const int startX = roundToInt (indexToX (selection.getStart()));
  42540. const int endX = roundToInt (indexToX (selection.getEnd()));
  42541. const int y = roundToInt (lineY);
  42542. const int nextY = roundToInt (lineY + lineHeight);
  42543. g.fillRect (startX, y, endX - startX, nextY - y);
  42544. }
  42545. void drawSelectedText (Graphics& g,
  42546. const Range<int>& selection,
  42547. const Colour& selectedTextColour) const
  42548. {
  42549. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42550. {
  42551. GlyphArrangement ga;
  42552. ga.addLineOfText (currentSection->font,
  42553. atom->getTrimmedText (passwordCharacter),
  42554. atomX,
  42555. (float) roundToInt (lineY + lineHeight - maxDescent));
  42556. if (selection.getEnd() < indexInText + atom->numChars)
  42557. {
  42558. GlyphArrangement ga2 (ga);
  42559. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42560. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42561. g.setColour (currentSection->colour);
  42562. ga2.draw (g);
  42563. }
  42564. if (selection.getStart() > indexInText)
  42565. {
  42566. GlyphArrangement ga2 (ga);
  42567. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42568. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42569. g.setColour (currentSection->colour);
  42570. ga2.draw (g);
  42571. }
  42572. g.setColour (selectedTextColour);
  42573. ga.draw (g);
  42574. }
  42575. }
  42576. float indexToX (const int indexToFind) const
  42577. {
  42578. if (indexToFind <= indexInText)
  42579. return atomX;
  42580. if (indexToFind >= indexInText + atom->numChars)
  42581. return atomRight;
  42582. GlyphArrangement g;
  42583. g.addLineOfText (currentSection->font,
  42584. atom->getText (passwordCharacter),
  42585. atomX, 0.0f);
  42586. if (indexToFind - indexInText >= g.getNumGlyphs())
  42587. return atomRight;
  42588. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42589. }
  42590. int xToIndex (const float xToFind) const
  42591. {
  42592. if (xToFind <= atomX || atom->isNewLine())
  42593. return indexInText;
  42594. if (xToFind >= atomRight)
  42595. return indexInText + atom->numChars;
  42596. GlyphArrangement g;
  42597. g.addLineOfText (currentSection->font,
  42598. atom->getText (passwordCharacter),
  42599. atomX, 0.0f);
  42600. int j;
  42601. for (j = 0; j < g.getNumGlyphs(); ++j)
  42602. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42603. break;
  42604. return indexInText + j;
  42605. }
  42606. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42607. {
  42608. while (next())
  42609. {
  42610. if (indexInText + atom->numChars > index)
  42611. {
  42612. cx = indexToX (index);
  42613. cy = lineY;
  42614. lineHeight_ = lineHeight;
  42615. return true;
  42616. }
  42617. }
  42618. cx = atomX;
  42619. cy = lineY;
  42620. lineHeight_ = lineHeight;
  42621. return false;
  42622. }
  42623. juce_UseDebuggingNewOperator
  42624. int indexInText;
  42625. float lineY, lineHeight, maxDescent;
  42626. float atomX, atomRight;
  42627. const TextAtom* atom;
  42628. const UniformTextSection* currentSection;
  42629. private:
  42630. const Array <UniformTextSection*>& sections;
  42631. int sectionIndex, atomIndex;
  42632. const float wordWrapWidth;
  42633. const juce_wchar passwordCharacter;
  42634. TextAtom tempAtom;
  42635. Iterator& operator= (const Iterator&);
  42636. void moveToEndOfLastAtom()
  42637. {
  42638. if (atom != 0)
  42639. {
  42640. atomX = atomRight;
  42641. if (atom->isNewLine())
  42642. {
  42643. atomX = 0.0f;
  42644. lineY += lineHeight;
  42645. }
  42646. }
  42647. }
  42648. bool shouldWrap (const float x) const
  42649. {
  42650. return (x - 0.0001f) >= wordWrapWidth;
  42651. }
  42652. };
  42653. class TextEditor::InsertAction : public UndoableAction
  42654. {
  42655. TextEditor& owner;
  42656. const String text;
  42657. const int insertIndex, oldCaretPos, newCaretPos;
  42658. const Font font;
  42659. const Colour colour;
  42660. InsertAction (const InsertAction&);
  42661. InsertAction& operator= (const InsertAction&);
  42662. public:
  42663. InsertAction (TextEditor& owner_,
  42664. const String& text_,
  42665. const int insertIndex_,
  42666. const Font& font_,
  42667. const Colour& colour_,
  42668. const int oldCaretPos_,
  42669. const int newCaretPos_)
  42670. : owner (owner_),
  42671. text (text_),
  42672. insertIndex (insertIndex_),
  42673. oldCaretPos (oldCaretPos_),
  42674. newCaretPos (newCaretPos_),
  42675. font (font_),
  42676. colour (colour_)
  42677. {
  42678. }
  42679. ~InsertAction()
  42680. {
  42681. }
  42682. bool perform()
  42683. {
  42684. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42685. return true;
  42686. }
  42687. bool undo()
  42688. {
  42689. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42690. return true;
  42691. }
  42692. int getSizeInUnits()
  42693. {
  42694. return text.length() + 16;
  42695. }
  42696. };
  42697. class TextEditor::RemoveAction : public UndoableAction
  42698. {
  42699. TextEditor& owner;
  42700. const Range<int> range;
  42701. const int oldCaretPos, newCaretPos;
  42702. Array <UniformTextSection*> removedSections;
  42703. RemoveAction (const RemoveAction&);
  42704. RemoveAction& operator= (const RemoveAction&);
  42705. public:
  42706. RemoveAction (TextEditor& owner_,
  42707. const Range<int> range_,
  42708. const int oldCaretPos_,
  42709. const int newCaretPos_,
  42710. const Array <UniformTextSection*>& removedSections_)
  42711. : owner (owner_),
  42712. range (range_),
  42713. oldCaretPos (oldCaretPos_),
  42714. newCaretPos (newCaretPos_),
  42715. removedSections (removedSections_)
  42716. {
  42717. }
  42718. ~RemoveAction()
  42719. {
  42720. for (int i = removedSections.size(); --i >= 0;)
  42721. {
  42722. UniformTextSection* const section = removedSections.getUnchecked (i);
  42723. section->clear();
  42724. delete section;
  42725. }
  42726. }
  42727. bool perform()
  42728. {
  42729. owner.remove (range, 0, newCaretPos);
  42730. return true;
  42731. }
  42732. bool undo()
  42733. {
  42734. owner.reinsert (range.getStart(), removedSections);
  42735. owner.moveCursorTo (oldCaretPos, false);
  42736. return true;
  42737. }
  42738. int getSizeInUnits()
  42739. {
  42740. int n = 0;
  42741. for (int i = removedSections.size(); --i >= 0;)
  42742. n += removedSections.getUnchecked (i)->getTotalLength();
  42743. return n + 16;
  42744. }
  42745. };
  42746. class TextEditor::TextHolderComponent : public Component,
  42747. public Timer,
  42748. public Value::Listener
  42749. {
  42750. public:
  42751. TextHolderComponent (TextEditor& owner_)
  42752. : owner (owner_)
  42753. {
  42754. setWantsKeyboardFocus (false);
  42755. setInterceptsMouseClicks (false, true);
  42756. owner.getTextValue().addListener (this);
  42757. }
  42758. ~TextHolderComponent()
  42759. {
  42760. owner.getTextValue().removeListener (this);
  42761. }
  42762. void paint (Graphics& g)
  42763. {
  42764. owner.drawContent (g);
  42765. }
  42766. void timerCallback()
  42767. {
  42768. owner.timerCallbackInt();
  42769. }
  42770. const MouseCursor getMouseCursor()
  42771. {
  42772. return owner.getMouseCursor();
  42773. }
  42774. void valueChanged (Value&)
  42775. {
  42776. owner.textWasChangedByValue();
  42777. }
  42778. private:
  42779. TextEditor& owner;
  42780. TextHolderComponent (const TextHolderComponent&);
  42781. TextHolderComponent& operator= (const TextHolderComponent&);
  42782. };
  42783. class TextEditorViewport : public Viewport
  42784. {
  42785. public:
  42786. TextEditorViewport (TextEditor* const owner_)
  42787. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42788. {
  42789. }
  42790. ~TextEditorViewport()
  42791. {
  42792. }
  42793. void visibleAreaChanged (int, int, int, int)
  42794. {
  42795. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42796. // appear and disappear, causing the wrap width to change.
  42797. {
  42798. const float wordWrapWidth = owner->getWordWrapWidth();
  42799. if (wordWrapWidth != lastWordWrapWidth)
  42800. {
  42801. lastWordWrapWidth = wordWrapWidth;
  42802. rentrant = true;
  42803. owner->updateTextHolderSize();
  42804. rentrant = false;
  42805. }
  42806. }
  42807. }
  42808. private:
  42809. TextEditor* const owner;
  42810. float lastWordWrapWidth;
  42811. bool rentrant;
  42812. TextEditorViewport (const TextEditorViewport&);
  42813. TextEditorViewport& operator= (const TextEditorViewport&);
  42814. };
  42815. namespace TextEditorDefs
  42816. {
  42817. const int flashSpeedIntervalMs = 380;
  42818. const int textChangeMessageId = 0x10003001;
  42819. const int returnKeyMessageId = 0x10003002;
  42820. const int escapeKeyMessageId = 0x10003003;
  42821. const int focusLossMessageId = 0x10003004;
  42822. const int maxActionsPerTransaction = 100;
  42823. static int getCharacterCategory (const juce_wchar character)
  42824. {
  42825. return CharacterFunctions::isLetterOrDigit (character)
  42826. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42827. }
  42828. }
  42829. TextEditor::TextEditor (const String& name,
  42830. const juce_wchar passwordCharacter_)
  42831. : Component (name),
  42832. borderSize (1, 1, 1, 3),
  42833. readOnly (false),
  42834. multiline (false),
  42835. wordWrap (false),
  42836. returnKeyStartsNewLine (false),
  42837. caretVisible (true),
  42838. popupMenuEnabled (true),
  42839. selectAllTextWhenFocused (false),
  42840. scrollbarVisible (true),
  42841. wasFocused (false),
  42842. caretFlashState (true),
  42843. keepCursorOnScreen (true),
  42844. tabKeyUsed (false),
  42845. menuActive (false),
  42846. valueTextNeedsUpdating (false),
  42847. cursorX (0),
  42848. cursorY (0),
  42849. cursorHeight (0),
  42850. maxTextLength (0),
  42851. leftIndent (4),
  42852. topIndent (4),
  42853. lastTransactionTime (0),
  42854. currentFont (14.0f),
  42855. totalNumChars (0),
  42856. caretPosition (0),
  42857. passwordCharacter (passwordCharacter_),
  42858. dragType (notDragging)
  42859. {
  42860. setOpaque (true);
  42861. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42862. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42863. viewport->setWantsKeyboardFocus (false);
  42864. viewport->setScrollBarsShown (false, false);
  42865. setMouseCursor (MouseCursor::IBeamCursor);
  42866. setWantsKeyboardFocus (true);
  42867. }
  42868. TextEditor::~TextEditor()
  42869. {
  42870. textValue.referTo (Value());
  42871. clearInternal (0);
  42872. viewport = 0;
  42873. textHolder = 0;
  42874. }
  42875. void TextEditor::newTransaction()
  42876. {
  42877. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42878. undoManager.beginNewTransaction();
  42879. }
  42880. void TextEditor::doUndoRedo (const bool isRedo)
  42881. {
  42882. if (! isReadOnly())
  42883. {
  42884. if (isRedo ? undoManager.redo()
  42885. : undoManager.undo())
  42886. {
  42887. scrollToMakeSureCursorIsVisible();
  42888. repaint();
  42889. textChanged();
  42890. }
  42891. }
  42892. }
  42893. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42894. const bool shouldWordWrap)
  42895. {
  42896. if (multiline != shouldBeMultiLine
  42897. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42898. {
  42899. multiline = shouldBeMultiLine;
  42900. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42901. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42902. scrollbarVisible && multiline);
  42903. viewport->setViewPosition (0, 0);
  42904. resized();
  42905. scrollToMakeSureCursorIsVisible();
  42906. }
  42907. }
  42908. bool TextEditor::isMultiLine() const
  42909. {
  42910. return multiline;
  42911. }
  42912. void TextEditor::setScrollbarsShown (bool shown)
  42913. {
  42914. if (scrollbarVisible != shown)
  42915. {
  42916. scrollbarVisible = shown;
  42917. shown = shown && isMultiLine();
  42918. viewport->setScrollBarsShown (shown, shown);
  42919. }
  42920. }
  42921. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42922. {
  42923. if (readOnly != shouldBeReadOnly)
  42924. {
  42925. readOnly = shouldBeReadOnly;
  42926. enablementChanged();
  42927. }
  42928. }
  42929. bool TextEditor::isReadOnly() const
  42930. {
  42931. return readOnly || ! isEnabled();
  42932. }
  42933. bool TextEditor::isTextInputActive() const
  42934. {
  42935. return ! isReadOnly();
  42936. }
  42937. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42938. {
  42939. returnKeyStartsNewLine = shouldStartNewLine;
  42940. }
  42941. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42942. {
  42943. tabKeyUsed = shouldTabKeyBeUsed;
  42944. }
  42945. void TextEditor::setPopupMenuEnabled (const bool b)
  42946. {
  42947. popupMenuEnabled = b;
  42948. }
  42949. void TextEditor::setSelectAllWhenFocused (const bool b)
  42950. {
  42951. selectAllTextWhenFocused = b;
  42952. }
  42953. const Font TextEditor::getFont() const
  42954. {
  42955. return currentFont;
  42956. }
  42957. void TextEditor::setFont (const Font& newFont)
  42958. {
  42959. currentFont = newFont;
  42960. scrollToMakeSureCursorIsVisible();
  42961. }
  42962. void TextEditor::applyFontToAllText (const Font& newFont)
  42963. {
  42964. currentFont = newFont;
  42965. const Colour overallColour (findColour (textColourId));
  42966. for (int i = sections.size(); --i >= 0;)
  42967. {
  42968. UniformTextSection* const uts = sections.getUnchecked (i);
  42969. uts->setFont (newFont, passwordCharacter);
  42970. uts->colour = overallColour;
  42971. }
  42972. coalesceSimilarSections();
  42973. updateTextHolderSize();
  42974. scrollToMakeSureCursorIsVisible();
  42975. repaint();
  42976. }
  42977. void TextEditor::colourChanged()
  42978. {
  42979. setOpaque (findColour (backgroundColourId).isOpaque());
  42980. repaint();
  42981. }
  42982. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42983. {
  42984. caretVisible = shouldCaretBeVisible;
  42985. if (shouldCaretBeVisible)
  42986. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42987. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42988. : MouseCursor::NormalCursor);
  42989. }
  42990. void TextEditor::setInputRestrictions (const int maxLen,
  42991. const String& chars)
  42992. {
  42993. maxTextLength = jmax (0, maxLen);
  42994. allowedCharacters = chars;
  42995. }
  42996. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42997. {
  42998. textToShowWhenEmpty = text;
  42999. colourForTextWhenEmpty = colourToUse;
  43000. }
  43001. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43002. {
  43003. if (passwordCharacter != newPasswordCharacter)
  43004. {
  43005. passwordCharacter = newPasswordCharacter;
  43006. resized();
  43007. repaint();
  43008. }
  43009. }
  43010. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43011. {
  43012. viewport->setScrollBarThickness (newThicknessPixels);
  43013. }
  43014. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43015. {
  43016. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43017. }
  43018. void TextEditor::clear()
  43019. {
  43020. clearInternal (0);
  43021. updateTextHolderSize();
  43022. undoManager.clearUndoHistory();
  43023. }
  43024. void TextEditor::setText (const String& newText,
  43025. const bool sendTextChangeMessage)
  43026. {
  43027. const int newLength = newText.length();
  43028. if (newLength != getTotalNumChars() || getText() != newText)
  43029. {
  43030. const int oldCursorPos = caretPosition;
  43031. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43032. clearInternal (0);
  43033. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43034. // if you're adding text with line-feeds to a single-line text editor, it
  43035. // ain't gonna look right!
  43036. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43037. if (cursorWasAtEnd && ! isMultiLine())
  43038. moveCursorTo (getTotalNumChars(), false);
  43039. else
  43040. moveCursorTo (oldCursorPos, false);
  43041. if (sendTextChangeMessage)
  43042. textChanged();
  43043. updateTextHolderSize();
  43044. scrollToMakeSureCursorIsVisible();
  43045. undoManager.clearUndoHistory();
  43046. repaint();
  43047. }
  43048. }
  43049. Value& TextEditor::getTextValue()
  43050. {
  43051. if (valueTextNeedsUpdating)
  43052. {
  43053. valueTextNeedsUpdating = false;
  43054. textValue = getText();
  43055. }
  43056. return textValue;
  43057. }
  43058. void TextEditor::textWasChangedByValue()
  43059. {
  43060. if (textValue.getValueSource().getReferenceCount() > 1)
  43061. setText (textValue.getValue());
  43062. }
  43063. void TextEditor::textChanged()
  43064. {
  43065. updateTextHolderSize();
  43066. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43067. if (textValue.getValueSource().getReferenceCount() > 1)
  43068. {
  43069. valueTextNeedsUpdating = false;
  43070. textValue = getText();
  43071. }
  43072. }
  43073. void TextEditor::returnPressed()
  43074. {
  43075. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43076. }
  43077. void TextEditor::escapePressed()
  43078. {
  43079. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43080. }
  43081. void TextEditor::addListener (Listener* const newListener)
  43082. {
  43083. listeners.add (newListener);
  43084. }
  43085. void TextEditor::removeListener (Listener* const listenerToRemove)
  43086. {
  43087. listeners.remove (listenerToRemove);
  43088. }
  43089. void TextEditor::timerCallbackInt()
  43090. {
  43091. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43092. if (caretFlashState != newState)
  43093. {
  43094. caretFlashState = newState;
  43095. if (caretFlashState)
  43096. wasFocused = true;
  43097. if (caretVisible
  43098. && hasKeyboardFocus (false)
  43099. && ! isReadOnly())
  43100. {
  43101. repaintCaret();
  43102. }
  43103. }
  43104. const unsigned int now = Time::getApproximateMillisecondCounter();
  43105. if (now > lastTransactionTime + 200)
  43106. newTransaction();
  43107. }
  43108. void TextEditor::repaintCaret()
  43109. {
  43110. if (! findColour (caretColourId).isTransparent())
  43111. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43112. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43113. 4,
  43114. roundToInt (cursorHeight) + 2);
  43115. }
  43116. void TextEditor::repaintText (const Range<int>& range)
  43117. {
  43118. if (! range.isEmpty())
  43119. {
  43120. float x = 0, y = 0, lh = currentFont.getHeight();
  43121. const float wordWrapWidth = getWordWrapWidth();
  43122. if (wordWrapWidth > 0)
  43123. {
  43124. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43125. i.getCharPosition (range.getStart(), x, y, lh);
  43126. const int y1 = (int) y;
  43127. int y2;
  43128. if (range.getEnd() >= getTotalNumChars())
  43129. {
  43130. y2 = textHolder->getHeight();
  43131. }
  43132. else
  43133. {
  43134. i.getCharPosition (range.getEnd(), x, y, lh);
  43135. y2 = (int) (y + lh * 2.0f);
  43136. }
  43137. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43138. }
  43139. }
  43140. }
  43141. void TextEditor::moveCaret (int newCaretPos)
  43142. {
  43143. if (newCaretPos < 0)
  43144. newCaretPos = 0;
  43145. else if (newCaretPos > getTotalNumChars())
  43146. newCaretPos = getTotalNumChars();
  43147. if (newCaretPos != getCaretPosition())
  43148. {
  43149. repaintCaret();
  43150. caretFlashState = true;
  43151. caretPosition = newCaretPos;
  43152. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43153. scrollToMakeSureCursorIsVisible();
  43154. repaintCaret();
  43155. }
  43156. }
  43157. void TextEditor::setCaretPosition (const int newIndex)
  43158. {
  43159. moveCursorTo (newIndex, false);
  43160. }
  43161. int TextEditor::getCaretPosition() const
  43162. {
  43163. return caretPosition;
  43164. }
  43165. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43166. const int desiredCaretY)
  43167. {
  43168. updateCaretPosition();
  43169. int vx = roundToInt (cursorX) - desiredCaretX;
  43170. int vy = roundToInt (cursorY) - desiredCaretY;
  43171. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43172. {
  43173. vx += desiredCaretX - proportionOfWidth (0.2f);
  43174. }
  43175. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43176. {
  43177. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43178. }
  43179. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43180. if (! isMultiLine())
  43181. {
  43182. vy = viewport->getViewPositionY();
  43183. }
  43184. else
  43185. {
  43186. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43187. const int curH = roundToInt (cursorHeight);
  43188. if (desiredCaretY < 0)
  43189. {
  43190. vy = jmax (0, desiredCaretY + vy);
  43191. }
  43192. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43193. {
  43194. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43195. }
  43196. }
  43197. viewport->setViewPosition (vx, vy);
  43198. }
  43199. const Rectangle<int> TextEditor::getCaretRectangle()
  43200. {
  43201. updateCaretPosition();
  43202. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43203. roundToInt (cursorY) - viewport->getY(),
  43204. 1, roundToInt (cursorHeight));
  43205. }
  43206. float TextEditor::getWordWrapWidth() const
  43207. {
  43208. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43209. : 1.0e10f;
  43210. }
  43211. void TextEditor::updateTextHolderSize()
  43212. {
  43213. const float wordWrapWidth = getWordWrapWidth();
  43214. if (wordWrapWidth > 0)
  43215. {
  43216. float maxWidth = 0.0f;
  43217. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43218. while (i.next())
  43219. maxWidth = jmax (maxWidth, i.atomRight);
  43220. const int w = leftIndent + roundToInt (maxWidth);
  43221. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43222. currentFont.getHeight()));
  43223. textHolder->setSize (w + 1, h + 1);
  43224. }
  43225. }
  43226. int TextEditor::getTextWidth() const
  43227. {
  43228. return textHolder->getWidth();
  43229. }
  43230. int TextEditor::getTextHeight() const
  43231. {
  43232. return textHolder->getHeight();
  43233. }
  43234. void TextEditor::setIndents (const int newLeftIndent,
  43235. const int newTopIndent)
  43236. {
  43237. leftIndent = newLeftIndent;
  43238. topIndent = newTopIndent;
  43239. }
  43240. void TextEditor::setBorder (const BorderSize& border)
  43241. {
  43242. borderSize = border;
  43243. resized();
  43244. }
  43245. const BorderSize TextEditor::getBorder() const
  43246. {
  43247. return borderSize;
  43248. }
  43249. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43250. {
  43251. keepCursorOnScreen = shouldScrollToShowCursor;
  43252. }
  43253. void TextEditor::updateCaretPosition()
  43254. {
  43255. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43256. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43257. }
  43258. void TextEditor::scrollToMakeSureCursorIsVisible()
  43259. {
  43260. updateCaretPosition();
  43261. if (keepCursorOnScreen)
  43262. {
  43263. int x = viewport->getViewPositionX();
  43264. int y = viewport->getViewPositionY();
  43265. const int relativeCursorX = roundToInt (cursorX) - x;
  43266. const int relativeCursorY = roundToInt (cursorY) - y;
  43267. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43268. {
  43269. x += relativeCursorX - proportionOfWidth (0.2f);
  43270. }
  43271. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43272. {
  43273. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43274. }
  43275. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43276. if (! isMultiLine())
  43277. {
  43278. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43279. }
  43280. else
  43281. {
  43282. const int curH = roundToInt (cursorHeight);
  43283. if (relativeCursorY < 0)
  43284. {
  43285. y = jmax (0, relativeCursorY + y);
  43286. }
  43287. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43288. {
  43289. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43290. }
  43291. }
  43292. viewport->setViewPosition (x, y);
  43293. }
  43294. }
  43295. void TextEditor::moveCursorTo (const int newPosition,
  43296. const bool isSelecting)
  43297. {
  43298. if (isSelecting)
  43299. {
  43300. moveCaret (newPosition);
  43301. const Range<int> oldSelection (selection);
  43302. if (dragType == notDragging)
  43303. {
  43304. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43305. dragType = draggingSelectionStart;
  43306. else
  43307. dragType = draggingSelectionEnd;
  43308. }
  43309. if (dragType == draggingSelectionStart)
  43310. {
  43311. if (getCaretPosition() >= selection.getEnd())
  43312. dragType = draggingSelectionEnd;
  43313. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43314. }
  43315. else
  43316. {
  43317. if (getCaretPosition() < selection.getStart())
  43318. dragType = draggingSelectionStart;
  43319. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43320. }
  43321. repaintText (selection.getUnionWith (oldSelection));
  43322. }
  43323. else
  43324. {
  43325. dragType = notDragging;
  43326. repaintText (selection);
  43327. moveCaret (newPosition);
  43328. selection = Range<int>::emptyRange (getCaretPosition());
  43329. }
  43330. }
  43331. int TextEditor::getTextIndexAt (const int x,
  43332. const int y)
  43333. {
  43334. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43335. (float) (y + viewport->getViewPositionY() - topIndent));
  43336. }
  43337. void TextEditor::insertTextAtCaret (const String& newText_)
  43338. {
  43339. String newText (newText_);
  43340. if (allowedCharacters.isNotEmpty())
  43341. newText = newText.retainCharacters (allowedCharacters);
  43342. if ((! returnKeyStartsNewLine) && newText == "\n")
  43343. {
  43344. returnPressed();
  43345. return;
  43346. }
  43347. if (! isMultiLine())
  43348. newText = newText.replaceCharacters ("\r\n", " ");
  43349. else
  43350. newText = newText.replace ("\r\n", "\n");
  43351. const int newCaretPos = selection.getStart() + newText.length();
  43352. const int insertIndex = selection.getStart();
  43353. remove (selection, getUndoManager(),
  43354. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43355. if (maxTextLength > 0)
  43356. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43357. if (newText.isNotEmpty())
  43358. insert (newText,
  43359. insertIndex,
  43360. currentFont,
  43361. findColour (textColourId),
  43362. getUndoManager(),
  43363. newCaretPos);
  43364. textChanged();
  43365. }
  43366. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43367. {
  43368. moveCursorTo (newSelection.getStart(), false);
  43369. moveCursorTo (newSelection.getEnd(), true);
  43370. }
  43371. void TextEditor::copy()
  43372. {
  43373. if (passwordCharacter == 0)
  43374. {
  43375. const String selectedText (getHighlightedText());
  43376. if (selectedText.isNotEmpty())
  43377. SystemClipboard::copyTextToClipboard (selectedText);
  43378. }
  43379. }
  43380. void TextEditor::paste()
  43381. {
  43382. if (! isReadOnly())
  43383. {
  43384. const String clip (SystemClipboard::getTextFromClipboard());
  43385. if (clip.isNotEmpty())
  43386. insertTextAtCaret (clip);
  43387. }
  43388. }
  43389. void TextEditor::cut()
  43390. {
  43391. if (! isReadOnly())
  43392. {
  43393. moveCaret (selection.getEnd());
  43394. insertTextAtCaret (String::empty);
  43395. }
  43396. }
  43397. void TextEditor::drawContent (Graphics& g)
  43398. {
  43399. const float wordWrapWidth = getWordWrapWidth();
  43400. if (wordWrapWidth > 0)
  43401. {
  43402. g.setOrigin (leftIndent, topIndent);
  43403. const Rectangle<int> clip (g.getClipBounds());
  43404. Colour selectedTextColour;
  43405. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43406. while (i.lineY + 200.0 < clip.getY() && i.next())
  43407. {}
  43408. if (! selection.isEmpty())
  43409. {
  43410. g.setColour (findColour (highlightColourId)
  43411. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43412. selectedTextColour = findColour (highlightedTextColourId);
  43413. Iterator i2 (i);
  43414. while (i2.next() && i2.lineY < clip.getBottom())
  43415. {
  43416. if (i2.lineY + i2.lineHeight >= clip.getY()
  43417. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43418. {
  43419. i2.drawSelection (g, selection);
  43420. }
  43421. }
  43422. }
  43423. const UniformTextSection* lastSection = 0;
  43424. while (i.next() && i.lineY < clip.getBottom())
  43425. {
  43426. if (i.lineY + i.lineHeight >= clip.getY())
  43427. {
  43428. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43429. {
  43430. i.drawSelectedText (g, selection, selectedTextColour);
  43431. lastSection = 0;
  43432. }
  43433. else
  43434. {
  43435. i.draw (g, lastSection);
  43436. }
  43437. }
  43438. }
  43439. }
  43440. }
  43441. void TextEditor::paint (Graphics& g)
  43442. {
  43443. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43444. }
  43445. void TextEditor::paintOverChildren (Graphics& g)
  43446. {
  43447. if (caretFlashState
  43448. && hasKeyboardFocus (false)
  43449. && caretVisible
  43450. && ! isReadOnly())
  43451. {
  43452. g.setColour (findColour (caretColourId));
  43453. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43454. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43455. 2.0f, cursorHeight);
  43456. }
  43457. if (textToShowWhenEmpty.isNotEmpty()
  43458. && (! hasKeyboardFocus (false))
  43459. && getTotalNumChars() == 0)
  43460. {
  43461. g.setColour (colourForTextWhenEmpty);
  43462. g.setFont (getFont());
  43463. if (isMultiLine())
  43464. {
  43465. g.drawText (textToShowWhenEmpty,
  43466. 0, 0, getWidth(), getHeight(),
  43467. Justification::centred, true);
  43468. }
  43469. else
  43470. {
  43471. g.drawText (textToShowWhenEmpty,
  43472. leftIndent, topIndent,
  43473. viewport->getWidth() - leftIndent,
  43474. viewport->getHeight() - topIndent,
  43475. Justification::centredLeft, true);
  43476. }
  43477. }
  43478. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43479. }
  43480. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43481. {
  43482. public:
  43483. TextEditorMenuPerformer (TextEditor* const editor_)
  43484. : editor (editor_)
  43485. {
  43486. }
  43487. void modalStateFinished (int returnValue)
  43488. {
  43489. if (editor != 0 && returnValue != 0)
  43490. editor->performPopupMenuAction (returnValue);
  43491. }
  43492. private:
  43493. Component::SafePointer<TextEditor> editor;
  43494. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43495. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43496. };
  43497. void TextEditor::mouseDown (const MouseEvent& e)
  43498. {
  43499. beginDragAutoRepeat (100);
  43500. newTransaction();
  43501. if (wasFocused || ! selectAllTextWhenFocused)
  43502. {
  43503. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43504. {
  43505. moveCursorTo (getTextIndexAt (e.x, e.y),
  43506. e.mods.isShiftDown());
  43507. }
  43508. else
  43509. {
  43510. PopupMenu m;
  43511. m.setLookAndFeel (&getLookAndFeel());
  43512. addPopupMenuItems (m, &e);
  43513. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43514. }
  43515. }
  43516. }
  43517. void TextEditor::mouseDrag (const MouseEvent& e)
  43518. {
  43519. if (wasFocused || ! selectAllTextWhenFocused)
  43520. {
  43521. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43522. {
  43523. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43524. }
  43525. }
  43526. }
  43527. void TextEditor::mouseUp (const MouseEvent& e)
  43528. {
  43529. newTransaction();
  43530. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43531. if (wasFocused || ! selectAllTextWhenFocused)
  43532. {
  43533. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43534. {
  43535. moveCaret (getTextIndexAt (e.x, e.y));
  43536. }
  43537. }
  43538. wasFocused = true;
  43539. }
  43540. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43541. {
  43542. int tokenEnd = getTextIndexAt (e.x, e.y);
  43543. int tokenStart = tokenEnd;
  43544. if (e.getNumberOfClicks() > 3)
  43545. {
  43546. tokenStart = 0;
  43547. tokenEnd = getTotalNumChars();
  43548. }
  43549. else
  43550. {
  43551. const String t (getText());
  43552. const int totalLength = getTotalNumChars();
  43553. while (tokenEnd < totalLength)
  43554. {
  43555. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43556. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43557. ++tokenEnd;
  43558. else
  43559. break;
  43560. }
  43561. tokenStart = tokenEnd;
  43562. while (tokenStart > 0)
  43563. {
  43564. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43565. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43566. --tokenStart;
  43567. else
  43568. break;
  43569. }
  43570. if (e.getNumberOfClicks() > 2)
  43571. {
  43572. while (tokenEnd < totalLength)
  43573. {
  43574. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43575. ++tokenEnd;
  43576. else
  43577. break;
  43578. }
  43579. while (tokenStart > 0)
  43580. {
  43581. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43582. --tokenStart;
  43583. else
  43584. break;
  43585. }
  43586. }
  43587. }
  43588. moveCursorTo (tokenEnd, false);
  43589. moveCursorTo (tokenStart, true);
  43590. }
  43591. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43592. {
  43593. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43594. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43595. }
  43596. bool TextEditor::keyPressed (const KeyPress& key)
  43597. {
  43598. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43599. return false;
  43600. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43601. if (key.isKeyCode (KeyPress::leftKey)
  43602. || key.isKeyCode (KeyPress::upKey))
  43603. {
  43604. newTransaction();
  43605. int newPos;
  43606. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43607. newPos = indexAtPosition (cursorX, cursorY - 1);
  43608. else if (moveInWholeWordSteps)
  43609. newPos = findWordBreakBefore (getCaretPosition());
  43610. else
  43611. newPos = getCaretPosition() - 1;
  43612. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43613. }
  43614. else if (key.isKeyCode (KeyPress::rightKey)
  43615. || key.isKeyCode (KeyPress::downKey))
  43616. {
  43617. newTransaction();
  43618. int newPos;
  43619. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43620. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43621. else if (moveInWholeWordSteps)
  43622. newPos = findWordBreakAfter (getCaretPosition());
  43623. else
  43624. newPos = getCaretPosition() + 1;
  43625. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43626. }
  43627. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43628. {
  43629. newTransaction();
  43630. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43631. key.getModifiers().isShiftDown());
  43632. }
  43633. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43634. {
  43635. newTransaction();
  43636. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43637. key.getModifiers().isShiftDown());
  43638. }
  43639. else if (key.isKeyCode (KeyPress::homeKey))
  43640. {
  43641. newTransaction();
  43642. if (isMultiLine() && ! moveInWholeWordSteps)
  43643. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43644. key.getModifiers().isShiftDown());
  43645. else
  43646. moveCursorTo (0, key.getModifiers().isShiftDown());
  43647. }
  43648. else if (key.isKeyCode (KeyPress::endKey))
  43649. {
  43650. newTransaction();
  43651. if (isMultiLine() && ! moveInWholeWordSteps)
  43652. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43653. key.getModifiers().isShiftDown());
  43654. else
  43655. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43656. }
  43657. else if (key.isKeyCode (KeyPress::backspaceKey))
  43658. {
  43659. if (moveInWholeWordSteps)
  43660. {
  43661. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43662. }
  43663. else
  43664. {
  43665. if (selection.isEmpty() && selection.getStart() > 0)
  43666. selection.setStart (selection.getEnd() - 1);
  43667. }
  43668. cut();
  43669. }
  43670. else if (key.isKeyCode (KeyPress::deleteKey))
  43671. {
  43672. if (key.getModifiers().isShiftDown())
  43673. copy();
  43674. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43675. selection.setEnd (selection.getStart() + 1);
  43676. cut();
  43677. }
  43678. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43679. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43680. {
  43681. newTransaction();
  43682. copy();
  43683. }
  43684. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43685. {
  43686. newTransaction();
  43687. copy();
  43688. cut();
  43689. }
  43690. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43691. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43692. {
  43693. newTransaction();
  43694. paste();
  43695. }
  43696. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43697. {
  43698. newTransaction();
  43699. doUndoRedo (false);
  43700. }
  43701. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43702. {
  43703. newTransaction();
  43704. doUndoRedo (true);
  43705. }
  43706. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43707. {
  43708. newTransaction();
  43709. moveCursorTo (getTotalNumChars(), false);
  43710. moveCursorTo (0, true);
  43711. }
  43712. else if (key == KeyPress::returnKey)
  43713. {
  43714. newTransaction();
  43715. insertTextAtCaret ("\n");
  43716. }
  43717. else if (key.isKeyCode (KeyPress::escapeKey))
  43718. {
  43719. newTransaction();
  43720. moveCursorTo (getCaretPosition(), false);
  43721. escapePressed();
  43722. }
  43723. else if (key.getTextCharacter() >= ' '
  43724. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43725. {
  43726. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43727. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43728. }
  43729. else
  43730. {
  43731. return false;
  43732. }
  43733. return true;
  43734. }
  43735. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43736. {
  43737. if (! isKeyDown)
  43738. return false;
  43739. #if JUCE_WINDOWS
  43740. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43741. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43742. #endif
  43743. // (overridden to avoid forwarding key events to the parent)
  43744. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43745. }
  43746. const int baseMenuItemID = 0x7fff0000;
  43747. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43748. {
  43749. const bool writable = ! isReadOnly();
  43750. if (passwordCharacter == 0)
  43751. {
  43752. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43753. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43754. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43755. }
  43756. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43757. m.addSeparator();
  43758. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43759. m.addSeparator();
  43760. if (getUndoManager() != 0)
  43761. {
  43762. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43763. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43764. }
  43765. }
  43766. void TextEditor::performPopupMenuAction (const int menuItemID)
  43767. {
  43768. switch (menuItemID)
  43769. {
  43770. case baseMenuItemID + 1:
  43771. copy();
  43772. cut();
  43773. break;
  43774. case baseMenuItemID + 2:
  43775. copy();
  43776. break;
  43777. case baseMenuItemID + 3:
  43778. paste();
  43779. break;
  43780. case baseMenuItemID + 4:
  43781. cut();
  43782. break;
  43783. case baseMenuItemID + 5:
  43784. moveCursorTo (getTotalNumChars(), false);
  43785. moveCursorTo (0, true);
  43786. break;
  43787. case baseMenuItemID + 6:
  43788. doUndoRedo (false);
  43789. break;
  43790. case baseMenuItemID + 7:
  43791. doUndoRedo (true);
  43792. break;
  43793. default:
  43794. break;
  43795. }
  43796. }
  43797. void TextEditor::focusGained (FocusChangeType)
  43798. {
  43799. newTransaction();
  43800. caretFlashState = true;
  43801. if (selectAllTextWhenFocused)
  43802. {
  43803. moveCursorTo (0, false);
  43804. moveCursorTo (getTotalNumChars(), true);
  43805. }
  43806. repaint();
  43807. if (caretVisible)
  43808. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43809. ComponentPeer* const peer = getPeer();
  43810. if (peer != 0 && ! isReadOnly())
  43811. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43812. }
  43813. void TextEditor::focusLost (FocusChangeType)
  43814. {
  43815. newTransaction();
  43816. wasFocused = false;
  43817. textHolder->stopTimer();
  43818. caretFlashState = false;
  43819. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43820. repaint();
  43821. }
  43822. void TextEditor::resized()
  43823. {
  43824. viewport->setBoundsInset (borderSize);
  43825. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43826. updateTextHolderSize();
  43827. if (! isMultiLine())
  43828. {
  43829. scrollToMakeSureCursorIsVisible();
  43830. }
  43831. else
  43832. {
  43833. updateCaretPosition();
  43834. }
  43835. }
  43836. void TextEditor::handleCommandMessage (const int commandId)
  43837. {
  43838. Component::BailOutChecker checker (this);
  43839. switch (commandId)
  43840. {
  43841. case TextEditorDefs::textChangeMessageId:
  43842. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43843. break;
  43844. case TextEditorDefs::returnKeyMessageId:
  43845. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43846. break;
  43847. case TextEditorDefs::escapeKeyMessageId:
  43848. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43849. break;
  43850. case TextEditorDefs::focusLossMessageId:
  43851. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43852. break;
  43853. default:
  43854. jassertfalse;
  43855. break;
  43856. }
  43857. }
  43858. void TextEditor::enablementChanged()
  43859. {
  43860. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43861. : MouseCursor::IBeamCursor);
  43862. repaint();
  43863. }
  43864. UndoManager* TextEditor::getUndoManager() throw()
  43865. {
  43866. return isReadOnly() ? 0 : &undoManager;
  43867. }
  43868. void TextEditor::clearInternal (UndoManager* const um)
  43869. {
  43870. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43871. }
  43872. void TextEditor::insert (const String& text,
  43873. const int insertIndex,
  43874. const Font& font,
  43875. const Colour& colour,
  43876. UndoManager* const um,
  43877. const int caretPositionToMoveTo)
  43878. {
  43879. if (text.isNotEmpty())
  43880. {
  43881. if (um != 0)
  43882. {
  43883. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43884. newTransaction();
  43885. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43886. caretPosition, caretPositionToMoveTo));
  43887. }
  43888. else
  43889. {
  43890. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43891. // a line gets moved due to word wrap
  43892. int index = 0;
  43893. int nextIndex = 0;
  43894. for (int i = 0; i < sections.size(); ++i)
  43895. {
  43896. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43897. if (insertIndex == index)
  43898. {
  43899. sections.insert (i, new UniformTextSection (text,
  43900. font, colour,
  43901. passwordCharacter));
  43902. break;
  43903. }
  43904. else if (insertIndex > index && insertIndex < nextIndex)
  43905. {
  43906. splitSection (i, insertIndex - index);
  43907. sections.insert (i + 1, new UniformTextSection (text,
  43908. font, colour,
  43909. passwordCharacter));
  43910. break;
  43911. }
  43912. index = nextIndex;
  43913. }
  43914. if (nextIndex == insertIndex)
  43915. sections.add (new UniformTextSection (text,
  43916. font, colour,
  43917. passwordCharacter));
  43918. coalesceSimilarSections();
  43919. totalNumChars = -1;
  43920. valueTextNeedsUpdating = true;
  43921. moveCursorTo (caretPositionToMoveTo, false);
  43922. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43923. }
  43924. }
  43925. }
  43926. void TextEditor::reinsert (const int insertIndex,
  43927. const Array <UniformTextSection*>& sectionsToInsert)
  43928. {
  43929. int index = 0;
  43930. int nextIndex = 0;
  43931. for (int i = 0; i < sections.size(); ++i)
  43932. {
  43933. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43934. if (insertIndex == index)
  43935. {
  43936. for (int j = sectionsToInsert.size(); --j >= 0;)
  43937. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43938. break;
  43939. }
  43940. else if (insertIndex > index && insertIndex < nextIndex)
  43941. {
  43942. splitSection (i, insertIndex - index);
  43943. for (int j = sectionsToInsert.size(); --j >= 0;)
  43944. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43945. break;
  43946. }
  43947. index = nextIndex;
  43948. }
  43949. if (nextIndex == insertIndex)
  43950. {
  43951. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43952. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43953. }
  43954. coalesceSimilarSections();
  43955. totalNumChars = -1;
  43956. valueTextNeedsUpdating = true;
  43957. }
  43958. void TextEditor::remove (const Range<int>& range,
  43959. UndoManager* const um,
  43960. const int caretPositionToMoveTo)
  43961. {
  43962. if (! range.isEmpty())
  43963. {
  43964. int index = 0;
  43965. for (int i = 0; i < sections.size(); ++i)
  43966. {
  43967. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43968. if (range.getStart() > index && range.getStart() < nextIndex)
  43969. {
  43970. splitSection (i, range.getStart() - index);
  43971. --i;
  43972. }
  43973. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43974. {
  43975. splitSection (i, range.getEnd() - index);
  43976. --i;
  43977. }
  43978. else
  43979. {
  43980. index = nextIndex;
  43981. if (index > range.getEnd())
  43982. break;
  43983. }
  43984. }
  43985. index = 0;
  43986. if (um != 0)
  43987. {
  43988. Array <UniformTextSection*> removedSections;
  43989. for (int i = 0; i < sections.size(); ++i)
  43990. {
  43991. if (range.getEnd() <= range.getStart())
  43992. break;
  43993. UniformTextSection* const section = sections.getUnchecked (i);
  43994. const int nextIndex = index + section->getTotalLength();
  43995. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43996. removedSections.add (new UniformTextSection (*section));
  43997. index = nextIndex;
  43998. }
  43999. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44000. newTransaction();
  44001. um->perform (new RemoveAction (*this, range, caretPosition,
  44002. caretPositionToMoveTo, removedSections));
  44003. }
  44004. else
  44005. {
  44006. Range<int> remainingRange (range);
  44007. for (int i = 0; i < sections.size(); ++i)
  44008. {
  44009. UniformTextSection* const section = sections.getUnchecked (i);
  44010. const int nextIndex = index + section->getTotalLength();
  44011. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44012. {
  44013. sections.remove(i);
  44014. section->clear();
  44015. delete section;
  44016. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44017. if (remainingRange.isEmpty())
  44018. break;
  44019. --i;
  44020. }
  44021. else
  44022. {
  44023. index = nextIndex;
  44024. }
  44025. }
  44026. coalesceSimilarSections();
  44027. totalNumChars = -1;
  44028. valueTextNeedsUpdating = true;
  44029. moveCursorTo (caretPositionToMoveTo, false);
  44030. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44031. }
  44032. }
  44033. }
  44034. const String TextEditor::getText() const
  44035. {
  44036. String t;
  44037. t.preallocateStorage (getTotalNumChars());
  44038. String::Concatenator concatenator (t);
  44039. for (int i = 0; i < sections.size(); ++i)
  44040. sections.getUnchecked (i)->appendAllText (concatenator);
  44041. return t;
  44042. }
  44043. const String TextEditor::getTextInRange (const Range<int>& range) const
  44044. {
  44045. String t;
  44046. if (! range.isEmpty())
  44047. {
  44048. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44049. String::Concatenator concatenator (t);
  44050. int index = 0;
  44051. for (int i = 0; i < sections.size(); ++i)
  44052. {
  44053. const UniformTextSection* const s = sections.getUnchecked (i);
  44054. const int nextIndex = index + s->getTotalLength();
  44055. if (range.getStart() < nextIndex)
  44056. {
  44057. if (range.getEnd() <= index)
  44058. break;
  44059. s->appendSubstring (concatenator, range - index);
  44060. }
  44061. index = nextIndex;
  44062. }
  44063. }
  44064. return t;
  44065. }
  44066. const String TextEditor::getHighlightedText() const
  44067. {
  44068. return getTextInRange (selection);
  44069. }
  44070. int TextEditor::getTotalNumChars() const
  44071. {
  44072. if (totalNumChars < 0)
  44073. {
  44074. totalNumChars = 0;
  44075. for (int i = sections.size(); --i >= 0;)
  44076. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44077. }
  44078. return totalNumChars;
  44079. }
  44080. bool TextEditor::isEmpty() const
  44081. {
  44082. return getTotalNumChars() == 0;
  44083. }
  44084. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44085. {
  44086. const float wordWrapWidth = getWordWrapWidth();
  44087. if (wordWrapWidth > 0 && sections.size() > 0)
  44088. {
  44089. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44090. i.getCharPosition (index, cx, cy, lineHeight);
  44091. }
  44092. else
  44093. {
  44094. cx = cy = 0;
  44095. lineHeight = currentFont.getHeight();
  44096. }
  44097. }
  44098. int TextEditor::indexAtPosition (const float x, const float y)
  44099. {
  44100. const float wordWrapWidth = getWordWrapWidth();
  44101. if (wordWrapWidth > 0)
  44102. {
  44103. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44104. while (i.next())
  44105. {
  44106. if (i.lineY + i.lineHeight > y)
  44107. {
  44108. if (i.lineY > y)
  44109. return jmax (0, i.indexInText - 1);
  44110. if (i.atomX >= x)
  44111. return i.indexInText;
  44112. if (x < i.atomRight)
  44113. return i.xToIndex (x);
  44114. }
  44115. }
  44116. }
  44117. return getTotalNumChars();
  44118. }
  44119. int TextEditor::findWordBreakAfter (const int position) const
  44120. {
  44121. const String t (getTextInRange (Range<int> (position, position + 512)));
  44122. const int totalLength = t.length();
  44123. int i = 0;
  44124. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44125. ++i;
  44126. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44127. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44128. ++i;
  44129. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44130. ++i;
  44131. return position + i;
  44132. }
  44133. int TextEditor::findWordBreakBefore (const int position) const
  44134. {
  44135. if (position <= 0)
  44136. return 0;
  44137. const int startOfBuffer = jmax (0, position - 512);
  44138. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44139. int i = position - startOfBuffer;
  44140. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44141. --i;
  44142. if (i > 0)
  44143. {
  44144. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44145. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44146. --i;
  44147. }
  44148. jassert (startOfBuffer + i >= 0);
  44149. return startOfBuffer + i;
  44150. }
  44151. void TextEditor::splitSection (const int sectionIndex,
  44152. const int charToSplitAt)
  44153. {
  44154. jassert (sections[sectionIndex] != 0);
  44155. sections.insert (sectionIndex + 1,
  44156. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44157. }
  44158. void TextEditor::coalesceSimilarSections()
  44159. {
  44160. for (int i = 0; i < sections.size() - 1; ++i)
  44161. {
  44162. UniformTextSection* const s1 = sections.getUnchecked (i);
  44163. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44164. if (s1->font == s2->font
  44165. && s1->colour == s2->colour)
  44166. {
  44167. s1->append (*s2, passwordCharacter);
  44168. sections.remove (i + 1);
  44169. delete s2;
  44170. --i;
  44171. }
  44172. }
  44173. }
  44174. END_JUCE_NAMESPACE
  44175. /*** End of inlined file: juce_TextEditor.cpp ***/
  44176. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44177. BEGIN_JUCE_NAMESPACE
  44178. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44179. class ToolbarSpacerComp : public ToolbarItemComponent
  44180. {
  44181. public:
  44182. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44183. : ToolbarItemComponent (itemId_, String::empty, false),
  44184. fixedSize (fixedSize_),
  44185. drawBar (drawBar_)
  44186. {
  44187. }
  44188. ~ToolbarSpacerComp()
  44189. {
  44190. }
  44191. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44192. int& preferredSize, int& minSize, int& maxSize)
  44193. {
  44194. if (fixedSize <= 0)
  44195. {
  44196. preferredSize = toolbarThickness * 2;
  44197. minSize = 4;
  44198. maxSize = 32768;
  44199. }
  44200. else
  44201. {
  44202. maxSize = roundToInt (toolbarThickness * fixedSize);
  44203. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44204. preferredSize = maxSize;
  44205. if (getEditingMode() == editableOnPalette)
  44206. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44207. }
  44208. return true;
  44209. }
  44210. void paintButtonArea (Graphics&, int, int, bool, bool)
  44211. {
  44212. }
  44213. void contentAreaChanged (const Rectangle<int>&)
  44214. {
  44215. }
  44216. int getResizeOrder() const throw()
  44217. {
  44218. return fixedSize <= 0 ? 0 : 1;
  44219. }
  44220. void paint (Graphics& g)
  44221. {
  44222. const int w = getWidth();
  44223. const int h = getHeight();
  44224. if (drawBar)
  44225. {
  44226. g.setColour (findColour (Toolbar::separatorColourId, true));
  44227. const float thickness = 0.2f;
  44228. if (isToolbarVertical())
  44229. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44230. else
  44231. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44232. }
  44233. if (getEditingMode() != normalMode && ! drawBar)
  44234. {
  44235. g.setColour (findColour (Toolbar::separatorColourId, true));
  44236. const int indentX = jmin (2, (w - 3) / 2);
  44237. const int indentY = jmin (2, (h - 3) / 2);
  44238. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44239. if (fixedSize <= 0)
  44240. {
  44241. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44242. if (isToolbarVertical())
  44243. {
  44244. x1 = w * 0.5f;
  44245. y1 = h * 0.4f;
  44246. x2 = x1;
  44247. y2 = indentX * 2.0f;
  44248. x3 = x1;
  44249. y3 = h * 0.6f;
  44250. x4 = x1;
  44251. y4 = h - y2;
  44252. hw = w * 0.15f;
  44253. hl = w * 0.2f;
  44254. }
  44255. else
  44256. {
  44257. x1 = w * 0.4f;
  44258. y1 = h * 0.5f;
  44259. x2 = indentX * 2.0f;
  44260. y2 = y1;
  44261. x3 = w * 0.6f;
  44262. y3 = y1;
  44263. x4 = w - x2;
  44264. y4 = y1;
  44265. hw = h * 0.15f;
  44266. hl = h * 0.2f;
  44267. }
  44268. Path p;
  44269. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44270. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44271. g.fillPath (p);
  44272. }
  44273. }
  44274. }
  44275. juce_UseDebuggingNewOperator
  44276. private:
  44277. const float fixedSize;
  44278. const bool drawBar;
  44279. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44280. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44281. };
  44282. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44283. {
  44284. public:
  44285. MissingItemsComponent (Toolbar& owner_, const int height_)
  44286. : PopupMenuCustomComponent (true),
  44287. owner (owner_),
  44288. height (height_)
  44289. {
  44290. for (int i = owner_.items.size(); --i >= 0;)
  44291. {
  44292. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44293. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44294. {
  44295. oldIndexes.insert (0, i);
  44296. addAndMakeVisible (tc, 0);
  44297. }
  44298. }
  44299. layout (400);
  44300. }
  44301. ~MissingItemsComponent()
  44302. {
  44303. // deleting the toolbar while its menu it open??
  44304. jassert (owner.isValidComponent());
  44305. for (int i = 0; i < getNumChildComponents(); ++i)
  44306. {
  44307. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44308. if (tc != 0)
  44309. {
  44310. tc->setVisible (false);
  44311. const int index = oldIndexes.remove (i);
  44312. owner.addChildComponent (tc, index);
  44313. --i;
  44314. }
  44315. }
  44316. owner.resized();
  44317. }
  44318. void layout (const int preferredWidth)
  44319. {
  44320. const int indent = 8;
  44321. int x = indent;
  44322. int y = indent;
  44323. int maxX = 0;
  44324. for (int i = 0; i < getNumChildComponents(); ++i)
  44325. {
  44326. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44327. if (tc != 0)
  44328. {
  44329. int preferredSize = 1, minSize = 1, maxSize = 1;
  44330. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44331. {
  44332. if (x + preferredSize > preferredWidth && x > indent)
  44333. {
  44334. x = indent;
  44335. y += height;
  44336. }
  44337. tc->setBounds (x, y, preferredSize, height);
  44338. x += preferredSize;
  44339. maxX = jmax (maxX, x);
  44340. }
  44341. }
  44342. }
  44343. setSize (maxX + 8, y + height + 8);
  44344. }
  44345. void getIdealSize (int& idealWidth, int& idealHeight)
  44346. {
  44347. idealWidth = getWidth();
  44348. idealHeight = getHeight();
  44349. }
  44350. juce_UseDebuggingNewOperator
  44351. private:
  44352. Toolbar& owner;
  44353. const int height;
  44354. Array <int> oldIndexes;
  44355. MissingItemsComponent (const MissingItemsComponent&);
  44356. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44357. };
  44358. Toolbar::Toolbar()
  44359. : vertical (false),
  44360. isEditingActive (false),
  44361. toolbarStyle (Toolbar::iconsOnly)
  44362. {
  44363. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44364. missingItemsButton->setAlwaysOnTop (true);
  44365. missingItemsButton->addButtonListener (this);
  44366. }
  44367. Toolbar::~Toolbar()
  44368. {
  44369. animator.cancelAllAnimations (true);
  44370. deleteAllChildren();
  44371. }
  44372. void Toolbar::setVertical (const bool shouldBeVertical)
  44373. {
  44374. if (vertical != shouldBeVertical)
  44375. {
  44376. vertical = shouldBeVertical;
  44377. resized();
  44378. }
  44379. }
  44380. void Toolbar::clear()
  44381. {
  44382. for (int i = items.size(); --i >= 0;)
  44383. {
  44384. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44385. items.remove (i);
  44386. delete tc;
  44387. }
  44388. resized();
  44389. }
  44390. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44391. {
  44392. if (itemId == ToolbarItemFactory::separatorBarId)
  44393. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44394. else if (itemId == ToolbarItemFactory::spacerId)
  44395. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44396. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44397. return new ToolbarSpacerComp (itemId, 0, false);
  44398. return factory.createItem (itemId);
  44399. }
  44400. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44401. const int itemId,
  44402. const int insertIndex)
  44403. {
  44404. // An ID can't be zero - this might indicate a mistake somewhere?
  44405. jassert (itemId != 0);
  44406. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44407. if (tc != 0)
  44408. {
  44409. #if JUCE_DEBUG
  44410. Array <int> allowedIds;
  44411. factory.getAllToolbarItemIds (allowedIds);
  44412. // If your factory can create an item for a given ID, it must also return
  44413. // that ID from its getAllToolbarItemIds() method!
  44414. jassert (allowedIds.contains (itemId));
  44415. #endif
  44416. items.insert (insertIndex, tc);
  44417. addAndMakeVisible (tc, insertIndex);
  44418. }
  44419. }
  44420. void Toolbar::addItem (ToolbarItemFactory& factory,
  44421. const int itemId,
  44422. const int insertIndex)
  44423. {
  44424. addItemInternal (factory, itemId, insertIndex);
  44425. resized();
  44426. }
  44427. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44428. {
  44429. Array <int> ids;
  44430. factoryToUse.getDefaultItemSet (ids);
  44431. clear();
  44432. for (int i = 0; i < ids.size(); ++i)
  44433. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44434. resized();
  44435. }
  44436. void Toolbar::removeToolbarItem (const int itemIndex)
  44437. {
  44438. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44439. if (tc != 0)
  44440. {
  44441. items.removeValue (tc);
  44442. delete tc;
  44443. resized();
  44444. }
  44445. }
  44446. int Toolbar::getNumItems() const throw()
  44447. {
  44448. return items.size();
  44449. }
  44450. int Toolbar::getItemId (const int itemIndex) const throw()
  44451. {
  44452. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44453. return tc != 0 ? tc->getItemId() : 0;
  44454. }
  44455. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44456. {
  44457. return items [itemIndex];
  44458. }
  44459. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44460. {
  44461. for (;;)
  44462. {
  44463. index += delta;
  44464. ToolbarItemComponent* const tc = getItemComponent (index);
  44465. if (tc == 0)
  44466. break;
  44467. if (tc->isActive)
  44468. return tc;
  44469. }
  44470. return 0;
  44471. }
  44472. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44473. {
  44474. if (toolbarStyle != newStyle)
  44475. {
  44476. toolbarStyle = newStyle;
  44477. updateAllItemPositions (false);
  44478. }
  44479. }
  44480. const String Toolbar::toString() const
  44481. {
  44482. String s ("TB:");
  44483. for (int i = 0; i < getNumItems(); ++i)
  44484. s << getItemId(i) << ' ';
  44485. return s.trimEnd();
  44486. }
  44487. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44488. const String& savedVersion)
  44489. {
  44490. if (! savedVersion.startsWith ("TB:"))
  44491. return false;
  44492. StringArray tokens;
  44493. tokens.addTokens (savedVersion.substring (3), false);
  44494. clear();
  44495. for (int i = 0; i < tokens.size(); ++i)
  44496. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44497. resized();
  44498. return true;
  44499. }
  44500. void Toolbar::paint (Graphics& g)
  44501. {
  44502. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44503. }
  44504. int Toolbar::getThickness() const throw()
  44505. {
  44506. return vertical ? getWidth() : getHeight();
  44507. }
  44508. int Toolbar::getLength() const throw()
  44509. {
  44510. return vertical ? getHeight() : getWidth();
  44511. }
  44512. void Toolbar::setEditingActive (const bool active)
  44513. {
  44514. if (isEditingActive != active)
  44515. {
  44516. isEditingActive = active;
  44517. updateAllItemPositions (false);
  44518. }
  44519. }
  44520. void Toolbar::resized()
  44521. {
  44522. updateAllItemPositions (false);
  44523. }
  44524. void Toolbar::updateAllItemPositions (const bool animate)
  44525. {
  44526. if (getWidth() > 0 && getHeight() > 0)
  44527. {
  44528. StretchableObjectResizer resizer;
  44529. int i;
  44530. for (i = 0; i < items.size(); ++i)
  44531. {
  44532. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44533. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44534. : ToolbarItemComponent::normalMode);
  44535. tc->setStyle (toolbarStyle);
  44536. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44537. int preferredSize = 1, minSize = 1, maxSize = 1;
  44538. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44539. preferredSize, minSize, maxSize))
  44540. {
  44541. tc->isActive = true;
  44542. resizer.addItem (preferredSize, minSize, maxSize,
  44543. spacer != 0 ? spacer->getResizeOrder() : 2);
  44544. }
  44545. else
  44546. {
  44547. tc->isActive = false;
  44548. tc->setVisible (false);
  44549. }
  44550. }
  44551. resizer.resizeToFit (getLength());
  44552. int totalLength = 0;
  44553. for (i = 0; i < resizer.getNumItems(); ++i)
  44554. totalLength += (int) resizer.getItemSize (i);
  44555. const bool itemsOffTheEnd = totalLength > getLength();
  44556. const int extrasButtonSize = getThickness() / 2;
  44557. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44558. missingItemsButton->setVisible (itemsOffTheEnd);
  44559. missingItemsButton->setEnabled (! isEditingActive);
  44560. if (vertical)
  44561. missingItemsButton->setCentrePosition (getWidth() / 2,
  44562. getHeight() - 4 - extrasButtonSize / 2);
  44563. else
  44564. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44565. getHeight() / 2);
  44566. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44567. : missingItemsButton->getX()) - 4
  44568. : getLength();
  44569. int pos = 0, activeIndex = 0;
  44570. for (i = 0; i < items.size(); ++i)
  44571. {
  44572. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44573. if (tc->isActive)
  44574. {
  44575. const int size = (int) resizer.getItemSize (activeIndex++);
  44576. Rectangle<int> newBounds;
  44577. if (vertical)
  44578. newBounds.setBounds (0, pos, getWidth(), size);
  44579. else
  44580. newBounds.setBounds (pos, 0, size, getHeight());
  44581. if (animate)
  44582. {
  44583. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44584. }
  44585. else
  44586. {
  44587. animator.cancelAnimation (tc, false);
  44588. tc->setBounds (newBounds);
  44589. }
  44590. pos += size;
  44591. tc->setVisible (pos <= maxLength
  44592. && ((! tc->isBeingDragged)
  44593. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44594. }
  44595. }
  44596. }
  44597. }
  44598. void Toolbar::buttonClicked (Button*)
  44599. {
  44600. jassert (missingItemsButton->isShowing());
  44601. if (missingItemsButton->isShowing())
  44602. {
  44603. PopupMenu m;
  44604. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44605. m.showAt (missingItemsButton);
  44606. }
  44607. }
  44608. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44609. Component* /*sourceComponent*/)
  44610. {
  44611. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44612. }
  44613. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44614. {
  44615. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44616. if (tc != 0)
  44617. {
  44618. if (getNumItems() == 0)
  44619. {
  44620. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44621. {
  44622. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44623. if (palette != 0)
  44624. palette->replaceComponent (tc);
  44625. }
  44626. else
  44627. {
  44628. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44629. }
  44630. items.add (tc);
  44631. addChildComponent (tc);
  44632. updateAllItemPositions (false);
  44633. }
  44634. else
  44635. {
  44636. for (int i = getNumItems(); --i >= 0;)
  44637. {
  44638. int currentIndex = getIndexOfChildComponent (tc);
  44639. if (currentIndex < 0)
  44640. {
  44641. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44642. {
  44643. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44644. if (palette != 0)
  44645. palette->replaceComponent (tc);
  44646. }
  44647. else
  44648. {
  44649. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44650. }
  44651. items.add (tc);
  44652. addChildComponent (tc);
  44653. currentIndex = getIndexOfChildComponent (tc);
  44654. updateAllItemPositions (true);
  44655. }
  44656. int newIndex = currentIndex;
  44657. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44658. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44659. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44660. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44661. if (prev != 0)
  44662. {
  44663. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44664. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44665. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44666. {
  44667. newIndex = getIndexOfChildComponent (prev);
  44668. }
  44669. }
  44670. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44671. if (next != 0)
  44672. {
  44673. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44674. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44675. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44676. {
  44677. newIndex = getIndexOfChildComponent (next) + 1;
  44678. }
  44679. }
  44680. if (newIndex != currentIndex)
  44681. {
  44682. items.removeValue (tc);
  44683. removeChildComponent (tc);
  44684. addChildComponent (tc, newIndex);
  44685. items.insert (newIndex, tc);
  44686. updateAllItemPositions (true);
  44687. }
  44688. else
  44689. {
  44690. break;
  44691. }
  44692. }
  44693. }
  44694. }
  44695. }
  44696. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44697. {
  44698. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44699. if (tc != 0)
  44700. {
  44701. if (isParentOf (tc))
  44702. {
  44703. items.removeValue (tc);
  44704. removeChildComponent (tc);
  44705. updateAllItemPositions (true);
  44706. }
  44707. }
  44708. }
  44709. void Toolbar::itemDropped (const String&, Component*, int, int)
  44710. {
  44711. }
  44712. void Toolbar::mouseDown (const MouseEvent& e)
  44713. {
  44714. if (e.mods.isPopupMenu())
  44715. {
  44716. }
  44717. }
  44718. class ToolbarCustomisationDialog : public DialogWindow
  44719. {
  44720. public:
  44721. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44722. Toolbar* const toolbar_,
  44723. const int optionFlags)
  44724. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44725. toolbar (toolbar_)
  44726. {
  44727. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44728. setResizable (true, true);
  44729. setResizeLimits (400, 300, 1500, 1000);
  44730. positionNearBar();
  44731. }
  44732. ~ToolbarCustomisationDialog()
  44733. {
  44734. setContentComponent (0, true);
  44735. }
  44736. void closeButtonPressed()
  44737. {
  44738. setVisible (false);
  44739. }
  44740. bool canModalEventBeSentToComponent (const Component* comp)
  44741. {
  44742. return toolbar->isParentOf (comp);
  44743. }
  44744. void positionNearBar()
  44745. {
  44746. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44747. const int tbx = toolbar->getScreenX();
  44748. const int tby = toolbar->getScreenY();
  44749. const int gap = 8;
  44750. int x, y;
  44751. if (toolbar->isVertical())
  44752. {
  44753. y = tby;
  44754. if (tbx > screenSize.getCentreX())
  44755. x = tbx - getWidth() - gap;
  44756. else
  44757. x = tbx + toolbar->getWidth() + gap;
  44758. }
  44759. else
  44760. {
  44761. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44762. if (tby > screenSize.getCentreY())
  44763. y = tby - getHeight() - gap;
  44764. else
  44765. y = tby + toolbar->getHeight() + gap;
  44766. }
  44767. setTopLeftPosition (x, y);
  44768. }
  44769. private:
  44770. Toolbar* const toolbar;
  44771. class CustomiserPanel : public Component,
  44772. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44773. private ButtonListener
  44774. {
  44775. public:
  44776. CustomiserPanel (ToolbarItemFactory& factory_,
  44777. Toolbar* const toolbar_,
  44778. const int optionFlags)
  44779. : factory (factory_),
  44780. toolbar (toolbar_),
  44781. styleBox (0),
  44782. defaultButton (0)
  44783. {
  44784. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44785. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44786. | Toolbar::allowIconsWithTextChoice
  44787. | Toolbar::allowTextOnlyChoice)) != 0)
  44788. {
  44789. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44790. styleBox->setEditableText (false);
  44791. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44792. styleBox->addItem (TRANS("Show icons only"), 1);
  44793. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44794. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44795. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44796. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44797. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44798. styleBox->setSelectedId (1);
  44799. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44800. styleBox->setSelectedId (2);
  44801. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44802. styleBox->setSelectedId (3);
  44803. styleBox->addListener (this);
  44804. }
  44805. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44806. {
  44807. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44808. defaultButton->addButtonListener (this);
  44809. }
  44810. addAndMakeVisible (instructions = new Label (String::empty,
  44811. 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.")));
  44812. instructions->setFont (Font (13.0f));
  44813. setSize (500, 300);
  44814. }
  44815. ~CustomiserPanel()
  44816. {
  44817. deleteAllChildren();
  44818. }
  44819. void comboBoxChanged (ComboBox*)
  44820. {
  44821. if (styleBox->getSelectedId() == 1)
  44822. toolbar->setStyle (Toolbar::iconsOnly);
  44823. else if (styleBox->getSelectedId() == 2)
  44824. toolbar->setStyle (Toolbar::iconsWithText);
  44825. else if (styleBox->getSelectedId() == 3)
  44826. toolbar->setStyle (Toolbar::textOnly);
  44827. palette->resized(); // to make it update the styles
  44828. }
  44829. void buttonClicked (Button*)
  44830. {
  44831. toolbar->addDefaultItems (factory);
  44832. }
  44833. void paint (Graphics& g)
  44834. {
  44835. Colour background;
  44836. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44837. if (dw != 0)
  44838. background = dw->getBackgroundColour();
  44839. g.setColour (background.contrasting().withAlpha (0.3f));
  44840. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44841. }
  44842. void resized()
  44843. {
  44844. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44845. if (styleBox != 0)
  44846. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44847. if (defaultButton != 0)
  44848. {
  44849. defaultButton->changeWidthToFitText (22);
  44850. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44851. }
  44852. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44853. }
  44854. private:
  44855. ToolbarItemFactory& factory;
  44856. Toolbar* const toolbar;
  44857. Label* instructions;
  44858. ToolbarItemPalette* palette;
  44859. ComboBox* styleBox;
  44860. TextButton* defaultButton;
  44861. };
  44862. };
  44863. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44864. {
  44865. setEditingActive (true);
  44866. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44867. dw.runModalLoop();
  44868. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44869. setEditingActive (false);
  44870. }
  44871. END_JUCE_NAMESPACE
  44872. /*** End of inlined file: juce_Toolbar.cpp ***/
  44873. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44874. BEGIN_JUCE_NAMESPACE
  44875. ToolbarItemFactory::ToolbarItemFactory()
  44876. {
  44877. }
  44878. ToolbarItemFactory::~ToolbarItemFactory()
  44879. {
  44880. }
  44881. class ItemDragAndDropOverlayComponent : public Component
  44882. {
  44883. public:
  44884. ItemDragAndDropOverlayComponent()
  44885. : isDragging (false)
  44886. {
  44887. setAlwaysOnTop (true);
  44888. setRepaintsOnMouseActivity (true);
  44889. setMouseCursor (MouseCursor::DraggingHandCursor);
  44890. }
  44891. ~ItemDragAndDropOverlayComponent()
  44892. {
  44893. }
  44894. void paint (Graphics& g)
  44895. {
  44896. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44897. if (isMouseOverOrDragging()
  44898. && tc != 0
  44899. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44900. {
  44901. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44902. g.drawRect (0, 0, getWidth(), getHeight(),
  44903. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44904. }
  44905. }
  44906. void mouseDown (const MouseEvent& e)
  44907. {
  44908. isDragging = false;
  44909. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44910. if (tc != 0)
  44911. {
  44912. tc->dragOffsetX = e.x;
  44913. tc->dragOffsetY = e.y;
  44914. }
  44915. }
  44916. void mouseDrag (const MouseEvent& e)
  44917. {
  44918. if (! (isDragging || e.mouseWasClicked()))
  44919. {
  44920. isDragging = true;
  44921. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44922. if (dnd != 0)
  44923. {
  44924. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44925. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44926. if (tc != 0)
  44927. {
  44928. tc->isBeingDragged = true;
  44929. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44930. tc->setVisible (false);
  44931. }
  44932. }
  44933. }
  44934. }
  44935. void mouseUp (const MouseEvent&)
  44936. {
  44937. isDragging = false;
  44938. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44939. if (tc != 0)
  44940. {
  44941. tc->isBeingDragged = false;
  44942. Toolbar* const tb = tc->getToolbar();
  44943. if (tb != 0)
  44944. tb->updateAllItemPositions (true);
  44945. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44946. delete tc;
  44947. }
  44948. }
  44949. void parentSizeChanged()
  44950. {
  44951. setBounds (0, 0, getParentWidth(), getParentHeight());
  44952. }
  44953. juce_UseDebuggingNewOperator
  44954. private:
  44955. bool isDragging;
  44956. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44957. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44958. };
  44959. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44960. const String& labelText,
  44961. const bool isBeingUsedAsAButton_)
  44962. : Button (labelText),
  44963. itemId (itemId_),
  44964. mode (normalMode),
  44965. toolbarStyle (Toolbar::iconsOnly),
  44966. dragOffsetX (0),
  44967. dragOffsetY (0),
  44968. isActive (true),
  44969. isBeingDragged (false),
  44970. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44971. {
  44972. // Your item ID can't be 0!
  44973. jassert (itemId_ != 0);
  44974. }
  44975. ToolbarItemComponent::~ToolbarItemComponent()
  44976. {
  44977. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44978. overlayComp = 0;
  44979. }
  44980. Toolbar* ToolbarItemComponent::getToolbar() const
  44981. {
  44982. return dynamic_cast <Toolbar*> (getParentComponent());
  44983. }
  44984. bool ToolbarItemComponent::isToolbarVertical() const
  44985. {
  44986. const Toolbar* const t = getToolbar();
  44987. return t != 0 && t->isVertical();
  44988. }
  44989. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44990. {
  44991. if (toolbarStyle != newStyle)
  44992. {
  44993. toolbarStyle = newStyle;
  44994. repaint();
  44995. resized();
  44996. }
  44997. }
  44998. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44999. {
  45000. if (isBeingUsedAsAButton)
  45001. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45002. over, down, *this);
  45003. if (toolbarStyle != Toolbar::iconsOnly)
  45004. {
  45005. const int indent = contentArea.getX();
  45006. int y = indent;
  45007. int h = getHeight() - indent * 2;
  45008. if (toolbarStyle == Toolbar::iconsWithText)
  45009. {
  45010. y = contentArea.getBottom() + indent / 2;
  45011. h -= contentArea.getHeight();
  45012. }
  45013. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45014. getButtonText(), *this);
  45015. }
  45016. if (! contentArea.isEmpty())
  45017. {
  45018. g.saveState();
  45019. g.setOrigin (contentArea.getX(), contentArea.getY());
  45020. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45021. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45022. g.restoreState();
  45023. }
  45024. }
  45025. void ToolbarItemComponent::resized()
  45026. {
  45027. if (toolbarStyle != Toolbar::textOnly)
  45028. {
  45029. const int indent = jmin (proportionOfWidth (0.08f),
  45030. proportionOfHeight (0.08f));
  45031. contentArea = Rectangle<int> (indent, indent,
  45032. getWidth() - indent * 2,
  45033. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45034. : (getHeight() - indent * 2));
  45035. }
  45036. else
  45037. {
  45038. contentArea = Rectangle<int>();
  45039. }
  45040. contentAreaChanged (contentArea);
  45041. }
  45042. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45043. {
  45044. if (mode != newMode)
  45045. {
  45046. mode = newMode;
  45047. repaint();
  45048. if (mode == normalMode)
  45049. {
  45050. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45051. overlayComp = 0;
  45052. }
  45053. else if (overlayComp == 0)
  45054. {
  45055. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45056. overlayComp->parentSizeChanged();
  45057. }
  45058. resized();
  45059. }
  45060. }
  45061. END_JUCE_NAMESPACE
  45062. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45063. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45064. BEGIN_JUCE_NAMESPACE
  45065. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45066. Toolbar* const toolbar_)
  45067. : factory (factory_),
  45068. toolbar (toolbar_)
  45069. {
  45070. Component* const itemHolder = new Component();
  45071. Array <int> allIds;
  45072. factory_.getAllToolbarItemIds (allIds);
  45073. for (int i = 0; i < allIds.size(); ++i)
  45074. {
  45075. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45076. jassert (tc != 0);
  45077. if (tc != 0)
  45078. {
  45079. itemHolder->addAndMakeVisible (tc);
  45080. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45081. }
  45082. }
  45083. viewport = new Viewport();
  45084. viewport->setViewedComponent (itemHolder);
  45085. addAndMakeVisible (viewport);
  45086. }
  45087. ToolbarItemPalette::~ToolbarItemPalette()
  45088. {
  45089. viewport->getViewedComponent()->deleteAllChildren();
  45090. deleteAllChildren();
  45091. }
  45092. void ToolbarItemPalette::resized()
  45093. {
  45094. viewport->setBoundsInset (BorderSize (1));
  45095. Component* const itemHolder = viewport->getViewedComponent();
  45096. const int indent = 8;
  45097. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45098. const int height = toolbar->getThickness();
  45099. int x = indent;
  45100. int y = indent;
  45101. int maxX = 0;
  45102. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45103. {
  45104. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45105. if (tc != 0)
  45106. {
  45107. tc->setStyle (toolbar->getStyle());
  45108. int preferredSize = 1, minSize = 1, maxSize = 1;
  45109. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45110. {
  45111. if (x + preferredSize > preferredWidth && x > indent)
  45112. {
  45113. x = indent;
  45114. y += height;
  45115. }
  45116. tc->setBounds (x, y, preferredSize, height);
  45117. x += preferredSize + 8;
  45118. maxX = jmax (maxX, x);
  45119. }
  45120. }
  45121. }
  45122. itemHolder->setSize (maxX, y + height + 8);
  45123. }
  45124. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45125. {
  45126. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45127. jassert (tc != 0);
  45128. if (tc != 0)
  45129. {
  45130. tc->setBounds (comp->getBounds());
  45131. tc->setStyle (toolbar->getStyle());
  45132. tc->setEditingMode (comp->getEditingMode());
  45133. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45134. }
  45135. }
  45136. END_JUCE_NAMESPACE
  45137. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45138. /*** Start of inlined file: juce_TreeView.cpp ***/
  45139. BEGIN_JUCE_NAMESPACE
  45140. class TreeViewContentComponent : public Component,
  45141. public TooltipClient
  45142. {
  45143. public:
  45144. TreeViewContentComponent (TreeView& owner_)
  45145. : owner (owner_),
  45146. buttonUnderMouse (0),
  45147. isDragging (false)
  45148. {
  45149. }
  45150. ~TreeViewContentComponent()
  45151. {
  45152. deleteAllChildren();
  45153. }
  45154. void mouseDown (const MouseEvent& e)
  45155. {
  45156. updateButtonUnderMouse (e);
  45157. isDragging = false;
  45158. needSelectionOnMouseUp = false;
  45159. Rectangle<int> pos;
  45160. TreeViewItem* const item = findItemAt (e.y, pos);
  45161. if (item == 0)
  45162. return;
  45163. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45164. // as selection clicks)
  45165. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45166. {
  45167. if (e.x >= pos.getX() - owner.getIndentSize())
  45168. item->setOpen (! item->isOpen());
  45169. // (clicks to the left of an open/close button are ignored)
  45170. }
  45171. else
  45172. {
  45173. // mouse-down inside the body of the item..
  45174. if (! owner.isMultiSelectEnabled())
  45175. item->setSelected (true, true);
  45176. else if (item->isSelected())
  45177. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45178. else
  45179. selectBasedOnModifiers (item, e.mods);
  45180. if (e.x >= pos.getX())
  45181. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45182. }
  45183. }
  45184. void mouseUp (const MouseEvent& e)
  45185. {
  45186. updateButtonUnderMouse (e);
  45187. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45188. {
  45189. Rectangle<int> pos;
  45190. TreeViewItem* const item = findItemAt (e.y, pos);
  45191. if (item != 0)
  45192. selectBasedOnModifiers (item, e.mods);
  45193. }
  45194. }
  45195. void mouseDoubleClick (const MouseEvent& e)
  45196. {
  45197. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45198. {
  45199. Rectangle<int> pos;
  45200. TreeViewItem* const item = findItemAt (e.y, pos);
  45201. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45202. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45203. }
  45204. }
  45205. void mouseDrag (const MouseEvent& e)
  45206. {
  45207. if (isEnabled()
  45208. && ! (isDragging || e.mouseWasClicked()
  45209. || e.getDistanceFromDragStart() < 5
  45210. || e.mods.isPopupMenu()))
  45211. {
  45212. isDragging = true;
  45213. Rectangle<int> pos;
  45214. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45215. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45216. {
  45217. const String dragDescription (item->getDragSourceDescription());
  45218. if (dragDescription.isNotEmpty())
  45219. {
  45220. DragAndDropContainer* const dragContainer
  45221. = DragAndDropContainer::findParentDragContainerFor (this);
  45222. if (dragContainer != 0)
  45223. {
  45224. pos.setSize (pos.getWidth(), item->itemHeight);
  45225. Image dragImage (Component::createComponentSnapshot (pos, true));
  45226. dragImage.multiplyAllAlphas (0.6f);
  45227. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45228. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45229. }
  45230. else
  45231. {
  45232. // to be able to do a drag-and-drop operation, the treeview needs to
  45233. // be inside a component which is also a DragAndDropContainer.
  45234. jassertfalse;
  45235. }
  45236. }
  45237. }
  45238. }
  45239. }
  45240. void mouseMove (const MouseEvent& e)
  45241. {
  45242. updateButtonUnderMouse (e);
  45243. }
  45244. void mouseExit (const MouseEvent& e)
  45245. {
  45246. updateButtonUnderMouse (e);
  45247. }
  45248. void paint (Graphics& g)
  45249. {
  45250. if (owner.rootItem != 0)
  45251. {
  45252. owner.handleAsyncUpdate();
  45253. if (! owner.rootItemVisible)
  45254. g.setOrigin (0, -owner.rootItem->itemHeight);
  45255. owner.rootItem->paintRecursively (g, getWidth());
  45256. }
  45257. }
  45258. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45259. {
  45260. if (owner.rootItem != 0)
  45261. {
  45262. owner.handleAsyncUpdate();
  45263. if (! owner.rootItemVisible)
  45264. y += owner.rootItem->itemHeight;
  45265. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45266. if (ti != 0)
  45267. itemPosition = ti->getItemPosition (false);
  45268. return ti;
  45269. }
  45270. return 0;
  45271. }
  45272. void updateComponents()
  45273. {
  45274. const int visibleTop = -getY();
  45275. const int visibleBottom = visibleTop + getParentHeight();
  45276. BigInteger itemsToKeep;
  45277. {
  45278. TreeViewItem* item = owner.rootItem;
  45279. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45280. while (item != 0 && y < visibleBottom)
  45281. {
  45282. y += item->itemHeight;
  45283. if (y >= visibleTop)
  45284. {
  45285. const int index = rowComponentIds.indexOf (item->uid);
  45286. if (index < 0)
  45287. {
  45288. Component* const comp = item->createItemComponent();
  45289. if (comp != 0)
  45290. {
  45291. addAndMakeVisible (comp);
  45292. itemsToKeep.setBit (rowComponentItems.size());
  45293. rowComponentItems.add (item);
  45294. rowComponentIds.add (item->uid);
  45295. rowComponents.add (comp);
  45296. }
  45297. }
  45298. else
  45299. {
  45300. itemsToKeep.setBit (index);
  45301. }
  45302. }
  45303. item = item->getNextVisibleItem (true);
  45304. }
  45305. }
  45306. for (int i = rowComponentItems.size(); --i >= 0;)
  45307. {
  45308. Component* const comp = rowComponents.getUnchecked(i);
  45309. bool keep = false;
  45310. if (isParentOf (comp))
  45311. {
  45312. if (itemsToKeep[i])
  45313. {
  45314. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45315. Rectangle<int> pos (item->getItemPosition (false));
  45316. pos.setSize (pos.getWidth(), item->itemHeight);
  45317. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45318. {
  45319. keep = true;
  45320. comp->setBounds (pos);
  45321. }
  45322. }
  45323. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45324. {
  45325. keep = true;
  45326. comp->setSize (0, 0);
  45327. }
  45328. }
  45329. if (! keep)
  45330. {
  45331. delete comp;
  45332. rowComponents.remove (i);
  45333. rowComponentIds.remove (i);
  45334. rowComponentItems.remove (i);
  45335. }
  45336. }
  45337. }
  45338. void updateButtonUnderMouse (const MouseEvent& e)
  45339. {
  45340. TreeViewItem* newItem = 0;
  45341. if (owner.openCloseButtonsVisible)
  45342. {
  45343. Rectangle<int> pos;
  45344. TreeViewItem* item = findItemAt (e.y, pos);
  45345. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45346. {
  45347. newItem = item;
  45348. if (! newItem->mightContainSubItems())
  45349. newItem = 0;
  45350. }
  45351. }
  45352. if (buttonUnderMouse != newItem)
  45353. {
  45354. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45355. {
  45356. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45357. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45358. }
  45359. buttonUnderMouse = newItem;
  45360. if (buttonUnderMouse != 0)
  45361. {
  45362. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45363. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45364. }
  45365. }
  45366. }
  45367. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45368. {
  45369. return item == buttonUnderMouse;
  45370. }
  45371. void resized()
  45372. {
  45373. owner.itemsChanged();
  45374. }
  45375. const String getTooltip()
  45376. {
  45377. Rectangle<int> pos;
  45378. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45379. if (item != 0)
  45380. return item->getTooltip();
  45381. return owner.getTooltip();
  45382. }
  45383. juce_UseDebuggingNewOperator
  45384. private:
  45385. TreeView& owner;
  45386. Array <TreeViewItem*> rowComponentItems;
  45387. Array <int> rowComponentIds;
  45388. Array <Component*> rowComponents;
  45389. TreeViewItem* buttonUnderMouse;
  45390. bool isDragging, needSelectionOnMouseUp;
  45391. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45392. {
  45393. TreeViewItem* firstSelected = 0;
  45394. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45395. {
  45396. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45397. jassert (lastSelected != 0);
  45398. int rowStart = firstSelected->getRowNumberInTree();
  45399. int rowEnd = lastSelected->getRowNumberInTree();
  45400. if (rowStart > rowEnd)
  45401. swapVariables (rowStart, rowEnd);
  45402. int ourRow = item->getRowNumberInTree();
  45403. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45404. if (ourRow > otherEnd)
  45405. swapVariables (ourRow, otherEnd);
  45406. for (int i = ourRow; i <= otherEnd; ++i)
  45407. owner.getItemOnRow (i)->setSelected (true, false);
  45408. }
  45409. else
  45410. {
  45411. const bool cmd = modifiers.isCommandDown();
  45412. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45413. }
  45414. }
  45415. bool containsItem (TreeViewItem* const item) const
  45416. {
  45417. for (int i = rowComponentItems.size(); --i >= 0;)
  45418. if (rowComponentItems.getUnchecked(i) == item)
  45419. return true;
  45420. return false;
  45421. }
  45422. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45423. {
  45424. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45425. {
  45426. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45427. if (source->isDragging())
  45428. {
  45429. Component* const underMouse = source->getComponentUnderMouse();
  45430. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45431. return true;
  45432. }
  45433. }
  45434. return false;
  45435. }
  45436. TreeViewContentComponent (const TreeViewContentComponent&);
  45437. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45438. };
  45439. class TreeView::TreeViewport : public Viewport
  45440. {
  45441. public:
  45442. TreeViewport() throw() : lastX (-1) {}
  45443. ~TreeViewport() throw() {}
  45444. void updateComponents (const bool triggerResize = false)
  45445. {
  45446. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45447. if (tvc != 0)
  45448. {
  45449. if (triggerResize)
  45450. tvc->resized();
  45451. else
  45452. tvc->updateComponents();
  45453. }
  45454. repaint();
  45455. }
  45456. void visibleAreaChanged (int x, int, int, int)
  45457. {
  45458. const bool hasScrolledSideways = (x != lastX);
  45459. lastX = x;
  45460. updateComponents (hasScrolledSideways);
  45461. }
  45462. juce_UseDebuggingNewOperator
  45463. private:
  45464. int lastX;
  45465. TreeViewport (const TreeViewport&);
  45466. TreeViewport& operator= (const TreeViewport&);
  45467. };
  45468. TreeView::TreeView (const String& componentName)
  45469. : Component (componentName),
  45470. rootItem (0),
  45471. indentSize (24),
  45472. defaultOpenness (false),
  45473. needsRecalculating (true),
  45474. rootItemVisible (true),
  45475. multiSelectEnabled (false),
  45476. openCloseButtonsVisible (true)
  45477. {
  45478. addAndMakeVisible (viewport = new TreeViewport());
  45479. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45480. viewport->setWantsKeyboardFocus (false);
  45481. setWantsKeyboardFocus (true);
  45482. }
  45483. TreeView::~TreeView()
  45484. {
  45485. if (rootItem != 0)
  45486. rootItem->setOwnerView (0);
  45487. }
  45488. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45489. {
  45490. if (rootItem != newRootItem)
  45491. {
  45492. if (newRootItem != 0)
  45493. {
  45494. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45495. if (newRootItem->ownerView != 0)
  45496. newRootItem->ownerView->setRootItem (0);
  45497. }
  45498. if (rootItem != 0)
  45499. rootItem->setOwnerView (0);
  45500. rootItem = newRootItem;
  45501. if (newRootItem != 0)
  45502. newRootItem->setOwnerView (this);
  45503. needsRecalculating = true;
  45504. handleAsyncUpdate();
  45505. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45506. {
  45507. rootItem->setOpen (false); // force a re-open
  45508. rootItem->setOpen (true);
  45509. }
  45510. }
  45511. }
  45512. void TreeView::deleteRootItem()
  45513. {
  45514. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45515. setRootItem (0);
  45516. }
  45517. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45518. {
  45519. rootItemVisible = shouldBeVisible;
  45520. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45521. {
  45522. rootItem->setOpen (false); // force a re-open
  45523. rootItem->setOpen (true);
  45524. }
  45525. itemsChanged();
  45526. }
  45527. void TreeView::colourChanged()
  45528. {
  45529. setOpaque (findColour (backgroundColourId).isOpaque());
  45530. repaint();
  45531. }
  45532. void TreeView::setIndentSize (const int newIndentSize)
  45533. {
  45534. if (indentSize != newIndentSize)
  45535. {
  45536. indentSize = newIndentSize;
  45537. resized();
  45538. }
  45539. }
  45540. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45541. {
  45542. if (defaultOpenness != isOpenByDefault)
  45543. {
  45544. defaultOpenness = isOpenByDefault;
  45545. itemsChanged();
  45546. }
  45547. }
  45548. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45549. {
  45550. multiSelectEnabled = canMultiSelect;
  45551. }
  45552. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45553. {
  45554. if (openCloseButtonsVisible != shouldBeVisible)
  45555. {
  45556. openCloseButtonsVisible = shouldBeVisible;
  45557. itemsChanged();
  45558. }
  45559. }
  45560. Viewport* TreeView::getViewport() const throw()
  45561. {
  45562. return viewport;
  45563. }
  45564. void TreeView::clearSelectedItems()
  45565. {
  45566. if (rootItem != 0)
  45567. rootItem->deselectAllRecursively();
  45568. }
  45569. int TreeView::getNumSelectedItems() const throw()
  45570. {
  45571. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45572. }
  45573. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45574. {
  45575. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45576. }
  45577. int TreeView::getNumRowsInTree() const
  45578. {
  45579. if (rootItem != 0)
  45580. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45581. return 0;
  45582. }
  45583. TreeViewItem* TreeView::getItemOnRow (int index) const
  45584. {
  45585. if (! rootItemVisible)
  45586. ++index;
  45587. if (rootItem != 0 && index >= 0)
  45588. return rootItem->getItemOnRow (index);
  45589. return 0;
  45590. }
  45591. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45592. {
  45593. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45594. Rectangle<int> pos;
  45595. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45596. }
  45597. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45598. {
  45599. if (rootItem == 0)
  45600. return 0;
  45601. return rootItem->findItemFromIdentifierString (identifierString);
  45602. }
  45603. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45604. {
  45605. XmlElement* e = 0;
  45606. if (rootItem != 0)
  45607. {
  45608. e = rootItem->getOpennessState();
  45609. if (e != 0 && alsoIncludeScrollPosition)
  45610. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45611. }
  45612. return e;
  45613. }
  45614. void TreeView::restoreOpennessState (const XmlElement& newState)
  45615. {
  45616. if (rootItem != 0)
  45617. {
  45618. rootItem->restoreOpennessState (newState);
  45619. if (newState.hasAttribute ("scrollPos"))
  45620. viewport->setViewPosition (viewport->getViewPositionX(),
  45621. newState.getIntAttribute ("scrollPos"));
  45622. }
  45623. }
  45624. void TreeView::paint (Graphics& g)
  45625. {
  45626. g.fillAll (findColour (backgroundColourId));
  45627. }
  45628. void TreeView::resized()
  45629. {
  45630. viewport->setBounds (getLocalBounds());
  45631. itemsChanged();
  45632. handleAsyncUpdate();
  45633. }
  45634. void TreeView::enablementChanged()
  45635. {
  45636. repaint();
  45637. }
  45638. void TreeView::moveSelectedRow (int delta)
  45639. {
  45640. if (delta == 0)
  45641. return;
  45642. int rowSelected = 0;
  45643. TreeViewItem* const firstSelected = getSelectedItem (0);
  45644. if (firstSelected != 0)
  45645. rowSelected = firstSelected->getRowNumberInTree();
  45646. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45647. for (;;)
  45648. {
  45649. TreeViewItem* item = getItemOnRow (rowSelected);
  45650. if (item != 0)
  45651. {
  45652. if (! item->canBeSelected())
  45653. {
  45654. // if the row we want to highlight doesn't allow it, try skipping
  45655. // to the next item..
  45656. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45657. rowSelected + (delta < 0 ? -1 : 1));
  45658. if (rowSelected != nextRowToTry)
  45659. {
  45660. rowSelected = nextRowToTry;
  45661. continue;
  45662. }
  45663. else
  45664. {
  45665. break;
  45666. }
  45667. }
  45668. item->setSelected (true, true);
  45669. scrollToKeepItemVisible (item);
  45670. }
  45671. break;
  45672. }
  45673. }
  45674. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45675. {
  45676. if (item != 0 && item->ownerView == this)
  45677. {
  45678. handleAsyncUpdate();
  45679. item = item->getDeepestOpenParentItem();
  45680. int y = item->y;
  45681. int viewTop = viewport->getViewPositionY();
  45682. if (y < viewTop)
  45683. {
  45684. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45685. }
  45686. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45687. {
  45688. viewport->setViewPosition (viewport->getViewPositionX(),
  45689. (y + item->itemHeight) - viewport->getViewHeight());
  45690. }
  45691. }
  45692. }
  45693. bool TreeView::keyPressed (const KeyPress& key)
  45694. {
  45695. if (key.isKeyCode (KeyPress::upKey))
  45696. {
  45697. moveSelectedRow (-1);
  45698. }
  45699. else if (key.isKeyCode (KeyPress::downKey))
  45700. {
  45701. moveSelectedRow (1);
  45702. }
  45703. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45704. {
  45705. if (rootItem != 0)
  45706. {
  45707. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45708. if (key.isKeyCode (KeyPress::pageUpKey))
  45709. rowsOnScreen = -rowsOnScreen;
  45710. moveSelectedRow (rowsOnScreen);
  45711. }
  45712. }
  45713. else if (key.isKeyCode (KeyPress::homeKey))
  45714. {
  45715. moveSelectedRow (-0x3fffffff);
  45716. }
  45717. else if (key.isKeyCode (KeyPress::endKey))
  45718. {
  45719. moveSelectedRow (0x3fffffff);
  45720. }
  45721. else if (key.isKeyCode (KeyPress::returnKey))
  45722. {
  45723. TreeViewItem* const firstSelected = getSelectedItem (0);
  45724. if (firstSelected != 0)
  45725. firstSelected->setOpen (! firstSelected->isOpen());
  45726. }
  45727. else if (key.isKeyCode (KeyPress::leftKey))
  45728. {
  45729. TreeViewItem* const firstSelected = getSelectedItem (0);
  45730. if (firstSelected != 0)
  45731. {
  45732. if (firstSelected->isOpen())
  45733. {
  45734. firstSelected->setOpen (false);
  45735. }
  45736. else
  45737. {
  45738. TreeViewItem* parent = firstSelected->parentItem;
  45739. if ((! rootItemVisible) && parent == rootItem)
  45740. parent = 0;
  45741. if (parent != 0)
  45742. {
  45743. parent->setSelected (true, true);
  45744. scrollToKeepItemVisible (parent);
  45745. }
  45746. }
  45747. }
  45748. }
  45749. else if (key.isKeyCode (KeyPress::rightKey))
  45750. {
  45751. TreeViewItem* const firstSelected = getSelectedItem (0);
  45752. if (firstSelected != 0)
  45753. {
  45754. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45755. moveSelectedRow (1);
  45756. else
  45757. firstSelected->setOpen (true);
  45758. }
  45759. }
  45760. else
  45761. {
  45762. return false;
  45763. }
  45764. return true;
  45765. }
  45766. void TreeView::itemsChanged() throw()
  45767. {
  45768. needsRecalculating = true;
  45769. repaint();
  45770. triggerAsyncUpdate();
  45771. }
  45772. void TreeView::handleAsyncUpdate()
  45773. {
  45774. if (needsRecalculating)
  45775. {
  45776. needsRecalculating = false;
  45777. const ScopedLock sl (nodeAlterationLock);
  45778. if (rootItem != 0)
  45779. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45780. viewport->updateComponents();
  45781. if (rootItem != 0)
  45782. {
  45783. viewport->getViewedComponent()
  45784. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45785. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45786. }
  45787. else
  45788. {
  45789. viewport->getViewedComponent()->setSize (0, 0);
  45790. }
  45791. }
  45792. }
  45793. class TreeView::InsertPointHighlight : public Component
  45794. {
  45795. public:
  45796. InsertPointHighlight()
  45797. : lastItem (0)
  45798. {
  45799. setSize (100, 12);
  45800. setAlwaysOnTop (true);
  45801. setInterceptsMouseClicks (false, false);
  45802. }
  45803. ~InsertPointHighlight() {}
  45804. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45805. {
  45806. lastItem = item;
  45807. lastIndex = insertIndex;
  45808. const int offset = getHeight() / 2;
  45809. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45810. }
  45811. void paint (Graphics& g)
  45812. {
  45813. Path p;
  45814. const float h = (float) getHeight();
  45815. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45816. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45817. p.lineTo ((float) getWidth(), h / 2.0f);
  45818. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45819. g.strokePath (p, PathStrokeType (2.0f));
  45820. }
  45821. TreeViewItem* lastItem;
  45822. int lastIndex;
  45823. private:
  45824. InsertPointHighlight (const InsertPointHighlight&);
  45825. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45826. };
  45827. class TreeView::TargetGroupHighlight : public Component
  45828. {
  45829. public:
  45830. TargetGroupHighlight()
  45831. {
  45832. setAlwaysOnTop (true);
  45833. setInterceptsMouseClicks (false, false);
  45834. }
  45835. ~TargetGroupHighlight() {}
  45836. void setTargetPosition (TreeViewItem* const item) throw()
  45837. {
  45838. Rectangle<int> r (item->getItemPosition (true));
  45839. r.setHeight (item->getItemHeight());
  45840. setBounds (r);
  45841. }
  45842. void paint (Graphics& g)
  45843. {
  45844. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45845. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45846. }
  45847. private:
  45848. TargetGroupHighlight (const TargetGroupHighlight&);
  45849. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45850. };
  45851. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45852. {
  45853. beginDragAutoRepeat (100);
  45854. if (dragInsertPointHighlight == 0)
  45855. {
  45856. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45857. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45858. }
  45859. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45860. dragTargetGroupHighlight->setTargetPosition (item);
  45861. }
  45862. void TreeView::hideDragHighlight() throw()
  45863. {
  45864. dragInsertPointHighlight = 0;
  45865. dragTargetGroupHighlight = 0;
  45866. }
  45867. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45868. const StringArray& files, const String& sourceDescription,
  45869. Component* sourceComponent) const throw()
  45870. {
  45871. insertIndex = 0;
  45872. TreeViewItem* item = getItemAt (y);
  45873. if (item == 0)
  45874. return 0;
  45875. Rectangle<int> itemPos (item->getItemPosition (true));
  45876. insertIndex = item->getIndexInParent();
  45877. const int oldY = y;
  45878. y = itemPos.getY();
  45879. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45880. {
  45881. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45882. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45883. {
  45884. // Check if we're trying to drag into an empty group item..
  45885. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45886. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45887. {
  45888. insertIndex = 0;
  45889. x = itemPos.getX() + getIndentSize();
  45890. y = itemPos.getBottom();
  45891. return item;
  45892. }
  45893. }
  45894. }
  45895. if (oldY > itemPos.getCentreY())
  45896. {
  45897. y += item->getItemHeight();
  45898. while (item->isLastOfSiblings() && item->parentItem != 0
  45899. && item->parentItem->parentItem != 0)
  45900. {
  45901. if (x > itemPos.getX())
  45902. break;
  45903. item = item->parentItem;
  45904. itemPos = item->getItemPosition (true);
  45905. insertIndex = item->getIndexInParent();
  45906. }
  45907. ++insertIndex;
  45908. }
  45909. x = itemPos.getX();
  45910. return item->parentItem;
  45911. }
  45912. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45913. {
  45914. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45915. int insertIndex;
  45916. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45917. if (item != 0)
  45918. {
  45919. if (scrolled || dragInsertPointHighlight == 0
  45920. || dragInsertPointHighlight->lastItem != item
  45921. || dragInsertPointHighlight->lastIndex != insertIndex)
  45922. {
  45923. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45924. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45925. showDragHighlight (item, insertIndex, x, y);
  45926. else
  45927. hideDragHighlight();
  45928. }
  45929. }
  45930. else
  45931. {
  45932. hideDragHighlight();
  45933. }
  45934. }
  45935. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45936. {
  45937. hideDragHighlight();
  45938. int insertIndex;
  45939. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45940. if (item != 0)
  45941. {
  45942. if (files.size() > 0)
  45943. {
  45944. if (item->isInterestedInFileDrag (files))
  45945. item->filesDropped (files, insertIndex);
  45946. }
  45947. else
  45948. {
  45949. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45950. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45951. }
  45952. }
  45953. }
  45954. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45955. {
  45956. return true;
  45957. }
  45958. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45959. {
  45960. fileDragMove (files, x, y);
  45961. }
  45962. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45963. {
  45964. handleDrag (files, String::empty, 0, x, y);
  45965. }
  45966. void TreeView::fileDragExit (const StringArray&)
  45967. {
  45968. hideDragHighlight();
  45969. }
  45970. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45971. {
  45972. handleDrop (files, String::empty, 0, x, y);
  45973. }
  45974. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45975. {
  45976. return true;
  45977. }
  45978. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45979. {
  45980. itemDragMove (sourceDescription, sourceComponent, x, y);
  45981. }
  45982. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45983. {
  45984. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45985. }
  45986. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45987. {
  45988. hideDragHighlight();
  45989. }
  45990. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45991. {
  45992. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45993. }
  45994. enum TreeViewOpenness
  45995. {
  45996. opennessDefault = 0,
  45997. opennessClosed = 1,
  45998. opennessOpen = 2
  45999. };
  46000. TreeViewItem::TreeViewItem()
  46001. : ownerView (0),
  46002. parentItem (0),
  46003. y (0),
  46004. itemHeight (0),
  46005. totalHeight (0),
  46006. selected (false),
  46007. redrawNeeded (true),
  46008. drawLinesInside (true),
  46009. drawsInLeftMargin (false),
  46010. openness (opennessDefault)
  46011. {
  46012. static int nextUID = 0;
  46013. uid = nextUID++;
  46014. }
  46015. TreeViewItem::~TreeViewItem()
  46016. {
  46017. }
  46018. const String TreeViewItem::getUniqueName() const
  46019. {
  46020. return String::empty;
  46021. }
  46022. void TreeViewItem::itemOpennessChanged (bool)
  46023. {
  46024. }
  46025. int TreeViewItem::getNumSubItems() const throw()
  46026. {
  46027. return subItems.size();
  46028. }
  46029. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46030. {
  46031. return subItems [index];
  46032. }
  46033. void TreeViewItem::clearSubItems()
  46034. {
  46035. if (subItems.size() > 0)
  46036. {
  46037. if (ownerView != 0)
  46038. {
  46039. const ScopedLock sl (ownerView->nodeAlterationLock);
  46040. subItems.clear();
  46041. treeHasChanged();
  46042. }
  46043. else
  46044. {
  46045. subItems.clear();
  46046. }
  46047. }
  46048. }
  46049. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46050. {
  46051. if (newItem != 0)
  46052. {
  46053. newItem->parentItem = this;
  46054. newItem->setOwnerView (ownerView);
  46055. newItem->y = 0;
  46056. newItem->itemHeight = newItem->getItemHeight();
  46057. newItem->totalHeight = 0;
  46058. newItem->itemWidth = newItem->getItemWidth();
  46059. newItem->totalWidth = 0;
  46060. if (ownerView != 0)
  46061. {
  46062. const ScopedLock sl (ownerView->nodeAlterationLock);
  46063. subItems.insert (insertPosition, newItem);
  46064. treeHasChanged();
  46065. if (newItem->isOpen())
  46066. newItem->itemOpennessChanged (true);
  46067. }
  46068. else
  46069. {
  46070. subItems.insert (insertPosition, newItem);
  46071. if (newItem->isOpen())
  46072. newItem->itemOpennessChanged (true);
  46073. }
  46074. }
  46075. }
  46076. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46077. {
  46078. if (ownerView != 0)
  46079. {
  46080. const ScopedLock sl (ownerView->nodeAlterationLock);
  46081. if (((unsigned int) index) < (unsigned int) subItems.size())
  46082. {
  46083. subItems.remove (index, deleteItem);
  46084. treeHasChanged();
  46085. }
  46086. }
  46087. else
  46088. {
  46089. subItems.remove (index, deleteItem);
  46090. }
  46091. }
  46092. bool TreeViewItem::isOpen() const throw()
  46093. {
  46094. if (openness == opennessDefault)
  46095. return ownerView != 0 && ownerView->defaultOpenness;
  46096. else
  46097. return openness == opennessOpen;
  46098. }
  46099. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46100. {
  46101. if (isOpen() != shouldBeOpen)
  46102. {
  46103. openness = shouldBeOpen ? opennessOpen
  46104. : opennessClosed;
  46105. treeHasChanged();
  46106. itemOpennessChanged (isOpen());
  46107. }
  46108. }
  46109. bool TreeViewItem::isSelected() const throw()
  46110. {
  46111. return selected;
  46112. }
  46113. void TreeViewItem::deselectAllRecursively()
  46114. {
  46115. setSelected (false, false);
  46116. for (int i = 0; i < subItems.size(); ++i)
  46117. subItems.getUnchecked(i)->deselectAllRecursively();
  46118. }
  46119. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46120. const bool deselectOtherItemsFirst)
  46121. {
  46122. if (shouldBeSelected && ! canBeSelected())
  46123. return;
  46124. if (deselectOtherItemsFirst)
  46125. getTopLevelItem()->deselectAllRecursively();
  46126. if (shouldBeSelected != selected)
  46127. {
  46128. selected = shouldBeSelected;
  46129. if (ownerView != 0)
  46130. ownerView->repaint();
  46131. itemSelectionChanged (shouldBeSelected);
  46132. }
  46133. }
  46134. void TreeViewItem::paintItem (Graphics&, int, int)
  46135. {
  46136. }
  46137. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46138. {
  46139. ownerView->getLookAndFeel()
  46140. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46141. }
  46142. void TreeViewItem::itemClicked (const MouseEvent&)
  46143. {
  46144. }
  46145. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46146. {
  46147. if (mightContainSubItems())
  46148. setOpen (! isOpen());
  46149. }
  46150. void TreeViewItem::itemSelectionChanged (bool)
  46151. {
  46152. }
  46153. const String TreeViewItem::getTooltip()
  46154. {
  46155. return String::empty;
  46156. }
  46157. const String TreeViewItem::getDragSourceDescription()
  46158. {
  46159. return String::empty;
  46160. }
  46161. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46162. {
  46163. return false;
  46164. }
  46165. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46166. {
  46167. }
  46168. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46169. {
  46170. return false;
  46171. }
  46172. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46173. {
  46174. }
  46175. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46176. {
  46177. const int indentX = getIndentX();
  46178. int width = itemWidth;
  46179. if (ownerView != 0 && width < 0)
  46180. width = ownerView->viewport->getViewWidth() - indentX;
  46181. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46182. if (relativeToTreeViewTopLeft)
  46183. r -= ownerView->viewport->getViewPosition();
  46184. return r;
  46185. }
  46186. void TreeViewItem::treeHasChanged() const throw()
  46187. {
  46188. if (ownerView != 0)
  46189. ownerView->itemsChanged();
  46190. }
  46191. void TreeViewItem::repaintItem() const
  46192. {
  46193. if (ownerView != 0 && areAllParentsOpen())
  46194. {
  46195. Rectangle<int> r (getItemPosition (true));
  46196. r.setLeft (0);
  46197. ownerView->viewport->repaint (r);
  46198. }
  46199. }
  46200. bool TreeViewItem::areAllParentsOpen() const throw()
  46201. {
  46202. return parentItem == 0
  46203. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46204. }
  46205. void TreeViewItem::updatePositions (int newY)
  46206. {
  46207. y = newY;
  46208. itemHeight = getItemHeight();
  46209. totalHeight = itemHeight;
  46210. itemWidth = getItemWidth();
  46211. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46212. if (isOpen())
  46213. {
  46214. newY += totalHeight;
  46215. for (int i = 0; i < subItems.size(); ++i)
  46216. {
  46217. TreeViewItem* const ti = subItems.getUnchecked(i);
  46218. ti->updatePositions (newY);
  46219. newY += ti->totalHeight;
  46220. totalHeight += ti->totalHeight;
  46221. totalWidth = jmax (totalWidth, ti->totalWidth);
  46222. }
  46223. }
  46224. }
  46225. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46226. {
  46227. TreeViewItem* result = this;
  46228. TreeViewItem* item = this;
  46229. while (item->parentItem != 0)
  46230. {
  46231. item = item->parentItem;
  46232. if (! item->isOpen())
  46233. result = item;
  46234. }
  46235. return result;
  46236. }
  46237. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46238. {
  46239. ownerView = newOwner;
  46240. for (int i = subItems.size(); --i >= 0;)
  46241. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46242. }
  46243. int TreeViewItem::getIndentX() const throw()
  46244. {
  46245. const int indentWidth = ownerView->getIndentSize();
  46246. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46247. if (! ownerView->openCloseButtonsVisible)
  46248. x -= indentWidth;
  46249. TreeViewItem* p = parentItem;
  46250. while (p != 0)
  46251. {
  46252. x += indentWidth;
  46253. p = p->parentItem;
  46254. }
  46255. return x;
  46256. }
  46257. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46258. {
  46259. drawsInLeftMargin = canDrawInLeftMargin;
  46260. }
  46261. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46262. {
  46263. jassert (ownerView != 0);
  46264. if (ownerView == 0)
  46265. return;
  46266. const int indent = getIndentX();
  46267. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46268. {
  46269. g.saveState();
  46270. g.setOrigin (indent, 0);
  46271. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46272. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46273. paintItem (g, itemW, itemHeight);
  46274. g.restoreState();
  46275. }
  46276. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46277. const float halfH = itemHeight * 0.5f;
  46278. int depth = 0;
  46279. TreeViewItem* p = parentItem;
  46280. while (p != 0)
  46281. {
  46282. ++depth;
  46283. p = p->parentItem;
  46284. }
  46285. if (! ownerView->rootItemVisible)
  46286. --depth;
  46287. const int indentWidth = ownerView->getIndentSize();
  46288. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46289. {
  46290. float x = (depth + 0.5f) * indentWidth;
  46291. if (depth >= 0)
  46292. {
  46293. if (parentItem != 0 && parentItem->drawLinesInside)
  46294. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46295. if ((parentItem != 0 && parentItem->drawLinesInside)
  46296. || (parentItem == 0 && drawLinesInside))
  46297. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46298. }
  46299. p = parentItem;
  46300. int d = depth;
  46301. while (p != 0 && --d >= 0)
  46302. {
  46303. x -= (float) indentWidth;
  46304. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46305. && ! p->isLastOfSiblings())
  46306. {
  46307. g.drawLine (x, 0, x, (float) itemHeight);
  46308. }
  46309. p = p->parentItem;
  46310. }
  46311. if (mightContainSubItems())
  46312. {
  46313. g.saveState();
  46314. g.setOrigin (depth * indentWidth, 0);
  46315. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46316. paintOpenCloseButton (g, indentWidth, itemHeight,
  46317. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46318. ->isMouseOverButton (this));
  46319. g.restoreState();
  46320. }
  46321. }
  46322. if (isOpen())
  46323. {
  46324. const Rectangle<int> clip (g.getClipBounds());
  46325. for (int i = 0; i < subItems.size(); ++i)
  46326. {
  46327. TreeViewItem* const ti = subItems.getUnchecked(i);
  46328. const int relY = ti->y - y;
  46329. if (relY >= clip.getBottom())
  46330. break;
  46331. if (relY + ti->totalHeight >= clip.getY())
  46332. {
  46333. g.saveState();
  46334. g.setOrigin (0, relY);
  46335. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46336. ti->paintRecursively (g, width);
  46337. g.restoreState();
  46338. }
  46339. }
  46340. }
  46341. }
  46342. bool TreeViewItem::isLastOfSiblings() const throw()
  46343. {
  46344. return parentItem == 0
  46345. || parentItem->subItems.getLast() == this;
  46346. }
  46347. int TreeViewItem::getIndexInParent() const throw()
  46348. {
  46349. if (parentItem == 0)
  46350. return 0;
  46351. return parentItem->subItems.indexOf (this);
  46352. }
  46353. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46354. {
  46355. return (parentItem == 0) ? this
  46356. : parentItem->getTopLevelItem();
  46357. }
  46358. int TreeViewItem::getNumRows() const throw()
  46359. {
  46360. int num = 1;
  46361. if (isOpen())
  46362. {
  46363. for (int i = subItems.size(); --i >= 0;)
  46364. num += subItems.getUnchecked(i)->getNumRows();
  46365. }
  46366. return num;
  46367. }
  46368. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46369. {
  46370. if (index == 0)
  46371. return this;
  46372. if (index > 0 && isOpen())
  46373. {
  46374. --index;
  46375. for (int i = 0; i < subItems.size(); ++i)
  46376. {
  46377. TreeViewItem* const item = subItems.getUnchecked(i);
  46378. if (index == 0)
  46379. return item;
  46380. const int numRows = item->getNumRows();
  46381. if (numRows > index)
  46382. return item->getItemOnRow (index);
  46383. index -= numRows;
  46384. }
  46385. }
  46386. return 0;
  46387. }
  46388. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46389. {
  46390. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46391. {
  46392. const int h = itemHeight;
  46393. if (targetY < h)
  46394. return this;
  46395. if (isOpen())
  46396. {
  46397. targetY -= h;
  46398. for (int i = 0; i < subItems.size(); ++i)
  46399. {
  46400. TreeViewItem* const ti = subItems.getUnchecked(i);
  46401. if (targetY < ti->totalHeight)
  46402. return ti->findItemRecursively (targetY);
  46403. targetY -= ti->totalHeight;
  46404. }
  46405. }
  46406. }
  46407. return 0;
  46408. }
  46409. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46410. {
  46411. int total = 0;
  46412. if (isSelected())
  46413. ++total;
  46414. for (int i = subItems.size(); --i >= 0;)
  46415. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46416. return total;
  46417. }
  46418. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46419. {
  46420. if (isSelected())
  46421. {
  46422. if (index == 0)
  46423. return this;
  46424. --index;
  46425. }
  46426. if (index >= 0)
  46427. {
  46428. for (int i = 0; i < subItems.size(); ++i)
  46429. {
  46430. TreeViewItem* const item = subItems.getUnchecked(i);
  46431. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46432. if (found != 0)
  46433. return found;
  46434. index -= item->countSelectedItemsRecursively();
  46435. }
  46436. }
  46437. return 0;
  46438. }
  46439. int TreeViewItem::getRowNumberInTree() const throw()
  46440. {
  46441. if (parentItem != 0 && ownerView != 0)
  46442. {
  46443. int n = 1 + parentItem->getRowNumberInTree();
  46444. int ourIndex = parentItem->subItems.indexOf (this);
  46445. jassert (ourIndex >= 0);
  46446. while (--ourIndex >= 0)
  46447. n += parentItem->subItems [ourIndex]->getNumRows();
  46448. if (parentItem->parentItem == 0
  46449. && ! ownerView->rootItemVisible)
  46450. --n;
  46451. return n;
  46452. }
  46453. else
  46454. {
  46455. return 0;
  46456. }
  46457. }
  46458. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46459. {
  46460. drawLinesInside = drawLines;
  46461. }
  46462. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46463. {
  46464. if (recurse && isOpen() && subItems.size() > 0)
  46465. return subItems [0];
  46466. if (parentItem != 0)
  46467. {
  46468. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46469. if (nextIndex >= parentItem->subItems.size())
  46470. return parentItem->getNextVisibleItem (false);
  46471. return parentItem->subItems [nextIndex];
  46472. }
  46473. return 0;
  46474. }
  46475. const String TreeViewItem::getItemIdentifierString() const
  46476. {
  46477. String s;
  46478. if (parentItem != 0)
  46479. s = parentItem->getItemIdentifierString();
  46480. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46481. }
  46482. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46483. {
  46484. const String thisId (getUniqueName());
  46485. if (thisId == identifierString)
  46486. return this;
  46487. if (identifierString.startsWith (thisId + "/"))
  46488. {
  46489. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46490. bool wasOpen = isOpen();
  46491. setOpen (true);
  46492. for (int i = subItems.size(); --i >= 0;)
  46493. {
  46494. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46495. if (item != 0)
  46496. return item;
  46497. }
  46498. setOpen (wasOpen);
  46499. }
  46500. return 0;
  46501. }
  46502. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46503. {
  46504. if (e.hasTagName ("CLOSED"))
  46505. {
  46506. setOpen (false);
  46507. }
  46508. else if (e.hasTagName ("OPEN"))
  46509. {
  46510. setOpen (true);
  46511. forEachXmlChildElement (e, n)
  46512. {
  46513. const String id (n->getStringAttribute ("id"));
  46514. for (int i = 0; i < subItems.size(); ++i)
  46515. {
  46516. TreeViewItem* const ti = subItems.getUnchecked(i);
  46517. if (ti->getUniqueName() == id)
  46518. {
  46519. ti->restoreOpennessState (*n);
  46520. break;
  46521. }
  46522. }
  46523. }
  46524. }
  46525. }
  46526. XmlElement* TreeViewItem::getOpennessState() const throw()
  46527. {
  46528. const String name (getUniqueName());
  46529. if (name.isNotEmpty())
  46530. {
  46531. XmlElement* e;
  46532. if (isOpen())
  46533. {
  46534. e = new XmlElement ("OPEN");
  46535. for (int i = 0; i < subItems.size(); ++i)
  46536. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46537. }
  46538. else
  46539. {
  46540. e = new XmlElement ("CLOSED");
  46541. }
  46542. e->setAttribute ("id", name);
  46543. return e;
  46544. }
  46545. else
  46546. {
  46547. // trying to save the openness for an element that has no name - this won't
  46548. // work because it needs the names to identify what to open.
  46549. jassertfalse;
  46550. }
  46551. return 0;
  46552. }
  46553. END_JUCE_NAMESPACE
  46554. /*** End of inlined file: juce_TreeView.cpp ***/
  46555. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46556. BEGIN_JUCE_NAMESPACE
  46557. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46558. : fileList (listToShow)
  46559. {
  46560. }
  46561. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46562. {
  46563. }
  46564. FileBrowserListener::~FileBrowserListener()
  46565. {
  46566. }
  46567. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46568. {
  46569. listeners.add (listener);
  46570. }
  46571. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46572. {
  46573. listeners.remove (listener);
  46574. }
  46575. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46576. {
  46577. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46578. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46579. }
  46580. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46581. {
  46582. if (fileList.getDirectory().exists())
  46583. {
  46584. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46585. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46586. }
  46587. }
  46588. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46589. {
  46590. if (fileList.getDirectory().exists())
  46591. {
  46592. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46593. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46594. }
  46595. }
  46596. END_JUCE_NAMESPACE
  46597. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46598. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46599. BEGIN_JUCE_NAMESPACE
  46600. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46601. TimeSliceThread& thread_)
  46602. : fileFilter (fileFilter_),
  46603. thread (thread_),
  46604. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46605. fileFindHandle (0),
  46606. shouldStop (true)
  46607. {
  46608. }
  46609. DirectoryContentsList::~DirectoryContentsList()
  46610. {
  46611. clear();
  46612. }
  46613. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46614. {
  46615. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46616. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46617. }
  46618. bool DirectoryContentsList::ignoresHiddenFiles() const
  46619. {
  46620. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46621. }
  46622. const File& DirectoryContentsList::getDirectory() const
  46623. {
  46624. return root;
  46625. }
  46626. void DirectoryContentsList::setDirectory (const File& directory,
  46627. const bool includeDirectories,
  46628. const bool includeFiles)
  46629. {
  46630. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46631. if (directory != root)
  46632. {
  46633. clear();
  46634. root = directory;
  46635. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46636. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46637. }
  46638. int newFlags = fileTypeFlags;
  46639. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46640. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46641. setTypeFlags (newFlags);
  46642. }
  46643. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46644. {
  46645. if (fileTypeFlags != newFlags)
  46646. {
  46647. fileTypeFlags = newFlags;
  46648. refresh();
  46649. }
  46650. }
  46651. void DirectoryContentsList::clear()
  46652. {
  46653. shouldStop = true;
  46654. thread.removeTimeSliceClient (this);
  46655. fileFindHandle = 0;
  46656. if (files.size() > 0)
  46657. {
  46658. files.clear();
  46659. changed();
  46660. }
  46661. }
  46662. void DirectoryContentsList::refresh()
  46663. {
  46664. clear();
  46665. if (root.isDirectory())
  46666. {
  46667. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46668. shouldStop = false;
  46669. thread.addTimeSliceClient (this);
  46670. }
  46671. }
  46672. int DirectoryContentsList::getNumFiles() const
  46673. {
  46674. return files.size();
  46675. }
  46676. bool DirectoryContentsList::getFileInfo (const int index,
  46677. FileInfo& result) const
  46678. {
  46679. const ScopedLock sl (fileListLock);
  46680. const FileInfo* const info = files [index];
  46681. if (info != 0)
  46682. {
  46683. result = *info;
  46684. return true;
  46685. }
  46686. return false;
  46687. }
  46688. const File DirectoryContentsList::getFile (const int index) const
  46689. {
  46690. const ScopedLock sl (fileListLock);
  46691. const FileInfo* const info = files [index];
  46692. if (info != 0)
  46693. return root.getChildFile (info->filename);
  46694. return File::nonexistent;
  46695. }
  46696. bool DirectoryContentsList::isStillLoading() const
  46697. {
  46698. return fileFindHandle != 0;
  46699. }
  46700. void DirectoryContentsList::changed()
  46701. {
  46702. sendChangeMessage (this);
  46703. }
  46704. bool DirectoryContentsList::useTimeSlice()
  46705. {
  46706. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46707. bool hasChanged = false;
  46708. for (int i = 100; --i >= 0;)
  46709. {
  46710. if (! checkNextFile (hasChanged))
  46711. {
  46712. if (hasChanged)
  46713. changed();
  46714. return false;
  46715. }
  46716. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46717. break;
  46718. }
  46719. if (hasChanged)
  46720. changed();
  46721. return true;
  46722. }
  46723. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46724. {
  46725. if (fileFindHandle != 0)
  46726. {
  46727. bool fileFoundIsDir, isHidden, isReadOnly;
  46728. int64 fileSize;
  46729. Time modTime, creationTime;
  46730. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46731. &modTime, &creationTime, &isReadOnly))
  46732. {
  46733. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46734. fileSize, modTime, creationTime, isReadOnly))
  46735. {
  46736. hasChanged = true;
  46737. }
  46738. return true;
  46739. }
  46740. else
  46741. {
  46742. fileFindHandle = 0;
  46743. }
  46744. }
  46745. return false;
  46746. }
  46747. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46748. const DirectoryContentsList::FileInfo* const second)
  46749. {
  46750. #if JUCE_WINDOWS
  46751. if (first->isDirectory != second->isDirectory)
  46752. return first->isDirectory ? -1 : 1;
  46753. #endif
  46754. return first->filename.compareIgnoreCase (second->filename);
  46755. }
  46756. bool DirectoryContentsList::addFile (const File& file,
  46757. const bool isDir,
  46758. const int64 fileSize,
  46759. const Time& modTime,
  46760. const Time& creationTime,
  46761. const bool isReadOnly)
  46762. {
  46763. if (fileFilter == 0
  46764. || ((! isDir) && fileFilter->isFileSuitable (file))
  46765. || (isDir && fileFilter->isDirectorySuitable (file)))
  46766. {
  46767. ScopedPointer <FileInfo> info (new FileInfo());
  46768. info->filename = file.getFileName();
  46769. info->fileSize = fileSize;
  46770. info->modificationTime = modTime;
  46771. info->creationTime = creationTime;
  46772. info->isDirectory = isDir;
  46773. info->isReadOnly = isReadOnly;
  46774. const ScopedLock sl (fileListLock);
  46775. for (int i = files.size(); --i >= 0;)
  46776. if (files.getUnchecked(i)->filename == info->filename)
  46777. return false;
  46778. files.addSorted (*this, info.release());
  46779. return true;
  46780. }
  46781. return false;
  46782. }
  46783. END_JUCE_NAMESPACE
  46784. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46785. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46786. BEGIN_JUCE_NAMESPACE
  46787. FileBrowserComponent::FileBrowserComponent (int flags_,
  46788. const File& initialFileOrDirectory,
  46789. const FileFilter* fileFilter_,
  46790. FilePreviewComponent* previewComp_)
  46791. : FileFilter (String::empty),
  46792. fileFilter (fileFilter_),
  46793. flags (flags_),
  46794. previewComp (previewComp_),
  46795. thread ("Juce FileBrowser")
  46796. {
  46797. // You need to specify one or other of the open/save flags..
  46798. jassert ((flags & (saveMode | openMode)) != 0);
  46799. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46800. // You need to specify at least one of these flags..
  46801. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46802. String filename;
  46803. if (initialFileOrDirectory == File::nonexistent)
  46804. {
  46805. currentRoot = File::getCurrentWorkingDirectory();
  46806. }
  46807. else if (initialFileOrDirectory.isDirectory())
  46808. {
  46809. currentRoot = initialFileOrDirectory;
  46810. }
  46811. else
  46812. {
  46813. chosenFiles.add (initialFileOrDirectory);
  46814. currentRoot = initialFileOrDirectory.getParentDirectory();
  46815. filename = initialFileOrDirectory.getFileName();
  46816. }
  46817. fileList = new DirectoryContentsList (this, thread);
  46818. if ((flags & useTreeView) != 0)
  46819. {
  46820. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46821. if ((flags & canSelectMultipleItems) != 0)
  46822. tree->setMultiSelectEnabled (true);
  46823. addAndMakeVisible (tree);
  46824. fileListComponent = tree;
  46825. }
  46826. else
  46827. {
  46828. FileListComponent* const list = new FileListComponent (*fileList);
  46829. list->setOutlineThickness (1);
  46830. if ((flags & canSelectMultipleItems) != 0)
  46831. list->setMultipleSelectionEnabled (true);
  46832. addAndMakeVisible (list);
  46833. fileListComponent = list;
  46834. }
  46835. fileListComponent->addListener (this);
  46836. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46837. currentPathBox->setEditableText (true);
  46838. StringArray rootNames, rootPaths;
  46839. const BigInteger separators (getRoots (rootNames, rootPaths));
  46840. for (int i = 0; i < rootNames.size(); ++i)
  46841. {
  46842. if (separators [i])
  46843. currentPathBox->addSeparator();
  46844. currentPathBox->addItem (rootNames[i], i + 1);
  46845. }
  46846. currentPathBox->addSeparator();
  46847. currentPathBox->addListener (this);
  46848. addAndMakeVisible (filenameBox = new TextEditor());
  46849. filenameBox->setMultiLine (false);
  46850. filenameBox->setSelectAllWhenFocused (true);
  46851. filenameBox->setText (filename, false);
  46852. filenameBox->addListener (this);
  46853. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46854. Label* label = new Label ("f", TRANS("file:"));
  46855. addAndMakeVisible (label);
  46856. label->attachToComponent (filenameBox, true);
  46857. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46858. goUpButton->addButtonListener (this);
  46859. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46860. if (previewComp != 0)
  46861. addAndMakeVisible (previewComp);
  46862. setRoot (currentRoot);
  46863. thread.startThread (4);
  46864. }
  46865. FileBrowserComponent::~FileBrowserComponent()
  46866. {
  46867. if (previewComp != 0)
  46868. removeChildComponent (previewComp);
  46869. deleteAllChildren();
  46870. fileList = 0;
  46871. thread.stopThread (10000);
  46872. }
  46873. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46874. {
  46875. listeners.add (newListener);
  46876. }
  46877. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46878. {
  46879. listeners.remove (listener);
  46880. }
  46881. bool FileBrowserComponent::isSaveMode() const throw()
  46882. {
  46883. return (flags & saveMode) != 0;
  46884. }
  46885. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46886. {
  46887. if (chosenFiles.size() == 0 && currentFileIsValid())
  46888. return 1;
  46889. return chosenFiles.size();
  46890. }
  46891. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46892. {
  46893. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46894. return currentRoot;
  46895. if (! filenameBox->isReadOnly())
  46896. return currentRoot.getChildFile (filenameBox->getText());
  46897. return chosenFiles[index];
  46898. }
  46899. bool FileBrowserComponent::currentFileIsValid() const
  46900. {
  46901. if (isSaveMode())
  46902. return ! getSelectedFile (0).isDirectory();
  46903. else
  46904. return getSelectedFile (0).exists();
  46905. }
  46906. const File FileBrowserComponent::getHighlightedFile() const throw()
  46907. {
  46908. return fileListComponent->getSelectedFile (0);
  46909. }
  46910. void FileBrowserComponent::deselectAllFiles()
  46911. {
  46912. fileListComponent->deselectAllFiles();
  46913. }
  46914. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46915. {
  46916. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46917. : false;
  46918. }
  46919. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46920. {
  46921. return true;
  46922. }
  46923. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46924. {
  46925. if (f.isDirectory())
  46926. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46927. return (flags & canSelectFiles) != 0 && f.exists()
  46928. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46929. }
  46930. const File FileBrowserComponent::getRoot() const
  46931. {
  46932. return currentRoot;
  46933. }
  46934. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46935. {
  46936. if (currentRoot != newRootDirectory)
  46937. {
  46938. fileListComponent->scrollToTop();
  46939. String path (newRootDirectory.getFullPathName());
  46940. if (path.isEmpty())
  46941. path = File::separatorString;
  46942. StringArray rootNames, rootPaths;
  46943. getRoots (rootNames, rootPaths);
  46944. if (! rootPaths.contains (path, true))
  46945. {
  46946. bool alreadyListed = false;
  46947. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46948. {
  46949. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46950. {
  46951. alreadyListed = true;
  46952. break;
  46953. }
  46954. }
  46955. if (! alreadyListed)
  46956. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46957. }
  46958. }
  46959. currentRoot = newRootDirectory;
  46960. fileList->setDirectory (currentRoot, true, true);
  46961. String currentRootName (currentRoot.getFullPathName());
  46962. if (currentRootName.isEmpty())
  46963. currentRootName = File::separatorString;
  46964. currentPathBox->setText (currentRootName, true);
  46965. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46966. && currentRoot.getParentDirectory() != currentRoot);
  46967. }
  46968. void FileBrowserComponent::goUp()
  46969. {
  46970. setRoot (getRoot().getParentDirectory());
  46971. }
  46972. void FileBrowserComponent::refresh()
  46973. {
  46974. fileList->refresh();
  46975. }
  46976. const String FileBrowserComponent::getActionVerb() const
  46977. {
  46978. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46979. }
  46980. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46981. {
  46982. return previewComp;
  46983. }
  46984. void FileBrowserComponent::resized()
  46985. {
  46986. getLookAndFeel()
  46987. .layoutFileBrowserComponent (*this, fileListComponent,
  46988. previewComp, currentPathBox,
  46989. filenameBox, goUpButton);
  46990. }
  46991. void FileBrowserComponent::sendListenerChangeMessage()
  46992. {
  46993. Component::BailOutChecker checker (this);
  46994. if (previewComp != 0)
  46995. previewComp->selectedFileChanged (getSelectedFile (0));
  46996. // You shouldn't delete the browser when the file gets changed!
  46997. jassert (! checker.shouldBailOut());
  46998. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46999. }
  47000. void FileBrowserComponent::selectionChanged()
  47001. {
  47002. StringArray newFilenames;
  47003. bool resetChosenFiles = true;
  47004. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47005. {
  47006. const File f (fileListComponent->getSelectedFile (i));
  47007. if (isFileOrDirSuitable (f))
  47008. {
  47009. if (resetChosenFiles)
  47010. {
  47011. chosenFiles.clear();
  47012. resetChosenFiles = false;
  47013. }
  47014. chosenFiles.add (f);
  47015. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47016. }
  47017. }
  47018. if (newFilenames.size() > 0)
  47019. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47020. sendListenerChangeMessage();
  47021. }
  47022. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47023. {
  47024. Component::BailOutChecker checker (this);
  47025. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47026. }
  47027. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47028. {
  47029. if (f.isDirectory())
  47030. {
  47031. setRoot (f);
  47032. if ((flags & canSelectDirectories) != 0)
  47033. filenameBox->setText (String::empty);
  47034. }
  47035. else
  47036. {
  47037. Component::BailOutChecker checker (this);
  47038. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47039. }
  47040. }
  47041. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47042. {
  47043. (void) key;
  47044. #if JUCE_LINUX || JUCE_WINDOWS
  47045. if (key.getModifiers().isCommandDown()
  47046. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47047. {
  47048. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47049. fileList->refresh();
  47050. return true;
  47051. }
  47052. #endif
  47053. return false;
  47054. }
  47055. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47056. {
  47057. sendListenerChangeMessage();
  47058. }
  47059. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47060. {
  47061. if (filenameBox->getText().containsChar (File::separator))
  47062. {
  47063. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47064. if (f.isDirectory())
  47065. {
  47066. setRoot (f);
  47067. chosenFiles.clear();
  47068. filenameBox->setText (String::empty);
  47069. }
  47070. else
  47071. {
  47072. setRoot (f.getParentDirectory());
  47073. chosenFiles.clear();
  47074. chosenFiles.add (f);
  47075. filenameBox->setText (f.getFileName());
  47076. }
  47077. }
  47078. else
  47079. {
  47080. fileDoubleClicked (getSelectedFile (0));
  47081. }
  47082. }
  47083. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47084. {
  47085. }
  47086. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47087. {
  47088. if (! isSaveMode())
  47089. selectionChanged();
  47090. }
  47091. void FileBrowserComponent::buttonClicked (Button*)
  47092. {
  47093. goUp();
  47094. }
  47095. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47096. {
  47097. const String newText (currentPathBox->getText().trim().unquoted());
  47098. if (newText.isNotEmpty())
  47099. {
  47100. const int index = currentPathBox->getSelectedId() - 1;
  47101. StringArray rootNames, rootPaths;
  47102. getRoots (rootNames, rootPaths);
  47103. if (rootPaths [index].isNotEmpty())
  47104. {
  47105. setRoot (File (rootPaths [index]));
  47106. }
  47107. else
  47108. {
  47109. File f (newText);
  47110. for (;;)
  47111. {
  47112. if (f.isDirectory())
  47113. {
  47114. setRoot (f);
  47115. break;
  47116. }
  47117. if (f.getParentDirectory() == f)
  47118. break;
  47119. f = f.getParentDirectory();
  47120. }
  47121. }
  47122. }
  47123. }
  47124. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47125. {
  47126. BigInteger separators;
  47127. #if JUCE_WINDOWS
  47128. Array<File> roots;
  47129. File::findFileSystemRoots (roots);
  47130. rootPaths.clear();
  47131. for (int i = 0; i < roots.size(); ++i)
  47132. {
  47133. const File& drive = roots.getReference(i);
  47134. String name (drive.getFullPathName());
  47135. rootPaths.add (name);
  47136. if (drive.isOnHardDisk())
  47137. {
  47138. String volume (drive.getVolumeLabel());
  47139. if (volume.isEmpty())
  47140. volume = TRANS("Hard Drive");
  47141. name << " [" << drive.getVolumeLabel() << ']';
  47142. }
  47143. else if (drive.isOnCDRomDrive())
  47144. {
  47145. name << TRANS(" [CD/DVD drive]");
  47146. }
  47147. rootNames.add (name);
  47148. }
  47149. separators.setBit (rootPaths.size());
  47150. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47151. rootNames.add ("Documents");
  47152. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47153. rootNames.add ("Desktop");
  47154. #endif
  47155. #if JUCE_MAC
  47156. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47157. rootNames.add ("Home folder");
  47158. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47159. rootNames.add ("Documents");
  47160. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47161. rootNames.add ("Desktop");
  47162. separators.setBit (rootPaths.size());
  47163. Array <File> volumes;
  47164. File vol ("/Volumes");
  47165. vol.findChildFiles (volumes, File::findDirectories, false);
  47166. for (int i = 0; i < volumes.size(); ++i)
  47167. {
  47168. const File& volume = volumes.getReference(i);
  47169. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47170. {
  47171. rootPaths.add (volume.getFullPathName());
  47172. rootNames.add (volume.getFileName());
  47173. }
  47174. }
  47175. #endif
  47176. #if JUCE_LINUX
  47177. rootPaths.add ("/");
  47178. rootNames.add ("/");
  47179. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47180. rootNames.add ("Home folder");
  47181. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47182. rootNames.add ("Desktop");
  47183. #endif
  47184. return separators;
  47185. }
  47186. END_JUCE_NAMESPACE
  47187. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47188. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47189. BEGIN_JUCE_NAMESPACE
  47190. FileChooser::FileChooser (const String& chooserBoxTitle,
  47191. const File& currentFileOrDirectory,
  47192. const String& fileFilters,
  47193. const bool useNativeDialogBox_)
  47194. : title (chooserBoxTitle),
  47195. filters (fileFilters),
  47196. startingFile (currentFileOrDirectory),
  47197. useNativeDialogBox (useNativeDialogBox_)
  47198. {
  47199. #if JUCE_LINUX
  47200. useNativeDialogBox = false;
  47201. #endif
  47202. if (! fileFilters.containsNonWhitespaceChars())
  47203. filters = "*";
  47204. }
  47205. FileChooser::~FileChooser()
  47206. {
  47207. }
  47208. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47209. {
  47210. return showDialog (false, true, false, false, false, previewComponent);
  47211. }
  47212. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47213. {
  47214. return showDialog (false, true, false, false, true, previewComponent);
  47215. }
  47216. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47217. {
  47218. return showDialog (true, true, false, false, true, previewComponent);
  47219. }
  47220. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47221. {
  47222. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47223. }
  47224. bool FileChooser::browseForDirectory()
  47225. {
  47226. return showDialog (true, false, false, false, false, 0);
  47227. }
  47228. const File FileChooser::getResult() const
  47229. {
  47230. // if you've used a multiple-file select, you should use the getResults() method
  47231. // to retrieve all the files that were chosen.
  47232. jassert (results.size() <= 1);
  47233. return results.getFirst();
  47234. }
  47235. const Array<File>& FileChooser::getResults() const
  47236. {
  47237. return results;
  47238. }
  47239. bool FileChooser::showDialog (const bool selectsDirectories,
  47240. const bool selectsFiles,
  47241. const bool isSave,
  47242. const bool warnAboutOverwritingExistingFiles,
  47243. const bool selectMultipleFiles,
  47244. FilePreviewComponent* const previewComponent)
  47245. {
  47246. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47247. results.clear();
  47248. // the preview component needs to be the right size before you pass it in here..
  47249. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47250. && previewComponent->getHeight() > 10));
  47251. #if JUCE_WINDOWS
  47252. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47253. #elif JUCE_MAC
  47254. if (useNativeDialogBox && (previewComponent == 0))
  47255. #else
  47256. if (false)
  47257. #endif
  47258. {
  47259. showPlatformDialog (results, title, startingFile, filters,
  47260. selectsDirectories, selectsFiles, isSave,
  47261. warnAboutOverwritingExistingFiles,
  47262. selectMultipleFiles,
  47263. previewComponent);
  47264. }
  47265. else
  47266. {
  47267. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47268. selectsDirectories ? "*" : String::empty,
  47269. String::empty);
  47270. int flags = isSave ? FileBrowserComponent::saveMode
  47271. : FileBrowserComponent::openMode;
  47272. if (selectsFiles)
  47273. flags |= FileBrowserComponent::canSelectFiles;
  47274. if (selectsDirectories)
  47275. {
  47276. flags |= FileBrowserComponent::canSelectDirectories;
  47277. if (! isSave)
  47278. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47279. }
  47280. if (selectMultipleFiles)
  47281. flags |= FileBrowserComponent::canSelectMultipleItems;
  47282. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47283. FileChooserDialogBox box (title, String::empty,
  47284. browserComponent,
  47285. warnAboutOverwritingExistingFiles,
  47286. browserComponent.findColour (AlertWindow::backgroundColourId));
  47287. if (box.show())
  47288. {
  47289. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47290. results.add (browserComponent.getSelectedFile (i));
  47291. }
  47292. }
  47293. if (previouslyFocused != 0)
  47294. previouslyFocused->grabKeyboardFocus();
  47295. return results.size() > 0;
  47296. }
  47297. FilePreviewComponent::FilePreviewComponent()
  47298. {
  47299. }
  47300. FilePreviewComponent::~FilePreviewComponent()
  47301. {
  47302. }
  47303. END_JUCE_NAMESPACE
  47304. /*** End of inlined file: juce_FileChooser.cpp ***/
  47305. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47306. BEGIN_JUCE_NAMESPACE
  47307. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47308. const String& instructions,
  47309. FileBrowserComponent& chooserComponent,
  47310. const bool warnAboutOverwritingExistingFiles_,
  47311. const Colour& backgroundColour)
  47312. : ResizableWindow (name, backgroundColour, true),
  47313. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47314. {
  47315. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47316. setResizable (true, true);
  47317. setResizeLimits (300, 300, 1200, 1000);
  47318. content->okButton.addButtonListener (this);
  47319. content->cancelButton.addButtonListener (this);
  47320. content->chooserComponent.addListener (this);
  47321. }
  47322. FileChooserDialogBox::~FileChooserDialogBox()
  47323. {
  47324. content->chooserComponent.removeListener (this);
  47325. }
  47326. bool FileChooserDialogBox::show (int w, int h)
  47327. {
  47328. return showAt (-1, -1, w, h);
  47329. }
  47330. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47331. {
  47332. if (w <= 0)
  47333. {
  47334. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47335. if (previewComp != 0)
  47336. w = 400 + previewComp->getWidth();
  47337. else
  47338. w = 600;
  47339. }
  47340. if (h <= 0)
  47341. h = 500;
  47342. if (x < 0 || y < 0)
  47343. centreWithSize (w, h);
  47344. else
  47345. setBounds (x, y, w, h);
  47346. const bool ok = (runModalLoop() != 0);
  47347. setVisible (false);
  47348. return ok;
  47349. }
  47350. void FileChooserDialogBox::buttonClicked (Button* button)
  47351. {
  47352. if (button == &(content->okButton))
  47353. {
  47354. if (warnAboutOverwritingExistingFiles
  47355. && content->chooserComponent.isSaveMode()
  47356. && content->chooserComponent.getSelectedFile(0).exists())
  47357. {
  47358. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47359. TRANS("File already exists"),
  47360. TRANS("There's already a file called:")
  47361. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47362. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47363. TRANS("overwrite"),
  47364. TRANS("cancel")))
  47365. {
  47366. return;
  47367. }
  47368. }
  47369. exitModalState (1);
  47370. }
  47371. else if (button == &(content->cancelButton))
  47372. {
  47373. closeButtonPressed();
  47374. }
  47375. }
  47376. void FileChooserDialogBox::closeButtonPressed()
  47377. {
  47378. setVisible (false);
  47379. }
  47380. void FileChooserDialogBox::selectionChanged()
  47381. {
  47382. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47383. }
  47384. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47385. {
  47386. }
  47387. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47388. {
  47389. selectionChanged();
  47390. content->okButton.triggerClick();
  47391. }
  47392. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47393. : Component (name), instructions (instructions_),
  47394. chooserComponent (chooserComponent_),
  47395. okButton (chooserComponent_.getActionVerb()),
  47396. cancelButton (TRANS ("Cancel"))
  47397. {
  47398. addAndMakeVisible (&chooserComponent);
  47399. addAndMakeVisible (&okButton);
  47400. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47401. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47402. addAndMakeVisible (&cancelButton);
  47403. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47404. setInterceptsMouseClicks (false, true);
  47405. }
  47406. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47407. {
  47408. }
  47409. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47410. {
  47411. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47412. text.draw (g);
  47413. }
  47414. void FileChooserDialogBox::ContentComponent::resized()
  47415. {
  47416. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47417. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47418. const int y = roundToInt (bb.getBottom()) + 10;
  47419. const int buttonHeight = 26;
  47420. const int buttonY = getHeight() - buttonHeight - 8;
  47421. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47422. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47423. proportionOfWidth (0.2f), buttonHeight);
  47424. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47425. proportionOfWidth (0.2f), buttonHeight);
  47426. }
  47427. END_JUCE_NAMESPACE
  47428. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47429. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47430. BEGIN_JUCE_NAMESPACE
  47431. FileFilter::FileFilter (const String& filterDescription)
  47432. : description (filterDescription)
  47433. {
  47434. }
  47435. FileFilter::~FileFilter()
  47436. {
  47437. }
  47438. const String& FileFilter::getDescription() const throw()
  47439. {
  47440. return description;
  47441. }
  47442. END_JUCE_NAMESPACE
  47443. /*** End of inlined file: juce_FileFilter.cpp ***/
  47444. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47445. BEGIN_JUCE_NAMESPACE
  47446. const Image juce_createIconForFile (const File& file);
  47447. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47448. : ListBox (String::empty, 0),
  47449. DirectoryContentsDisplayComponent (listToShow)
  47450. {
  47451. setModel (this);
  47452. fileList.addChangeListener (this);
  47453. }
  47454. FileListComponent::~FileListComponent()
  47455. {
  47456. fileList.removeChangeListener (this);
  47457. }
  47458. int FileListComponent::getNumSelectedFiles() const
  47459. {
  47460. return getNumSelectedRows();
  47461. }
  47462. const File FileListComponent::getSelectedFile (int index) const
  47463. {
  47464. return fileList.getFile (getSelectedRow (index));
  47465. }
  47466. void FileListComponent::deselectAllFiles()
  47467. {
  47468. deselectAllRows();
  47469. }
  47470. void FileListComponent::scrollToTop()
  47471. {
  47472. getVerticalScrollBar()->setCurrentRangeStart (0);
  47473. }
  47474. void FileListComponent::changeListenerCallback (void*)
  47475. {
  47476. updateContent();
  47477. if (lastDirectory != fileList.getDirectory())
  47478. {
  47479. lastDirectory = fileList.getDirectory();
  47480. deselectAllRows();
  47481. }
  47482. }
  47483. class FileListItemComponent : public Component,
  47484. public TimeSliceClient,
  47485. public AsyncUpdater
  47486. {
  47487. public:
  47488. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47489. : owner (owner_), thread (thread_),
  47490. highlighted (false), index (0), icon (0)
  47491. {
  47492. }
  47493. ~FileListItemComponent()
  47494. {
  47495. thread.removeTimeSliceClient (this);
  47496. clearIcon();
  47497. }
  47498. void paint (Graphics& g)
  47499. {
  47500. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47501. file.getFileName(),
  47502. &icon,
  47503. fileSize, modTime,
  47504. isDirectory, highlighted,
  47505. index);
  47506. }
  47507. void mouseDown (const MouseEvent& e)
  47508. {
  47509. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47510. owner.sendMouseClickMessage (file, e);
  47511. }
  47512. void mouseDoubleClick (const MouseEvent&)
  47513. {
  47514. owner.sendDoubleClickMessage (file);
  47515. }
  47516. void update (const File& root,
  47517. const DirectoryContentsList::FileInfo* const fileInfo,
  47518. const int index_,
  47519. const bool highlighted_)
  47520. {
  47521. thread.removeTimeSliceClient (this);
  47522. if (highlighted_ != highlighted
  47523. || index_ != index)
  47524. {
  47525. index = index_;
  47526. highlighted = highlighted_;
  47527. repaint();
  47528. }
  47529. File newFile;
  47530. String newFileSize;
  47531. String newModTime;
  47532. if (fileInfo != 0)
  47533. {
  47534. newFile = root.getChildFile (fileInfo->filename);
  47535. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47536. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47537. }
  47538. if (newFile != file
  47539. || fileSize != newFileSize
  47540. || modTime != newModTime)
  47541. {
  47542. file = newFile;
  47543. fileSize = newFileSize;
  47544. modTime = newModTime;
  47545. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47546. repaint();
  47547. clearIcon();
  47548. }
  47549. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47550. {
  47551. updateIcon (true);
  47552. if (! icon.isValid())
  47553. thread.addTimeSliceClient (this);
  47554. }
  47555. }
  47556. bool useTimeSlice()
  47557. {
  47558. updateIcon (false);
  47559. return false;
  47560. }
  47561. void handleAsyncUpdate()
  47562. {
  47563. repaint();
  47564. }
  47565. juce_UseDebuggingNewOperator
  47566. private:
  47567. FileListComponent& owner;
  47568. TimeSliceThread& thread;
  47569. bool highlighted;
  47570. int index;
  47571. File file;
  47572. String fileSize;
  47573. String modTime;
  47574. Image icon;
  47575. bool isDirectory;
  47576. void clearIcon()
  47577. {
  47578. icon = Image::null;
  47579. }
  47580. void updateIcon (const bool onlyUpdateIfCached)
  47581. {
  47582. if (icon.isNull())
  47583. {
  47584. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47585. Image im (ImageCache::getFromHashCode (hashCode));
  47586. if (im.isNull() && ! onlyUpdateIfCached)
  47587. {
  47588. im = juce_createIconForFile (file);
  47589. if (im.isValid())
  47590. ImageCache::addImageToCache (im, hashCode);
  47591. }
  47592. if (im.isValid())
  47593. {
  47594. icon = im;
  47595. triggerAsyncUpdate();
  47596. }
  47597. }
  47598. }
  47599. };
  47600. int FileListComponent::getNumRows()
  47601. {
  47602. return fileList.getNumFiles();
  47603. }
  47604. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47605. {
  47606. }
  47607. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47608. {
  47609. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47610. if (comp == 0)
  47611. {
  47612. delete existingComponentToUpdate;
  47613. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47614. }
  47615. DirectoryContentsList::FileInfo fileInfo;
  47616. if (fileList.getFileInfo (row, fileInfo))
  47617. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47618. else
  47619. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47620. return comp;
  47621. }
  47622. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47623. {
  47624. sendSelectionChangeMessage();
  47625. }
  47626. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47627. {
  47628. }
  47629. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47630. {
  47631. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47632. }
  47633. END_JUCE_NAMESPACE
  47634. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47635. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47636. BEGIN_JUCE_NAMESPACE
  47637. FilenameComponent::FilenameComponent (const String& name,
  47638. const File& currentFile,
  47639. const bool canEditFilename,
  47640. const bool isDirectory,
  47641. const bool isForSaving,
  47642. const String& fileBrowserWildcard,
  47643. const String& enforcedSuffix_,
  47644. const String& textWhenNothingSelected)
  47645. : Component (name),
  47646. maxRecentFiles (30),
  47647. isDir (isDirectory),
  47648. isSaving (isForSaving),
  47649. isFileDragOver (false),
  47650. wildcard (fileBrowserWildcard),
  47651. enforcedSuffix (enforcedSuffix_)
  47652. {
  47653. addAndMakeVisible (&filenameBox);
  47654. filenameBox.setEditableText (canEditFilename);
  47655. filenameBox.addListener (this);
  47656. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47657. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47658. setBrowseButtonText ("...");
  47659. setCurrentFile (currentFile, true);
  47660. }
  47661. FilenameComponent::~FilenameComponent()
  47662. {
  47663. }
  47664. void FilenameComponent::paintOverChildren (Graphics& g)
  47665. {
  47666. if (isFileDragOver)
  47667. {
  47668. g.setColour (Colours::red.withAlpha (0.2f));
  47669. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47670. }
  47671. }
  47672. void FilenameComponent::resized()
  47673. {
  47674. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47675. }
  47676. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47677. {
  47678. browseButtonText = newBrowseButtonText;
  47679. lookAndFeelChanged();
  47680. }
  47681. void FilenameComponent::lookAndFeelChanged()
  47682. {
  47683. browseButton = 0;
  47684. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47685. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47686. resized();
  47687. browseButton->addButtonListener (this);
  47688. }
  47689. void FilenameComponent::setTooltip (const String& newTooltip)
  47690. {
  47691. SettableTooltipClient::setTooltip (newTooltip);
  47692. filenameBox.setTooltip (newTooltip);
  47693. }
  47694. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47695. {
  47696. defaultBrowseFile = newDefaultDirectory;
  47697. }
  47698. void FilenameComponent::buttonClicked (Button*)
  47699. {
  47700. FileChooser fc (TRANS("Choose a new file"),
  47701. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47702. : getCurrentFile(),
  47703. wildcard);
  47704. if (isDir ? fc.browseForDirectory()
  47705. : (isSaving ? fc.browseForFileToSave (false)
  47706. : fc.browseForFileToOpen()))
  47707. {
  47708. setCurrentFile (fc.getResult(), true);
  47709. }
  47710. }
  47711. void FilenameComponent::comboBoxChanged (ComboBox*)
  47712. {
  47713. setCurrentFile (getCurrentFile(), true);
  47714. }
  47715. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47716. {
  47717. return true;
  47718. }
  47719. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47720. {
  47721. isFileDragOver = false;
  47722. repaint();
  47723. const File f (filenames[0]);
  47724. if (f.exists() && (f.isDirectory() == isDir))
  47725. setCurrentFile (f, true);
  47726. }
  47727. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47728. {
  47729. isFileDragOver = true;
  47730. repaint();
  47731. }
  47732. void FilenameComponent::fileDragExit (const StringArray&)
  47733. {
  47734. isFileDragOver = false;
  47735. repaint();
  47736. }
  47737. const File FilenameComponent::getCurrentFile() const
  47738. {
  47739. File f (filenameBox.getText());
  47740. if (enforcedSuffix.isNotEmpty())
  47741. f = f.withFileExtension (enforcedSuffix);
  47742. return f;
  47743. }
  47744. void FilenameComponent::setCurrentFile (File newFile,
  47745. const bool addToRecentlyUsedList,
  47746. const bool sendChangeNotification)
  47747. {
  47748. if (enforcedSuffix.isNotEmpty())
  47749. newFile = newFile.withFileExtension (enforcedSuffix);
  47750. if (newFile.getFullPathName() != lastFilename)
  47751. {
  47752. lastFilename = newFile.getFullPathName();
  47753. if (addToRecentlyUsedList)
  47754. addRecentlyUsedFile (newFile);
  47755. filenameBox.setText (lastFilename, true);
  47756. if (sendChangeNotification)
  47757. triggerAsyncUpdate();
  47758. }
  47759. }
  47760. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47761. {
  47762. filenameBox.setEditableText (shouldBeEditable);
  47763. }
  47764. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47765. {
  47766. StringArray names;
  47767. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47768. names.add (filenameBox.getItemText (i));
  47769. return names;
  47770. }
  47771. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47772. {
  47773. if (filenames != getRecentlyUsedFilenames())
  47774. {
  47775. filenameBox.clear();
  47776. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47777. filenameBox.addItem (filenames[i], i + 1);
  47778. }
  47779. }
  47780. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47781. {
  47782. maxRecentFiles = jmax (1, newMaximum);
  47783. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47784. }
  47785. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47786. {
  47787. StringArray files (getRecentlyUsedFilenames());
  47788. if (file.getFullPathName().isNotEmpty())
  47789. {
  47790. files.removeString (file.getFullPathName(), true);
  47791. files.insert (0, file.getFullPathName());
  47792. setRecentlyUsedFilenames (files);
  47793. }
  47794. }
  47795. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47796. {
  47797. listeners.add (listener);
  47798. }
  47799. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47800. {
  47801. listeners.remove (listener);
  47802. }
  47803. void FilenameComponent::handleAsyncUpdate()
  47804. {
  47805. Component::BailOutChecker checker (this);
  47806. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47807. }
  47808. END_JUCE_NAMESPACE
  47809. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47810. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47811. BEGIN_JUCE_NAMESPACE
  47812. FileSearchPathListComponent::FileSearchPathListComponent()
  47813. {
  47814. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47815. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47816. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47817. listBox->setOutlineThickness (1);
  47818. addAndMakeVisible (addButton = new TextButton ("+"));
  47819. addButton->addButtonListener (this);
  47820. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47821. addAndMakeVisible (removeButton = new TextButton ("-"));
  47822. removeButton->addButtonListener (this);
  47823. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47824. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47825. changeButton->addButtonListener (this);
  47826. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47827. upButton->addButtonListener (this);
  47828. {
  47829. Path arrowPath;
  47830. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47831. DrawablePath arrowImage;
  47832. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47833. arrowImage.setPath (arrowPath);
  47834. upButton->setImages (&arrowImage);
  47835. }
  47836. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47837. downButton->addButtonListener (this);
  47838. {
  47839. Path arrowPath;
  47840. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47841. DrawablePath arrowImage;
  47842. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47843. arrowImage.setPath (arrowPath);
  47844. downButton->setImages (&arrowImage);
  47845. }
  47846. updateButtons();
  47847. }
  47848. FileSearchPathListComponent::~FileSearchPathListComponent()
  47849. {
  47850. deleteAllChildren();
  47851. }
  47852. void FileSearchPathListComponent::updateButtons()
  47853. {
  47854. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47855. removeButton->setEnabled (anythingSelected);
  47856. changeButton->setEnabled (anythingSelected);
  47857. upButton->setEnabled (anythingSelected);
  47858. downButton->setEnabled (anythingSelected);
  47859. }
  47860. void FileSearchPathListComponent::changed()
  47861. {
  47862. listBox->updateContent();
  47863. listBox->repaint();
  47864. updateButtons();
  47865. }
  47866. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47867. {
  47868. if (newPath.toString() != path.toString())
  47869. {
  47870. path = newPath;
  47871. changed();
  47872. }
  47873. }
  47874. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47875. {
  47876. defaultBrowseTarget = newDefaultDirectory;
  47877. }
  47878. int FileSearchPathListComponent::getNumRows()
  47879. {
  47880. return path.getNumPaths();
  47881. }
  47882. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47883. {
  47884. if (rowIsSelected)
  47885. g.fillAll (findColour (TextEditor::highlightColourId));
  47886. g.setColour (findColour (ListBox::textColourId));
  47887. Font f (height * 0.7f);
  47888. f.setHorizontalScale (0.9f);
  47889. g.setFont (f);
  47890. g.drawText (path [rowNumber].getFullPathName(),
  47891. 4, 0, width - 6, height,
  47892. Justification::centredLeft, true);
  47893. }
  47894. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47895. {
  47896. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47897. {
  47898. path.remove (row);
  47899. changed();
  47900. }
  47901. }
  47902. void FileSearchPathListComponent::returnKeyPressed (int row)
  47903. {
  47904. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47905. if (chooser.browseForDirectory())
  47906. {
  47907. path.remove (row);
  47908. path.add (chooser.getResult(), row);
  47909. changed();
  47910. }
  47911. }
  47912. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47913. {
  47914. returnKeyPressed (row);
  47915. }
  47916. void FileSearchPathListComponent::selectedRowsChanged (int)
  47917. {
  47918. updateButtons();
  47919. }
  47920. void FileSearchPathListComponent::paint (Graphics& g)
  47921. {
  47922. g.fillAll (findColour (backgroundColourId));
  47923. }
  47924. void FileSearchPathListComponent::resized()
  47925. {
  47926. const int buttonH = 22;
  47927. const int buttonY = getHeight() - buttonH - 4;
  47928. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47929. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47930. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47931. changeButton->changeWidthToFitText (buttonH);
  47932. downButton->setSize (buttonH * 2, buttonH);
  47933. upButton->setSize (buttonH * 2, buttonH);
  47934. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47935. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47936. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47937. }
  47938. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47939. {
  47940. return true;
  47941. }
  47942. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47943. {
  47944. for (int i = filenames.size(); --i >= 0;)
  47945. {
  47946. const File f (filenames[i]);
  47947. if (f.isDirectory())
  47948. {
  47949. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47950. path.add (f, row);
  47951. changed();
  47952. }
  47953. }
  47954. }
  47955. void FileSearchPathListComponent::buttonClicked (Button* button)
  47956. {
  47957. const int currentRow = listBox->getSelectedRow();
  47958. if (button == removeButton)
  47959. {
  47960. deleteKeyPressed (currentRow);
  47961. }
  47962. else if (button == addButton)
  47963. {
  47964. File start (defaultBrowseTarget);
  47965. if (start == File::nonexistent)
  47966. start = path [0];
  47967. if (start == File::nonexistent)
  47968. start = File::getCurrentWorkingDirectory();
  47969. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47970. if (chooser.browseForDirectory())
  47971. {
  47972. path.add (chooser.getResult(), currentRow);
  47973. }
  47974. }
  47975. else if (button == changeButton)
  47976. {
  47977. returnKeyPressed (currentRow);
  47978. }
  47979. else if (button == upButton)
  47980. {
  47981. if (currentRow > 0 && currentRow < path.getNumPaths())
  47982. {
  47983. const File f (path[currentRow]);
  47984. path.remove (currentRow);
  47985. path.add (f, currentRow - 1);
  47986. listBox->selectRow (currentRow - 1);
  47987. }
  47988. }
  47989. else if (button == downButton)
  47990. {
  47991. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47992. {
  47993. const File f (path[currentRow]);
  47994. path.remove (currentRow);
  47995. path.add (f, currentRow + 1);
  47996. listBox->selectRow (currentRow + 1);
  47997. }
  47998. }
  47999. changed();
  48000. }
  48001. END_JUCE_NAMESPACE
  48002. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48003. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48004. BEGIN_JUCE_NAMESPACE
  48005. const Image juce_createIconForFile (const File& file);
  48006. class FileListTreeItem : public TreeViewItem,
  48007. public TimeSliceClient,
  48008. public AsyncUpdater,
  48009. public ChangeListener
  48010. {
  48011. public:
  48012. FileListTreeItem (FileTreeComponent& owner_,
  48013. DirectoryContentsList* const parentContentsList_,
  48014. const int indexInContentsList_,
  48015. const File& file_,
  48016. TimeSliceThread& thread_)
  48017. : file (file_),
  48018. owner (owner_),
  48019. parentContentsList (parentContentsList_),
  48020. indexInContentsList (indexInContentsList_),
  48021. subContentsList (0),
  48022. canDeleteSubContentsList (false),
  48023. thread (thread_),
  48024. icon (0)
  48025. {
  48026. DirectoryContentsList::FileInfo fileInfo;
  48027. if (parentContentsList_ != 0
  48028. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48029. {
  48030. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48031. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48032. isDirectory = fileInfo.isDirectory;
  48033. }
  48034. else
  48035. {
  48036. isDirectory = true;
  48037. }
  48038. }
  48039. ~FileListTreeItem()
  48040. {
  48041. thread.removeTimeSliceClient (this);
  48042. clearSubItems();
  48043. if (canDeleteSubContentsList)
  48044. delete subContentsList;
  48045. }
  48046. bool mightContainSubItems() { return isDirectory; }
  48047. const String getUniqueName() const { return file.getFullPathName(); }
  48048. int getItemHeight() const { return 22; }
  48049. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48050. void itemOpennessChanged (bool isNowOpen)
  48051. {
  48052. if (isNowOpen)
  48053. {
  48054. clearSubItems();
  48055. isDirectory = file.isDirectory();
  48056. if (isDirectory)
  48057. {
  48058. if (subContentsList == 0)
  48059. {
  48060. jassert (parentContentsList != 0);
  48061. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48062. l->setDirectory (file, true, true);
  48063. setSubContentsList (l);
  48064. canDeleteSubContentsList = true;
  48065. }
  48066. changeListenerCallback (0);
  48067. }
  48068. }
  48069. }
  48070. void setSubContentsList (DirectoryContentsList* newList)
  48071. {
  48072. jassert (subContentsList == 0);
  48073. subContentsList = newList;
  48074. newList->addChangeListener (this);
  48075. }
  48076. void changeListenerCallback (void*)
  48077. {
  48078. clearSubItems();
  48079. if (isOpen() && subContentsList != 0)
  48080. {
  48081. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48082. {
  48083. FileListTreeItem* const item
  48084. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48085. addSubItem (item);
  48086. }
  48087. }
  48088. }
  48089. void paintItem (Graphics& g, int width, int height)
  48090. {
  48091. if (file != File::nonexistent)
  48092. {
  48093. updateIcon (true);
  48094. if (icon.isNull())
  48095. thread.addTimeSliceClient (this);
  48096. }
  48097. owner.getLookAndFeel()
  48098. .drawFileBrowserRow (g, width, height,
  48099. file.getFileName(),
  48100. &icon, fileSize, modTime,
  48101. isDirectory, isSelected(),
  48102. indexInContentsList);
  48103. }
  48104. void itemClicked (const MouseEvent& e)
  48105. {
  48106. owner.sendMouseClickMessage (file, e);
  48107. }
  48108. void itemDoubleClicked (const MouseEvent& e)
  48109. {
  48110. TreeViewItem::itemDoubleClicked (e);
  48111. owner.sendDoubleClickMessage (file);
  48112. }
  48113. void itemSelectionChanged (bool)
  48114. {
  48115. owner.sendSelectionChangeMessage();
  48116. }
  48117. bool useTimeSlice()
  48118. {
  48119. updateIcon (false);
  48120. thread.removeTimeSliceClient (this);
  48121. return false;
  48122. }
  48123. void handleAsyncUpdate()
  48124. {
  48125. owner.repaint();
  48126. }
  48127. const File file;
  48128. juce_UseDebuggingNewOperator
  48129. private:
  48130. FileTreeComponent& owner;
  48131. DirectoryContentsList* parentContentsList;
  48132. int indexInContentsList;
  48133. DirectoryContentsList* subContentsList;
  48134. bool isDirectory, canDeleteSubContentsList;
  48135. TimeSliceThread& thread;
  48136. Image icon;
  48137. String fileSize;
  48138. String modTime;
  48139. void updateIcon (const bool onlyUpdateIfCached)
  48140. {
  48141. if (icon.isNull())
  48142. {
  48143. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48144. Image im (ImageCache::getFromHashCode (hashCode));
  48145. if (im.isNull() && ! onlyUpdateIfCached)
  48146. {
  48147. im = juce_createIconForFile (file);
  48148. if (im.isValid())
  48149. ImageCache::addImageToCache (im, hashCode);
  48150. }
  48151. if (im.isValid())
  48152. {
  48153. icon = im;
  48154. triggerAsyncUpdate();
  48155. }
  48156. }
  48157. }
  48158. };
  48159. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48160. : DirectoryContentsDisplayComponent (listToShow)
  48161. {
  48162. FileListTreeItem* const root
  48163. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48164. listToShow.getTimeSliceThread());
  48165. root->setSubContentsList (&listToShow);
  48166. setRootItemVisible (false);
  48167. setRootItem (root);
  48168. }
  48169. FileTreeComponent::~FileTreeComponent()
  48170. {
  48171. deleteRootItem();
  48172. }
  48173. const File FileTreeComponent::getSelectedFile (const int index) const
  48174. {
  48175. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48176. return item != 0 ? item->file
  48177. : File::nonexistent;
  48178. }
  48179. void FileTreeComponent::deselectAllFiles()
  48180. {
  48181. clearSelectedItems();
  48182. }
  48183. void FileTreeComponent::scrollToTop()
  48184. {
  48185. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48186. }
  48187. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48188. {
  48189. dragAndDropDescription = description;
  48190. }
  48191. END_JUCE_NAMESPACE
  48192. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48193. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48194. BEGIN_JUCE_NAMESPACE
  48195. ImagePreviewComponent::ImagePreviewComponent()
  48196. {
  48197. }
  48198. ImagePreviewComponent::~ImagePreviewComponent()
  48199. {
  48200. }
  48201. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48202. {
  48203. const int availableW = proportionOfWidth (0.97f);
  48204. const int availableH = getHeight() - 13 * 4;
  48205. const double scale = jmin (1.0,
  48206. availableW / (double) w,
  48207. availableH / (double) h);
  48208. w = roundToInt (scale * w);
  48209. h = roundToInt (scale * h);
  48210. }
  48211. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48212. {
  48213. if (fileToLoad != file)
  48214. {
  48215. fileToLoad = file;
  48216. startTimer (100);
  48217. }
  48218. }
  48219. void ImagePreviewComponent::timerCallback()
  48220. {
  48221. stopTimer();
  48222. currentThumbnail = Image::null;
  48223. currentDetails = String::empty;
  48224. repaint();
  48225. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48226. if (in != 0)
  48227. {
  48228. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48229. if (format != 0)
  48230. {
  48231. currentThumbnail = format->decodeImage (*in);
  48232. if (currentThumbnail.isValid())
  48233. {
  48234. int w = currentThumbnail.getWidth();
  48235. int h = currentThumbnail.getHeight();
  48236. currentDetails
  48237. << fileToLoad.getFileName() << "\n"
  48238. << format->getFormatName() << "\n"
  48239. << w << " x " << h << " pixels\n"
  48240. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48241. getThumbSize (w, h);
  48242. currentThumbnail = currentThumbnail.rescaled (w, h);
  48243. }
  48244. }
  48245. }
  48246. }
  48247. void ImagePreviewComponent::paint (Graphics& g)
  48248. {
  48249. if (currentThumbnail.isValid())
  48250. {
  48251. g.setFont (13.0f);
  48252. int w = currentThumbnail.getWidth();
  48253. int h = currentThumbnail.getHeight();
  48254. getThumbSize (w, h);
  48255. const int numLines = 4;
  48256. const int totalH = 13 * numLines + h + 4;
  48257. const int y = (getHeight() - totalH) / 2;
  48258. g.drawImageWithin (currentThumbnail,
  48259. (getWidth() - w) / 2, y, w, h,
  48260. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48261. false);
  48262. g.drawFittedText (currentDetails,
  48263. 0, y + h + 4, getWidth(), 100,
  48264. Justification::centredTop, numLines);
  48265. }
  48266. }
  48267. END_JUCE_NAMESPACE
  48268. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48269. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48270. BEGIN_JUCE_NAMESPACE
  48271. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48272. const String& directoryWildcardPatterns,
  48273. const String& description_)
  48274. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48275. : (description_ + " (" + fileWildcardPatterns + ")"))
  48276. {
  48277. parse (fileWildcardPatterns, fileWildcards);
  48278. parse (directoryWildcardPatterns, directoryWildcards);
  48279. }
  48280. WildcardFileFilter::~WildcardFileFilter()
  48281. {
  48282. }
  48283. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48284. {
  48285. return match (file, fileWildcards);
  48286. }
  48287. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48288. {
  48289. return match (file, directoryWildcards);
  48290. }
  48291. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48292. {
  48293. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48294. result.trim();
  48295. result.removeEmptyStrings();
  48296. // special case for *.*, because people use it to mean "any file", but it
  48297. // would actually ignore files with no extension.
  48298. for (int i = result.size(); --i >= 0;)
  48299. if (result[i] == "*.*")
  48300. result.set (i, "*");
  48301. }
  48302. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48303. {
  48304. const String filename (file.getFileName());
  48305. for (int i = wildcards.size(); --i >= 0;)
  48306. if (filename.matchesWildcard (wildcards[i], true))
  48307. return true;
  48308. return false;
  48309. }
  48310. END_JUCE_NAMESPACE
  48311. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48312. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48313. BEGIN_JUCE_NAMESPACE
  48314. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48315. {
  48316. }
  48317. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48318. {
  48319. }
  48320. namespace KeyboardFocusHelpers
  48321. {
  48322. // This will sort a set of components, so that they are ordered in terms of
  48323. // left-to-right and then top-to-bottom.
  48324. class ScreenPositionComparator
  48325. {
  48326. public:
  48327. ScreenPositionComparator() {}
  48328. static int compareElements (const Component* const first, const Component* const second)
  48329. {
  48330. int explicitOrder1 = first->getExplicitFocusOrder();
  48331. if (explicitOrder1 <= 0)
  48332. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48333. int explicitOrder2 = second->getExplicitFocusOrder();
  48334. if (explicitOrder2 <= 0)
  48335. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48336. if (explicitOrder1 != explicitOrder2)
  48337. return explicitOrder1 - explicitOrder2;
  48338. const int diff = first->getY() - second->getY();
  48339. return (diff == 0) ? first->getX() - second->getX()
  48340. : diff;
  48341. }
  48342. };
  48343. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48344. {
  48345. if (parent->getNumChildComponents() > 0)
  48346. {
  48347. Array <Component*> localComps;
  48348. ScreenPositionComparator comparator;
  48349. int i;
  48350. for (i = parent->getNumChildComponents(); --i >= 0;)
  48351. {
  48352. Component* const c = parent->getChildComponent (i);
  48353. if (c->isVisible() && c->isEnabled())
  48354. localComps.addSorted (comparator, c);
  48355. }
  48356. for (i = 0; i < localComps.size(); ++i)
  48357. {
  48358. Component* const c = localComps.getUnchecked (i);
  48359. if (c->getWantsKeyboardFocus())
  48360. comps.add (c);
  48361. if (! c->isFocusContainer())
  48362. findAllFocusableComponents (c, comps);
  48363. }
  48364. }
  48365. }
  48366. }
  48367. static Component* getIncrementedComponent (Component* const current, const int delta)
  48368. {
  48369. Component* focusContainer = current->getParentComponent();
  48370. if (focusContainer != 0)
  48371. {
  48372. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48373. focusContainer = focusContainer->getParentComponent();
  48374. if (focusContainer != 0)
  48375. {
  48376. Array <Component*> comps;
  48377. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48378. if (comps.size() > 0)
  48379. {
  48380. const int index = comps.indexOf (current);
  48381. return comps [(index + comps.size() + delta) % comps.size()];
  48382. }
  48383. }
  48384. }
  48385. return 0;
  48386. }
  48387. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48388. {
  48389. return getIncrementedComponent (current, 1);
  48390. }
  48391. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48392. {
  48393. return getIncrementedComponent (current, -1);
  48394. }
  48395. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48396. {
  48397. Array <Component*> comps;
  48398. if (parentComponent != 0)
  48399. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48400. return comps.getFirst();
  48401. }
  48402. END_JUCE_NAMESPACE
  48403. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48404. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48405. BEGIN_JUCE_NAMESPACE
  48406. bool KeyListener::keyStateChanged (const bool, Component*)
  48407. {
  48408. return false;
  48409. }
  48410. END_JUCE_NAMESPACE
  48411. /*** End of inlined file: juce_KeyListener.cpp ***/
  48412. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48413. BEGIN_JUCE_NAMESPACE
  48414. // N.B. these two includes are put here deliberately to avoid problems with
  48415. // old GCCs failing on long include paths
  48416. const int maxKeys = 3;
  48417. class KeyMappingChangeButton : public Button
  48418. {
  48419. public:
  48420. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48421. const CommandID commandID_,
  48422. const String& keyName,
  48423. const int keyNum_)
  48424. : Button (keyName),
  48425. owner (owner_),
  48426. commandID (commandID_),
  48427. keyNum (keyNum_)
  48428. {
  48429. setWantsKeyboardFocus (false);
  48430. setTriggeredOnMouseDown (keyNum >= 0);
  48431. if (keyNum_ < 0)
  48432. setTooltip (TRANS("adds a new key-mapping"));
  48433. else
  48434. setTooltip (TRANS("click to change this key-mapping"));
  48435. }
  48436. ~KeyMappingChangeButton()
  48437. {
  48438. }
  48439. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48440. {
  48441. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48442. keyNum >= 0 ? getName() : String::empty);
  48443. }
  48444. void clicked()
  48445. {
  48446. if (keyNum >= 0)
  48447. {
  48448. // existing key clicked..
  48449. PopupMenu m;
  48450. m.addItem (1, TRANS("change this key-mapping"));
  48451. m.addSeparator();
  48452. m.addItem (2, TRANS("remove this key-mapping"));
  48453. const int res = m.show();
  48454. if (res == 1)
  48455. {
  48456. owner->assignNewKey (commandID, keyNum);
  48457. }
  48458. else if (res == 2)
  48459. {
  48460. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48461. }
  48462. }
  48463. else
  48464. {
  48465. // + button pressed..
  48466. owner->assignNewKey (commandID, -1);
  48467. }
  48468. }
  48469. void fitToContent (const int h) throw()
  48470. {
  48471. if (keyNum < 0)
  48472. {
  48473. setSize (h, h);
  48474. }
  48475. else
  48476. {
  48477. Font f (h * 0.6f);
  48478. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48479. }
  48480. }
  48481. juce_UseDebuggingNewOperator
  48482. private:
  48483. KeyMappingEditorComponent* const owner;
  48484. const CommandID commandID;
  48485. const int keyNum;
  48486. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48487. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48488. };
  48489. class KeyMappingItemComponent : public Component
  48490. {
  48491. public:
  48492. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48493. const CommandID commandID_)
  48494. : owner (owner_),
  48495. commandID (commandID_)
  48496. {
  48497. setInterceptsMouseClicks (false, true);
  48498. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48499. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48500. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48501. {
  48502. KeyMappingChangeButton* const kb
  48503. = new KeyMappingChangeButton (owner_, commandID,
  48504. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48505. kb->setEnabled (! isReadOnly);
  48506. addAndMakeVisible (kb);
  48507. }
  48508. KeyMappingChangeButton* const kb
  48509. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48510. addChildComponent (kb);
  48511. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48512. }
  48513. ~KeyMappingItemComponent()
  48514. {
  48515. deleteAllChildren();
  48516. }
  48517. void paint (Graphics& g)
  48518. {
  48519. g.setFont (getHeight() * 0.7f);
  48520. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48521. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48522. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48523. Justification::centredLeft, true);
  48524. }
  48525. void resized()
  48526. {
  48527. int x = getWidth() - 4;
  48528. for (int i = getNumChildComponents(); --i >= 0;)
  48529. {
  48530. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48531. kb->fitToContent (getHeight() - 2);
  48532. kb->setTopRightPosition (x, 1);
  48533. x -= kb->getWidth() + 5;
  48534. }
  48535. }
  48536. juce_UseDebuggingNewOperator
  48537. private:
  48538. KeyMappingEditorComponent* const owner;
  48539. const CommandID commandID;
  48540. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48541. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48542. };
  48543. class KeyMappingTreeViewItem : public TreeViewItem
  48544. {
  48545. public:
  48546. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48547. const CommandID commandID_)
  48548. : owner (owner_),
  48549. commandID (commandID_)
  48550. {
  48551. }
  48552. ~KeyMappingTreeViewItem()
  48553. {
  48554. }
  48555. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48556. bool mightContainSubItems() { return false; }
  48557. int getItemHeight() const { return 20; }
  48558. Component* createItemComponent()
  48559. {
  48560. return new KeyMappingItemComponent (owner, commandID);
  48561. }
  48562. juce_UseDebuggingNewOperator
  48563. private:
  48564. KeyMappingEditorComponent* const owner;
  48565. const CommandID commandID;
  48566. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48567. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48568. };
  48569. class KeyCategoryTreeViewItem : public TreeViewItem
  48570. {
  48571. public:
  48572. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48573. const String& name)
  48574. : owner (owner_),
  48575. categoryName (name)
  48576. {
  48577. }
  48578. ~KeyCategoryTreeViewItem()
  48579. {
  48580. }
  48581. const String getUniqueName() const { return categoryName + "_cat"; }
  48582. bool mightContainSubItems() { return true; }
  48583. int getItemHeight() const { return 28; }
  48584. void paintItem (Graphics& g, int width, int height)
  48585. {
  48586. g.setFont (height * 0.6f, Font::bold);
  48587. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48588. g.drawText (categoryName,
  48589. 2, 0, width - 2, height,
  48590. Justification::centredLeft, true);
  48591. }
  48592. void itemOpennessChanged (bool isNowOpen)
  48593. {
  48594. if (isNowOpen)
  48595. {
  48596. if (getNumSubItems() == 0)
  48597. {
  48598. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48599. for (int i = 0; i < commands.size(); ++i)
  48600. {
  48601. if (owner->shouldCommandBeIncluded (commands[i]))
  48602. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48603. }
  48604. }
  48605. }
  48606. else
  48607. {
  48608. clearSubItems();
  48609. }
  48610. }
  48611. juce_UseDebuggingNewOperator
  48612. private:
  48613. KeyMappingEditorComponent* owner;
  48614. String categoryName;
  48615. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48616. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48617. };
  48618. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48619. const bool showResetToDefaultButton)
  48620. : mappings (mappingManager)
  48621. {
  48622. jassert (mappingManager != 0); // can't be null!
  48623. mappingManager->addChangeListener (this);
  48624. setLinesDrawnForSubItems (false);
  48625. resetButton = 0;
  48626. if (showResetToDefaultButton)
  48627. {
  48628. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48629. resetButton->addButtonListener (this);
  48630. }
  48631. addAndMakeVisible (tree = new TreeView());
  48632. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48633. tree->setRootItemVisible (false);
  48634. tree->setDefaultOpenness (true);
  48635. tree->setRootItem (this);
  48636. }
  48637. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48638. {
  48639. mappings->removeChangeListener (this);
  48640. deleteAllChildren();
  48641. }
  48642. bool KeyMappingEditorComponent::mightContainSubItems()
  48643. {
  48644. return true;
  48645. }
  48646. const String KeyMappingEditorComponent::getUniqueName() const
  48647. {
  48648. return "keys";
  48649. }
  48650. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48651. const Colour& textColour)
  48652. {
  48653. setColour (backgroundColourId, mainBackground);
  48654. setColour (textColourId, textColour);
  48655. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48656. }
  48657. void KeyMappingEditorComponent::parentHierarchyChanged()
  48658. {
  48659. changeListenerCallback (0);
  48660. }
  48661. void KeyMappingEditorComponent::resized()
  48662. {
  48663. int h = getHeight();
  48664. if (resetButton != 0)
  48665. {
  48666. const int buttonHeight = 20;
  48667. h -= buttonHeight + 8;
  48668. int x = getWidth() - 8;
  48669. resetButton->changeWidthToFitText (buttonHeight);
  48670. resetButton->setTopRightPosition (x, h + 6);
  48671. }
  48672. tree->setBounds (0, 0, getWidth(), h);
  48673. }
  48674. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48675. {
  48676. if (button == resetButton)
  48677. {
  48678. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48679. TRANS("Reset to defaults"),
  48680. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48681. TRANS("Reset")))
  48682. {
  48683. mappings->resetToDefaultMappings();
  48684. }
  48685. }
  48686. }
  48687. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48688. {
  48689. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48690. clearSubItems();
  48691. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48692. for (int i = 0; i < categories.size(); ++i)
  48693. {
  48694. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48695. int count = 0;
  48696. for (int j = 0; j < commands.size(); ++j)
  48697. if (shouldCommandBeIncluded (commands[j]))
  48698. ++count;
  48699. if (count > 0)
  48700. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48701. }
  48702. if (oldOpenness != 0)
  48703. tree->restoreOpennessState (*oldOpenness);
  48704. }
  48705. class KeyEntryWindow : public AlertWindow
  48706. {
  48707. public:
  48708. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48709. : AlertWindow (TRANS("New key-mapping"),
  48710. TRANS("Please press a key combination now..."),
  48711. AlertWindow::NoIcon),
  48712. owner (owner_)
  48713. {
  48714. addButton (TRANS("ok"), 1);
  48715. addButton (TRANS("cancel"), 0);
  48716. // (avoid return + escape keys getting processed by the buttons..)
  48717. for (int i = getNumChildComponents(); --i >= 0;)
  48718. getChildComponent (i)->setWantsKeyboardFocus (false);
  48719. setWantsKeyboardFocus (true);
  48720. grabKeyboardFocus();
  48721. }
  48722. ~KeyEntryWindow()
  48723. {
  48724. }
  48725. bool keyPressed (const KeyPress& key)
  48726. {
  48727. lastPress = key;
  48728. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48729. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48730. if (previousCommand != 0)
  48731. {
  48732. message << "\n\n"
  48733. << TRANS("(Currently assigned to \"")
  48734. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48735. << "\")";
  48736. }
  48737. setMessage (message);
  48738. return true;
  48739. }
  48740. bool keyStateChanged (bool)
  48741. {
  48742. return true;
  48743. }
  48744. KeyPress lastPress;
  48745. juce_UseDebuggingNewOperator
  48746. private:
  48747. KeyMappingEditorComponent* owner;
  48748. KeyEntryWindow (const KeyEntryWindow&);
  48749. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48750. };
  48751. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48752. {
  48753. KeyEntryWindow entryWindow (this);
  48754. if (entryWindow.runModalLoop() != 0)
  48755. {
  48756. entryWindow.setVisible (false);
  48757. if (entryWindow.lastPress.isValid())
  48758. {
  48759. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48760. if (previousCommand != 0)
  48761. {
  48762. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48763. TRANS("Change key-mapping"),
  48764. TRANS("This key is already assigned to the command \"")
  48765. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48766. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48767. TRANS("re-assign"),
  48768. TRANS("cancel")))
  48769. {
  48770. return;
  48771. }
  48772. }
  48773. mappings->removeKeyPress (entryWindow.lastPress);
  48774. if (index >= 0)
  48775. mappings->removeKeyPress (commandID, index);
  48776. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48777. }
  48778. }
  48779. }
  48780. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48781. {
  48782. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48783. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48784. }
  48785. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48786. {
  48787. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48788. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48789. }
  48790. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48791. {
  48792. return key.getTextDescription();
  48793. }
  48794. END_JUCE_NAMESPACE
  48795. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48796. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48797. BEGIN_JUCE_NAMESPACE
  48798. KeyPress::KeyPress() throw()
  48799. : keyCode (0),
  48800. mods (0),
  48801. textCharacter (0)
  48802. {
  48803. }
  48804. KeyPress::KeyPress (const int keyCode_,
  48805. const ModifierKeys& mods_,
  48806. const juce_wchar textCharacter_) throw()
  48807. : keyCode (keyCode_),
  48808. mods (mods_),
  48809. textCharacter (textCharacter_)
  48810. {
  48811. }
  48812. KeyPress::KeyPress (const int keyCode_) throw()
  48813. : keyCode (keyCode_),
  48814. textCharacter (0)
  48815. {
  48816. }
  48817. KeyPress::KeyPress (const KeyPress& other) throw()
  48818. : keyCode (other.keyCode),
  48819. mods (other.mods),
  48820. textCharacter (other.textCharacter)
  48821. {
  48822. }
  48823. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48824. {
  48825. keyCode = other.keyCode;
  48826. mods = other.mods;
  48827. textCharacter = other.textCharacter;
  48828. return *this;
  48829. }
  48830. bool KeyPress::operator== (const KeyPress& other) const throw()
  48831. {
  48832. return mods.getRawFlags() == other.mods.getRawFlags()
  48833. && (textCharacter == other.textCharacter
  48834. || textCharacter == 0
  48835. || other.textCharacter == 0)
  48836. && (keyCode == other.keyCode
  48837. || (keyCode < 256
  48838. && other.keyCode < 256
  48839. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48840. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48841. }
  48842. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48843. {
  48844. return ! operator== (other);
  48845. }
  48846. bool KeyPress::isCurrentlyDown() const
  48847. {
  48848. return isKeyCurrentlyDown (keyCode)
  48849. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48850. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48851. }
  48852. namespace KeyPressHelpers
  48853. {
  48854. struct KeyNameAndCode
  48855. {
  48856. const char* name;
  48857. int code;
  48858. };
  48859. static const KeyNameAndCode translations[] =
  48860. {
  48861. { "spacebar", KeyPress::spaceKey },
  48862. { "return", KeyPress::returnKey },
  48863. { "escape", KeyPress::escapeKey },
  48864. { "backspace", KeyPress::backspaceKey },
  48865. { "cursor left", KeyPress::leftKey },
  48866. { "cursor right", KeyPress::rightKey },
  48867. { "cursor up", KeyPress::upKey },
  48868. { "cursor down", KeyPress::downKey },
  48869. { "page up", KeyPress::pageUpKey },
  48870. { "page down", KeyPress::pageDownKey },
  48871. { "home", KeyPress::homeKey },
  48872. { "end", KeyPress::endKey },
  48873. { "delete", KeyPress::deleteKey },
  48874. { "insert", KeyPress::insertKey },
  48875. { "tab", KeyPress::tabKey },
  48876. { "play", KeyPress::playKey },
  48877. { "stop", KeyPress::stopKey },
  48878. { "fast forward", KeyPress::fastForwardKey },
  48879. { "rewind", KeyPress::rewindKey }
  48880. };
  48881. static const String numberPadPrefix() { return "numpad "; }
  48882. }
  48883. const KeyPress KeyPress::createFromDescription (const String& desc)
  48884. {
  48885. int modifiers = 0;
  48886. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48887. || desc.containsWholeWordIgnoreCase ("control")
  48888. || desc.containsWholeWordIgnoreCase ("ctl"))
  48889. modifiers |= ModifierKeys::ctrlModifier;
  48890. if (desc.containsWholeWordIgnoreCase ("shift")
  48891. || desc.containsWholeWordIgnoreCase ("shft"))
  48892. modifiers |= ModifierKeys::shiftModifier;
  48893. if (desc.containsWholeWordIgnoreCase ("alt")
  48894. || desc.containsWholeWordIgnoreCase ("option"))
  48895. modifiers |= ModifierKeys::altModifier;
  48896. if (desc.containsWholeWordIgnoreCase ("command")
  48897. || desc.containsWholeWordIgnoreCase ("cmd"))
  48898. modifiers |= ModifierKeys::commandModifier;
  48899. int key = 0;
  48900. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48901. {
  48902. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48903. {
  48904. key = KeyPressHelpers::translations[i].code;
  48905. break;
  48906. }
  48907. }
  48908. if (key == 0)
  48909. {
  48910. // see if it's a numpad key..
  48911. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48912. {
  48913. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48914. if (lastChar >= '0' && lastChar <= '9')
  48915. key = numberPad0 + lastChar - '0';
  48916. else if (lastChar == '+')
  48917. key = numberPadAdd;
  48918. else if (lastChar == '-')
  48919. key = numberPadSubtract;
  48920. else if (lastChar == '*')
  48921. key = numberPadMultiply;
  48922. else if (lastChar == '/')
  48923. key = numberPadDivide;
  48924. else if (lastChar == '.')
  48925. key = numberPadDecimalPoint;
  48926. else if (lastChar == '=')
  48927. key = numberPadEquals;
  48928. else if (desc.endsWith ("separator"))
  48929. key = numberPadSeparator;
  48930. else if (desc.endsWith ("delete"))
  48931. key = numberPadDelete;
  48932. }
  48933. if (key == 0)
  48934. {
  48935. // see if it's a function key..
  48936. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48937. for (int i = 1; i <= 12; ++i)
  48938. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48939. key = F1Key + i - 1;
  48940. if (key == 0)
  48941. {
  48942. // give up and use the hex code..
  48943. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48944. .toLowerCase()
  48945. .retainCharacters ("0123456789abcdef")
  48946. .getHexValue32();
  48947. if (hexCode > 0)
  48948. key = hexCode;
  48949. else
  48950. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48951. }
  48952. }
  48953. }
  48954. return KeyPress (key, ModifierKeys (modifiers), 0);
  48955. }
  48956. const String KeyPress::getTextDescription() const
  48957. {
  48958. String desc;
  48959. if (keyCode > 0)
  48960. {
  48961. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48962. // want to store it as being a slash, not shift+whatever.
  48963. if (textCharacter == '/')
  48964. return "/";
  48965. if (mods.isCtrlDown())
  48966. desc << "ctrl + ";
  48967. if (mods.isShiftDown())
  48968. desc << "shift + ";
  48969. #if JUCE_MAC
  48970. // only do this on the mac, because on Windows ctrl and command are the same,
  48971. // and this would get confusing
  48972. if (mods.isCommandDown())
  48973. desc << "command + ";
  48974. if (mods.isAltDown())
  48975. desc << "option + ";
  48976. #else
  48977. if (mods.isAltDown())
  48978. desc << "alt + ";
  48979. #endif
  48980. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48981. if (keyCode == KeyPressHelpers::translations[i].code)
  48982. return desc + KeyPressHelpers::translations[i].name;
  48983. if (keyCode >= F1Key && keyCode <= F16Key)
  48984. desc << 'F' << (1 + keyCode - F1Key);
  48985. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48986. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48987. else if (keyCode >= 33 && keyCode < 176)
  48988. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48989. else if (keyCode == numberPadAdd)
  48990. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48991. else if (keyCode == numberPadSubtract)
  48992. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48993. else if (keyCode == numberPadMultiply)
  48994. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48995. else if (keyCode == numberPadDivide)
  48996. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48997. else if (keyCode == numberPadSeparator)
  48998. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48999. else if (keyCode == numberPadDecimalPoint)
  49000. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49001. else if (keyCode == numberPadDelete)
  49002. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49003. else
  49004. desc << '#' << String::toHexString (keyCode);
  49005. }
  49006. return desc;
  49007. }
  49008. END_JUCE_NAMESPACE
  49009. /*** End of inlined file: juce_KeyPress.cpp ***/
  49010. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49011. BEGIN_JUCE_NAMESPACE
  49012. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49013. : commandManager (commandManager_)
  49014. {
  49015. // A manager is needed to get the descriptions of commands, and will be called when
  49016. // a command is invoked. So you can't leave this null..
  49017. jassert (commandManager_ != 0);
  49018. Desktop::getInstance().addFocusChangeListener (this);
  49019. }
  49020. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49021. : commandManager (other.commandManager)
  49022. {
  49023. Desktop::getInstance().addFocusChangeListener (this);
  49024. }
  49025. KeyPressMappingSet::~KeyPressMappingSet()
  49026. {
  49027. Desktop::getInstance().removeFocusChangeListener (this);
  49028. }
  49029. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49030. {
  49031. for (int i = 0; i < mappings.size(); ++i)
  49032. if (mappings.getUnchecked(i)->commandID == commandID)
  49033. return mappings.getUnchecked (i)->keypresses;
  49034. return Array <KeyPress> ();
  49035. }
  49036. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49037. const KeyPress& newKeyPress,
  49038. int insertIndex)
  49039. {
  49040. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49041. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49042. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49043. && ! newKeyPress.getModifiers().isShiftDown()));
  49044. if (findCommandForKeyPress (newKeyPress) != commandID)
  49045. {
  49046. removeKeyPress (newKeyPress);
  49047. if (newKeyPress.isValid())
  49048. {
  49049. for (int i = mappings.size(); --i >= 0;)
  49050. {
  49051. if (mappings.getUnchecked(i)->commandID == commandID)
  49052. {
  49053. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49054. sendChangeMessage (this);
  49055. return;
  49056. }
  49057. }
  49058. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49059. if (ci != 0)
  49060. {
  49061. CommandMapping* const cm = new CommandMapping();
  49062. cm->commandID = commandID;
  49063. cm->keypresses.add (newKeyPress);
  49064. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49065. mappings.add (cm);
  49066. sendChangeMessage (this);
  49067. }
  49068. }
  49069. }
  49070. }
  49071. void KeyPressMappingSet::resetToDefaultMappings()
  49072. {
  49073. mappings.clear();
  49074. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49075. {
  49076. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49077. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49078. {
  49079. addKeyPress (ci->commandID,
  49080. ci->defaultKeypresses.getReference (j));
  49081. }
  49082. }
  49083. sendChangeMessage (this);
  49084. }
  49085. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49086. {
  49087. clearAllKeyPresses (commandID);
  49088. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49089. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49090. {
  49091. addKeyPress (ci->commandID,
  49092. ci->defaultKeypresses.getReference (j));
  49093. }
  49094. }
  49095. void KeyPressMappingSet::clearAllKeyPresses()
  49096. {
  49097. if (mappings.size() > 0)
  49098. {
  49099. sendChangeMessage (this);
  49100. mappings.clear();
  49101. }
  49102. }
  49103. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49104. {
  49105. for (int i = mappings.size(); --i >= 0;)
  49106. {
  49107. if (mappings.getUnchecked(i)->commandID == commandID)
  49108. {
  49109. mappings.remove (i);
  49110. sendChangeMessage (this);
  49111. }
  49112. }
  49113. }
  49114. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49115. {
  49116. if (keypress.isValid())
  49117. {
  49118. for (int i = mappings.size(); --i >= 0;)
  49119. {
  49120. CommandMapping* const cm = mappings.getUnchecked(i);
  49121. for (int j = cm->keypresses.size(); --j >= 0;)
  49122. {
  49123. if (keypress == cm->keypresses [j])
  49124. {
  49125. cm->keypresses.remove (j);
  49126. sendChangeMessage (this);
  49127. }
  49128. }
  49129. }
  49130. }
  49131. }
  49132. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49133. {
  49134. for (int i = mappings.size(); --i >= 0;)
  49135. {
  49136. if (mappings.getUnchecked(i)->commandID == commandID)
  49137. {
  49138. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49139. sendChangeMessage (this);
  49140. break;
  49141. }
  49142. }
  49143. }
  49144. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49145. {
  49146. for (int i = 0; i < mappings.size(); ++i)
  49147. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49148. return mappings.getUnchecked(i)->commandID;
  49149. return 0;
  49150. }
  49151. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49152. {
  49153. for (int i = mappings.size(); --i >= 0;)
  49154. if (mappings.getUnchecked(i)->commandID == commandID)
  49155. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49156. return false;
  49157. }
  49158. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49159. const KeyPress& key,
  49160. const bool isKeyDown,
  49161. const int millisecsSinceKeyPressed,
  49162. Component* const originatingComponent) const
  49163. {
  49164. ApplicationCommandTarget::InvocationInfo info (commandID);
  49165. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49166. info.isKeyDown = isKeyDown;
  49167. info.keyPress = key;
  49168. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49169. info.originatingComponent = originatingComponent;
  49170. commandManager->invoke (info, false);
  49171. }
  49172. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49173. {
  49174. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49175. {
  49176. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49177. {
  49178. // if the XML was created as a set of differences from the default mappings,
  49179. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49180. resetToDefaultMappings();
  49181. }
  49182. else
  49183. {
  49184. // if the XML was created calling createXml (false), then we need to clear all
  49185. // the keys and treat the xml as describing the entire set of mappings.
  49186. clearAllKeyPresses();
  49187. }
  49188. forEachXmlChildElement (xmlVersion, map)
  49189. {
  49190. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49191. if (commandId != 0)
  49192. {
  49193. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49194. if (map->hasTagName ("MAPPING"))
  49195. {
  49196. addKeyPress (commandId, key);
  49197. }
  49198. else if (map->hasTagName ("UNMAPPING"))
  49199. {
  49200. if (containsMapping (commandId, key))
  49201. removeKeyPress (key);
  49202. }
  49203. }
  49204. }
  49205. return true;
  49206. }
  49207. return false;
  49208. }
  49209. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49210. {
  49211. ScopedPointer <KeyPressMappingSet> defaultSet;
  49212. if (saveDifferencesFromDefaultSet)
  49213. {
  49214. defaultSet = new KeyPressMappingSet (commandManager);
  49215. defaultSet->resetToDefaultMappings();
  49216. }
  49217. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49218. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49219. int i;
  49220. for (i = 0; i < mappings.size(); ++i)
  49221. {
  49222. const CommandMapping* const cm = mappings.getUnchecked(i);
  49223. for (int j = 0; j < cm->keypresses.size(); ++j)
  49224. {
  49225. if (defaultSet == 0
  49226. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49227. {
  49228. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49229. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49230. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49231. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49232. }
  49233. }
  49234. }
  49235. if (defaultSet != 0)
  49236. {
  49237. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49238. {
  49239. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49240. for (int j = 0; j < cm->keypresses.size(); ++j)
  49241. {
  49242. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49243. {
  49244. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49245. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49246. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49247. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49248. }
  49249. }
  49250. }
  49251. }
  49252. return doc;
  49253. }
  49254. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49255. Component* originatingComponent)
  49256. {
  49257. bool used = false;
  49258. const CommandID commandID = findCommandForKeyPress (key);
  49259. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49260. if (ci != 0
  49261. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49262. {
  49263. ApplicationCommandInfo info (0);
  49264. if (commandManager->getTargetForCommand (commandID, info) != 0
  49265. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49266. {
  49267. invokeCommand (commandID, key, true, 0, originatingComponent);
  49268. used = true;
  49269. }
  49270. else
  49271. {
  49272. if (originatingComponent != 0)
  49273. originatingComponent->getLookAndFeel().playAlertSound();
  49274. }
  49275. }
  49276. return used;
  49277. }
  49278. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49279. {
  49280. bool used = false;
  49281. const uint32 now = Time::getMillisecondCounter();
  49282. for (int i = mappings.size(); --i >= 0;)
  49283. {
  49284. CommandMapping* const cm = mappings.getUnchecked(i);
  49285. if (cm->wantsKeyUpDownCallbacks)
  49286. {
  49287. for (int j = cm->keypresses.size(); --j >= 0;)
  49288. {
  49289. const KeyPress key (cm->keypresses.getReference (j));
  49290. const bool isDown = key.isCurrentlyDown();
  49291. int keyPressEntryIndex = 0;
  49292. bool wasDown = false;
  49293. for (int k = keysDown.size(); --k >= 0;)
  49294. {
  49295. if (key == keysDown.getUnchecked(k)->key)
  49296. {
  49297. keyPressEntryIndex = k;
  49298. wasDown = true;
  49299. used = true;
  49300. break;
  49301. }
  49302. }
  49303. if (isDown != wasDown)
  49304. {
  49305. int millisecs = 0;
  49306. if (isDown)
  49307. {
  49308. KeyPressTime* const k = new KeyPressTime();
  49309. k->key = key;
  49310. k->timeWhenPressed = now;
  49311. keysDown.add (k);
  49312. }
  49313. else
  49314. {
  49315. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49316. if (now > pressTime)
  49317. millisecs = now - pressTime;
  49318. keysDown.remove (keyPressEntryIndex);
  49319. }
  49320. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49321. used = true;
  49322. }
  49323. }
  49324. }
  49325. }
  49326. return used;
  49327. }
  49328. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49329. {
  49330. if (focusedComponent != 0)
  49331. focusedComponent->keyStateChanged (false);
  49332. }
  49333. END_JUCE_NAMESPACE
  49334. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49335. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49336. BEGIN_JUCE_NAMESPACE
  49337. ModifierKeys::ModifierKeys (const int flags_) throw()
  49338. : flags (flags_)
  49339. {
  49340. }
  49341. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49342. : flags (other.flags)
  49343. {
  49344. }
  49345. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49346. {
  49347. flags = other.flags;
  49348. return *this;
  49349. }
  49350. ModifierKeys ModifierKeys::currentModifiers;
  49351. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49352. {
  49353. return currentModifiers;
  49354. }
  49355. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49356. {
  49357. int num = 0;
  49358. if (isLeftButtonDown()) ++num;
  49359. if (isRightButtonDown()) ++num;
  49360. if (isMiddleButtonDown()) ++num;
  49361. return num;
  49362. }
  49363. END_JUCE_NAMESPACE
  49364. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49365. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49366. BEGIN_JUCE_NAMESPACE
  49367. class ComponentAnimator::AnimationTask
  49368. {
  49369. public:
  49370. AnimationTask (Component* const comp)
  49371. : component (comp)
  49372. {
  49373. }
  49374. Component::SafePointer<Component> component;
  49375. Rectangle<int> destination;
  49376. int msElapsed, msTotal;
  49377. double startSpeed, midSpeed, endSpeed, lastProgress;
  49378. double left, top, right, bottom;
  49379. bool useTimeslice (const int elapsed)
  49380. {
  49381. if (component == 0)
  49382. return false;
  49383. msElapsed += elapsed;
  49384. double newProgress = msElapsed / (double) msTotal;
  49385. if (newProgress >= 0 && newProgress < 1.0)
  49386. {
  49387. newProgress = timeToDistance (newProgress);
  49388. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49389. jassert (newProgress >= lastProgress);
  49390. lastProgress = newProgress;
  49391. left += (destination.getX() - left) * delta;
  49392. top += (destination.getY() - top) * delta;
  49393. right += (destination.getRight() - right) * delta;
  49394. bottom += (destination.getBottom() - bottom) * delta;
  49395. if (delta < 1.0)
  49396. {
  49397. const Rectangle<int> newBounds (roundToInt (left),
  49398. roundToInt (top),
  49399. roundToInt (right - left),
  49400. roundToInt (bottom - top));
  49401. if (newBounds != destination)
  49402. {
  49403. component->setBounds (newBounds);
  49404. return true;
  49405. }
  49406. }
  49407. }
  49408. component->setBounds (destination);
  49409. return false;
  49410. }
  49411. void moveToFinalDestination()
  49412. {
  49413. if (component != 0)
  49414. component->setBounds (destination);
  49415. }
  49416. private:
  49417. inline double timeToDistance (const double time) const
  49418. {
  49419. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49420. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49421. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49422. }
  49423. };
  49424. ComponentAnimator::ComponentAnimator()
  49425. : lastTime (0)
  49426. {
  49427. }
  49428. ComponentAnimator::~ComponentAnimator()
  49429. {
  49430. cancelAllAnimations (false);
  49431. jassert (tasks.size() == 0);
  49432. }
  49433. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49434. {
  49435. for (int i = tasks.size(); --i >= 0;)
  49436. if (component == tasks.getUnchecked(i)->component.getComponent())
  49437. return tasks.getUnchecked(i);
  49438. return 0;
  49439. }
  49440. void ComponentAnimator::animateComponent (Component* const component,
  49441. const Rectangle<int>& finalPosition,
  49442. const int millisecondsToSpendMoving,
  49443. const double startSpeed,
  49444. const double endSpeed)
  49445. {
  49446. if (component != 0)
  49447. {
  49448. AnimationTask* at = findTaskFor (component);
  49449. if (at == 0)
  49450. {
  49451. at = new AnimationTask (component);
  49452. tasks.add (at);
  49453. sendChangeMessage (this);
  49454. }
  49455. at->msElapsed = 0;
  49456. at->lastProgress = 0;
  49457. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49458. at->destination = finalPosition;
  49459. // the speeds must be 0 or greater!
  49460. jassert (startSpeed >= 0 && endSpeed >= 0)
  49461. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49462. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49463. at->midSpeed = invTotalDistance;
  49464. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49465. at->left = component->getX();
  49466. at->top = component->getY();
  49467. at->right = component->getRight();
  49468. at->bottom = component->getBottom();
  49469. if (! isTimerRunning())
  49470. {
  49471. lastTime = Time::getMillisecondCounter();
  49472. startTimer (1000 / 50);
  49473. }
  49474. }
  49475. }
  49476. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49477. {
  49478. for (int i = tasks.size(); --i >= 0;)
  49479. {
  49480. AnimationTask* const at = tasks.getUnchecked(i);
  49481. if (moveComponentsToTheirFinalPositions)
  49482. at->moveToFinalDestination();
  49483. delete at;
  49484. tasks.remove (i);
  49485. sendChangeMessage (this);
  49486. }
  49487. }
  49488. void ComponentAnimator::cancelAnimation (Component* const component,
  49489. const bool moveComponentToItsFinalPosition)
  49490. {
  49491. AnimationTask* const at = findTaskFor (component);
  49492. if (at != 0)
  49493. {
  49494. if (moveComponentToItsFinalPosition)
  49495. at->moveToFinalDestination();
  49496. tasks.removeValue (at);
  49497. delete at;
  49498. sendChangeMessage (this);
  49499. }
  49500. }
  49501. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49502. {
  49503. AnimationTask* const at = findTaskFor (component);
  49504. if (at != 0)
  49505. return at->destination;
  49506. else if (component != 0)
  49507. return component->getBounds();
  49508. return Rectangle<int>();
  49509. }
  49510. bool ComponentAnimator::isAnimating (Component* component) const
  49511. {
  49512. return findTaskFor (component) != 0;
  49513. }
  49514. void ComponentAnimator::timerCallback()
  49515. {
  49516. const uint32 timeNow = Time::getMillisecondCounter();
  49517. if (lastTime == 0 || lastTime == timeNow)
  49518. lastTime = timeNow;
  49519. const int elapsed = timeNow - lastTime;
  49520. for (int i = tasks.size(); --i >= 0;)
  49521. {
  49522. AnimationTask* const at = tasks.getUnchecked(i);
  49523. if (! at->useTimeslice (elapsed))
  49524. {
  49525. tasks.remove (i);
  49526. delete at;
  49527. sendChangeMessage (this);
  49528. }
  49529. }
  49530. lastTime = timeNow;
  49531. if (tasks.size() == 0)
  49532. stopTimer();
  49533. }
  49534. END_JUCE_NAMESPACE
  49535. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49536. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49537. BEGIN_JUCE_NAMESPACE
  49538. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49539. : minW (0),
  49540. maxW (0x3fffffff),
  49541. minH (0),
  49542. maxH (0x3fffffff),
  49543. minOffTop (0),
  49544. minOffLeft (0),
  49545. minOffBottom (0),
  49546. minOffRight (0),
  49547. aspectRatio (0.0)
  49548. {
  49549. }
  49550. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49551. {
  49552. }
  49553. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49554. {
  49555. minW = minimumWidth;
  49556. }
  49557. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49558. {
  49559. maxW = maximumWidth;
  49560. }
  49561. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49562. {
  49563. minH = minimumHeight;
  49564. }
  49565. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49566. {
  49567. maxH = maximumHeight;
  49568. }
  49569. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49570. {
  49571. jassert (maxW >= minimumWidth);
  49572. jassert (maxH >= minimumHeight);
  49573. jassert (minimumWidth > 0 && minimumHeight > 0);
  49574. minW = minimumWidth;
  49575. minH = minimumHeight;
  49576. if (minW > maxW)
  49577. maxW = minW;
  49578. if (minH > maxH)
  49579. maxH = minH;
  49580. }
  49581. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49582. {
  49583. jassert (maximumWidth >= minW);
  49584. jassert (maximumHeight >= minH);
  49585. jassert (maximumWidth > 0 && maximumHeight > 0);
  49586. maxW = jmax (minW, maximumWidth);
  49587. maxH = jmax (minH, maximumHeight);
  49588. }
  49589. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49590. const int minimumHeight,
  49591. const int maximumWidth,
  49592. const int maximumHeight) throw()
  49593. {
  49594. jassert (maximumWidth >= minimumWidth);
  49595. jassert (maximumHeight >= minimumHeight);
  49596. jassert (maximumWidth > 0 && maximumHeight > 0);
  49597. jassert (minimumWidth > 0 && minimumHeight > 0);
  49598. minW = jmax (0, minimumWidth);
  49599. minH = jmax (0, minimumHeight);
  49600. maxW = jmax (minW, maximumWidth);
  49601. maxH = jmax (minH, maximumHeight);
  49602. }
  49603. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49604. const int minimumWhenOffTheLeft,
  49605. const int minimumWhenOffTheBottom,
  49606. const int minimumWhenOffTheRight) throw()
  49607. {
  49608. minOffTop = minimumWhenOffTheTop;
  49609. minOffLeft = minimumWhenOffTheLeft;
  49610. minOffBottom = minimumWhenOffTheBottom;
  49611. minOffRight = minimumWhenOffTheRight;
  49612. }
  49613. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49614. {
  49615. aspectRatio = jmax (0.0, widthOverHeight);
  49616. }
  49617. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49618. {
  49619. return aspectRatio;
  49620. }
  49621. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49622. const Rectangle<int>& targetBounds,
  49623. const bool isStretchingTop,
  49624. const bool isStretchingLeft,
  49625. const bool isStretchingBottom,
  49626. const bool isStretchingRight)
  49627. {
  49628. jassert (component != 0);
  49629. Rectangle<int> limits, bounds (targetBounds);
  49630. BorderSize border;
  49631. Component* const parent = component->getParentComponent();
  49632. if (parent == 0)
  49633. {
  49634. ComponentPeer* peer = component->getPeer();
  49635. if (peer != 0)
  49636. border = peer->getFrameSize();
  49637. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49638. }
  49639. else
  49640. {
  49641. limits.setSize (parent->getWidth(), parent->getHeight());
  49642. }
  49643. border.addTo (bounds);
  49644. checkBounds (bounds,
  49645. border.addedTo (component->getBounds()), limits,
  49646. isStretchingTop, isStretchingLeft,
  49647. isStretchingBottom, isStretchingRight);
  49648. border.subtractFrom (bounds);
  49649. applyBoundsToComponent (component, bounds);
  49650. }
  49651. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49652. {
  49653. setBoundsForComponent (component, component->getBounds(),
  49654. false, false, false, false);
  49655. }
  49656. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49657. const Rectangle<int>& bounds)
  49658. {
  49659. component->setBounds (bounds);
  49660. }
  49661. void ComponentBoundsConstrainer::resizeStart()
  49662. {
  49663. }
  49664. void ComponentBoundsConstrainer::resizeEnd()
  49665. {
  49666. }
  49667. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49668. const Rectangle<int>& old,
  49669. const Rectangle<int>& limits,
  49670. const bool isStretchingTop,
  49671. const bool isStretchingLeft,
  49672. const bool isStretchingBottom,
  49673. const bool isStretchingRight)
  49674. {
  49675. int x = bounds.getX();
  49676. int y = bounds.getY();
  49677. int w = bounds.getWidth();
  49678. int h = bounds.getHeight();
  49679. // constrain the size if it's being stretched..
  49680. if (isStretchingLeft)
  49681. {
  49682. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49683. w = old.getRight() - x;
  49684. }
  49685. if (isStretchingRight)
  49686. {
  49687. w = jlimit (minW, maxW, w);
  49688. }
  49689. if (isStretchingTop)
  49690. {
  49691. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49692. h = old.getBottom() - y;
  49693. }
  49694. if (isStretchingBottom)
  49695. {
  49696. h = jlimit (minH, maxH, h);
  49697. }
  49698. // constrain the aspect ratio if one has been specified..
  49699. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49700. {
  49701. bool adjustWidth;
  49702. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49703. {
  49704. adjustWidth = true;
  49705. }
  49706. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49707. {
  49708. adjustWidth = false;
  49709. }
  49710. else
  49711. {
  49712. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49713. const double newRatio = std::abs (w / (double) h);
  49714. adjustWidth = (oldRatio > newRatio);
  49715. }
  49716. if (adjustWidth)
  49717. {
  49718. w = roundToInt (h * aspectRatio);
  49719. if (w > maxW || w < minW)
  49720. {
  49721. w = jlimit (minW, maxW, w);
  49722. h = roundToInt (w / aspectRatio);
  49723. }
  49724. }
  49725. else
  49726. {
  49727. h = roundToInt (w / aspectRatio);
  49728. if (h > maxH || h < minH)
  49729. {
  49730. h = jlimit (minH, maxH, h);
  49731. w = roundToInt (h * aspectRatio);
  49732. }
  49733. }
  49734. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49735. {
  49736. x = old.getX() + (old.getWidth() - w) / 2;
  49737. }
  49738. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49739. {
  49740. y = old.getY() + (old.getHeight() - h) / 2;
  49741. }
  49742. else
  49743. {
  49744. if (isStretchingLeft)
  49745. x = old.getRight() - w;
  49746. if (isStretchingTop)
  49747. y = old.getBottom() - h;
  49748. }
  49749. }
  49750. // ...and constrain the position if limits have been set for that.
  49751. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49752. {
  49753. if (minOffTop > 0)
  49754. {
  49755. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49756. if (y < limit)
  49757. {
  49758. if (isStretchingTop)
  49759. h -= (limit - y);
  49760. y = limit;
  49761. }
  49762. }
  49763. if (minOffLeft > 0)
  49764. {
  49765. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49766. if (x < limit)
  49767. {
  49768. if (isStretchingLeft)
  49769. w -= (limit - x);
  49770. x = limit;
  49771. }
  49772. }
  49773. if (minOffBottom > 0)
  49774. {
  49775. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49776. if (y > limit)
  49777. {
  49778. if (isStretchingBottom)
  49779. h += (limit - y);
  49780. else
  49781. y = limit;
  49782. }
  49783. }
  49784. if (minOffRight > 0)
  49785. {
  49786. const int limit = limits.getRight() - jmin (minOffRight, w);
  49787. if (x > limit)
  49788. {
  49789. if (isStretchingRight)
  49790. w += (limit - x);
  49791. else
  49792. x = limit;
  49793. }
  49794. }
  49795. }
  49796. jassert (w >= 0 && h >= 0);
  49797. bounds = Rectangle<int> (x, y, w, h);
  49798. }
  49799. END_JUCE_NAMESPACE
  49800. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49801. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49802. BEGIN_JUCE_NAMESPACE
  49803. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49804. : component (component_),
  49805. lastPeer (0),
  49806. reentrant (false)
  49807. {
  49808. jassert (component != 0); // can't use this with a null pointer..
  49809. component->addComponentListener (this);
  49810. registerWithParentComps();
  49811. }
  49812. ComponentMovementWatcher::~ComponentMovementWatcher()
  49813. {
  49814. component->removeComponentListener (this);
  49815. unregister();
  49816. }
  49817. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49818. {
  49819. // agh! don't delete the target component without deleting this object first!
  49820. jassert (component != 0);
  49821. if (! reentrant)
  49822. {
  49823. reentrant = true;
  49824. ComponentPeer* const peer = component->getPeer();
  49825. if (peer != lastPeer)
  49826. {
  49827. componentPeerChanged();
  49828. if (component == 0)
  49829. return;
  49830. lastPeer = peer;
  49831. }
  49832. unregister();
  49833. registerWithParentComps();
  49834. reentrant = false;
  49835. componentMovedOrResized (*component, true, true);
  49836. }
  49837. }
  49838. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49839. {
  49840. // agh! don't delete the target component without deleting this object first!
  49841. jassert (component != 0);
  49842. if (wasMoved)
  49843. {
  49844. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49845. wasMoved = lastBounds.getPosition() != pos;
  49846. lastBounds.setPosition (pos);
  49847. }
  49848. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49849. lastBounds.setSize (component->getWidth(), component->getHeight());
  49850. if (wasMoved || wasResized)
  49851. componentMovedOrResized (wasMoved, wasResized);
  49852. }
  49853. void ComponentMovementWatcher::registerWithParentComps()
  49854. {
  49855. Component* p = component->getParentComponent();
  49856. while (p != 0)
  49857. {
  49858. p->addComponentListener (this);
  49859. registeredParentComps.add (p);
  49860. p = p->getParentComponent();
  49861. }
  49862. }
  49863. void ComponentMovementWatcher::unregister()
  49864. {
  49865. for (int i = registeredParentComps.size(); --i >= 0;)
  49866. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49867. registeredParentComps.clear();
  49868. }
  49869. END_JUCE_NAMESPACE
  49870. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49871. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49872. BEGIN_JUCE_NAMESPACE
  49873. GroupComponent::GroupComponent (const String& componentName,
  49874. const String& labelText)
  49875. : Component (componentName),
  49876. text (labelText),
  49877. justification (Justification::left)
  49878. {
  49879. setInterceptsMouseClicks (false, true);
  49880. }
  49881. GroupComponent::~GroupComponent()
  49882. {
  49883. }
  49884. void GroupComponent::setText (const String& newText)
  49885. {
  49886. if (text != newText)
  49887. {
  49888. text = newText;
  49889. repaint();
  49890. }
  49891. }
  49892. const String GroupComponent::getText() const
  49893. {
  49894. return text;
  49895. }
  49896. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49897. {
  49898. if (justification != newJustification)
  49899. {
  49900. justification = newJustification;
  49901. repaint();
  49902. }
  49903. }
  49904. void GroupComponent::paint (Graphics& g)
  49905. {
  49906. getLookAndFeel()
  49907. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49908. text, justification,
  49909. *this);
  49910. }
  49911. void GroupComponent::enablementChanged()
  49912. {
  49913. repaint();
  49914. }
  49915. void GroupComponent::colourChanged()
  49916. {
  49917. repaint();
  49918. }
  49919. END_JUCE_NAMESPACE
  49920. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49921. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49922. BEGIN_JUCE_NAMESPACE
  49923. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49924. : DocumentWindow (String::empty, backgroundColour,
  49925. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49926. {
  49927. }
  49928. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49929. {
  49930. }
  49931. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49932. {
  49933. MultiDocumentPanel* const owner = getOwner();
  49934. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49935. if (owner != 0)
  49936. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49937. }
  49938. void MultiDocumentPanelWindow::closeButtonPressed()
  49939. {
  49940. MultiDocumentPanel* const owner = getOwner();
  49941. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49942. if (owner != 0)
  49943. owner->closeDocument (getContentComponent(), true);
  49944. }
  49945. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49946. {
  49947. DocumentWindow::activeWindowStatusChanged();
  49948. updateOrder();
  49949. }
  49950. void MultiDocumentPanelWindow::broughtToFront()
  49951. {
  49952. DocumentWindow::broughtToFront();
  49953. updateOrder();
  49954. }
  49955. void MultiDocumentPanelWindow::updateOrder()
  49956. {
  49957. MultiDocumentPanel* const owner = getOwner();
  49958. if (owner != 0)
  49959. owner->updateOrder();
  49960. }
  49961. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49962. {
  49963. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49964. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49965. }
  49966. class MDITabbedComponentInternal : public TabbedComponent
  49967. {
  49968. public:
  49969. MDITabbedComponentInternal()
  49970. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49971. {
  49972. }
  49973. ~MDITabbedComponentInternal()
  49974. {
  49975. }
  49976. void currentTabChanged (int, const String&)
  49977. {
  49978. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49979. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49980. if (owner != 0)
  49981. owner->updateOrder();
  49982. }
  49983. };
  49984. MultiDocumentPanel::MultiDocumentPanel()
  49985. : mode (MaximisedWindowsWithTabs),
  49986. backgroundColour (Colours::lightblue),
  49987. maximumNumDocuments (0),
  49988. numDocsBeforeTabsUsed (0)
  49989. {
  49990. setOpaque (true);
  49991. }
  49992. MultiDocumentPanel::~MultiDocumentPanel()
  49993. {
  49994. closeAllDocuments (false);
  49995. }
  49996. static bool shouldDeleteComp (Component* const c)
  49997. {
  49998. return c->getProperties() ["mdiDocumentDelete_"];
  49999. }
  50000. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50001. {
  50002. while (components.size() > 0)
  50003. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50004. return false;
  50005. return true;
  50006. }
  50007. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50008. {
  50009. return new MultiDocumentPanelWindow (backgroundColour);
  50010. }
  50011. void MultiDocumentPanel::addWindow (Component* component)
  50012. {
  50013. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50014. dw->setResizable (true, false);
  50015. dw->setContentComponent (component, false, true);
  50016. dw->setName (component->getName());
  50017. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50018. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50019. int x = 4;
  50020. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50021. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50022. x += 16;
  50023. dw->setTopLeftPosition (x, x);
  50024. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50025. if (pos.toString().isNotEmpty())
  50026. dw->restoreWindowStateFromString (pos.toString());
  50027. addAndMakeVisible (dw);
  50028. dw->toFront (true);
  50029. }
  50030. bool MultiDocumentPanel::addDocument (Component* const component,
  50031. const Colour& docColour,
  50032. const bool deleteWhenRemoved)
  50033. {
  50034. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50035. // with a frame-within-a-frame! Just pass in the bare content component.
  50036. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50037. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50038. return false;
  50039. components.add (component);
  50040. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50041. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50042. component->addComponentListener (this);
  50043. if (mode == FloatingWindows)
  50044. {
  50045. if (isFullscreenWhenOneDocument())
  50046. {
  50047. if (components.size() == 1)
  50048. {
  50049. addAndMakeVisible (component);
  50050. }
  50051. else
  50052. {
  50053. if (components.size() == 2)
  50054. addWindow (components.getFirst());
  50055. addWindow (component);
  50056. }
  50057. }
  50058. else
  50059. {
  50060. addWindow (component);
  50061. }
  50062. }
  50063. else
  50064. {
  50065. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50066. {
  50067. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50068. Array <Component*> temp (components);
  50069. for (int i = 0; i < temp.size(); ++i)
  50070. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50071. resized();
  50072. }
  50073. else
  50074. {
  50075. if (tabComponent != 0)
  50076. tabComponent->addTab (component->getName(), docColour, component, false);
  50077. else
  50078. addAndMakeVisible (component);
  50079. }
  50080. setActiveDocument (component);
  50081. }
  50082. resized();
  50083. activeDocumentChanged();
  50084. return true;
  50085. }
  50086. bool MultiDocumentPanel::closeDocument (Component* component,
  50087. const bool checkItsOkToCloseFirst)
  50088. {
  50089. if (components.contains (component))
  50090. {
  50091. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50092. return false;
  50093. component->removeComponentListener (this);
  50094. const bool shouldDelete = shouldDeleteComp (component);
  50095. component->getProperties().remove ("mdiDocumentDelete_");
  50096. component->getProperties().remove ("mdiDocumentBkg_");
  50097. if (mode == FloatingWindows)
  50098. {
  50099. for (int i = getNumChildComponents(); --i >= 0;)
  50100. {
  50101. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50102. if (dw != 0 && dw->getContentComponent() == component)
  50103. {
  50104. dw->setContentComponent (0, false);
  50105. delete dw;
  50106. break;
  50107. }
  50108. }
  50109. if (shouldDelete)
  50110. delete component;
  50111. components.removeValue (component);
  50112. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50113. {
  50114. for (int i = getNumChildComponents(); --i >= 0;)
  50115. {
  50116. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50117. if (dw != 0)
  50118. {
  50119. dw->setContentComponent (0, false);
  50120. delete dw;
  50121. }
  50122. }
  50123. addAndMakeVisible (components.getFirst());
  50124. }
  50125. }
  50126. else
  50127. {
  50128. jassert (components.indexOf (component) >= 0);
  50129. if (tabComponent != 0)
  50130. {
  50131. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50132. if (tabComponent->getTabContentComponent (i) == component)
  50133. tabComponent->removeTab (i);
  50134. }
  50135. else
  50136. {
  50137. removeChildComponent (component);
  50138. }
  50139. if (shouldDelete)
  50140. delete component;
  50141. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50142. tabComponent = 0;
  50143. components.removeValue (component);
  50144. if (components.size() > 0 && tabComponent == 0)
  50145. addAndMakeVisible (components.getFirst());
  50146. }
  50147. resized();
  50148. activeDocumentChanged();
  50149. }
  50150. else
  50151. {
  50152. jassertfalse;
  50153. }
  50154. return true;
  50155. }
  50156. int MultiDocumentPanel::getNumDocuments() const throw()
  50157. {
  50158. return components.size();
  50159. }
  50160. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50161. {
  50162. return components [index];
  50163. }
  50164. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50165. {
  50166. if (mode == FloatingWindows)
  50167. {
  50168. for (int i = getNumChildComponents(); --i >= 0;)
  50169. {
  50170. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50171. if (dw != 0 && dw->isActiveWindow())
  50172. return dw->getContentComponent();
  50173. }
  50174. }
  50175. return components.getLast();
  50176. }
  50177. void MultiDocumentPanel::setActiveDocument (Component* component)
  50178. {
  50179. if (mode == FloatingWindows)
  50180. {
  50181. component = getContainerComp (component);
  50182. if (component != 0)
  50183. component->toFront (true);
  50184. }
  50185. else if (tabComponent != 0)
  50186. {
  50187. jassert (components.indexOf (component) >= 0);
  50188. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50189. {
  50190. if (tabComponent->getTabContentComponent (i) == component)
  50191. {
  50192. tabComponent->setCurrentTabIndex (i);
  50193. break;
  50194. }
  50195. }
  50196. }
  50197. else
  50198. {
  50199. component->grabKeyboardFocus();
  50200. }
  50201. }
  50202. void MultiDocumentPanel::activeDocumentChanged()
  50203. {
  50204. }
  50205. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50206. {
  50207. maximumNumDocuments = newNumber;
  50208. }
  50209. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50210. {
  50211. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50212. }
  50213. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50214. {
  50215. return numDocsBeforeTabsUsed != 0;
  50216. }
  50217. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50218. {
  50219. if (mode != newLayoutMode)
  50220. {
  50221. mode = newLayoutMode;
  50222. if (mode == FloatingWindows)
  50223. {
  50224. tabComponent = 0;
  50225. }
  50226. else
  50227. {
  50228. for (int i = getNumChildComponents(); --i >= 0;)
  50229. {
  50230. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50231. if (dw != 0)
  50232. {
  50233. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50234. dw->setContentComponent (0, false);
  50235. delete dw;
  50236. }
  50237. }
  50238. }
  50239. resized();
  50240. const Array <Component*> tempComps (components);
  50241. components.clear();
  50242. for (int i = 0; i < tempComps.size(); ++i)
  50243. {
  50244. Component* const c = tempComps.getUnchecked(i);
  50245. addDocument (c,
  50246. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50247. shouldDeleteComp (c));
  50248. }
  50249. }
  50250. }
  50251. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50252. {
  50253. if (backgroundColour != newBackgroundColour)
  50254. {
  50255. backgroundColour = newBackgroundColour;
  50256. setOpaque (newBackgroundColour.isOpaque());
  50257. repaint();
  50258. }
  50259. }
  50260. void MultiDocumentPanel::paint (Graphics& g)
  50261. {
  50262. g.fillAll (backgroundColour);
  50263. }
  50264. void MultiDocumentPanel::resized()
  50265. {
  50266. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50267. {
  50268. for (int i = getNumChildComponents(); --i >= 0;)
  50269. getChildComponent (i)->setBounds (getLocalBounds());
  50270. }
  50271. setWantsKeyboardFocus (components.size() == 0);
  50272. }
  50273. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50274. {
  50275. if (mode == FloatingWindows)
  50276. {
  50277. for (int i = 0; i < getNumChildComponents(); ++i)
  50278. {
  50279. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50280. if (dw != 0 && dw->getContentComponent() == c)
  50281. {
  50282. c = dw;
  50283. break;
  50284. }
  50285. }
  50286. }
  50287. return c;
  50288. }
  50289. void MultiDocumentPanel::componentNameChanged (Component&)
  50290. {
  50291. if (mode == FloatingWindows)
  50292. {
  50293. for (int i = 0; i < getNumChildComponents(); ++i)
  50294. {
  50295. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50296. if (dw != 0)
  50297. dw->setName (dw->getContentComponent()->getName());
  50298. }
  50299. }
  50300. else if (tabComponent != 0)
  50301. {
  50302. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50303. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50304. }
  50305. }
  50306. void MultiDocumentPanel::updateOrder()
  50307. {
  50308. const Array <Component*> oldList (components);
  50309. if (mode == FloatingWindows)
  50310. {
  50311. components.clear();
  50312. for (int i = 0; i < getNumChildComponents(); ++i)
  50313. {
  50314. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50315. if (dw != 0)
  50316. components.add (dw->getContentComponent());
  50317. }
  50318. }
  50319. else
  50320. {
  50321. if (tabComponent != 0)
  50322. {
  50323. Component* const current = tabComponent->getCurrentContentComponent();
  50324. if (current != 0)
  50325. {
  50326. components.removeValue (current);
  50327. components.add (current);
  50328. }
  50329. }
  50330. }
  50331. if (components != oldList)
  50332. activeDocumentChanged();
  50333. }
  50334. END_JUCE_NAMESPACE
  50335. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50336. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50337. BEGIN_JUCE_NAMESPACE
  50338. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50339. : zone (zoneFlags)
  50340. {
  50341. }
  50342. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50343. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50344. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50345. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50346. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50347. const BorderSize& border,
  50348. const Point<int>& position)
  50349. {
  50350. int z = 0;
  50351. if (totalSize.contains (position)
  50352. && ! border.subtractedFrom (totalSize).contains (position))
  50353. {
  50354. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50355. if (position.getX() < jmax (border.getLeft(), minW))
  50356. z |= left;
  50357. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50358. z |= right;
  50359. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50360. if (position.getY() < jmax (border.getTop(), minH))
  50361. z |= top;
  50362. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50363. z |= bottom;
  50364. }
  50365. return Zone (z);
  50366. }
  50367. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50368. {
  50369. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50370. switch (zone)
  50371. {
  50372. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50373. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50374. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50375. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50376. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50377. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50378. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50379. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50380. default: break;
  50381. }
  50382. return mc;
  50383. }
  50384. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50385. {
  50386. if (isDraggingWholeObject())
  50387. return b + offset;
  50388. if (isDraggingLeftEdge())
  50389. b.setLeft (b.getX() + offset.getX());
  50390. if (isDraggingRightEdge())
  50391. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50392. if (isDraggingTopEdge())
  50393. b.setTop (b.getY() + offset.getY());
  50394. if (isDraggingBottomEdge())
  50395. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50396. return b;
  50397. }
  50398. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50399. {
  50400. if (isDraggingWholeObject())
  50401. return b + offset;
  50402. if (isDraggingLeftEdge())
  50403. b.setLeft (b.getX() + offset.getX());
  50404. if (isDraggingRightEdge())
  50405. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50406. if (isDraggingTopEdge())
  50407. b.setTop (b.getY() + offset.getY());
  50408. if (isDraggingBottomEdge())
  50409. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50410. return b;
  50411. }
  50412. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50413. ComponentBoundsConstrainer* const constrainer_)
  50414. : component (componentToResize),
  50415. constrainer (constrainer_),
  50416. borderSize (5),
  50417. mouseZone (0)
  50418. {
  50419. }
  50420. ResizableBorderComponent::~ResizableBorderComponent()
  50421. {
  50422. }
  50423. void ResizableBorderComponent::paint (Graphics& g)
  50424. {
  50425. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50426. }
  50427. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50428. {
  50429. updateMouseZone (e);
  50430. }
  50431. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50432. {
  50433. updateMouseZone (e);
  50434. }
  50435. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50436. {
  50437. if (component == 0)
  50438. {
  50439. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50440. return;
  50441. }
  50442. updateMouseZone (e);
  50443. originalBounds = component->getBounds();
  50444. if (constrainer != 0)
  50445. constrainer->resizeStart();
  50446. }
  50447. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50448. {
  50449. if (component == 0)
  50450. {
  50451. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50452. return;
  50453. }
  50454. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50455. if (constrainer != 0)
  50456. constrainer->setBoundsForComponent (component, bounds,
  50457. mouseZone.isDraggingTopEdge(),
  50458. mouseZone.isDraggingLeftEdge(),
  50459. mouseZone.isDraggingBottomEdge(),
  50460. mouseZone.isDraggingRightEdge());
  50461. else
  50462. component->setBounds (bounds);
  50463. }
  50464. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50465. {
  50466. if (constrainer != 0)
  50467. constrainer->resizeEnd();
  50468. }
  50469. bool ResizableBorderComponent::hitTest (int x, int y)
  50470. {
  50471. return x < borderSize.getLeft()
  50472. || x >= getWidth() - borderSize.getRight()
  50473. || y < borderSize.getTop()
  50474. || y >= getHeight() - borderSize.getBottom();
  50475. }
  50476. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50477. {
  50478. if (borderSize != newBorderSize)
  50479. {
  50480. borderSize = newBorderSize;
  50481. repaint();
  50482. }
  50483. }
  50484. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50485. {
  50486. return borderSize;
  50487. }
  50488. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50489. {
  50490. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50491. if (mouseZone != newZone)
  50492. {
  50493. mouseZone = newZone;
  50494. setMouseCursor (newZone.getMouseCursor());
  50495. }
  50496. }
  50497. END_JUCE_NAMESPACE
  50498. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50499. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50500. BEGIN_JUCE_NAMESPACE
  50501. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50502. ComponentBoundsConstrainer* const constrainer_)
  50503. : component (componentToResize),
  50504. constrainer (constrainer_)
  50505. {
  50506. setRepaintsOnMouseActivity (true);
  50507. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50508. }
  50509. ResizableCornerComponent::~ResizableCornerComponent()
  50510. {
  50511. }
  50512. void ResizableCornerComponent::paint (Graphics& g)
  50513. {
  50514. getLookAndFeel()
  50515. .drawCornerResizer (g, getWidth(), getHeight(),
  50516. isMouseOverOrDragging(),
  50517. isMouseButtonDown());
  50518. }
  50519. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50520. {
  50521. if (component == 0)
  50522. {
  50523. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50524. return;
  50525. }
  50526. originalBounds = component->getBounds();
  50527. if (constrainer != 0)
  50528. constrainer->resizeStart();
  50529. }
  50530. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50531. {
  50532. if (component == 0)
  50533. {
  50534. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50535. return;
  50536. }
  50537. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50538. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50539. if (constrainer != 0)
  50540. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50541. else
  50542. component->setBounds (r);
  50543. }
  50544. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50545. {
  50546. if (constrainer != 0)
  50547. constrainer->resizeStart();
  50548. }
  50549. bool ResizableCornerComponent::hitTest (int x, int y)
  50550. {
  50551. if (getWidth() <= 0)
  50552. return false;
  50553. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50554. return y >= yAtX - getHeight() / 4;
  50555. }
  50556. END_JUCE_NAMESPACE
  50557. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50558. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50559. BEGIN_JUCE_NAMESPACE
  50560. class ScrollBar::ScrollbarButton : public Button
  50561. {
  50562. public:
  50563. int direction;
  50564. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50565. : Button (String::empty),
  50566. direction (direction_),
  50567. owner (owner_)
  50568. {
  50569. setWantsKeyboardFocus (false);
  50570. }
  50571. ~ScrollbarButton()
  50572. {
  50573. }
  50574. void paintButton (Graphics& g, bool over, bool down)
  50575. {
  50576. getLookAndFeel()
  50577. .drawScrollbarButton (g, owner,
  50578. getWidth(), getHeight(),
  50579. direction,
  50580. owner.isVertical(),
  50581. over, down);
  50582. }
  50583. void clicked()
  50584. {
  50585. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50586. }
  50587. juce_UseDebuggingNewOperator
  50588. private:
  50589. ScrollBar& owner;
  50590. ScrollbarButton (const ScrollbarButton&);
  50591. ScrollbarButton& operator= (const ScrollbarButton&);
  50592. };
  50593. ScrollBar::ScrollBar (const bool vertical_,
  50594. const bool buttonsAreVisible)
  50595. : totalRange (0.0, 1.0),
  50596. visibleRange (0.0, 0.1),
  50597. singleStepSize (0.1),
  50598. thumbAreaStart (0),
  50599. thumbAreaSize (0),
  50600. thumbStart (0),
  50601. thumbSize (0),
  50602. initialDelayInMillisecs (100),
  50603. repeatDelayInMillisecs (50),
  50604. minimumDelayInMillisecs (10),
  50605. vertical (vertical_),
  50606. isDraggingThumb (false),
  50607. autohides (true)
  50608. {
  50609. setButtonVisibility (buttonsAreVisible);
  50610. setRepaintsOnMouseActivity (true);
  50611. setFocusContainer (true);
  50612. }
  50613. ScrollBar::~ScrollBar()
  50614. {
  50615. upButton = 0;
  50616. downButton = 0;
  50617. }
  50618. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50619. {
  50620. if (totalRange != newRangeLimit)
  50621. {
  50622. totalRange = newRangeLimit;
  50623. setCurrentRange (visibleRange);
  50624. updateThumbPosition();
  50625. }
  50626. }
  50627. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50628. {
  50629. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50630. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50631. }
  50632. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50633. {
  50634. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50635. if (visibleRange != constrainedRange)
  50636. {
  50637. visibleRange = constrainedRange;
  50638. updateThumbPosition();
  50639. triggerAsyncUpdate();
  50640. }
  50641. }
  50642. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50643. {
  50644. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50645. }
  50646. void ScrollBar::setCurrentRangeStart (const double newStart)
  50647. {
  50648. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50649. }
  50650. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50651. {
  50652. singleStepSize = newSingleStepSize;
  50653. }
  50654. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50655. {
  50656. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50657. }
  50658. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50659. {
  50660. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50661. }
  50662. void ScrollBar::scrollToTop()
  50663. {
  50664. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50665. }
  50666. void ScrollBar::scrollToBottom()
  50667. {
  50668. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50669. }
  50670. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50671. const int repeatDelayInMillisecs_,
  50672. const int minimumDelayInMillisecs_)
  50673. {
  50674. initialDelayInMillisecs = initialDelayInMillisecs_;
  50675. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50676. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50677. if (upButton != 0)
  50678. {
  50679. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50680. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50681. }
  50682. }
  50683. void ScrollBar::addListener (Listener* const listener)
  50684. {
  50685. listeners.add (listener);
  50686. }
  50687. void ScrollBar::removeListener (Listener* const listener)
  50688. {
  50689. listeners.remove (listener);
  50690. }
  50691. void ScrollBar::handleAsyncUpdate()
  50692. {
  50693. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50694. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50695. }
  50696. void ScrollBar::updateThumbPosition()
  50697. {
  50698. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50699. : thumbAreaSize);
  50700. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50701. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50702. if (newThumbSize > thumbAreaSize)
  50703. newThumbSize = thumbAreaSize;
  50704. int newThumbStart = thumbAreaStart;
  50705. if (totalRange.getLength() > visibleRange.getLength())
  50706. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50707. / (totalRange.getLength() - visibleRange.getLength()));
  50708. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50709. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50710. {
  50711. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50712. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50713. if (vertical)
  50714. repaint (0, repaintStart, getWidth(), repaintSize);
  50715. else
  50716. repaint (repaintStart, 0, repaintSize, getHeight());
  50717. thumbStart = newThumbStart;
  50718. thumbSize = newThumbSize;
  50719. }
  50720. }
  50721. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50722. {
  50723. if (vertical != shouldBeVertical)
  50724. {
  50725. vertical = shouldBeVertical;
  50726. if (upButton != 0)
  50727. {
  50728. upButton->direction = vertical ? 0 : 3;
  50729. downButton->direction = vertical ? 2 : 1;
  50730. }
  50731. updateThumbPosition();
  50732. }
  50733. }
  50734. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50735. {
  50736. upButton = 0;
  50737. downButton = 0;
  50738. if (buttonsAreVisible)
  50739. {
  50740. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50741. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50742. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50743. }
  50744. updateThumbPosition();
  50745. }
  50746. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50747. {
  50748. autohides = shouldHideWhenFullRange;
  50749. updateThumbPosition();
  50750. }
  50751. bool ScrollBar::autoHides() const throw()
  50752. {
  50753. return autohides;
  50754. }
  50755. void ScrollBar::paint (Graphics& g)
  50756. {
  50757. if (thumbAreaSize > 0)
  50758. {
  50759. LookAndFeel& lf = getLookAndFeel();
  50760. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50761. ? thumbSize : 0;
  50762. if (vertical)
  50763. {
  50764. lf.drawScrollbar (g, *this,
  50765. 0, thumbAreaStart,
  50766. getWidth(), thumbAreaSize,
  50767. vertical,
  50768. thumbStart, thumb,
  50769. isMouseOver(), isMouseButtonDown());
  50770. }
  50771. else
  50772. {
  50773. lf.drawScrollbar (g, *this,
  50774. thumbAreaStart, 0,
  50775. thumbAreaSize, getHeight(),
  50776. vertical,
  50777. thumbStart, thumb,
  50778. isMouseOver(), isMouseButtonDown());
  50779. }
  50780. }
  50781. }
  50782. void ScrollBar::lookAndFeelChanged()
  50783. {
  50784. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50785. }
  50786. void ScrollBar::resized()
  50787. {
  50788. const int length = ((vertical) ? getHeight() : getWidth());
  50789. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50790. : 0;
  50791. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50792. {
  50793. thumbAreaStart = length >> 1;
  50794. thumbAreaSize = 0;
  50795. }
  50796. else
  50797. {
  50798. thumbAreaStart = buttonSize;
  50799. thumbAreaSize = length - (buttonSize << 1);
  50800. }
  50801. if (upButton != 0)
  50802. {
  50803. if (vertical)
  50804. {
  50805. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50806. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50807. }
  50808. else
  50809. {
  50810. upButton->setBounds (0, 0, buttonSize, getHeight());
  50811. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50812. }
  50813. }
  50814. updateThumbPosition();
  50815. }
  50816. void ScrollBar::mouseDown (const MouseEvent& e)
  50817. {
  50818. isDraggingThumb = false;
  50819. lastMousePos = vertical ? e.y : e.x;
  50820. dragStartMousePos = lastMousePos;
  50821. dragStartRange = visibleRange.getStart();
  50822. if (dragStartMousePos < thumbStart)
  50823. {
  50824. moveScrollbarInPages (-1);
  50825. startTimer (400);
  50826. }
  50827. else if (dragStartMousePos >= thumbStart + thumbSize)
  50828. {
  50829. moveScrollbarInPages (1);
  50830. startTimer (400);
  50831. }
  50832. else
  50833. {
  50834. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50835. && (thumbAreaSize > thumbSize);
  50836. }
  50837. }
  50838. void ScrollBar::mouseDrag (const MouseEvent& e)
  50839. {
  50840. if (isDraggingThumb)
  50841. {
  50842. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50843. setCurrentRangeStart (dragStartRange
  50844. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50845. / (thumbAreaSize - thumbSize));
  50846. }
  50847. else
  50848. {
  50849. lastMousePos = (vertical) ? e.y : e.x;
  50850. }
  50851. }
  50852. void ScrollBar::mouseUp (const MouseEvent&)
  50853. {
  50854. isDraggingThumb = false;
  50855. stopTimer();
  50856. repaint();
  50857. }
  50858. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50859. float wheelIncrementX,
  50860. float wheelIncrementY)
  50861. {
  50862. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50863. if (increment < 0)
  50864. increment = jmin (increment * 10.0f, -1.0f);
  50865. else if (increment > 0)
  50866. increment = jmax (increment * 10.0f, 1.0f);
  50867. setCurrentRange (visibleRange - singleStepSize * increment);
  50868. }
  50869. void ScrollBar::timerCallback()
  50870. {
  50871. if (isMouseButtonDown())
  50872. {
  50873. startTimer (40);
  50874. if (lastMousePos < thumbStart)
  50875. setCurrentRange (visibleRange - visibleRange.getLength());
  50876. else if (lastMousePos > thumbStart + thumbSize)
  50877. setCurrentRangeStart (visibleRange.getEnd());
  50878. }
  50879. else
  50880. {
  50881. stopTimer();
  50882. }
  50883. }
  50884. bool ScrollBar::keyPressed (const KeyPress& key)
  50885. {
  50886. if (! isVisible())
  50887. return false;
  50888. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50889. moveScrollbarInSteps (-1);
  50890. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50891. moveScrollbarInSteps (1);
  50892. else if (key.isKeyCode (KeyPress::pageUpKey))
  50893. moveScrollbarInPages (-1);
  50894. else if (key.isKeyCode (KeyPress::pageDownKey))
  50895. moveScrollbarInPages (1);
  50896. else if (key.isKeyCode (KeyPress::homeKey))
  50897. scrollToTop();
  50898. else if (key.isKeyCode (KeyPress::endKey))
  50899. scrollToBottom();
  50900. else
  50901. return false;
  50902. return true;
  50903. }
  50904. END_JUCE_NAMESPACE
  50905. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50906. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50907. BEGIN_JUCE_NAMESPACE
  50908. StretchableLayoutManager::StretchableLayoutManager()
  50909. : totalSize (0)
  50910. {
  50911. }
  50912. StretchableLayoutManager::~StretchableLayoutManager()
  50913. {
  50914. }
  50915. void StretchableLayoutManager::clearAllItems()
  50916. {
  50917. items.clear();
  50918. totalSize = 0;
  50919. }
  50920. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50921. const double minimumSize,
  50922. const double maximumSize,
  50923. const double preferredSize)
  50924. {
  50925. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50926. if (layout == 0)
  50927. {
  50928. layout = new ItemLayoutProperties();
  50929. layout->itemIndex = itemIndex;
  50930. int i;
  50931. for (i = 0; i < items.size(); ++i)
  50932. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50933. break;
  50934. items.insert (i, layout);
  50935. }
  50936. layout->minSize = minimumSize;
  50937. layout->maxSize = maximumSize;
  50938. layout->preferredSize = preferredSize;
  50939. layout->currentSize = 0;
  50940. }
  50941. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50942. double& minimumSize,
  50943. double& maximumSize,
  50944. double& preferredSize) const
  50945. {
  50946. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50947. if (layout != 0)
  50948. {
  50949. minimumSize = layout->minSize;
  50950. maximumSize = layout->maxSize;
  50951. preferredSize = layout->preferredSize;
  50952. return true;
  50953. }
  50954. return false;
  50955. }
  50956. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50957. {
  50958. totalSize = newTotalSize;
  50959. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50960. }
  50961. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50962. {
  50963. int pos = 0;
  50964. for (int i = 0; i < itemIndex; ++i)
  50965. {
  50966. const ItemLayoutProperties* const layout = getInfoFor (i);
  50967. if (layout != 0)
  50968. pos += layout->currentSize;
  50969. }
  50970. return pos;
  50971. }
  50972. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50973. {
  50974. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50975. if (layout != 0)
  50976. return layout->currentSize;
  50977. return 0;
  50978. }
  50979. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50980. {
  50981. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50982. if (layout != 0)
  50983. return -layout->currentSize / (double) totalSize;
  50984. return 0;
  50985. }
  50986. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50987. int newPosition)
  50988. {
  50989. for (int i = items.size(); --i >= 0;)
  50990. {
  50991. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50992. if (layout->itemIndex == itemIndex)
  50993. {
  50994. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50995. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50996. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50997. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50998. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50999. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51000. endPos += layout->currentSize;
  51001. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51002. updatePrefSizesToMatchCurrentPositions();
  51003. break;
  51004. }
  51005. }
  51006. }
  51007. void StretchableLayoutManager::layOutComponents (Component** const components,
  51008. int numComponents,
  51009. int x, int y, int w, int h,
  51010. const bool vertically,
  51011. const bool resizeOtherDimension)
  51012. {
  51013. setTotalSize (vertically ? h : w);
  51014. int pos = vertically ? y : x;
  51015. for (int i = 0; i < numComponents; ++i)
  51016. {
  51017. const ItemLayoutProperties* const layout = getInfoFor (i);
  51018. if (layout != 0)
  51019. {
  51020. Component* const c = components[i];
  51021. if (c != 0)
  51022. {
  51023. if (i == numComponents - 1)
  51024. {
  51025. // if it's the last item, crop it to exactly fit the available space..
  51026. if (resizeOtherDimension)
  51027. {
  51028. if (vertically)
  51029. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51030. else
  51031. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51032. }
  51033. else
  51034. {
  51035. if (vertically)
  51036. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51037. else
  51038. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51039. }
  51040. }
  51041. else
  51042. {
  51043. if (resizeOtherDimension)
  51044. {
  51045. if (vertically)
  51046. c->setBounds (x, pos, w, layout->currentSize);
  51047. else
  51048. c->setBounds (pos, y, layout->currentSize, h);
  51049. }
  51050. else
  51051. {
  51052. if (vertically)
  51053. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51054. else
  51055. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51056. }
  51057. }
  51058. }
  51059. pos += layout->currentSize;
  51060. }
  51061. }
  51062. }
  51063. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51064. {
  51065. for (int i = items.size(); --i >= 0;)
  51066. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51067. return items.getUnchecked(i);
  51068. return 0;
  51069. }
  51070. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51071. const int endIndex,
  51072. const int availableSpace,
  51073. int startPos)
  51074. {
  51075. // calculate the total sizes
  51076. int i;
  51077. double totalIdealSize = 0.0;
  51078. int totalMinimums = 0;
  51079. for (i = startIndex; i < endIndex; ++i)
  51080. {
  51081. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51082. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51083. totalMinimums += layout->currentSize;
  51084. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51085. }
  51086. if (totalIdealSize <= 0)
  51087. totalIdealSize = 1.0;
  51088. // now calc the best sizes..
  51089. int extraSpace = availableSpace - totalMinimums;
  51090. while (extraSpace > 0)
  51091. {
  51092. int numWantingMoreSpace = 0;
  51093. int numHavingTakenExtraSpace = 0;
  51094. // first figure out how many comps want a slice of the extra space..
  51095. for (i = startIndex; i < endIndex; ++i)
  51096. {
  51097. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51098. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51099. const int bestSize = jlimit (layout->currentSize,
  51100. jmax (layout->currentSize,
  51101. sizeToRealSize (layout->maxSize, totalSize)),
  51102. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51103. if (bestSize > layout->currentSize)
  51104. ++numWantingMoreSpace;
  51105. }
  51106. // ..share out the extra space..
  51107. for (i = startIndex; i < endIndex; ++i)
  51108. {
  51109. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51110. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51111. int bestSize = jlimit (layout->currentSize,
  51112. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51113. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51114. const int extraWanted = bestSize - layout->currentSize;
  51115. if (extraWanted > 0)
  51116. {
  51117. const int extraAllowed = jmin (extraWanted,
  51118. extraSpace / jmax (1, numWantingMoreSpace));
  51119. if (extraAllowed > 0)
  51120. {
  51121. ++numHavingTakenExtraSpace;
  51122. --numWantingMoreSpace;
  51123. layout->currentSize += extraAllowed;
  51124. extraSpace -= extraAllowed;
  51125. }
  51126. }
  51127. }
  51128. if (numHavingTakenExtraSpace <= 0)
  51129. break;
  51130. }
  51131. // ..and calculate the end position
  51132. for (i = startIndex; i < endIndex; ++i)
  51133. {
  51134. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51135. startPos += layout->currentSize;
  51136. }
  51137. return startPos;
  51138. }
  51139. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51140. const int endIndex) const
  51141. {
  51142. int totalMinimums = 0;
  51143. for (int i = startIndex; i < endIndex; ++i)
  51144. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51145. return totalMinimums;
  51146. }
  51147. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51148. {
  51149. int totalMaximums = 0;
  51150. for (int i = startIndex; i < endIndex; ++i)
  51151. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51152. return totalMaximums;
  51153. }
  51154. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51155. {
  51156. for (int i = 0; i < items.size(); ++i)
  51157. {
  51158. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51159. layout->preferredSize
  51160. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51161. : getItemCurrentAbsoluteSize (i);
  51162. }
  51163. }
  51164. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51165. {
  51166. if (size < 0)
  51167. size *= -totalSpace;
  51168. return roundToInt (size);
  51169. }
  51170. END_JUCE_NAMESPACE
  51171. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51172. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51173. BEGIN_JUCE_NAMESPACE
  51174. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51175. const int itemIndex_,
  51176. const bool isVertical_)
  51177. : layout (layout_),
  51178. itemIndex (itemIndex_),
  51179. isVertical (isVertical_)
  51180. {
  51181. setRepaintsOnMouseActivity (true);
  51182. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51183. : MouseCursor::UpDownResizeCursor));
  51184. }
  51185. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51186. {
  51187. }
  51188. void StretchableLayoutResizerBar::paint (Graphics& g)
  51189. {
  51190. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51191. getWidth(), getHeight(),
  51192. isVertical,
  51193. isMouseOver(),
  51194. isMouseButtonDown());
  51195. }
  51196. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51197. {
  51198. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51199. }
  51200. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51201. {
  51202. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51203. : e.getDistanceFromDragStartY());
  51204. layout->setItemPosition (itemIndex, desiredPos);
  51205. hasBeenMoved();
  51206. }
  51207. void StretchableLayoutResizerBar::hasBeenMoved()
  51208. {
  51209. if (getParentComponent() != 0)
  51210. getParentComponent()->resized();
  51211. }
  51212. END_JUCE_NAMESPACE
  51213. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51214. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51215. BEGIN_JUCE_NAMESPACE
  51216. StretchableObjectResizer::StretchableObjectResizer()
  51217. {
  51218. }
  51219. StretchableObjectResizer::~StretchableObjectResizer()
  51220. {
  51221. }
  51222. void StretchableObjectResizer::addItem (const double size,
  51223. const double minSize, const double maxSize,
  51224. const int order)
  51225. {
  51226. // the order must be >= 0 but less than the maximum integer value.
  51227. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51228. Item* const item = new Item();
  51229. item->size = size;
  51230. item->minSize = minSize;
  51231. item->maxSize = maxSize;
  51232. item->order = order;
  51233. items.add (item);
  51234. }
  51235. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51236. {
  51237. const Item* const it = items [index];
  51238. return it != 0 ? it->size : 0;
  51239. }
  51240. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51241. {
  51242. int order = 0;
  51243. for (;;)
  51244. {
  51245. double currentSize = 0;
  51246. double minSize = 0;
  51247. double maxSize = 0;
  51248. int nextHighestOrder = std::numeric_limits<int>::max();
  51249. for (int i = 0; i < items.size(); ++i)
  51250. {
  51251. const Item* const it = items.getUnchecked(i);
  51252. currentSize += it->size;
  51253. if (it->order <= order)
  51254. {
  51255. minSize += it->minSize;
  51256. maxSize += it->maxSize;
  51257. }
  51258. else
  51259. {
  51260. minSize += it->size;
  51261. maxSize += it->size;
  51262. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51263. }
  51264. }
  51265. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51266. if (thisIterationTarget >= currentSize)
  51267. {
  51268. const double availableExtraSpace = maxSize - currentSize;
  51269. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51270. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51271. for (int i = 0; i < items.size(); ++i)
  51272. {
  51273. Item* const it = items.getUnchecked(i);
  51274. if (it->order <= order)
  51275. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51276. }
  51277. }
  51278. else
  51279. {
  51280. const double amountOfSlack = currentSize - minSize;
  51281. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51282. const double scale = targetAmountOfSlack / amountOfSlack;
  51283. for (int i = 0; i < items.size(); ++i)
  51284. {
  51285. Item* const it = items.getUnchecked(i);
  51286. if (it->order <= order)
  51287. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51288. }
  51289. }
  51290. if (nextHighestOrder < std::numeric_limits<int>::max())
  51291. order = nextHighestOrder;
  51292. else
  51293. break;
  51294. }
  51295. }
  51296. END_JUCE_NAMESPACE
  51297. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51298. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51299. BEGIN_JUCE_NAMESPACE
  51300. TabBarButton::TabBarButton (const String& name,
  51301. TabbedButtonBar* const owner_,
  51302. const int index)
  51303. : Button (name),
  51304. owner (owner_),
  51305. tabIndex (index),
  51306. overlapPixels (0)
  51307. {
  51308. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51309. setComponentEffect (&shadow);
  51310. setWantsKeyboardFocus (false);
  51311. }
  51312. TabBarButton::~TabBarButton()
  51313. {
  51314. }
  51315. void TabBarButton::paintButton (Graphics& g,
  51316. bool isMouseOverButton,
  51317. bool isButtonDown)
  51318. {
  51319. int x, y, w, h;
  51320. getActiveArea (x, y, w, h);
  51321. g.setOrigin (x, y);
  51322. getLookAndFeel()
  51323. .drawTabButton (g, w, h,
  51324. owner->getTabBackgroundColour (tabIndex),
  51325. tabIndex, getButtonText(), *this,
  51326. owner->getOrientation(),
  51327. isMouseOverButton, isButtonDown,
  51328. getToggleState());
  51329. }
  51330. void TabBarButton::clicked (const ModifierKeys& mods)
  51331. {
  51332. if (mods.isPopupMenu())
  51333. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51334. else
  51335. owner->setCurrentTabIndex (tabIndex);
  51336. }
  51337. bool TabBarButton::hitTest (int mx, int my)
  51338. {
  51339. int x, y, w, h;
  51340. getActiveArea (x, y, w, h);
  51341. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51342. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51343. {
  51344. if (((unsigned int) mx) < (unsigned int) getWidth()
  51345. && my >= y + overlapPixels
  51346. && my < y + h - overlapPixels)
  51347. return true;
  51348. }
  51349. else
  51350. {
  51351. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51352. && ((unsigned int) my) < (unsigned int) getHeight())
  51353. return true;
  51354. }
  51355. Path p;
  51356. getLookAndFeel()
  51357. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51358. owner->getOrientation(),
  51359. false, false, getToggleState());
  51360. return p.contains ((float) (mx - x),
  51361. (float) (my - y));
  51362. }
  51363. int TabBarButton::getBestTabLength (const int depth)
  51364. {
  51365. return jlimit (depth * 2,
  51366. depth * 7,
  51367. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51368. }
  51369. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51370. {
  51371. x = 0;
  51372. y = 0;
  51373. int r = getWidth();
  51374. int b = getHeight();
  51375. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51376. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51377. r -= spaceAroundImage;
  51378. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51379. x += spaceAroundImage;
  51380. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51381. y += spaceAroundImage;
  51382. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51383. b -= spaceAroundImage;
  51384. w = r - x;
  51385. h = b - y;
  51386. }
  51387. class TabAreaBehindFrontButtonComponent : public Component
  51388. {
  51389. public:
  51390. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51391. : owner (owner_)
  51392. {
  51393. setInterceptsMouseClicks (false, false);
  51394. }
  51395. ~TabAreaBehindFrontButtonComponent()
  51396. {
  51397. }
  51398. void paint (Graphics& g)
  51399. {
  51400. getLookAndFeel()
  51401. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51402. *owner, owner->getOrientation());
  51403. }
  51404. void enablementChanged()
  51405. {
  51406. repaint();
  51407. }
  51408. private:
  51409. TabbedButtonBar* const owner;
  51410. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51411. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51412. };
  51413. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51414. : orientation (orientation_),
  51415. currentTabIndex (-1)
  51416. {
  51417. setInterceptsMouseClicks (false, true);
  51418. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51419. setFocusContainer (true);
  51420. }
  51421. TabbedButtonBar::~TabbedButtonBar()
  51422. {
  51423. extraTabsButton = 0;
  51424. deleteAllChildren();
  51425. }
  51426. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51427. {
  51428. orientation = newOrientation;
  51429. for (int i = getNumChildComponents(); --i >= 0;)
  51430. getChildComponent (i)->resized();
  51431. resized();
  51432. }
  51433. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51434. {
  51435. return new TabBarButton (name, this, index);
  51436. }
  51437. void TabbedButtonBar::clearTabs()
  51438. {
  51439. tabs.clear();
  51440. tabColours.clear();
  51441. currentTabIndex = -1;
  51442. extraTabsButton = 0;
  51443. removeChildComponent (behindFrontTab);
  51444. deleteAllChildren();
  51445. addChildComponent (behindFrontTab);
  51446. setCurrentTabIndex (-1);
  51447. }
  51448. void TabbedButtonBar::addTab (const String& tabName,
  51449. const Colour& tabBackgroundColour,
  51450. int insertIndex)
  51451. {
  51452. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51453. if (tabName.isNotEmpty())
  51454. {
  51455. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51456. insertIndex = tabs.size();
  51457. for (int i = tabs.size(); --i >= insertIndex;)
  51458. {
  51459. TabBarButton* const tb = getTabButton (i);
  51460. if (tb != 0)
  51461. tb->tabIndex++;
  51462. }
  51463. tabs.insert (insertIndex, tabName);
  51464. tabColours.insert (insertIndex, tabBackgroundColour);
  51465. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51466. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51467. addAndMakeVisible (tb, insertIndex);
  51468. resized();
  51469. if (currentTabIndex < 0)
  51470. setCurrentTabIndex (0);
  51471. }
  51472. }
  51473. void TabbedButtonBar::setTabName (const int tabIndex,
  51474. const String& newName)
  51475. {
  51476. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51477. && tabs[tabIndex] != newName)
  51478. {
  51479. tabs.set (tabIndex, newName);
  51480. TabBarButton* const tb = getTabButton (tabIndex);
  51481. if (tb != 0)
  51482. tb->setButtonText (newName);
  51483. resized();
  51484. }
  51485. }
  51486. void TabbedButtonBar::removeTab (const int tabIndex)
  51487. {
  51488. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51489. {
  51490. const int oldTabIndex = currentTabIndex;
  51491. if (currentTabIndex == tabIndex)
  51492. currentTabIndex = -1;
  51493. tabs.remove (tabIndex);
  51494. tabColours.remove (tabIndex);
  51495. delete getTabButton (tabIndex);
  51496. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51497. {
  51498. TabBarButton* const tb = getTabButton (i);
  51499. if (tb != 0)
  51500. tb->tabIndex--;
  51501. }
  51502. resized();
  51503. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51504. }
  51505. }
  51506. void TabbedButtonBar::moveTab (const int currentIndex,
  51507. const int newIndex)
  51508. {
  51509. tabs.move (currentIndex, newIndex);
  51510. tabColours.move (currentIndex, newIndex);
  51511. resized();
  51512. }
  51513. int TabbedButtonBar::getNumTabs() const
  51514. {
  51515. return tabs.size();
  51516. }
  51517. const StringArray TabbedButtonBar::getTabNames() const
  51518. {
  51519. return tabs;
  51520. }
  51521. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51522. {
  51523. if (currentTabIndex != newIndex)
  51524. {
  51525. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51526. newIndex = -1;
  51527. currentTabIndex = newIndex;
  51528. for (int i = 0; i < getNumChildComponents(); ++i)
  51529. {
  51530. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51531. if (tb != 0)
  51532. tb->setToggleState (tb->tabIndex == newIndex, false);
  51533. }
  51534. resized();
  51535. if (sendChangeMessage_)
  51536. sendChangeMessage (this);
  51537. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51538. }
  51539. }
  51540. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51541. {
  51542. for (int i = getNumChildComponents(); --i >= 0;)
  51543. {
  51544. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51545. if (tb != 0 && tb->tabIndex == index)
  51546. return tb;
  51547. }
  51548. return 0;
  51549. }
  51550. void TabbedButtonBar::lookAndFeelChanged()
  51551. {
  51552. extraTabsButton = 0;
  51553. resized();
  51554. }
  51555. void TabbedButtonBar::resized()
  51556. {
  51557. const double minimumScale = 0.7;
  51558. int depth = getWidth();
  51559. int length = getHeight();
  51560. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51561. swapVariables (depth, length);
  51562. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51563. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51564. int i, totalLength = overlap;
  51565. int numVisibleButtons = tabs.size();
  51566. for (i = 0; i < getNumChildComponents(); ++i)
  51567. {
  51568. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51569. if (tb != 0)
  51570. {
  51571. totalLength += tb->getBestTabLength (depth) - overlap;
  51572. tb->overlapPixels = overlap / 2;
  51573. }
  51574. }
  51575. double scale = 1.0;
  51576. if (totalLength > length)
  51577. scale = jmax (minimumScale, length / (double) totalLength);
  51578. const bool isTooBig = totalLength * scale > length;
  51579. int tabsButtonPos = 0;
  51580. if (isTooBig)
  51581. {
  51582. if (extraTabsButton == 0)
  51583. {
  51584. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51585. extraTabsButton->addButtonListener (this);
  51586. extraTabsButton->setAlwaysOnTop (true);
  51587. extraTabsButton->setTriggeredOnMouseDown (true);
  51588. }
  51589. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51590. extraTabsButton->setSize (buttonSize, buttonSize);
  51591. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51592. {
  51593. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51594. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51595. }
  51596. else
  51597. {
  51598. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51599. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51600. }
  51601. totalLength = 0;
  51602. for (i = 0; i < tabs.size(); ++i)
  51603. {
  51604. TabBarButton* const tb = getTabButton (i);
  51605. if (tb != 0)
  51606. {
  51607. const int newLength = totalLength + tb->getBestTabLength (depth);
  51608. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51609. {
  51610. totalLength += overlap;
  51611. break;
  51612. }
  51613. numVisibleButtons = i + 1;
  51614. totalLength = newLength - overlap;
  51615. }
  51616. }
  51617. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51618. }
  51619. else
  51620. {
  51621. extraTabsButton = 0;
  51622. }
  51623. int pos = 0;
  51624. TabBarButton* frontTab = 0;
  51625. for (i = 0; i < tabs.size(); ++i)
  51626. {
  51627. TabBarButton* const tb = getTabButton (i);
  51628. if (tb != 0)
  51629. {
  51630. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51631. if (i < numVisibleButtons)
  51632. {
  51633. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51634. tb->setBounds (pos, 0, bestLength, getHeight());
  51635. else
  51636. tb->setBounds (0, pos, getWidth(), bestLength);
  51637. tb->toBack();
  51638. if (tb->tabIndex == currentTabIndex)
  51639. frontTab = tb;
  51640. tb->setVisible (true);
  51641. }
  51642. else
  51643. {
  51644. tb->setVisible (false);
  51645. }
  51646. pos += bestLength - overlap;
  51647. }
  51648. }
  51649. behindFrontTab->setBounds (getLocalBounds());
  51650. if (frontTab != 0)
  51651. {
  51652. frontTab->toFront (false);
  51653. behindFrontTab->toBehind (frontTab);
  51654. }
  51655. }
  51656. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51657. {
  51658. return tabColours [tabIndex];
  51659. }
  51660. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51661. {
  51662. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51663. && tabColours [tabIndex] != newColour)
  51664. {
  51665. tabColours.set (tabIndex, newColour);
  51666. repaint();
  51667. }
  51668. }
  51669. void TabbedButtonBar::buttonClicked (Button* button)
  51670. {
  51671. if (button == extraTabsButton)
  51672. {
  51673. PopupMenu m;
  51674. for (int i = 0; i < tabs.size(); ++i)
  51675. {
  51676. TabBarButton* const tb = getTabButton (i);
  51677. if (tb != 0 && ! tb->isVisible())
  51678. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51679. }
  51680. const int res = m.showAt (extraTabsButton);
  51681. if (res != 0)
  51682. setCurrentTabIndex (res - 1);
  51683. }
  51684. }
  51685. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51686. {
  51687. }
  51688. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51689. {
  51690. }
  51691. END_JUCE_NAMESPACE
  51692. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51693. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51694. BEGIN_JUCE_NAMESPACE
  51695. class TabCompButtonBar : public TabbedButtonBar
  51696. {
  51697. public:
  51698. TabCompButtonBar (TabbedComponent* const owner_,
  51699. const TabbedButtonBar::Orientation orientation_)
  51700. : TabbedButtonBar (orientation_),
  51701. owner (owner_)
  51702. {
  51703. }
  51704. ~TabCompButtonBar()
  51705. {
  51706. }
  51707. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51708. {
  51709. owner->changeCallback (newCurrentTabIndex, newTabName);
  51710. }
  51711. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51712. {
  51713. owner->popupMenuClickOnTab (tabIndex, tabName);
  51714. }
  51715. const Colour getTabBackgroundColour (const int tabIndex)
  51716. {
  51717. return owner->tabs->getTabBackgroundColour (tabIndex);
  51718. }
  51719. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51720. {
  51721. return owner->createTabButton (tabName, tabIndex);
  51722. }
  51723. juce_UseDebuggingNewOperator
  51724. private:
  51725. TabbedComponent* const owner;
  51726. TabCompButtonBar (const TabCompButtonBar&);
  51727. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51728. };
  51729. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51730. : panelComponent (0),
  51731. tabDepth (30),
  51732. outlineThickness (1),
  51733. edgeIndent (0)
  51734. {
  51735. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51736. }
  51737. TabbedComponent::~TabbedComponent()
  51738. {
  51739. clearTabs();
  51740. delete tabs;
  51741. }
  51742. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51743. {
  51744. tabs->setOrientation (orientation);
  51745. resized();
  51746. }
  51747. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51748. {
  51749. return tabs->getOrientation();
  51750. }
  51751. void TabbedComponent::setTabBarDepth (const int newDepth)
  51752. {
  51753. if (tabDepth != newDepth)
  51754. {
  51755. tabDepth = newDepth;
  51756. resized();
  51757. }
  51758. }
  51759. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51760. {
  51761. return new TabBarButton (tabName, tabs, tabIndex);
  51762. }
  51763. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51764. void TabbedComponent::clearTabs()
  51765. {
  51766. if (panelComponent != 0)
  51767. {
  51768. panelComponent->setVisible (false);
  51769. removeChildComponent (panelComponent);
  51770. panelComponent = 0;
  51771. }
  51772. tabs->clearTabs();
  51773. for (int i = contentComponents.size(); --i >= 0;)
  51774. {
  51775. Component* const c = contentComponents.getUnchecked(i);
  51776. // be careful not to delete these components until they've been removed from the tab component
  51777. jassert (c == 0 || c->isValidComponent());
  51778. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51779. delete c;
  51780. }
  51781. contentComponents.clear();
  51782. }
  51783. void TabbedComponent::addTab (const String& tabName,
  51784. const Colour& tabBackgroundColour,
  51785. Component* const contentComponent,
  51786. const bool deleteComponentWhenNotNeeded,
  51787. const int insertIndex)
  51788. {
  51789. contentComponents.insert (insertIndex, contentComponent);
  51790. if (contentComponent != 0)
  51791. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51792. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51793. }
  51794. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51795. {
  51796. tabs->setTabName (tabIndex, newName);
  51797. }
  51798. void TabbedComponent::removeTab (const int tabIndex)
  51799. {
  51800. Component* const c = contentComponents [tabIndex];
  51801. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51802. {
  51803. if (c == panelComponent)
  51804. panelComponent = 0;
  51805. delete c;
  51806. }
  51807. contentComponents.remove (tabIndex);
  51808. tabs->removeTab (tabIndex);
  51809. }
  51810. int TabbedComponent::getNumTabs() const
  51811. {
  51812. return tabs->getNumTabs();
  51813. }
  51814. const StringArray TabbedComponent::getTabNames() const
  51815. {
  51816. return tabs->getTabNames();
  51817. }
  51818. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51819. {
  51820. return contentComponents [tabIndex];
  51821. }
  51822. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51823. {
  51824. return tabs->getTabBackgroundColour (tabIndex);
  51825. }
  51826. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51827. {
  51828. tabs->setTabBackgroundColour (tabIndex, newColour);
  51829. if (getCurrentTabIndex() == tabIndex)
  51830. repaint();
  51831. }
  51832. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51833. {
  51834. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51835. }
  51836. int TabbedComponent::getCurrentTabIndex() const
  51837. {
  51838. return tabs->getCurrentTabIndex();
  51839. }
  51840. const String& TabbedComponent::getCurrentTabName() const
  51841. {
  51842. return tabs->getCurrentTabName();
  51843. }
  51844. void TabbedComponent::setOutline (int thickness)
  51845. {
  51846. outlineThickness = thickness;
  51847. repaint();
  51848. }
  51849. void TabbedComponent::setIndent (const int indentThickness)
  51850. {
  51851. edgeIndent = indentThickness;
  51852. }
  51853. void TabbedComponent::paint (Graphics& g)
  51854. {
  51855. g.fillAll (findColour (backgroundColourId));
  51856. const TabbedButtonBar::Orientation o = getOrientation();
  51857. int x = 0;
  51858. int y = 0;
  51859. int r = getWidth();
  51860. int b = getHeight();
  51861. if (o == TabbedButtonBar::TabsAtTop)
  51862. y += tabDepth;
  51863. else if (o == TabbedButtonBar::TabsAtBottom)
  51864. b -= tabDepth;
  51865. else if (o == TabbedButtonBar::TabsAtLeft)
  51866. x += tabDepth;
  51867. else if (o == TabbedButtonBar::TabsAtRight)
  51868. r -= tabDepth;
  51869. g.reduceClipRegion (x, y, r - x, b - y);
  51870. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51871. if (outlineThickness > 0)
  51872. {
  51873. if (o == TabbedButtonBar::TabsAtTop)
  51874. --y;
  51875. else if (o == TabbedButtonBar::TabsAtBottom)
  51876. ++b;
  51877. else if (o == TabbedButtonBar::TabsAtLeft)
  51878. --x;
  51879. else if (o == TabbedButtonBar::TabsAtRight)
  51880. ++r;
  51881. g.setColour (findColour (outlineColourId));
  51882. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51883. }
  51884. }
  51885. void TabbedComponent::resized()
  51886. {
  51887. const TabbedButtonBar::Orientation o = getOrientation();
  51888. const int indent = edgeIndent + outlineThickness;
  51889. BorderSize indents (indent);
  51890. if (o == TabbedButtonBar::TabsAtTop)
  51891. {
  51892. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51893. indents.setTop (tabDepth + edgeIndent);
  51894. }
  51895. else if (o == TabbedButtonBar::TabsAtBottom)
  51896. {
  51897. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51898. indents.setBottom (tabDepth + edgeIndent);
  51899. }
  51900. else if (o == TabbedButtonBar::TabsAtLeft)
  51901. {
  51902. tabs->setBounds (0, 0, tabDepth, getHeight());
  51903. indents.setLeft (tabDepth + edgeIndent);
  51904. }
  51905. else if (o == TabbedButtonBar::TabsAtRight)
  51906. {
  51907. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51908. indents.setRight (tabDepth + edgeIndent);
  51909. }
  51910. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51911. for (int i = contentComponents.size(); --i >= 0;)
  51912. if (contentComponents.getUnchecked (i) != 0)
  51913. contentComponents.getUnchecked (i)->setBounds (bounds);
  51914. }
  51915. void TabbedComponent::lookAndFeelChanged()
  51916. {
  51917. for (int i = contentComponents.size(); --i >= 0;)
  51918. if (contentComponents.getUnchecked (i) != 0)
  51919. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51920. }
  51921. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51922. const String& newTabName)
  51923. {
  51924. if (panelComponent != 0)
  51925. {
  51926. panelComponent->setVisible (false);
  51927. removeChildComponent (panelComponent);
  51928. panelComponent = 0;
  51929. }
  51930. if (getCurrentTabIndex() >= 0)
  51931. {
  51932. panelComponent = contentComponents [getCurrentTabIndex()];
  51933. if (panelComponent != 0)
  51934. {
  51935. // do these ops as two stages instead of addAndMakeVisible() so that the
  51936. // component has always got a parent when it gets the visibilityChanged() callback
  51937. addChildComponent (panelComponent);
  51938. panelComponent->setVisible (true);
  51939. panelComponent->toFront (true);
  51940. }
  51941. repaint();
  51942. }
  51943. resized();
  51944. currentTabChanged (newCurrentTabIndex, newTabName);
  51945. }
  51946. void TabbedComponent::currentTabChanged (const int, const String&)
  51947. {
  51948. }
  51949. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51950. {
  51951. }
  51952. END_JUCE_NAMESPACE
  51953. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51954. /*** Start of inlined file: juce_Viewport.cpp ***/
  51955. BEGIN_JUCE_NAMESPACE
  51956. Viewport::Viewport (const String& componentName)
  51957. : Component (componentName),
  51958. scrollBarThickness (0),
  51959. singleStepX (16),
  51960. singleStepY (16),
  51961. showHScrollbar (true),
  51962. showVScrollbar (true),
  51963. verticalScrollBar (true),
  51964. horizontalScrollBar (false)
  51965. {
  51966. // content holder is used to clip the contents so they don't overlap the scrollbars
  51967. addAndMakeVisible (&contentHolder);
  51968. contentHolder.setInterceptsMouseClicks (false, true);
  51969. addChildComponent (&verticalScrollBar);
  51970. addChildComponent (&horizontalScrollBar);
  51971. verticalScrollBar.addListener (this);
  51972. horizontalScrollBar.addListener (this);
  51973. setInterceptsMouseClicks (false, true);
  51974. setWantsKeyboardFocus (true);
  51975. }
  51976. Viewport::~Viewport()
  51977. {
  51978. contentHolder.deleteAllChildren();
  51979. }
  51980. void Viewport::visibleAreaChanged (int, int, int, int)
  51981. {
  51982. }
  51983. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51984. {
  51985. if (contentComp.getComponent() != newViewedComponent)
  51986. {
  51987. {
  51988. ScopedPointer<Component> oldCompDeleter (contentComp);
  51989. contentComp = 0;
  51990. }
  51991. contentComp = newViewedComponent;
  51992. if (contentComp != 0)
  51993. {
  51994. contentComp->setTopLeftPosition (0, 0);
  51995. contentHolder.addAndMakeVisible (contentComp);
  51996. contentComp->addComponentListener (this);
  51997. }
  51998. updateVisibleArea();
  51999. }
  52000. }
  52001. int Viewport::getMaximumVisibleWidth() const
  52002. {
  52003. return contentHolder.getWidth();
  52004. }
  52005. int Viewport::getMaximumVisibleHeight() const
  52006. {
  52007. return contentHolder.getHeight();
  52008. }
  52009. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52010. {
  52011. if (contentComp != 0)
  52012. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52013. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52014. }
  52015. void Viewport::setViewPosition (const Point<int>& newPosition)
  52016. {
  52017. setViewPosition (newPosition.getX(), newPosition.getY());
  52018. }
  52019. void Viewport::setViewPositionProportionately (const double x, const double y)
  52020. {
  52021. if (contentComp != 0)
  52022. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52023. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52024. }
  52025. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52026. {
  52027. if (contentComp != 0)
  52028. {
  52029. int dx = 0, dy = 0;
  52030. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52031. {
  52032. if (mouseX < activeBorderThickness)
  52033. dx = activeBorderThickness - mouseX;
  52034. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52035. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52036. if (dx < 0)
  52037. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52038. else
  52039. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52040. }
  52041. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52042. {
  52043. if (mouseY < activeBorderThickness)
  52044. dy = activeBorderThickness - mouseY;
  52045. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52046. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52047. if (dy < 0)
  52048. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52049. else
  52050. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52051. }
  52052. if (dx != 0 || dy != 0)
  52053. {
  52054. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52055. contentComp->getY() + dy);
  52056. return true;
  52057. }
  52058. }
  52059. return false;
  52060. }
  52061. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52062. {
  52063. updateVisibleArea();
  52064. }
  52065. void Viewport::resized()
  52066. {
  52067. updateVisibleArea();
  52068. }
  52069. void Viewport::updateVisibleArea()
  52070. {
  52071. const int scrollbarWidth = getScrollBarThickness();
  52072. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52073. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52074. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52075. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52076. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52077. Rectangle<int> contentArea (getLocalBounds());
  52078. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52079. {
  52080. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52081. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52082. if (vBarVisible)
  52083. contentArea.setWidth (getWidth() - scrollbarWidth);
  52084. if (hBarVisible)
  52085. contentArea.setHeight (getHeight() - scrollbarWidth);
  52086. if (! contentArea.contains (contentComp->getBounds()))
  52087. {
  52088. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52089. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52090. }
  52091. }
  52092. if (vBarVisible)
  52093. contentArea.setWidth (getWidth() - scrollbarWidth);
  52094. if (hBarVisible)
  52095. contentArea.setHeight (getHeight() - scrollbarWidth);
  52096. contentHolder.setBounds (contentArea);
  52097. Rectangle<int> contentBounds;
  52098. if (contentComp != 0)
  52099. contentBounds = contentComp->getBounds();
  52100. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52101. if (hBarVisible)
  52102. {
  52103. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52104. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52105. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52106. horizontalScrollBar.setSingleStepSize (singleStepX);
  52107. horizontalScrollBar.cancelPendingUpdate();
  52108. }
  52109. if (vBarVisible)
  52110. {
  52111. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52112. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52113. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52114. verticalScrollBar.setSingleStepSize (singleStepY);
  52115. verticalScrollBar.cancelPendingUpdate();
  52116. }
  52117. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52118. horizontalScrollBar.setVisible (hBarVisible);
  52119. verticalScrollBar.setVisible (vBarVisible);
  52120. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52121. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52122. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52123. if (lastVisibleArea != visibleArea)
  52124. {
  52125. lastVisibleArea = visibleArea;
  52126. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52127. }
  52128. horizontalScrollBar.handleUpdateNowIfNeeded();
  52129. verticalScrollBar.handleUpdateNowIfNeeded();
  52130. }
  52131. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52132. {
  52133. if (singleStepX != stepX || singleStepY != stepY)
  52134. {
  52135. singleStepX = stepX;
  52136. singleStepY = stepY;
  52137. updateVisibleArea();
  52138. }
  52139. }
  52140. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52141. const bool showHorizontalScrollbarIfNeeded)
  52142. {
  52143. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52144. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52145. {
  52146. showVScrollbar = showVerticalScrollbarIfNeeded;
  52147. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52148. updateVisibleArea();
  52149. }
  52150. }
  52151. void Viewport::setScrollBarThickness (const int thickness)
  52152. {
  52153. if (scrollBarThickness != thickness)
  52154. {
  52155. scrollBarThickness = thickness;
  52156. updateVisibleArea();
  52157. }
  52158. }
  52159. int Viewport::getScrollBarThickness() const
  52160. {
  52161. return scrollBarThickness > 0 ? scrollBarThickness
  52162. : getLookAndFeel().getDefaultScrollbarWidth();
  52163. }
  52164. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52165. {
  52166. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52167. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52168. }
  52169. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52170. {
  52171. const int newRangeStartInt = roundToInt (newRangeStart);
  52172. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52173. {
  52174. setViewPosition (newRangeStartInt, getViewPositionY());
  52175. }
  52176. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52177. {
  52178. setViewPosition (getViewPositionX(), newRangeStartInt);
  52179. }
  52180. }
  52181. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52182. {
  52183. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52184. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52185. }
  52186. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52187. {
  52188. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52189. {
  52190. const bool hasVertBar = verticalScrollBar.isVisible();
  52191. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52192. if (hasHorzBar || hasVertBar)
  52193. {
  52194. if (wheelIncrementX != 0)
  52195. {
  52196. wheelIncrementX *= 14.0f * singleStepX;
  52197. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52198. : jmax (wheelIncrementX, 1.0f);
  52199. }
  52200. if (wheelIncrementY != 0)
  52201. {
  52202. wheelIncrementY *= 14.0f * singleStepY;
  52203. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52204. : jmax (wheelIncrementY, 1.0f);
  52205. }
  52206. Point<int> pos (getViewPosition());
  52207. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52208. {
  52209. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52210. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52211. }
  52212. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52213. {
  52214. if (wheelIncrementX == 0 && ! hasVertBar)
  52215. wheelIncrementX = wheelIncrementY;
  52216. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52217. }
  52218. else if (hasVertBar && wheelIncrementY != 0)
  52219. {
  52220. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52221. }
  52222. if (pos != getViewPosition())
  52223. {
  52224. setViewPosition (pos);
  52225. return true;
  52226. }
  52227. }
  52228. }
  52229. return false;
  52230. }
  52231. bool Viewport::keyPressed (const KeyPress& key)
  52232. {
  52233. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52234. || key.isKeyCode (KeyPress::downKey)
  52235. || key.isKeyCode (KeyPress::pageUpKey)
  52236. || key.isKeyCode (KeyPress::pageDownKey)
  52237. || key.isKeyCode (KeyPress::homeKey)
  52238. || key.isKeyCode (KeyPress::endKey);
  52239. if (verticalScrollBar.isVisible() && isUpDownKey)
  52240. return verticalScrollBar.keyPressed (key);
  52241. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52242. || key.isKeyCode (KeyPress::rightKey);
  52243. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52244. return horizontalScrollBar.keyPressed (key);
  52245. return false;
  52246. }
  52247. END_JUCE_NAMESPACE
  52248. /*** End of inlined file: juce_Viewport.cpp ***/
  52249. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52250. BEGIN_JUCE_NAMESPACE
  52251. static const Colour createBaseColour (const Colour& buttonColour,
  52252. const bool hasKeyboardFocus,
  52253. const bool isMouseOverButton,
  52254. const bool isButtonDown) throw()
  52255. {
  52256. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52257. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52258. if (isButtonDown)
  52259. return baseColour.contrasting (0.2f);
  52260. else if (isMouseOverButton)
  52261. return baseColour.contrasting (0.1f);
  52262. return baseColour;
  52263. }
  52264. LookAndFeel::LookAndFeel()
  52265. {
  52266. /* if this fails it means you're trying to create a LookAndFeel object before
  52267. the static Colours have been initialised. That ain't gonna work. It probably
  52268. means that you're using a static LookAndFeel object and that your compiler has
  52269. decided to intialise it before the Colours class.
  52270. */
  52271. jassert (Colours::white == Colour (0xffffffff));
  52272. // set up the standard set of colours..
  52273. const int textButtonColour = 0xffbbbbff;
  52274. const int textHighlightColour = 0x401111ee;
  52275. const int standardOutlineColour = 0xb2808080;
  52276. static const int standardColours[] =
  52277. {
  52278. TextButton::buttonColourId, textButtonColour,
  52279. TextButton::buttonOnColourId, 0xff4444ff,
  52280. TextButton::textColourOnId, 0xff000000,
  52281. TextButton::textColourOffId, 0xff000000,
  52282. ComboBox::buttonColourId, 0xffbbbbff,
  52283. ComboBox::outlineColourId, standardOutlineColour,
  52284. ToggleButton::textColourId, 0xff000000,
  52285. TextEditor::backgroundColourId, 0xffffffff,
  52286. TextEditor::textColourId, 0xff000000,
  52287. TextEditor::highlightColourId, textHighlightColour,
  52288. TextEditor::highlightedTextColourId, 0xff000000,
  52289. TextEditor::caretColourId, 0xff000000,
  52290. TextEditor::outlineColourId, 0x00000000,
  52291. TextEditor::focusedOutlineColourId, textButtonColour,
  52292. TextEditor::shadowColourId, 0x38000000,
  52293. Label::backgroundColourId, 0x00000000,
  52294. Label::textColourId, 0xff000000,
  52295. Label::outlineColourId, 0x00000000,
  52296. ScrollBar::backgroundColourId, 0x00000000,
  52297. ScrollBar::thumbColourId, 0xffffffff,
  52298. ScrollBar::trackColourId, 0xffffffff,
  52299. TreeView::linesColourId, 0x4c000000,
  52300. TreeView::backgroundColourId, 0x00000000,
  52301. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52302. PopupMenu::backgroundColourId, 0xffffffff,
  52303. PopupMenu::textColourId, 0xff000000,
  52304. PopupMenu::headerTextColourId, 0xff000000,
  52305. PopupMenu::highlightedTextColourId, 0xffffffff,
  52306. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52307. ComboBox::textColourId, 0xff000000,
  52308. ComboBox::backgroundColourId, 0xffffffff,
  52309. ComboBox::arrowColourId, 0x99000000,
  52310. ListBox::backgroundColourId, 0xffffffff,
  52311. ListBox::outlineColourId, standardOutlineColour,
  52312. ListBox::textColourId, 0xff000000,
  52313. Slider::backgroundColourId, 0x00000000,
  52314. Slider::thumbColourId, textButtonColour,
  52315. Slider::trackColourId, 0x7fffffff,
  52316. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52317. Slider::rotarySliderOutlineColourId, 0x66000000,
  52318. Slider::textBoxTextColourId, 0xff000000,
  52319. Slider::textBoxBackgroundColourId, 0xffffffff,
  52320. Slider::textBoxHighlightColourId, textHighlightColour,
  52321. Slider::textBoxOutlineColourId, standardOutlineColour,
  52322. ResizableWindow::backgroundColourId, 0xff777777,
  52323. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52324. AlertWindow::backgroundColourId, 0xffededed,
  52325. AlertWindow::textColourId, 0xff000000,
  52326. AlertWindow::outlineColourId, 0xff666666,
  52327. ProgressBar::backgroundColourId, 0xffeeeeee,
  52328. ProgressBar::foregroundColourId, 0xffaaaaee,
  52329. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52330. TooltipWindow::textColourId, 0xff000000,
  52331. TooltipWindow::outlineColourId, 0x4c000000,
  52332. TabbedComponent::backgroundColourId, 0x00000000,
  52333. TabbedComponent::outlineColourId, 0xff777777,
  52334. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52335. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52336. Toolbar::backgroundColourId, 0xfff6f8f9,
  52337. Toolbar::separatorColourId, 0x4c000000,
  52338. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52339. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52340. Toolbar::labelTextColourId, 0xff000000,
  52341. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52342. HyperlinkButton::textColourId, 0xcc1111ee,
  52343. GroupComponent::outlineColourId, 0x66000000,
  52344. GroupComponent::textColourId, 0xff000000,
  52345. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52346. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52347. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52348. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52349. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52350. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52351. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52352. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52353. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52354. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52355. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52356. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52357. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52358. CodeEditorComponent::caretColourId, 0xff000000,
  52359. CodeEditorComponent::highlightColourId, textHighlightColour,
  52360. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52361. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52362. ColourSelector::labelTextColourId, 0xff000000,
  52363. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52364. KeyMappingEditorComponent::textColourId, 0xff000000,
  52365. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52366. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52367. DrawableButton::textColourId, 0xff000000,
  52368. };
  52369. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52370. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52371. static String defaultSansName, defaultSerifName, defaultFixedName;
  52372. if (defaultSansName.isEmpty())
  52373. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52374. defaultSans = defaultSansName;
  52375. defaultSerif = defaultSerifName;
  52376. defaultFixed = defaultFixedName;
  52377. }
  52378. LookAndFeel::~LookAndFeel()
  52379. {
  52380. }
  52381. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52382. {
  52383. const int index = colourIds.indexOf (colourId);
  52384. if (index >= 0)
  52385. return colours [index];
  52386. jassertfalse;
  52387. return Colours::black;
  52388. }
  52389. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52390. {
  52391. const int index = colourIds.indexOf (colourId);
  52392. if (index >= 0)
  52393. {
  52394. colours.set (index, colour);
  52395. }
  52396. else
  52397. {
  52398. colourIds.add (colourId);
  52399. colours.add (colour);
  52400. }
  52401. }
  52402. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52403. {
  52404. return colourIds.contains (colourId);
  52405. }
  52406. static LookAndFeel* defaultLF = 0;
  52407. static LookAndFeel* currentDefaultLF = 0;
  52408. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52409. {
  52410. // if this happens, your app hasn't initialised itself properly.. if you're
  52411. // trying to hack your own main() function, have a look at
  52412. // JUCEApplication::initialiseForGUI()
  52413. jassert (currentDefaultLF != 0);
  52414. return *currentDefaultLF;
  52415. }
  52416. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52417. {
  52418. if (newDefaultLookAndFeel == 0)
  52419. {
  52420. if (defaultLF == 0)
  52421. defaultLF = new LookAndFeel();
  52422. newDefaultLookAndFeel = defaultLF;
  52423. }
  52424. currentDefaultLF = newDefaultLookAndFeel;
  52425. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52426. {
  52427. Component* const c = Desktop::getInstance().getComponent (i);
  52428. if (c != 0)
  52429. c->sendLookAndFeelChange();
  52430. }
  52431. }
  52432. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52433. {
  52434. if (currentDefaultLF == defaultLF)
  52435. currentDefaultLF = 0;
  52436. deleteAndZero (defaultLF);
  52437. }
  52438. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52439. {
  52440. String faceName (font.getTypefaceName());
  52441. if (faceName == Font::getDefaultSansSerifFontName())
  52442. faceName = defaultSans;
  52443. else if (faceName == Font::getDefaultSerifFontName())
  52444. faceName = defaultSerif;
  52445. else if (faceName == Font::getDefaultMonospacedFontName())
  52446. faceName = defaultFixed;
  52447. Font f (font);
  52448. f.setTypefaceName (faceName);
  52449. return Typeface::createSystemTypefaceFor (f);
  52450. }
  52451. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52452. {
  52453. defaultSans = newName;
  52454. }
  52455. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52456. {
  52457. return component.getMouseCursor();
  52458. }
  52459. void LookAndFeel::drawButtonBackground (Graphics& g,
  52460. Button& button,
  52461. const Colour& backgroundColour,
  52462. bool isMouseOverButton,
  52463. bool isButtonDown)
  52464. {
  52465. const int width = button.getWidth();
  52466. const int height = button.getHeight();
  52467. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52468. const float halfThickness = outlineThickness * 0.5f;
  52469. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52470. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52471. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52472. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52473. const Colour baseColour (createBaseColour (backgroundColour,
  52474. button.hasKeyboardFocus (true),
  52475. isMouseOverButton, isButtonDown)
  52476. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52477. drawGlassLozenge (g,
  52478. indentL,
  52479. indentT,
  52480. width - indentL - indentR,
  52481. height - indentT - indentB,
  52482. baseColour, outlineThickness, -1.0f,
  52483. button.isConnectedOnLeft(),
  52484. button.isConnectedOnRight(),
  52485. button.isConnectedOnTop(),
  52486. button.isConnectedOnBottom());
  52487. }
  52488. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52489. {
  52490. return button.getFont();
  52491. }
  52492. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52493. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52494. {
  52495. Font font (getFontForTextButton (button));
  52496. g.setFont (font);
  52497. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52498. : TextButton::textColourOffId)
  52499. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52500. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52501. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52502. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52503. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52504. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52505. g.drawFittedText (button.getButtonText(),
  52506. leftIndent,
  52507. yIndent,
  52508. button.getWidth() - leftIndent - rightIndent,
  52509. button.getHeight() - yIndent * 2,
  52510. Justification::centred, 2);
  52511. }
  52512. void LookAndFeel::drawTickBox (Graphics& g,
  52513. Component& component,
  52514. float x, float y, float w, float h,
  52515. const bool ticked,
  52516. const bool isEnabled,
  52517. const bool isMouseOverButton,
  52518. const bool isButtonDown)
  52519. {
  52520. const float boxSize = w * 0.7f;
  52521. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52522. createBaseColour (component.findColour (TextButton::buttonColourId)
  52523. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52524. true,
  52525. isMouseOverButton,
  52526. isButtonDown),
  52527. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52528. if (ticked)
  52529. {
  52530. Path tick;
  52531. tick.startNewSubPath (1.5f, 3.0f);
  52532. tick.lineTo (3.0f, 6.0f);
  52533. tick.lineTo (6.0f, 0.0f);
  52534. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52535. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52536. .translated (x, y));
  52537. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52538. }
  52539. }
  52540. void LookAndFeel::drawToggleButton (Graphics& g,
  52541. ToggleButton& button,
  52542. bool isMouseOverButton,
  52543. bool isButtonDown)
  52544. {
  52545. if (button.hasKeyboardFocus (true))
  52546. {
  52547. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52548. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52549. }
  52550. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52551. const float tickWidth = fontSize * 1.1f;
  52552. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52553. tickWidth, tickWidth,
  52554. button.getToggleState(),
  52555. button.isEnabled(),
  52556. isMouseOverButton,
  52557. isButtonDown);
  52558. g.setColour (button.findColour (ToggleButton::textColourId));
  52559. g.setFont (fontSize);
  52560. if (! button.isEnabled())
  52561. g.setOpacity (0.5f);
  52562. const int textX = (int) tickWidth + 5;
  52563. g.drawFittedText (button.getButtonText(),
  52564. textX, 0,
  52565. button.getWidth() - textX - 2, button.getHeight(),
  52566. Justification::centredLeft, 10);
  52567. }
  52568. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52569. {
  52570. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52571. const int tickWidth = jmin (24, button.getHeight());
  52572. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52573. button.getHeight());
  52574. }
  52575. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52576. const String& message,
  52577. const String& button1,
  52578. const String& button2,
  52579. const String& button3,
  52580. AlertWindow::AlertIconType iconType,
  52581. int numButtons,
  52582. Component* associatedComponent)
  52583. {
  52584. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52585. if (numButtons == 1)
  52586. {
  52587. aw->addButton (button1, 0,
  52588. KeyPress (KeyPress::escapeKey, 0, 0),
  52589. KeyPress (KeyPress::returnKey, 0, 0));
  52590. }
  52591. else
  52592. {
  52593. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52594. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52595. if (button1ShortCut == button2ShortCut)
  52596. button2ShortCut = KeyPress();
  52597. if (numButtons == 2)
  52598. {
  52599. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52600. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52601. }
  52602. else if (numButtons == 3)
  52603. {
  52604. aw->addButton (button1, 1, button1ShortCut);
  52605. aw->addButton (button2, 2, button2ShortCut);
  52606. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52607. }
  52608. }
  52609. return aw;
  52610. }
  52611. void LookAndFeel::drawAlertBox (Graphics& g,
  52612. AlertWindow& alert,
  52613. const Rectangle<int>& textArea,
  52614. TextLayout& textLayout)
  52615. {
  52616. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52617. int iconSpaceUsed = 0;
  52618. Justification alignment (Justification::horizontallyCentred);
  52619. const int iconWidth = 80;
  52620. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52621. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52622. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52623. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52624. iconSize, iconSize);
  52625. if (alert.getAlertType() != AlertWindow::NoIcon)
  52626. {
  52627. Path icon;
  52628. uint32 colour;
  52629. char character;
  52630. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52631. {
  52632. colour = 0x55ff5555;
  52633. character = '!';
  52634. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52635. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52636. (float) iconRect.getX(), (float) iconRect.getBottom());
  52637. icon = icon.createPathWithRoundedCorners (5.0f);
  52638. }
  52639. else
  52640. {
  52641. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52642. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52643. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52644. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52645. }
  52646. GlyphArrangement ga;
  52647. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52648. String::charToString (character),
  52649. (float) iconRect.getX(), (float) iconRect.getY(),
  52650. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52651. Justification::centred, false);
  52652. ga.createPath (icon);
  52653. icon.setUsingNonZeroWinding (false);
  52654. g.setColour (Colour (colour));
  52655. g.fillPath (icon);
  52656. iconSpaceUsed = iconWidth;
  52657. alignment = Justification::left;
  52658. }
  52659. g.setColour (alert.findColour (AlertWindow::textColourId));
  52660. textLayout.drawWithin (g,
  52661. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52662. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52663. alignment.getFlags() | Justification::top);
  52664. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52665. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52666. }
  52667. int LookAndFeel::getAlertBoxWindowFlags()
  52668. {
  52669. return ComponentPeer::windowAppearsOnTaskbar
  52670. | ComponentPeer::windowHasDropShadow;
  52671. }
  52672. int LookAndFeel::getAlertWindowButtonHeight()
  52673. {
  52674. return 28;
  52675. }
  52676. const Font LookAndFeel::getAlertWindowFont()
  52677. {
  52678. return Font (12.0f);
  52679. }
  52680. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52681. int width, int height,
  52682. double progress, const String& textToShow)
  52683. {
  52684. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52685. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52686. g.fillAll (background);
  52687. if (progress >= 0.0f && progress < 1.0f)
  52688. {
  52689. drawGlassLozenge (g, 1.0f, 1.0f,
  52690. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52691. (float) (height - 2),
  52692. foreground,
  52693. 0.5f, 0.0f,
  52694. true, true, true, true);
  52695. }
  52696. else
  52697. {
  52698. // spinning bar..
  52699. g.setColour (foreground);
  52700. const int stripeWidth = height * 2;
  52701. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52702. Path p;
  52703. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52704. p.addQuadrilateral (x, 0.0f,
  52705. x + stripeWidth * 0.5f, 0.0f,
  52706. x, (float) height,
  52707. x - stripeWidth * 0.5f, (float) height);
  52708. Image im (Image::ARGB, width, height, true);
  52709. {
  52710. Graphics g2 (im);
  52711. drawGlassLozenge (g2, 1.0f, 1.0f,
  52712. (float) (width - 2),
  52713. (float) (height - 2),
  52714. foreground,
  52715. 0.5f, 0.0f,
  52716. true, true, true, true);
  52717. }
  52718. g.setTiledImageFill (im, 0, 0, 0.85f);
  52719. g.fillPath (p);
  52720. }
  52721. if (textToShow.isNotEmpty())
  52722. {
  52723. g.setColour (Colour::contrasting (background, foreground));
  52724. g.setFont (height * 0.6f);
  52725. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52726. }
  52727. }
  52728. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52729. {
  52730. const float radius = jmin (w, h) * 0.4f;
  52731. const float thickness = radius * 0.15f;
  52732. Path p;
  52733. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52734. radius * 0.6f, thickness,
  52735. thickness * 0.5f);
  52736. const float cx = x + w * 0.5f;
  52737. const float cy = y + h * 0.5f;
  52738. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52739. for (int i = 0; i < 12; ++i)
  52740. {
  52741. const int n = (i + 12 - animationIndex) % 12;
  52742. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52743. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52744. .translated (cx, cy));
  52745. }
  52746. }
  52747. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52748. ScrollBar& scrollbar,
  52749. int width, int height,
  52750. int buttonDirection,
  52751. bool /*isScrollbarVertical*/,
  52752. bool /*isMouseOverButton*/,
  52753. bool isButtonDown)
  52754. {
  52755. Path p;
  52756. if (buttonDirection == 0)
  52757. p.addTriangle (width * 0.5f, height * 0.2f,
  52758. width * 0.1f, height * 0.7f,
  52759. width * 0.9f, height * 0.7f);
  52760. else if (buttonDirection == 1)
  52761. p.addTriangle (width * 0.8f, height * 0.5f,
  52762. width * 0.3f, height * 0.1f,
  52763. width * 0.3f, height * 0.9f);
  52764. else if (buttonDirection == 2)
  52765. p.addTriangle (width * 0.5f, height * 0.8f,
  52766. width * 0.1f, height * 0.3f,
  52767. width * 0.9f, height * 0.3f);
  52768. else if (buttonDirection == 3)
  52769. p.addTriangle (width * 0.2f, height * 0.5f,
  52770. width * 0.7f, height * 0.1f,
  52771. width * 0.7f, height * 0.9f);
  52772. if (isButtonDown)
  52773. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52774. else
  52775. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52776. g.fillPath (p);
  52777. g.setColour (Colour (0x80000000));
  52778. g.strokePath (p, PathStrokeType (0.5f));
  52779. }
  52780. void LookAndFeel::drawScrollbar (Graphics& g,
  52781. ScrollBar& scrollbar,
  52782. int x, int y,
  52783. int width, int height,
  52784. bool isScrollbarVertical,
  52785. int thumbStartPosition,
  52786. int thumbSize,
  52787. bool /*isMouseOver*/,
  52788. bool /*isMouseDown*/)
  52789. {
  52790. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52791. Path slotPath, thumbPath;
  52792. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52793. const float slotIndentx2 = slotIndent * 2.0f;
  52794. const float thumbIndent = slotIndent + 1.0f;
  52795. const float thumbIndentx2 = thumbIndent * 2.0f;
  52796. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52797. if (isScrollbarVertical)
  52798. {
  52799. slotPath.addRoundedRectangle (x + slotIndent,
  52800. y + slotIndent,
  52801. width - slotIndentx2,
  52802. height - slotIndentx2,
  52803. (width - slotIndentx2) * 0.5f);
  52804. if (thumbSize > 0)
  52805. thumbPath.addRoundedRectangle (x + thumbIndent,
  52806. thumbStartPosition + thumbIndent,
  52807. width - thumbIndentx2,
  52808. thumbSize - thumbIndentx2,
  52809. (width - thumbIndentx2) * 0.5f);
  52810. gx1 = (float) x;
  52811. gx2 = x + width * 0.7f;
  52812. }
  52813. else
  52814. {
  52815. slotPath.addRoundedRectangle (x + slotIndent,
  52816. y + slotIndent,
  52817. width - slotIndentx2,
  52818. height - slotIndentx2,
  52819. (height - slotIndentx2) * 0.5f);
  52820. if (thumbSize > 0)
  52821. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52822. y + thumbIndent,
  52823. thumbSize - thumbIndentx2,
  52824. height - thumbIndentx2,
  52825. (height - thumbIndentx2) * 0.5f);
  52826. gy1 = (float) y;
  52827. gy2 = y + height * 0.7f;
  52828. }
  52829. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52830. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52831. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52832. g.fillPath (slotPath);
  52833. if (isScrollbarVertical)
  52834. {
  52835. gx1 = x + width * 0.6f;
  52836. gx2 = (float) x + width;
  52837. }
  52838. else
  52839. {
  52840. gy1 = y + height * 0.6f;
  52841. gy2 = (float) y + height;
  52842. }
  52843. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52844. Colour (0x19000000), gx2, gy2, false));
  52845. g.fillPath (slotPath);
  52846. g.setColour (thumbColour);
  52847. g.fillPath (thumbPath);
  52848. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52849. Colours::transparentBlack, gx2, gy2, false));
  52850. g.saveState();
  52851. if (isScrollbarVertical)
  52852. g.reduceClipRegion (x + width / 2, y, width, height);
  52853. else
  52854. g.reduceClipRegion (x, y + height / 2, width, height);
  52855. g.fillPath (thumbPath);
  52856. g.restoreState();
  52857. g.setColour (Colour (0x4c000000));
  52858. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52859. }
  52860. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52861. {
  52862. return 0;
  52863. }
  52864. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52865. {
  52866. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52867. }
  52868. int LookAndFeel::getDefaultScrollbarWidth()
  52869. {
  52870. return 18;
  52871. }
  52872. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52873. {
  52874. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52875. : scrollbar.getHeight());
  52876. }
  52877. const Path LookAndFeel::getTickShape (const float height)
  52878. {
  52879. static const unsigned char tickShapeData[] =
  52880. {
  52881. 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,
  52882. 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,
  52883. 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,
  52884. 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,
  52885. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52886. };
  52887. Path p;
  52888. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52889. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52890. return p;
  52891. }
  52892. const Path LookAndFeel::getCrossShape (const float height)
  52893. {
  52894. static const unsigned char crossShapeData[] =
  52895. {
  52896. 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,
  52897. 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,
  52898. 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,
  52899. 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,
  52900. 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,
  52901. 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,
  52902. 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
  52903. };
  52904. Path p;
  52905. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52906. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52907. return p;
  52908. }
  52909. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52910. {
  52911. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52912. x += (w - boxSize) >> 1;
  52913. y += (h - boxSize) >> 1;
  52914. w = boxSize;
  52915. h = boxSize;
  52916. g.setColour (Colour (0xe5ffffff));
  52917. g.fillRect (x, y, w, h);
  52918. g.setColour (Colour (0x80000000));
  52919. g.drawRect (x, y, w, h);
  52920. const float size = boxSize / 2 + 1.0f;
  52921. const float centre = (float) (boxSize / 2);
  52922. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52923. if (isPlus)
  52924. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52925. }
  52926. void LookAndFeel::drawBubble (Graphics& g,
  52927. float tipX, float tipY,
  52928. float boxX, float boxY,
  52929. float boxW, float boxH)
  52930. {
  52931. int side = 0;
  52932. if (tipX < boxX)
  52933. side = 1;
  52934. else if (tipX > boxX + boxW)
  52935. side = 3;
  52936. else if (tipY > boxY + boxH)
  52937. side = 2;
  52938. const float indent = 2.0f;
  52939. Path p;
  52940. p.addBubble (boxX + indent,
  52941. boxY + indent,
  52942. boxW - indent * 2.0f,
  52943. boxH - indent * 2.0f,
  52944. 5.0f,
  52945. tipX, tipY,
  52946. side,
  52947. 0.5f,
  52948. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52949. //xxx need to take comp as param for colour
  52950. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52951. g.fillPath (p);
  52952. //xxx as above
  52953. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52954. g.strokePath (p, PathStrokeType (1.33f));
  52955. }
  52956. const Font LookAndFeel::getPopupMenuFont()
  52957. {
  52958. return Font (17.0f);
  52959. }
  52960. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52961. const bool isSeparator,
  52962. int standardMenuItemHeight,
  52963. int& idealWidth,
  52964. int& idealHeight)
  52965. {
  52966. if (isSeparator)
  52967. {
  52968. idealWidth = 50;
  52969. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52970. }
  52971. else
  52972. {
  52973. Font font (getPopupMenuFont());
  52974. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52975. font.setHeight (standardMenuItemHeight / 1.3f);
  52976. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52977. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52978. }
  52979. }
  52980. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52981. {
  52982. const Colour background (findColour (PopupMenu::backgroundColourId));
  52983. g.fillAll (background);
  52984. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52985. for (int i = 0; i < height; i += 3)
  52986. g.fillRect (0, i, width, 1);
  52987. #if ! JUCE_MAC
  52988. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52989. g.drawRect (0, 0, width, height);
  52990. #endif
  52991. }
  52992. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52993. int width, int height,
  52994. bool isScrollUpArrow)
  52995. {
  52996. const Colour background (findColour (PopupMenu::backgroundColourId));
  52997. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52998. background.withAlpha (0.0f),
  52999. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53000. false));
  53001. g.fillRect (1, 1, width - 2, height - 2);
  53002. const float hw = width * 0.5f;
  53003. const float arrowW = height * 0.3f;
  53004. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53005. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53006. Path p;
  53007. p.addTriangle (hw - arrowW, y1,
  53008. hw + arrowW, y1,
  53009. hw, y2);
  53010. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53011. g.fillPath (p);
  53012. }
  53013. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53014. int width, int height,
  53015. const bool isSeparator,
  53016. const bool isActive,
  53017. const bool isHighlighted,
  53018. const bool isTicked,
  53019. const bool hasSubMenu,
  53020. const String& text,
  53021. const String& shortcutKeyText,
  53022. Image* image,
  53023. const Colour* const textColourToUse)
  53024. {
  53025. const float halfH = height * 0.5f;
  53026. if (isSeparator)
  53027. {
  53028. const float separatorIndent = 5.5f;
  53029. g.setColour (Colour (0x33000000));
  53030. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53031. g.setColour (Colour (0x66ffffff));
  53032. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53033. }
  53034. else
  53035. {
  53036. Colour textColour (findColour (PopupMenu::textColourId));
  53037. if (textColourToUse != 0)
  53038. textColour = *textColourToUse;
  53039. if (isHighlighted)
  53040. {
  53041. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53042. g.fillRect (1, 1, width - 2, height - 2);
  53043. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53044. }
  53045. else
  53046. {
  53047. g.setColour (textColour);
  53048. }
  53049. if (! isActive)
  53050. g.setOpacity (0.3f);
  53051. Font font (getPopupMenuFont());
  53052. if (font.getHeight() > height / 1.3f)
  53053. font.setHeight (height / 1.3f);
  53054. g.setFont (font);
  53055. const int leftBorder = (height * 5) / 4;
  53056. const int rightBorder = 4;
  53057. if (image != 0)
  53058. {
  53059. g.drawImageWithin (*image,
  53060. 2, 1, leftBorder - 4, height - 2,
  53061. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53062. }
  53063. else if (isTicked)
  53064. {
  53065. const Path tick (getTickShape (1.0f));
  53066. const float th = font.getAscent();
  53067. const float ty = halfH - th * 0.5f;
  53068. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53069. th, true));
  53070. }
  53071. g.drawFittedText (text,
  53072. leftBorder, 0,
  53073. width - (leftBorder + rightBorder), height,
  53074. Justification::centredLeft, 1);
  53075. if (shortcutKeyText.isNotEmpty())
  53076. {
  53077. Font f2 (font);
  53078. f2.setHeight (f2.getHeight() * 0.75f);
  53079. f2.setHorizontalScale (0.95f);
  53080. g.setFont (f2);
  53081. g.drawText (shortcutKeyText,
  53082. leftBorder,
  53083. 0,
  53084. width - (leftBorder + rightBorder + 4),
  53085. height,
  53086. Justification::centredRight,
  53087. true);
  53088. }
  53089. if (hasSubMenu)
  53090. {
  53091. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53092. const float x = width - height * 0.6f;
  53093. Path p;
  53094. p.addTriangle (x, halfH - arrowH * 0.5f,
  53095. x, halfH + arrowH * 0.5f,
  53096. x + arrowH * 0.6f, halfH);
  53097. g.fillPath (p);
  53098. }
  53099. }
  53100. }
  53101. int LookAndFeel::getMenuWindowFlags()
  53102. {
  53103. return ComponentPeer::windowHasDropShadow;
  53104. }
  53105. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53106. bool, MenuBarComponent& menuBar)
  53107. {
  53108. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53109. if (menuBar.isEnabled())
  53110. {
  53111. drawShinyButtonShape (g,
  53112. -4.0f, 0.0f,
  53113. width + 8.0f, (float) height,
  53114. 0.0f,
  53115. baseColour,
  53116. 0.4f,
  53117. true, true, true, true);
  53118. }
  53119. else
  53120. {
  53121. g.fillAll (baseColour);
  53122. }
  53123. }
  53124. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53125. {
  53126. return Font (menuBar.getHeight() * 0.7f);
  53127. }
  53128. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53129. {
  53130. return getMenuBarFont (menuBar, itemIndex, itemText)
  53131. .getStringWidth (itemText) + menuBar.getHeight();
  53132. }
  53133. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53134. int width, int height,
  53135. int itemIndex,
  53136. const String& itemText,
  53137. bool isMouseOverItem,
  53138. bool isMenuOpen,
  53139. bool /*isMouseOverBar*/,
  53140. MenuBarComponent& menuBar)
  53141. {
  53142. if (! menuBar.isEnabled())
  53143. {
  53144. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53145. .withMultipliedAlpha (0.5f));
  53146. }
  53147. else if (isMenuOpen || isMouseOverItem)
  53148. {
  53149. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53150. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53151. }
  53152. else
  53153. {
  53154. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53155. }
  53156. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53157. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53158. }
  53159. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53160. TextEditor& textEditor)
  53161. {
  53162. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53163. }
  53164. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53165. {
  53166. if (textEditor.isEnabled())
  53167. {
  53168. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53169. {
  53170. const int border = 2;
  53171. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53172. g.drawRect (0, 0, width, height, border);
  53173. g.setOpacity (1.0f);
  53174. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53175. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53176. }
  53177. else
  53178. {
  53179. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53180. g.drawRect (0, 0, width, height);
  53181. g.setOpacity (1.0f);
  53182. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53183. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53184. }
  53185. }
  53186. }
  53187. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53188. const bool isButtonDown,
  53189. int buttonX, int buttonY,
  53190. int buttonW, int buttonH,
  53191. ComboBox& box)
  53192. {
  53193. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53194. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53195. {
  53196. g.setColour (box.findColour (TextButton::buttonColourId));
  53197. g.drawRect (0, 0, width, height, 2);
  53198. }
  53199. else
  53200. {
  53201. g.setColour (box.findColour (ComboBox::outlineColourId));
  53202. g.drawRect (0, 0, width, height);
  53203. }
  53204. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53205. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53206. box.hasKeyboardFocus (true),
  53207. false, isButtonDown)
  53208. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53209. drawGlassLozenge (g,
  53210. buttonX + outlineThickness, buttonY + outlineThickness,
  53211. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53212. baseColour, outlineThickness, -1.0f,
  53213. true, true, true, true);
  53214. if (box.isEnabled())
  53215. {
  53216. const float arrowX = 0.3f;
  53217. const float arrowH = 0.2f;
  53218. Path p;
  53219. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53220. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53221. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53222. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53223. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53224. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53225. g.setColour (box.findColour (ComboBox::arrowColourId));
  53226. g.fillPath (p);
  53227. }
  53228. }
  53229. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53230. {
  53231. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53232. }
  53233. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53234. {
  53235. return new Label (String::empty, String::empty);
  53236. }
  53237. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53238. {
  53239. label.setBounds (1, 1,
  53240. box.getWidth() + 3 - box.getHeight(),
  53241. box.getHeight() - 2);
  53242. label.setFont (getComboBoxFont (box));
  53243. }
  53244. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53245. {
  53246. g.fillAll (label.findColour (Label::backgroundColourId));
  53247. if (! label.isBeingEdited())
  53248. {
  53249. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53250. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53251. g.setFont (label.getFont());
  53252. g.drawFittedText (label.getText(),
  53253. label.getHorizontalBorderSize(),
  53254. label.getVerticalBorderSize(),
  53255. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53256. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53257. label.getJustificationType(),
  53258. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53259. label.getMinimumHorizontalScale());
  53260. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53261. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53262. }
  53263. else if (label.isEnabled())
  53264. {
  53265. g.setColour (label.findColour (Label::outlineColourId));
  53266. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53267. }
  53268. }
  53269. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53270. int x, int y,
  53271. int width, int height,
  53272. float /*sliderPos*/,
  53273. float /*minSliderPos*/,
  53274. float /*maxSliderPos*/,
  53275. const Slider::SliderStyle /*style*/,
  53276. Slider& slider)
  53277. {
  53278. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53279. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53280. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53281. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53282. Path indent;
  53283. if (slider.isHorizontal())
  53284. {
  53285. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53286. const float ih = sliderRadius;
  53287. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53288. gradCol2, 0.0f, iy + ih, false));
  53289. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53290. width + sliderRadius, ih,
  53291. 5.0f);
  53292. g.fillPath (indent);
  53293. }
  53294. else
  53295. {
  53296. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53297. const float iw = sliderRadius;
  53298. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53299. gradCol2, ix + iw, 0.0f, false));
  53300. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53301. iw, height + sliderRadius,
  53302. 5.0f);
  53303. g.fillPath (indent);
  53304. }
  53305. g.setColour (Colour (0x4c000000));
  53306. g.strokePath (indent, PathStrokeType (0.5f));
  53307. }
  53308. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53309. int x, int y,
  53310. int width, int height,
  53311. float sliderPos,
  53312. float minSliderPos,
  53313. float maxSliderPos,
  53314. const Slider::SliderStyle style,
  53315. Slider& slider)
  53316. {
  53317. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53318. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53319. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53320. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53321. slider.isMouseButtonDown() && slider.isEnabled()));
  53322. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53323. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53324. {
  53325. float kx, ky;
  53326. if (style == Slider::LinearVertical)
  53327. {
  53328. kx = x + width * 0.5f;
  53329. ky = sliderPos;
  53330. }
  53331. else
  53332. {
  53333. kx = sliderPos;
  53334. ky = y + height * 0.5f;
  53335. }
  53336. drawGlassSphere (g,
  53337. kx - sliderRadius,
  53338. ky - sliderRadius,
  53339. sliderRadius * 2.0f,
  53340. knobColour, outlineThickness);
  53341. }
  53342. else
  53343. {
  53344. if (style == Slider::ThreeValueVertical)
  53345. {
  53346. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53347. sliderPos - sliderRadius,
  53348. sliderRadius * 2.0f,
  53349. knobColour, outlineThickness);
  53350. }
  53351. else if (style == Slider::ThreeValueHorizontal)
  53352. {
  53353. drawGlassSphere (g,sliderPos - sliderRadius,
  53354. y + height * 0.5f - sliderRadius,
  53355. sliderRadius * 2.0f,
  53356. knobColour, outlineThickness);
  53357. }
  53358. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53359. {
  53360. const float sr = jmin (sliderRadius, width * 0.4f);
  53361. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53362. minSliderPos - sliderRadius,
  53363. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53364. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53365. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53366. }
  53367. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53368. {
  53369. const float sr = jmin (sliderRadius, height * 0.4f);
  53370. drawGlassPointer (g, minSliderPos - sr,
  53371. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53372. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53373. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53374. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53375. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53376. }
  53377. }
  53378. }
  53379. void LookAndFeel::drawLinearSlider (Graphics& g,
  53380. int x, int y,
  53381. int width, int height,
  53382. float sliderPos,
  53383. float minSliderPos,
  53384. float maxSliderPos,
  53385. const Slider::SliderStyle style,
  53386. Slider& slider)
  53387. {
  53388. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53389. if (style == Slider::LinearBar)
  53390. {
  53391. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53392. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53393. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53394. false,
  53395. isMouseOver,
  53396. isMouseOver || slider.isMouseButtonDown()));
  53397. drawShinyButtonShape (g,
  53398. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53399. baseColour,
  53400. slider.isEnabled() ? 0.9f : 0.3f,
  53401. true, true, true, true);
  53402. }
  53403. else
  53404. {
  53405. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53406. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53407. }
  53408. }
  53409. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53410. {
  53411. return jmin (7,
  53412. slider.getHeight() / 2,
  53413. slider.getWidth() / 2) + 2;
  53414. }
  53415. void LookAndFeel::drawRotarySlider (Graphics& g,
  53416. int x, int y,
  53417. int width, int height,
  53418. float sliderPos,
  53419. const float rotaryStartAngle,
  53420. const float rotaryEndAngle,
  53421. Slider& slider)
  53422. {
  53423. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53424. const float centreX = x + width * 0.5f;
  53425. const float centreY = y + height * 0.5f;
  53426. const float rx = centreX - radius;
  53427. const float ry = centreY - radius;
  53428. const float rw = radius * 2.0f;
  53429. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53430. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53431. if (radius > 12.0f)
  53432. {
  53433. if (slider.isEnabled())
  53434. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53435. else
  53436. g.setColour (Colour (0x80808080));
  53437. const float thickness = 0.7f;
  53438. {
  53439. Path filledArc;
  53440. filledArc.addPieSegment (rx, ry, rw, rw,
  53441. rotaryStartAngle,
  53442. angle,
  53443. thickness);
  53444. g.fillPath (filledArc);
  53445. }
  53446. if (thickness > 0)
  53447. {
  53448. const float innerRadius = radius * 0.2f;
  53449. Path p;
  53450. p.addTriangle (-innerRadius, 0.0f,
  53451. 0.0f, -radius * thickness * 1.1f,
  53452. innerRadius, 0.0f);
  53453. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53454. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53455. }
  53456. if (slider.isEnabled())
  53457. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53458. else
  53459. g.setColour (Colour (0x80808080));
  53460. Path outlineArc;
  53461. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53462. outlineArc.closeSubPath();
  53463. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53464. }
  53465. else
  53466. {
  53467. if (slider.isEnabled())
  53468. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53469. else
  53470. g.setColour (Colour (0x80808080));
  53471. Path p;
  53472. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53473. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53474. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53475. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53476. }
  53477. }
  53478. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53479. {
  53480. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53481. }
  53482. class SliderLabelComp : public Label
  53483. {
  53484. public:
  53485. SliderLabelComp() : Label (String::empty, String::empty) {}
  53486. ~SliderLabelComp() {}
  53487. void mouseWheelMove (const MouseEvent&, float, float) {}
  53488. };
  53489. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53490. {
  53491. Label* const l = new SliderLabelComp();
  53492. l->setJustificationType (Justification::centred);
  53493. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53494. l->setColour (Label::backgroundColourId,
  53495. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53496. : slider.findColour (Slider::textBoxBackgroundColourId));
  53497. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53498. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53499. l->setColour (TextEditor::backgroundColourId,
  53500. slider.findColour (Slider::textBoxBackgroundColourId)
  53501. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53502. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53503. return l;
  53504. }
  53505. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53506. {
  53507. return 0;
  53508. }
  53509. static const TextLayout layoutTooltipText (const String& text) throw()
  53510. {
  53511. const float tooltipFontSize = 12.0f;
  53512. const int maxToolTipWidth = 400;
  53513. const Font f (tooltipFontSize, Font::bold);
  53514. TextLayout tl (text, f);
  53515. tl.layout (maxToolTipWidth, Justification::left, true);
  53516. return tl;
  53517. }
  53518. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53519. {
  53520. const TextLayout tl (layoutTooltipText (tipText));
  53521. width = tl.getWidth() + 14;
  53522. height = tl.getHeight() + 6;
  53523. }
  53524. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53525. {
  53526. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53527. const Colour textCol (findColour (TooltipWindow::textColourId));
  53528. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53529. g.setColour (findColour (TooltipWindow::outlineColourId));
  53530. g.drawRect (0, 0, width, height, 1);
  53531. #endif
  53532. const TextLayout tl (layoutTooltipText (text));
  53533. g.setColour (findColour (TooltipWindow::textColourId));
  53534. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53535. }
  53536. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53537. {
  53538. return new TextButton (text, TRANS("click to browse for a different file"));
  53539. }
  53540. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53541. ComboBox* filenameBox,
  53542. Button* browseButton)
  53543. {
  53544. browseButton->setSize (80, filenameComp.getHeight());
  53545. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53546. if (tb != 0)
  53547. tb->changeWidthToFitText();
  53548. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53549. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53550. }
  53551. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53552. int imageX, int imageY, int imageW, int imageH,
  53553. const Colour& overlayColour,
  53554. float imageOpacity,
  53555. ImageButton& button)
  53556. {
  53557. if (! button.isEnabled())
  53558. imageOpacity *= 0.3f;
  53559. if (! overlayColour.isOpaque())
  53560. {
  53561. g.setOpacity (imageOpacity);
  53562. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53563. 0, 0, image->getWidth(), image->getHeight(), false);
  53564. }
  53565. if (! overlayColour.isTransparent())
  53566. {
  53567. g.setColour (overlayColour);
  53568. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53569. 0, 0, image->getWidth(), image->getHeight(), true);
  53570. }
  53571. }
  53572. void LookAndFeel::drawCornerResizer (Graphics& g,
  53573. int w, int h,
  53574. bool /*isMouseOver*/,
  53575. bool /*isMouseDragging*/)
  53576. {
  53577. const float lineThickness = jmin (w, h) * 0.075f;
  53578. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53579. {
  53580. g.setColour (Colours::lightgrey);
  53581. g.drawLine (w * i,
  53582. h + 1.0f,
  53583. w + 1.0f,
  53584. h * i,
  53585. lineThickness);
  53586. g.setColour (Colours::darkgrey);
  53587. g.drawLine (w * i + lineThickness,
  53588. h + 1.0f,
  53589. w + 1.0f,
  53590. h * i + lineThickness,
  53591. lineThickness);
  53592. }
  53593. }
  53594. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  53595. const BorderSize& /*borders*/)
  53596. {
  53597. }
  53598. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53599. const BorderSize& /*border*/, ResizableWindow& window)
  53600. {
  53601. g.fillAll (window.getBackgroundColour());
  53602. }
  53603. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  53604. const BorderSize& border, ResizableWindow&)
  53605. {
  53606. g.setColour (Colour (0x80000000));
  53607. g.drawRect (0, 0, w, h);
  53608. g.setColour (Colour (0x19000000));
  53609. g.drawRect (border.getLeft() - 1,
  53610. border.getTop() - 1,
  53611. w + 2 - border.getLeftAndRight(),
  53612. h + 2 - border.getTopAndBottom());
  53613. }
  53614. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53615. Graphics& g, int w, int h,
  53616. int titleSpaceX, int titleSpaceW,
  53617. const Image* icon,
  53618. bool drawTitleTextOnLeft)
  53619. {
  53620. const bool isActive = window.isActiveWindow();
  53621. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53622. 0.0f, 0.0f,
  53623. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53624. 0.0f, (float) h, false));
  53625. g.fillAll();
  53626. Font font (h * 0.65f, Font::bold);
  53627. g.setFont (font);
  53628. int textW = font.getStringWidth (window.getName());
  53629. int iconW = 0;
  53630. int iconH = 0;
  53631. if (icon != 0)
  53632. {
  53633. iconH = (int) font.getHeight();
  53634. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53635. }
  53636. textW = jmin (titleSpaceW, textW + iconW);
  53637. int textX = drawTitleTextOnLeft ? titleSpaceX
  53638. : jmax (titleSpaceX, (w - textW) / 2);
  53639. if (textX + textW > titleSpaceX + titleSpaceW)
  53640. textX = titleSpaceX + titleSpaceW - textW;
  53641. if (icon != 0)
  53642. {
  53643. g.setOpacity (isActive ? 1.0f : 0.6f);
  53644. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53645. RectanglePlacement::centred, false);
  53646. textX += iconW;
  53647. textW -= iconW;
  53648. }
  53649. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53650. g.setColour (findColour (DocumentWindow::textColourId));
  53651. else
  53652. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53653. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53654. }
  53655. class GlassWindowButton : public Button
  53656. {
  53657. public:
  53658. GlassWindowButton (const String& name, const Colour& col,
  53659. const Path& normalShape_,
  53660. const Path& toggledShape_) throw()
  53661. : Button (name),
  53662. colour (col),
  53663. normalShape (normalShape_),
  53664. toggledShape (toggledShape_)
  53665. {
  53666. }
  53667. ~GlassWindowButton()
  53668. {
  53669. }
  53670. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53671. {
  53672. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53673. if (! isEnabled())
  53674. alpha *= 0.5f;
  53675. float x = 0, y = 0, diam;
  53676. if (getWidth() < getHeight())
  53677. {
  53678. diam = (float) getWidth();
  53679. y = (getHeight() - getWidth()) * 0.5f;
  53680. }
  53681. else
  53682. {
  53683. diam = (float) getHeight();
  53684. y = (getWidth() - getHeight()) * 0.5f;
  53685. }
  53686. x += diam * 0.05f;
  53687. y += diam * 0.05f;
  53688. diam *= 0.9f;
  53689. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53690. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53691. g.fillEllipse (x, y, diam, diam);
  53692. x += 2.0f;
  53693. y += 2.0f;
  53694. diam -= 4.0f;
  53695. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53696. Path& p = getToggleState() ? toggledShape : normalShape;
  53697. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53698. diam * 0.4f, diam * 0.4f, true));
  53699. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53700. g.fillPath (p, t);
  53701. }
  53702. juce_UseDebuggingNewOperator
  53703. private:
  53704. Colour colour;
  53705. Path normalShape, toggledShape;
  53706. GlassWindowButton (const GlassWindowButton&);
  53707. GlassWindowButton& operator= (const GlassWindowButton&);
  53708. };
  53709. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53710. {
  53711. Path shape;
  53712. const float crossThickness = 0.25f;
  53713. if (buttonType == DocumentWindow::closeButton)
  53714. {
  53715. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53716. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53717. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53718. }
  53719. else if (buttonType == DocumentWindow::minimiseButton)
  53720. {
  53721. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53722. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53723. }
  53724. else if (buttonType == DocumentWindow::maximiseButton)
  53725. {
  53726. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53727. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53728. Path fullscreenShape;
  53729. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53730. fullscreenShape.lineTo (0.0f, 100.0f);
  53731. fullscreenShape.lineTo (0.0f, 0.0f);
  53732. fullscreenShape.lineTo (100.0f, 0.0f);
  53733. fullscreenShape.lineTo (100.0f, 45.0f);
  53734. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53735. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53736. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53737. }
  53738. jassertfalse;
  53739. return 0;
  53740. }
  53741. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53742. int titleBarX,
  53743. int titleBarY,
  53744. int titleBarW,
  53745. int titleBarH,
  53746. Button* minimiseButton,
  53747. Button* maximiseButton,
  53748. Button* closeButton,
  53749. bool positionTitleBarButtonsOnLeft)
  53750. {
  53751. const int buttonW = titleBarH - titleBarH / 8;
  53752. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53753. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53754. if (closeButton != 0)
  53755. {
  53756. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53757. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53758. }
  53759. if (positionTitleBarButtonsOnLeft)
  53760. swapVariables (minimiseButton, maximiseButton);
  53761. if (maximiseButton != 0)
  53762. {
  53763. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53764. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53765. }
  53766. if (minimiseButton != 0)
  53767. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53768. }
  53769. int LookAndFeel::getDefaultMenuBarHeight()
  53770. {
  53771. return 24;
  53772. }
  53773. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53774. {
  53775. return new DropShadower (0.4f, 1, 5, 10);
  53776. }
  53777. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53778. int w, int h,
  53779. bool /*isVerticalBar*/,
  53780. bool isMouseOver,
  53781. bool isMouseDragging)
  53782. {
  53783. float alpha = 0.5f;
  53784. if (isMouseOver || isMouseDragging)
  53785. {
  53786. g.fillAll (Colour (0x190000ff));
  53787. alpha = 1.0f;
  53788. }
  53789. const float cx = w * 0.5f;
  53790. const float cy = h * 0.5f;
  53791. const float cr = jmin (w, h) * 0.4f;
  53792. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53793. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53794. true));
  53795. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53796. }
  53797. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53798. const String& text,
  53799. const Justification& position,
  53800. GroupComponent& group)
  53801. {
  53802. const float textH = 15.0f;
  53803. const float indent = 3.0f;
  53804. const float textEdgeGap = 4.0f;
  53805. float cs = 5.0f;
  53806. Font f (textH);
  53807. Path p;
  53808. float x = indent;
  53809. float y = f.getAscent() - 3.0f;
  53810. float w = jmax (0.0f, width - x * 2.0f);
  53811. float h = jmax (0.0f, height - y - indent);
  53812. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53813. const float cs2 = 2.0f * cs;
  53814. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53815. float textX = cs + textEdgeGap;
  53816. if (position.testFlags (Justification::horizontallyCentred))
  53817. textX = cs + (w - cs2 - textW) * 0.5f;
  53818. else if (position.testFlags (Justification::right))
  53819. textX = w - cs - textW - textEdgeGap;
  53820. p.startNewSubPath (x + textX + textW, y);
  53821. p.lineTo (x + w - cs, y);
  53822. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53823. p.lineTo (x + w, y + h - cs);
  53824. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53825. p.lineTo (x + cs, y + h);
  53826. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53827. p.lineTo (x, y + cs);
  53828. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53829. p.lineTo (x + textX, y);
  53830. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53831. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53832. .withMultipliedAlpha (alpha));
  53833. g.strokePath (p, PathStrokeType (2.0f));
  53834. g.setColour (group.findColour (GroupComponent::textColourId)
  53835. .withMultipliedAlpha (alpha));
  53836. g.setFont (f);
  53837. g.drawText (text,
  53838. roundToInt (x + textX), 0,
  53839. roundToInt (textW),
  53840. roundToInt (textH),
  53841. Justification::centred, true);
  53842. }
  53843. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53844. {
  53845. return 1 + tabDepth / 3;
  53846. }
  53847. int LookAndFeel::getTabButtonSpaceAroundImage()
  53848. {
  53849. return 4;
  53850. }
  53851. void LookAndFeel::createTabButtonShape (Path& p,
  53852. int width, int height,
  53853. int /*tabIndex*/,
  53854. const String& /*text*/,
  53855. Button& /*button*/,
  53856. TabbedButtonBar::Orientation orientation,
  53857. const bool /*isMouseOver*/,
  53858. const bool /*isMouseDown*/,
  53859. const bool /*isFrontTab*/)
  53860. {
  53861. const float w = (float) width;
  53862. const float h = (float) height;
  53863. float length = w;
  53864. float depth = h;
  53865. if (orientation == TabbedButtonBar::TabsAtLeft
  53866. || orientation == TabbedButtonBar::TabsAtRight)
  53867. {
  53868. swapVariables (length, depth);
  53869. }
  53870. const float indent = (float) getTabButtonOverlap ((int) depth);
  53871. const float overhang = 4.0f;
  53872. if (orientation == TabbedButtonBar::TabsAtLeft)
  53873. {
  53874. p.startNewSubPath (w, 0.0f);
  53875. p.lineTo (0.0f, indent);
  53876. p.lineTo (0.0f, h - indent);
  53877. p.lineTo (w, h);
  53878. p.lineTo (w + overhang, h + overhang);
  53879. p.lineTo (w + overhang, -overhang);
  53880. }
  53881. else if (orientation == TabbedButtonBar::TabsAtRight)
  53882. {
  53883. p.startNewSubPath (0.0f, 0.0f);
  53884. p.lineTo (w, indent);
  53885. p.lineTo (w, h - indent);
  53886. p.lineTo (0.0f, h);
  53887. p.lineTo (-overhang, h + overhang);
  53888. p.lineTo (-overhang, -overhang);
  53889. }
  53890. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53891. {
  53892. p.startNewSubPath (0.0f, 0.0f);
  53893. p.lineTo (indent, h);
  53894. p.lineTo (w - indent, h);
  53895. p.lineTo (w, 0.0f);
  53896. p.lineTo (w + overhang, -overhang);
  53897. p.lineTo (-overhang, -overhang);
  53898. }
  53899. else
  53900. {
  53901. p.startNewSubPath (0.0f, h);
  53902. p.lineTo (indent, 0.0f);
  53903. p.lineTo (w - indent, 0.0f);
  53904. p.lineTo (w, h);
  53905. p.lineTo (w + overhang, h + overhang);
  53906. p.lineTo (-overhang, h + overhang);
  53907. }
  53908. p.closeSubPath();
  53909. p = p.createPathWithRoundedCorners (3.0f);
  53910. }
  53911. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53912. const Path& path,
  53913. const Colour& preferredColour,
  53914. int /*tabIndex*/,
  53915. const String& /*text*/,
  53916. Button& button,
  53917. TabbedButtonBar::Orientation /*orientation*/,
  53918. const bool /*isMouseOver*/,
  53919. const bool /*isMouseDown*/,
  53920. const bool isFrontTab)
  53921. {
  53922. g.setColour (isFrontTab ? preferredColour
  53923. : preferredColour.withMultipliedAlpha (0.9f));
  53924. g.fillPath (path);
  53925. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53926. : TabbedButtonBar::tabOutlineColourId, false)
  53927. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53928. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53929. }
  53930. void LookAndFeel::drawTabButtonText (Graphics& g,
  53931. int x, int y, int w, int h,
  53932. const Colour& preferredBackgroundColour,
  53933. int /*tabIndex*/,
  53934. const String& text,
  53935. Button& button,
  53936. TabbedButtonBar::Orientation orientation,
  53937. const bool isMouseOver,
  53938. const bool isMouseDown,
  53939. const bool isFrontTab)
  53940. {
  53941. int length = w;
  53942. int depth = h;
  53943. if (orientation == TabbedButtonBar::TabsAtLeft
  53944. || orientation == TabbedButtonBar::TabsAtRight)
  53945. {
  53946. swapVariables (length, depth);
  53947. }
  53948. Font font (depth * 0.6f);
  53949. font.setUnderline (button.hasKeyboardFocus (false));
  53950. GlyphArrangement textLayout;
  53951. textLayout.addFittedText (font, text.trim(),
  53952. 0.0f, 0.0f, (float) length, (float) depth,
  53953. Justification::centred,
  53954. jmax (1, depth / 12));
  53955. AffineTransform transform;
  53956. if (orientation == TabbedButtonBar::TabsAtLeft)
  53957. {
  53958. transform = transform.rotated (float_Pi * -0.5f)
  53959. .translated ((float) x, (float) (y + h));
  53960. }
  53961. else if (orientation == TabbedButtonBar::TabsAtRight)
  53962. {
  53963. transform = transform.rotated (float_Pi * 0.5f)
  53964. .translated ((float) (x + w), (float) y);
  53965. }
  53966. else
  53967. {
  53968. transform = transform.translated ((float) x, (float) y);
  53969. }
  53970. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53971. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53972. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53973. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53974. else
  53975. g.setColour (preferredBackgroundColour.contrasting());
  53976. if (! (isMouseOver || isMouseDown))
  53977. g.setOpacity (0.8f);
  53978. if (! button.isEnabled())
  53979. g.setOpacity (0.3f);
  53980. textLayout.draw (g, transform);
  53981. }
  53982. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53983. const String& text,
  53984. int tabDepth,
  53985. Button&)
  53986. {
  53987. Font f (tabDepth * 0.6f);
  53988. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53989. }
  53990. void LookAndFeel::drawTabButton (Graphics& g,
  53991. int w, int h,
  53992. const Colour& preferredColour,
  53993. int tabIndex,
  53994. const String& text,
  53995. Button& button,
  53996. TabbedButtonBar::Orientation orientation,
  53997. const bool isMouseOver,
  53998. const bool isMouseDown,
  53999. const bool isFrontTab)
  54000. {
  54001. int length = w;
  54002. int depth = h;
  54003. if (orientation == TabbedButtonBar::TabsAtLeft
  54004. || orientation == TabbedButtonBar::TabsAtRight)
  54005. {
  54006. swapVariables (length, depth);
  54007. }
  54008. Path tabShape;
  54009. createTabButtonShape (tabShape, w, h,
  54010. tabIndex, text, button, orientation,
  54011. isMouseOver, isMouseDown, isFrontTab);
  54012. fillTabButtonShape (g, tabShape, preferredColour,
  54013. tabIndex, text, button, orientation,
  54014. isMouseOver, isMouseDown, isFrontTab);
  54015. const int indent = getTabButtonOverlap (depth);
  54016. int x = 0, y = 0;
  54017. if (orientation == TabbedButtonBar::TabsAtLeft
  54018. || orientation == TabbedButtonBar::TabsAtRight)
  54019. {
  54020. y += indent;
  54021. h -= indent * 2;
  54022. }
  54023. else
  54024. {
  54025. x += indent;
  54026. w -= indent * 2;
  54027. }
  54028. drawTabButtonText (g, x, y, w, h, preferredColour,
  54029. tabIndex, text, button, orientation,
  54030. isMouseOver, isMouseDown, isFrontTab);
  54031. }
  54032. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54033. int w, int h,
  54034. TabbedButtonBar& tabBar,
  54035. TabbedButtonBar::Orientation orientation)
  54036. {
  54037. const float shadowSize = 0.2f;
  54038. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54039. Rectangle<int> shadowRect;
  54040. if (orientation == TabbedButtonBar::TabsAtLeft)
  54041. {
  54042. x1 = (float) w;
  54043. x2 = w * (1.0f - shadowSize);
  54044. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54045. }
  54046. else if (orientation == TabbedButtonBar::TabsAtRight)
  54047. {
  54048. x2 = w * shadowSize;
  54049. shadowRect.setBounds (0, 0, (int) x2, h);
  54050. }
  54051. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54052. {
  54053. y2 = h * shadowSize;
  54054. shadowRect.setBounds (0, 0, w, (int) y2);
  54055. }
  54056. else
  54057. {
  54058. y1 = (float) h;
  54059. y2 = h * (1.0f - shadowSize);
  54060. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54061. }
  54062. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54063. Colours::transparentBlack, x2, y2, false));
  54064. shadowRect.expand (2, 2);
  54065. g.fillRect (shadowRect);
  54066. g.setColour (Colour (0x80000000));
  54067. if (orientation == TabbedButtonBar::TabsAtLeft)
  54068. {
  54069. g.fillRect (w - 1, 0, 1, h);
  54070. }
  54071. else if (orientation == TabbedButtonBar::TabsAtRight)
  54072. {
  54073. g.fillRect (0, 0, 1, h);
  54074. }
  54075. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54076. {
  54077. g.fillRect (0, 0, w, 1);
  54078. }
  54079. else
  54080. {
  54081. g.fillRect (0, h - 1, w, 1);
  54082. }
  54083. }
  54084. Button* LookAndFeel::createTabBarExtrasButton()
  54085. {
  54086. const float thickness = 7.0f;
  54087. const float indent = 22.0f;
  54088. Path p;
  54089. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54090. DrawablePath ellipse;
  54091. ellipse.setPath (p);
  54092. ellipse.setFill (Colour (0x99ffffff));
  54093. p.clear();
  54094. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54095. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54096. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54097. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54098. p.setUsingNonZeroWinding (false);
  54099. DrawablePath dp;
  54100. dp.setPath (p);
  54101. dp.setFill (Colour (0x59000000));
  54102. DrawableComposite normalImage;
  54103. normalImage.insertDrawable (ellipse);
  54104. normalImage.insertDrawable (dp);
  54105. dp.setFill (Colour (0xcc000000));
  54106. DrawableComposite overImage;
  54107. overImage.insertDrawable (ellipse);
  54108. overImage.insertDrawable (dp);
  54109. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54110. db->setImages (&normalImage, &overImage, 0);
  54111. return db;
  54112. }
  54113. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54114. {
  54115. g.fillAll (Colours::white);
  54116. const int w = header.getWidth();
  54117. const int h = header.getHeight();
  54118. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54119. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54120. false));
  54121. g.fillRect (0, h / 2, w, h);
  54122. g.setColour (Colour (0x33000000));
  54123. g.fillRect (0, h - 1, w, 1);
  54124. for (int i = header.getNumColumns (true); --i >= 0;)
  54125. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54126. }
  54127. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54128. int width, int height,
  54129. bool isMouseOver, bool isMouseDown,
  54130. int columnFlags)
  54131. {
  54132. if (isMouseDown)
  54133. g.fillAll (Colour (0x8899aadd));
  54134. else if (isMouseOver)
  54135. g.fillAll (Colour (0x5599aadd));
  54136. int rightOfText = width - 4;
  54137. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54138. {
  54139. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54140. const float bottom = height - top;
  54141. const float w = height * 0.5f;
  54142. const float x = rightOfText - (w * 1.25f);
  54143. rightOfText = (int) x;
  54144. Path sortArrow;
  54145. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54146. g.setColour (Colour (0x99000000));
  54147. g.fillPath (sortArrow);
  54148. }
  54149. g.setColour (Colours::black);
  54150. g.setFont (height * 0.5f, Font::bold);
  54151. const int textX = 4;
  54152. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54153. }
  54154. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54155. {
  54156. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54157. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54158. background.darker (0.1f),
  54159. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54160. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54161. false));
  54162. g.fillAll();
  54163. }
  54164. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54165. {
  54166. return createTabBarExtrasButton();
  54167. }
  54168. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54169. bool isMouseOver, bool isMouseDown,
  54170. ToolbarItemComponent& component)
  54171. {
  54172. if (isMouseDown)
  54173. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54174. else if (isMouseOver)
  54175. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54176. }
  54177. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54178. const String& text, ToolbarItemComponent& component)
  54179. {
  54180. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54181. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54182. const float fontHeight = jmin (14.0f, height * 0.85f);
  54183. g.setFont (fontHeight);
  54184. g.drawFittedText (text,
  54185. x, y, width, height,
  54186. Justification::centred,
  54187. jmax (1, height / (int) fontHeight));
  54188. }
  54189. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54190. bool isOpen, int width, int height)
  54191. {
  54192. const int buttonSize = (height * 3) / 4;
  54193. const int buttonIndent = (height - buttonSize) / 2;
  54194. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54195. const int textX = buttonIndent * 2 + buttonSize + 2;
  54196. g.setColour (Colours::black);
  54197. g.setFont (height * 0.7f, Font::bold);
  54198. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54199. }
  54200. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54201. PropertyComponent&)
  54202. {
  54203. g.setColour (Colour (0x66ffffff));
  54204. g.fillRect (0, 0, width, height - 1);
  54205. }
  54206. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54207. PropertyComponent& component)
  54208. {
  54209. g.setColour (Colours::black);
  54210. if (! component.isEnabled())
  54211. g.setOpacity (0.6f);
  54212. g.setFont (jmin (height, 24) * 0.65f);
  54213. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54214. g.drawFittedText (component.getName(),
  54215. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54216. Justification::centredLeft, 2);
  54217. }
  54218. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54219. {
  54220. return Rectangle<int> (component.getWidth() / 3, 1,
  54221. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54222. }
  54223. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54224. {
  54225. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54226. {
  54227. Graphics g2 (content);
  54228. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54229. g2.fillPath (path);
  54230. g2.setColour (Colours::white.withAlpha (0.8f));
  54231. g2.strokePath (path, PathStrokeType (2.0f));
  54232. }
  54233. DropShadowEffect shadow;
  54234. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54235. shadow.applyEffect (content, g);
  54236. }
  54237. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54238. const String& instructions,
  54239. GlyphArrangement& text,
  54240. int width)
  54241. {
  54242. text.clear();
  54243. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54244. 8.0f, 22.0f, width - 16.0f,
  54245. Justification::centred);
  54246. text.addJustifiedText (Font (14.0f), instructions,
  54247. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54248. Justification::centred);
  54249. }
  54250. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54251. const String& filename, Image* icon,
  54252. const String& fileSizeDescription,
  54253. const String& fileTimeDescription,
  54254. const bool isDirectory,
  54255. const bool isItemSelected,
  54256. const int /*itemIndex*/)
  54257. {
  54258. if (isItemSelected)
  54259. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54260. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54261. g.setFont (height * 0.7f);
  54262. Image im;
  54263. if (icon != 0)
  54264. im = *icon;
  54265. if (im.isNull())
  54266. im = isDirectory ? getDefaultFolderImage()
  54267. : getDefaultDocumentFileImage();
  54268. const int x = 32;
  54269. if (im.isValid())
  54270. {
  54271. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54272. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54273. false);
  54274. }
  54275. if (width > 450 && ! isDirectory)
  54276. {
  54277. const int sizeX = roundToInt (width * 0.7f);
  54278. const int dateX = roundToInt (width * 0.8f);
  54279. g.drawFittedText (filename,
  54280. x, 0, sizeX - x, height,
  54281. Justification::centredLeft, 1);
  54282. g.setFont (height * 0.5f);
  54283. g.setColour (Colours::darkgrey);
  54284. if (! isDirectory)
  54285. {
  54286. g.drawFittedText (fileSizeDescription,
  54287. sizeX, 0, dateX - sizeX - 8, height,
  54288. Justification::centredRight, 1);
  54289. g.drawFittedText (fileTimeDescription,
  54290. dateX, 0, width - 8 - dateX, height,
  54291. Justification::centredRight, 1);
  54292. }
  54293. }
  54294. else
  54295. {
  54296. g.drawFittedText (filename,
  54297. x, 0, width - x, height,
  54298. Justification::centredLeft, 1);
  54299. }
  54300. }
  54301. Button* LookAndFeel::createFileBrowserGoUpButton()
  54302. {
  54303. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54304. Path arrowPath;
  54305. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54306. DrawablePath arrowImage;
  54307. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54308. arrowImage.setPath (arrowPath);
  54309. goUpButton->setImages (&arrowImage);
  54310. return goUpButton;
  54311. }
  54312. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54313. DirectoryContentsDisplayComponent* fileListComponent,
  54314. FilePreviewComponent* previewComp,
  54315. ComboBox* currentPathBox,
  54316. TextEditor* filenameBox,
  54317. Button* goUpButton)
  54318. {
  54319. const int x = 8;
  54320. int w = browserComp.getWidth() - x - x;
  54321. if (previewComp != 0)
  54322. {
  54323. const int previewWidth = w / 3;
  54324. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54325. w -= previewWidth + 4;
  54326. }
  54327. int y = 4;
  54328. const int controlsHeight = 22;
  54329. const int bottomSectionHeight = controlsHeight + 8;
  54330. const int upButtonWidth = 50;
  54331. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54332. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54333. y += controlsHeight + 4;
  54334. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54335. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54336. y = listAsComp->getBottom() + 4;
  54337. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54338. }
  54339. const Image LookAndFeel::getDefaultFolderImage()
  54340. {
  54341. 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,
  54342. 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,
  54343. 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,
  54344. 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,
  54345. 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,
  54346. 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,
  54347. 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,
  54348. 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,
  54349. 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,
  54350. 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,
  54351. 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,
  54352. 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,
  54353. 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,
  54354. 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,
  54355. 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,
  54356. 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,
  54357. 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,
  54358. 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,
  54359. 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,
  54360. 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,
  54361. 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,
  54362. 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,
  54363. 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,
  54364. 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,
  54365. 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,
  54366. 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,
  54367. 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,
  54368. 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,
  54369. 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,
  54370. 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,
  54371. 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,
  54372. 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,
  54373. 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,
  54374. 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,
  54375. 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,
  54376. 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,
  54377. 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,
  54378. 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,
  54379. 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,
  54380. 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,
  54381. 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,
  54382. 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,
  54383. 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,
  54384. 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};
  54385. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54386. }
  54387. const Image LookAndFeel::getDefaultDocumentFileImage()
  54388. {
  54389. 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,
  54390. 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,
  54391. 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,
  54392. 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,
  54393. 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,
  54394. 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,
  54395. 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,
  54396. 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,
  54397. 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,
  54398. 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,
  54399. 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,
  54400. 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,
  54401. 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,
  54402. 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,
  54403. 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,
  54404. 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,
  54405. 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,
  54406. 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,
  54407. 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,
  54408. 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,
  54409. 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,
  54410. 174,66,96,130,0,0};
  54411. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54412. }
  54413. void LookAndFeel::playAlertSound()
  54414. {
  54415. PlatformUtilities::beep();
  54416. }
  54417. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54418. {
  54419. g.setColour (Colours::white.withAlpha (0.7f));
  54420. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54421. g.setColour (Colours::black.withAlpha (0.2f));
  54422. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54423. const int totalBlocks = 7;
  54424. const int numBlocks = roundToInt (totalBlocks * level);
  54425. const float w = (width - 6.0f) / (float) totalBlocks;
  54426. for (int i = 0; i < totalBlocks; ++i)
  54427. {
  54428. if (i >= numBlocks)
  54429. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54430. else
  54431. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54432. : Colours::red);
  54433. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54434. }
  54435. }
  54436. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54437. {
  54438. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54439. if (keyDescription.isNotEmpty())
  54440. {
  54441. if (button.isEnabled())
  54442. {
  54443. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54444. g.fillAll (textColour.withAlpha (alpha));
  54445. g.setOpacity (0.3f);
  54446. g.drawBevel (0, 0, width, height, 2);
  54447. }
  54448. g.setColour (textColour);
  54449. g.setFont (height * 0.6f);
  54450. g.drawFittedText (keyDescription,
  54451. 3, 0, width - 6, height,
  54452. Justification::centred, 1);
  54453. }
  54454. else
  54455. {
  54456. const float thickness = 7.0f;
  54457. const float indent = 22.0f;
  54458. Path p;
  54459. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54460. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54461. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54462. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54463. p.setUsingNonZeroWinding (false);
  54464. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54465. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54466. }
  54467. if (button.hasKeyboardFocus (false))
  54468. {
  54469. g.setColour (textColour.withAlpha (0.4f));
  54470. g.drawRect (0, 0, width, height);
  54471. }
  54472. }
  54473. static void createRoundedPath (Path& p,
  54474. const float x, const float y,
  54475. const float w, const float h,
  54476. const float cs,
  54477. const bool curveTopLeft, const bool curveTopRight,
  54478. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54479. {
  54480. const float cs2 = 2.0f * cs;
  54481. if (curveTopLeft)
  54482. {
  54483. p.startNewSubPath (x, y + cs);
  54484. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54485. }
  54486. else
  54487. {
  54488. p.startNewSubPath (x, y);
  54489. }
  54490. if (curveTopRight)
  54491. {
  54492. p.lineTo (x + w - cs, y);
  54493. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54494. }
  54495. else
  54496. {
  54497. p.lineTo (x + w, y);
  54498. }
  54499. if (curveBottomRight)
  54500. {
  54501. p.lineTo (x + w, y + h - cs);
  54502. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54503. }
  54504. else
  54505. {
  54506. p.lineTo (x + w, y + h);
  54507. }
  54508. if (curveBottomLeft)
  54509. {
  54510. p.lineTo (x + cs, y + h);
  54511. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54512. }
  54513. else
  54514. {
  54515. p.lineTo (x, y + h);
  54516. }
  54517. p.closeSubPath();
  54518. }
  54519. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54520. float x, float y, float w, float h,
  54521. float maxCornerSize,
  54522. const Colour& baseColour,
  54523. const float strokeWidth,
  54524. const bool flatOnLeft,
  54525. const bool flatOnRight,
  54526. const bool flatOnTop,
  54527. const bool flatOnBottom) throw()
  54528. {
  54529. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54530. return;
  54531. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54532. Path outline;
  54533. createRoundedPath (outline, x, y, w, h, cs,
  54534. ! (flatOnLeft || flatOnTop),
  54535. ! (flatOnRight || flatOnTop),
  54536. ! (flatOnLeft || flatOnBottom),
  54537. ! (flatOnRight || flatOnBottom));
  54538. ColourGradient cg (baseColour, 0.0f, y,
  54539. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54540. false);
  54541. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54542. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54543. g.setGradientFill (cg);
  54544. g.fillPath (outline);
  54545. g.setColour (Colour (0x80000000));
  54546. g.strokePath (outline, PathStrokeType (strokeWidth));
  54547. }
  54548. void LookAndFeel::drawGlassSphere (Graphics& g,
  54549. const float x, const float y,
  54550. const float diameter,
  54551. const Colour& colour,
  54552. const float outlineThickness) throw()
  54553. {
  54554. if (diameter <= outlineThickness)
  54555. return;
  54556. Path p;
  54557. p.addEllipse (x, y, diameter, diameter);
  54558. {
  54559. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54560. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54561. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54562. g.setGradientFill (cg);
  54563. g.fillPath (p);
  54564. }
  54565. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54566. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54567. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54568. ColourGradient cg (Colours::transparentBlack,
  54569. x + diameter * 0.5f, y + diameter * 0.5f,
  54570. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54571. x, y + diameter * 0.5f, true);
  54572. cg.addColour (0.7, Colours::transparentBlack);
  54573. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54574. g.setGradientFill (cg);
  54575. g.fillPath (p);
  54576. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54577. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54578. }
  54579. void LookAndFeel::drawGlassPointer (Graphics& g,
  54580. const float x, const float y,
  54581. const float diameter,
  54582. const Colour& colour, const float outlineThickness,
  54583. const int direction) throw()
  54584. {
  54585. if (diameter <= outlineThickness)
  54586. return;
  54587. Path p;
  54588. p.startNewSubPath (x + diameter * 0.5f, y);
  54589. p.lineTo (x + diameter, y + diameter * 0.6f);
  54590. p.lineTo (x + diameter, y + diameter);
  54591. p.lineTo (x, y + diameter);
  54592. p.lineTo (x, y + diameter * 0.6f);
  54593. p.closeSubPath();
  54594. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54595. {
  54596. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54597. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54598. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54599. g.setGradientFill (cg);
  54600. g.fillPath (p);
  54601. }
  54602. ColourGradient cg (Colours::transparentBlack,
  54603. x + diameter * 0.5f, y + diameter * 0.5f,
  54604. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54605. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54606. cg.addColour (0.5, Colours::transparentBlack);
  54607. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54608. g.setGradientFill (cg);
  54609. g.fillPath (p);
  54610. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54611. g.strokePath (p, PathStrokeType (outlineThickness));
  54612. }
  54613. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54614. const float x, const float y,
  54615. const float width, const float height,
  54616. const Colour& colour,
  54617. const float outlineThickness,
  54618. const float cornerSize,
  54619. const bool flatOnLeft,
  54620. const bool flatOnRight,
  54621. const bool flatOnTop,
  54622. const bool flatOnBottom) throw()
  54623. {
  54624. if (width <= outlineThickness || height <= outlineThickness)
  54625. return;
  54626. const int intX = (int) x;
  54627. const int intY = (int) y;
  54628. const int intW = (int) width;
  54629. const int intH = (int) height;
  54630. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54631. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54632. const int intEdge = (int) edgeBlurRadius;
  54633. Path outline;
  54634. createRoundedPath (outline, x, y, width, height, cs,
  54635. ! (flatOnLeft || flatOnTop),
  54636. ! (flatOnRight || flatOnTop),
  54637. ! (flatOnLeft || flatOnBottom),
  54638. ! (flatOnRight || flatOnBottom));
  54639. {
  54640. ColourGradient cg (colour.darker (0.2f), 0, y,
  54641. colour.darker (0.2f), 0, y + height, false);
  54642. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54643. cg.addColour (0.4, colour);
  54644. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54645. g.setGradientFill (cg);
  54646. g.fillPath (outline);
  54647. }
  54648. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54649. colour.darker (0.2f), x, y + height * 0.5f, true);
  54650. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54651. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54652. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54653. {
  54654. g.saveState();
  54655. g.setGradientFill (cg);
  54656. g.reduceClipRegion (intX, intY, intEdge, intH);
  54657. g.fillPath (outline);
  54658. g.restoreState();
  54659. }
  54660. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54661. {
  54662. cg.point1.setX (x + width - edgeBlurRadius);
  54663. cg.point2.setX (x + width);
  54664. g.saveState();
  54665. g.setGradientFill (cg);
  54666. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54667. g.fillPath (outline);
  54668. g.restoreState();
  54669. }
  54670. {
  54671. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54672. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54673. Path highlight;
  54674. createRoundedPath (highlight,
  54675. x + leftIndent,
  54676. y + cs * 0.1f,
  54677. width - (leftIndent + rightIndent),
  54678. height * 0.4f, cs * 0.4f,
  54679. ! (flatOnLeft || flatOnTop),
  54680. ! (flatOnRight || flatOnTop),
  54681. ! (flatOnLeft || flatOnBottom),
  54682. ! (flatOnRight || flatOnBottom));
  54683. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54684. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54685. g.fillPath (highlight);
  54686. }
  54687. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54688. g.strokePath (outline, PathStrokeType (outlineThickness));
  54689. }
  54690. END_JUCE_NAMESPACE
  54691. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54692. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54693. BEGIN_JUCE_NAMESPACE
  54694. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54695. {
  54696. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54697. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54698. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54699. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54700. setColour (Slider::thumbColourId, Colours::white);
  54701. setColour (Slider::trackColourId, Colour (0x7f000000));
  54702. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54703. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54704. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54705. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54706. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54707. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54708. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54709. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54710. }
  54711. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54712. {
  54713. }
  54714. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54715. Button& button,
  54716. const Colour& backgroundColour,
  54717. bool isMouseOverButton,
  54718. bool isButtonDown)
  54719. {
  54720. const int width = button.getWidth();
  54721. const int height = button.getHeight();
  54722. const float indent = 2.0f;
  54723. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54724. roundToInt (height * 0.4f));
  54725. Path p;
  54726. p.addRoundedRectangle (indent, indent,
  54727. width - indent * 2.0f,
  54728. height - indent * 2.0f,
  54729. (float) cornerSize);
  54730. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54731. if (isMouseOverButton)
  54732. {
  54733. if (isButtonDown)
  54734. bc = bc.brighter();
  54735. else if (bc.getBrightness() > 0.5f)
  54736. bc = bc.darker (0.1f);
  54737. else
  54738. bc = bc.brighter (0.1f);
  54739. }
  54740. g.setColour (bc);
  54741. g.fillPath (p);
  54742. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54743. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54744. }
  54745. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54746. Component& /*component*/,
  54747. float x, float y, float w, float h,
  54748. const bool ticked,
  54749. const bool isEnabled,
  54750. const bool /*isMouseOverButton*/,
  54751. const bool isButtonDown)
  54752. {
  54753. Path box;
  54754. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54755. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54756. : Colours::lightgrey.withAlpha (0.1f));
  54757. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54758. g.fillPath (box, trans);
  54759. g.setColour (Colours::black.withAlpha (0.6f));
  54760. g.strokePath (box, PathStrokeType (0.9f), trans);
  54761. if (ticked)
  54762. {
  54763. Path tick;
  54764. tick.startNewSubPath (1.5f, 3.0f);
  54765. tick.lineTo (3.0f, 6.0f);
  54766. tick.lineTo (6.0f, 0.0f);
  54767. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54768. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54769. }
  54770. }
  54771. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54772. ToggleButton& button,
  54773. bool isMouseOverButton,
  54774. bool isButtonDown)
  54775. {
  54776. if (button.hasKeyboardFocus (true))
  54777. {
  54778. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54779. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54780. }
  54781. const int tickWidth = jmin (20, button.getHeight() - 4);
  54782. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54783. (float) tickWidth, (float) tickWidth,
  54784. button.getToggleState(),
  54785. button.isEnabled(),
  54786. isMouseOverButton,
  54787. isButtonDown);
  54788. g.setColour (button.findColour (ToggleButton::textColourId));
  54789. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54790. if (! button.isEnabled())
  54791. g.setOpacity (0.5f);
  54792. const int textX = tickWidth + 5;
  54793. g.drawFittedText (button.getButtonText(),
  54794. textX, 4,
  54795. button.getWidth() - textX - 2, button.getHeight() - 8,
  54796. Justification::centredLeft, 10);
  54797. }
  54798. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54799. int width, int height,
  54800. double progress, const String& textToShow)
  54801. {
  54802. if (progress < 0 || progress >= 1.0)
  54803. {
  54804. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54805. }
  54806. else
  54807. {
  54808. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54809. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54810. g.fillAll (background);
  54811. g.setColour (foreground);
  54812. g.fillRect (1, 1,
  54813. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54814. height - 2);
  54815. if (textToShow.isNotEmpty())
  54816. {
  54817. g.setColour (Colour::contrasting (background, foreground));
  54818. g.setFont (height * 0.6f);
  54819. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54820. }
  54821. }
  54822. }
  54823. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54824. ScrollBar& bar,
  54825. int width, int height,
  54826. int buttonDirection,
  54827. bool isScrollbarVertical,
  54828. bool isMouseOverButton,
  54829. bool isButtonDown)
  54830. {
  54831. if (isScrollbarVertical)
  54832. width -= 2;
  54833. else
  54834. height -= 2;
  54835. Path p;
  54836. if (buttonDirection == 0)
  54837. p.addTriangle (width * 0.5f, height * 0.2f,
  54838. width * 0.1f, height * 0.7f,
  54839. width * 0.9f, height * 0.7f);
  54840. else if (buttonDirection == 1)
  54841. p.addTriangle (width * 0.8f, height * 0.5f,
  54842. width * 0.3f, height * 0.1f,
  54843. width * 0.3f, height * 0.9f);
  54844. else if (buttonDirection == 2)
  54845. p.addTriangle (width * 0.5f, height * 0.8f,
  54846. width * 0.1f, height * 0.3f,
  54847. width * 0.9f, height * 0.3f);
  54848. else if (buttonDirection == 3)
  54849. p.addTriangle (width * 0.2f, height * 0.5f,
  54850. width * 0.7f, height * 0.1f,
  54851. width * 0.7f, height * 0.9f);
  54852. if (isButtonDown)
  54853. g.setColour (Colours::white);
  54854. else if (isMouseOverButton)
  54855. g.setColour (Colours::white.withAlpha (0.7f));
  54856. else
  54857. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54858. g.fillPath (p);
  54859. g.setColour (Colours::black.withAlpha (0.5f));
  54860. g.strokePath (p, PathStrokeType (0.5f));
  54861. }
  54862. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54863. ScrollBar& bar,
  54864. int x, int y,
  54865. int width, int height,
  54866. bool isScrollbarVertical,
  54867. int thumbStartPosition,
  54868. int thumbSize,
  54869. bool isMouseOver,
  54870. bool isMouseDown)
  54871. {
  54872. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54873. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54874. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54875. if (thumbSize > 0.0f)
  54876. {
  54877. Rectangle<int> thumb;
  54878. if (isScrollbarVertical)
  54879. {
  54880. width -= 2;
  54881. g.fillRect (x + roundToInt (width * 0.35f), y,
  54882. roundToInt (width * 0.3f), height);
  54883. thumb.setBounds (x + 1, thumbStartPosition,
  54884. width - 2, thumbSize);
  54885. }
  54886. else
  54887. {
  54888. height -= 2;
  54889. g.fillRect (x, y + roundToInt (height * 0.35f),
  54890. width, roundToInt (height * 0.3f));
  54891. thumb.setBounds (thumbStartPosition, y + 1,
  54892. thumbSize, height - 2);
  54893. }
  54894. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54895. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54896. g.fillRect (thumb);
  54897. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54898. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54899. if (thumbSize > 16)
  54900. {
  54901. for (int i = 3; --i >= 0;)
  54902. {
  54903. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54904. g.setColour (Colours::black.withAlpha (0.15f));
  54905. if (isScrollbarVertical)
  54906. {
  54907. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54908. g.setColour (Colours::white.withAlpha (0.15f));
  54909. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54910. }
  54911. else
  54912. {
  54913. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54914. g.setColour (Colours::white.withAlpha (0.15f));
  54915. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54916. }
  54917. }
  54918. }
  54919. }
  54920. }
  54921. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54922. {
  54923. return &scrollbarShadow;
  54924. }
  54925. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54926. {
  54927. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54928. g.setColour (Colours::black.withAlpha (0.6f));
  54929. g.drawRect (0, 0, width, height);
  54930. }
  54931. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54932. bool, MenuBarComponent& menuBar)
  54933. {
  54934. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54935. }
  54936. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54937. {
  54938. if (textEditor.isEnabled())
  54939. {
  54940. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54941. g.drawRect (0, 0, width, height);
  54942. }
  54943. }
  54944. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54945. const bool isButtonDown,
  54946. int buttonX, int buttonY,
  54947. int buttonW, int buttonH,
  54948. ComboBox& box)
  54949. {
  54950. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54951. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54952. : ComboBox::backgroundColourId));
  54953. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54954. g.setColour (box.findColour (ComboBox::outlineColourId));
  54955. g.drawRect (0, 0, width, height);
  54956. const float arrowX = 0.2f;
  54957. const float arrowH = 0.3f;
  54958. if (box.isEnabled())
  54959. {
  54960. Path p;
  54961. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54962. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54963. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54964. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54965. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54966. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54967. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54968. : ComboBox::buttonColourId));
  54969. g.fillPath (p);
  54970. }
  54971. }
  54972. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54973. {
  54974. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54975. f.setHorizontalScale (0.9f);
  54976. return f;
  54977. }
  54978. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54979. {
  54980. Path p;
  54981. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54982. g.setColour (fill);
  54983. g.fillPath (p);
  54984. g.setColour (outline);
  54985. g.strokePath (p, PathStrokeType (0.3f));
  54986. }
  54987. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54988. int x, int y,
  54989. int w, int h,
  54990. float sliderPos,
  54991. float minSliderPos,
  54992. float maxSliderPos,
  54993. const Slider::SliderStyle style,
  54994. Slider& slider)
  54995. {
  54996. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54997. if (style == Slider::LinearBar)
  54998. {
  54999. g.setColour (slider.findColour (Slider::thumbColourId));
  55000. g.fillRect (x, y, (int) sliderPos - x, h);
  55001. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55002. g.drawRect (x, y, (int) sliderPos - x, h);
  55003. }
  55004. else
  55005. {
  55006. g.setColour (slider.findColour (Slider::trackColourId)
  55007. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55008. if (slider.isHorizontal())
  55009. {
  55010. g.fillRect (x, y + roundToInt (h * 0.6f),
  55011. w, roundToInt (h * 0.2f));
  55012. }
  55013. else
  55014. {
  55015. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55016. jmin (4, roundToInt (w * 0.2f)), h);
  55017. }
  55018. float alpha = 0.35f;
  55019. if (slider.isEnabled())
  55020. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55021. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55022. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55023. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55024. {
  55025. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55026. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55027. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55028. fill, outline);
  55029. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55030. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55031. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55032. fill, outline);
  55033. }
  55034. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55035. {
  55036. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55037. minSliderPos - 7.0f, y + h * 0.9f ,
  55038. minSliderPos, y + h * 0.9f,
  55039. fill, outline);
  55040. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55041. maxSliderPos, y + h * 0.9f,
  55042. maxSliderPos + 7.0f, y + h * 0.9f,
  55043. fill, outline);
  55044. }
  55045. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55046. {
  55047. drawTriangle (g, sliderPos, y + h * 0.9f,
  55048. sliderPos - 7.0f, y + h * 0.2f,
  55049. sliderPos + 7.0f, y + h * 0.2f,
  55050. fill, outline);
  55051. }
  55052. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55053. {
  55054. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55055. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55056. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55057. fill, outline);
  55058. }
  55059. }
  55060. }
  55061. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55062. {
  55063. if (isIncrement)
  55064. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55065. else
  55066. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55067. }
  55068. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55069. {
  55070. return &scrollbarShadow;
  55071. }
  55072. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55073. {
  55074. return 8;
  55075. }
  55076. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55077. int w, int h,
  55078. bool isMouseOver,
  55079. bool isMouseDragging)
  55080. {
  55081. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55082. : Colours::darkgrey);
  55083. const float lineThickness = jmin (w, h) * 0.1f;
  55084. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55085. {
  55086. g.drawLine (w * i,
  55087. h + 1.0f,
  55088. w + 1.0f,
  55089. h * i,
  55090. lineThickness);
  55091. }
  55092. }
  55093. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55094. {
  55095. Path shape;
  55096. if (buttonType == DocumentWindow::closeButton)
  55097. {
  55098. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55099. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55100. ShapeButton* const b = new ShapeButton ("close",
  55101. Colour (0x7fff3333),
  55102. Colour (0xd7ff3333),
  55103. Colour (0xf7ff3333));
  55104. b->setShape (shape, true, true, true);
  55105. return b;
  55106. }
  55107. else if (buttonType == DocumentWindow::minimiseButton)
  55108. {
  55109. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55110. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55111. DrawablePath dp;
  55112. dp.setPath (shape);
  55113. dp.setFill (Colours::black.withAlpha (0.3f));
  55114. b->setImages (&dp);
  55115. return b;
  55116. }
  55117. else if (buttonType == DocumentWindow::maximiseButton)
  55118. {
  55119. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55120. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55121. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55122. DrawablePath dp;
  55123. dp.setPath (shape);
  55124. dp.setFill (Colours::black.withAlpha (0.3f));
  55125. b->setImages (&dp);
  55126. return b;
  55127. }
  55128. jassertfalse;
  55129. return 0;
  55130. }
  55131. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55132. int titleBarX,
  55133. int titleBarY,
  55134. int titleBarW,
  55135. int titleBarH,
  55136. Button* minimiseButton,
  55137. Button* maximiseButton,
  55138. Button* closeButton,
  55139. bool positionTitleBarButtonsOnLeft)
  55140. {
  55141. titleBarY += titleBarH / 8;
  55142. titleBarH -= titleBarH / 4;
  55143. const int buttonW = titleBarH;
  55144. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55145. : titleBarX + titleBarW - buttonW - 4;
  55146. if (closeButton != 0)
  55147. {
  55148. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55149. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55150. : -(buttonW + buttonW / 5);
  55151. }
  55152. if (positionTitleBarButtonsOnLeft)
  55153. swapVariables (minimiseButton, maximiseButton);
  55154. if (maximiseButton != 0)
  55155. {
  55156. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55157. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55158. }
  55159. if (minimiseButton != 0)
  55160. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55161. }
  55162. END_JUCE_NAMESPACE
  55163. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55164. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55165. BEGIN_JUCE_NAMESPACE
  55166. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55167. : model (0),
  55168. itemUnderMouse (-1),
  55169. currentPopupIndex (-1),
  55170. topLevelIndexClicked (0),
  55171. lastMouseX (0),
  55172. lastMouseY (0)
  55173. {
  55174. setRepaintsOnMouseActivity (true);
  55175. setWantsKeyboardFocus (false);
  55176. setMouseClickGrabsKeyboardFocus (false);
  55177. setModel (model_);
  55178. }
  55179. MenuBarComponent::~MenuBarComponent()
  55180. {
  55181. setModel (0);
  55182. Desktop::getInstance().removeGlobalMouseListener (this);
  55183. }
  55184. MenuBarModel* MenuBarComponent::getModel() const throw()
  55185. {
  55186. return model;
  55187. }
  55188. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55189. {
  55190. if (model != newModel)
  55191. {
  55192. if (model != 0)
  55193. model->removeListener (this);
  55194. model = newModel;
  55195. if (model != 0)
  55196. model->addListener (this);
  55197. repaint();
  55198. menuBarItemsChanged (0);
  55199. }
  55200. }
  55201. void MenuBarComponent::paint (Graphics& g)
  55202. {
  55203. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55204. getLookAndFeel().drawMenuBarBackground (g,
  55205. getWidth(),
  55206. getHeight(),
  55207. isMouseOverBar,
  55208. *this);
  55209. if (model != 0)
  55210. {
  55211. for (int i = 0; i < menuNames.size(); ++i)
  55212. {
  55213. g.saveState();
  55214. g.setOrigin (xPositions [i], 0);
  55215. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55216. getLookAndFeel().drawMenuBarItem (g,
  55217. xPositions[i + 1] - xPositions[i],
  55218. getHeight(),
  55219. i,
  55220. menuNames[i],
  55221. i == itemUnderMouse,
  55222. i == currentPopupIndex,
  55223. isMouseOverBar,
  55224. *this);
  55225. g.restoreState();
  55226. }
  55227. }
  55228. }
  55229. void MenuBarComponent::resized()
  55230. {
  55231. xPositions.clear();
  55232. int x = 2;
  55233. xPositions.add (x);
  55234. for (int i = 0; i < menuNames.size(); ++i)
  55235. {
  55236. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55237. xPositions.add (x);
  55238. }
  55239. }
  55240. int MenuBarComponent::getItemAt (const int x, const int y)
  55241. {
  55242. for (int i = 0; i < xPositions.size(); ++i)
  55243. if (x >= xPositions[i] && x < xPositions[i + 1])
  55244. return reallyContains (x, y, true) ? i : -1;
  55245. return -1;
  55246. }
  55247. void MenuBarComponent::repaintMenuItem (int index)
  55248. {
  55249. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55250. {
  55251. const int x1 = xPositions [index];
  55252. const int x2 = xPositions [index + 1];
  55253. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55254. }
  55255. }
  55256. void MenuBarComponent::setItemUnderMouse (const int index)
  55257. {
  55258. if (itemUnderMouse != index)
  55259. {
  55260. repaintMenuItem (itemUnderMouse);
  55261. itemUnderMouse = index;
  55262. repaintMenuItem (itemUnderMouse);
  55263. }
  55264. }
  55265. void MenuBarComponent::setOpenItem (int index)
  55266. {
  55267. if (currentPopupIndex != index)
  55268. {
  55269. repaintMenuItem (currentPopupIndex);
  55270. currentPopupIndex = index;
  55271. repaintMenuItem (currentPopupIndex);
  55272. if (index >= 0)
  55273. Desktop::getInstance().addGlobalMouseListener (this);
  55274. else
  55275. Desktop::getInstance().removeGlobalMouseListener (this);
  55276. }
  55277. }
  55278. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55279. {
  55280. setItemUnderMouse (getItemAt (x, y));
  55281. }
  55282. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55283. {
  55284. public:
  55285. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55286. : bar (bar_), topLevelIndex (topLevelIndex_)
  55287. {
  55288. }
  55289. ~AsyncCallback() {}
  55290. void modalStateFinished (int returnValue)
  55291. {
  55292. if (bar != 0)
  55293. bar->menuDismissed (topLevelIndex, returnValue);
  55294. }
  55295. private:
  55296. Component::SafePointer<MenuBarComponent> bar;
  55297. const int topLevelIndex;
  55298. AsyncCallback (const AsyncCallback&);
  55299. AsyncCallback& operator= (const AsyncCallback&);
  55300. };
  55301. void MenuBarComponent::showMenu (int index)
  55302. {
  55303. if (index != currentPopupIndex)
  55304. {
  55305. PopupMenu::dismissAllActiveMenus();
  55306. menuBarItemsChanged (0);
  55307. setOpenItem (index);
  55308. setItemUnderMouse (index);
  55309. if (index >= 0)
  55310. {
  55311. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55312. menuNames [itemUnderMouse]));
  55313. if (m.lookAndFeel == 0)
  55314. m.setLookAndFeel (&getLookAndFeel());
  55315. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55316. m.showMenu (itemPos + getScreenPosition(),
  55317. 0, itemPos.getWidth(), 0, 0, true, this,
  55318. new AsyncCallback (this, index));
  55319. }
  55320. }
  55321. }
  55322. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55323. {
  55324. topLevelIndexClicked = topLevelIndex;
  55325. postCommandMessage (itemId);
  55326. }
  55327. void MenuBarComponent::handleCommandMessage (int commandId)
  55328. {
  55329. const Point<int> mousePos (getMouseXYRelative());
  55330. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55331. if (! isCurrentlyBlockedByAnotherModalComponent())
  55332. setOpenItem (-1);
  55333. if (commandId != 0 && model != 0)
  55334. model->menuItemSelected (commandId, topLevelIndexClicked);
  55335. }
  55336. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55337. {
  55338. if (e.eventComponent == this)
  55339. updateItemUnderMouse (e.x, e.y);
  55340. }
  55341. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55342. {
  55343. if (e.eventComponent == this)
  55344. updateItemUnderMouse (e.x, e.y);
  55345. }
  55346. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55347. {
  55348. if (currentPopupIndex < 0)
  55349. {
  55350. const MouseEvent e2 (e.getEventRelativeTo (this));
  55351. updateItemUnderMouse (e2.x, e2.y);
  55352. currentPopupIndex = -2;
  55353. showMenu (itemUnderMouse);
  55354. }
  55355. }
  55356. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55357. {
  55358. const MouseEvent e2 (e.getEventRelativeTo (this));
  55359. const int item = getItemAt (e2.x, e2.y);
  55360. if (item >= 0)
  55361. showMenu (item);
  55362. }
  55363. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55364. {
  55365. const MouseEvent e2 (e.getEventRelativeTo (this));
  55366. updateItemUnderMouse (e2.x, e2.y);
  55367. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55368. {
  55369. setOpenItem (-1);
  55370. PopupMenu::dismissAllActiveMenus();
  55371. }
  55372. }
  55373. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55374. {
  55375. const MouseEvent e2 (e.getEventRelativeTo (this));
  55376. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55377. {
  55378. if (currentPopupIndex >= 0)
  55379. {
  55380. const int item = getItemAt (e2.x, e2.y);
  55381. if (item >= 0)
  55382. showMenu (item);
  55383. }
  55384. else
  55385. {
  55386. updateItemUnderMouse (e2.x, e2.y);
  55387. }
  55388. lastMouseX = e2.x;
  55389. lastMouseY = e2.y;
  55390. }
  55391. }
  55392. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55393. {
  55394. bool used = false;
  55395. const int numMenus = menuNames.size();
  55396. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55397. if (key.isKeyCode (KeyPress::leftKey))
  55398. {
  55399. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55400. used = true;
  55401. }
  55402. else if (key.isKeyCode (KeyPress::rightKey))
  55403. {
  55404. showMenu ((currentIndex + 1) % numMenus);
  55405. used = true;
  55406. }
  55407. return used;
  55408. }
  55409. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55410. {
  55411. StringArray newNames;
  55412. if (model != 0)
  55413. newNames = model->getMenuBarNames();
  55414. if (newNames != menuNames)
  55415. {
  55416. menuNames = newNames;
  55417. repaint();
  55418. resized();
  55419. }
  55420. }
  55421. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55422. const ApplicationCommandTarget::InvocationInfo& info)
  55423. {
  55424. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55425. return;
  55426. for (int i = 0; i < menuNames.size(); ++i)
  55427. {
  55428. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55429. if (menu.containsCommandItem (info.commandID))
  55430. {
  55431. setItemUnderMouse (i);
  55432. startTimer (200);
  55433. break;
  55434. }
  55435. }
  55436. }
  55437. void MenuBarComponent::timerCallback()
  55438. {
  55439. stopTimer();
  55440. const Point<int> mousePos (getMouseXYRelative());
  55441. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55442. }
  55443. END_JUCE_NAMESPACE
  55444. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55445. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55446. BEGIN_JUCE_NAMESPACE
  55447. MenuBarModel::MenuBarModel() throw()
  55448. : manager (0)
  55449. {
  55450. }
  55451. MenuBarModel::~MenuBarModel()
  55452. {
  55453. setApplicationCommandManagerToWatch (0);
  55454. }
  55455. void MenuBarModel::menuItemsChanged()
  55456. {
  55457. triggerAsyncUpdate();
  55458. }
  55459. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55460. {
  55461. if (manager != newManager)
  55462. {
  55463. if (manager != 0)
  55464. manager->removeListener (this);
  55465. manager = newManager;
  55466. if (manager != 0)
  55467. manager->addListener (this);
  55468. }
  55469. }
  55470. void MenuBarModel::addListener (Listener* const newListener) throw()
  55471. {
  55472. listeners.add (newListener);
  55473. }
  55474. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55475. {
  55476. // Trying to remove a listener that isn't on the list!
  55477. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55478. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55479. jassert (listeners.contains (listenerToRemove));
  55480. listeners.remove (listenerToRemove);
  55481. }
  55482. void MenuBarModel::handleAsyncUpdate()
  55483. {
  55484. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55485. }
  55486. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55487. {
  55488. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55489. }
  55490. void MenuBarModel::applicationCommandListChanged()
  55491. {
  55492. menuItemsChanged();
  55493. }
  55494. END_JUCE_NAMESPACE
  55495. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55496. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55497. BEGIN_JUCE_NAMESPACE
  55498. class PopupMenu::Item
  55499. {
  55500. public:
  55501. Item()
  55502. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55503. usesColour (false), customComp (0), commandManager (0)
  55504. {
  55505. }
  55506. Item (const int itemId_,
  55507. const String& text_,
  55508. const bool active_,
  55509. const bool isTicked_,
  55510. const Image& im,
  55511. const Colour& textColour_,
  55512. const bool usesColour_,
  55513. PopupMenuCustomComponent* const customComp_,
  55514. const PopupMenu* const subMenu_,
  55515. ApplicationCommandManager* const commandManager_)
  55516. : itemId (itemId_), text (text_), textColour (textColour_),
  55517. active (active_), isSeparator (false), isTicked (isTicked_),
  55518. usesColour (usesColour_), image (im), customComp (customComp_),
  55519. commandManager (commandManager_)
  55520. {
  55521. if (subMenu_ != 0)
  55522. subMenu = new PopupMenu (*subMenu_);
  55523. if (commandManager_ != 0 && itemId_ != 0)
  55524. {
  55525. String shortcutKey;
  55526. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55527. ->getKeyPressesAssignedToCommand (itemId_));
  55528. for (int i = 0; i < keyPresses.size(); ++i)
  55529. {
  55530. const String key (keyPresses.getReference(i).getTextDescription());
  55531. if (shortcutKey.isNotEmpty())
  55532. shortcutKey << ", ";
  55533. if (key.length() == 1)
  55534. shortcutKey << "shortcut: '" << key << '\'';
  55535. else
  55536. shortcutKey << key;
  55537. }
  55538. shortcutKey = shortcutKey.trim();
  55539. if (shortcutKey.isNotEmpty())
  55540. text << "<end>" << shortcutKey;
  55541. }
  55542. }
  55543. Item (const Item& other)
  55544. : itemId (other.itemId),
  55545. text (other.text),
  55546. textColour (other.textColour),
  55547. active (other.active),
  55548. isSeparator (other.isSeparator),
  55549. isTicked (other.isTicked),
  55550. usesColour (other.usesColour),
  55551. image (other.image),
  55552. customComp (other.customComp),
  55553. commandManager (other.commandManager)
  55554. {
  55555. if (other.subMenu != 0)
  55556. subMenu = new PopupMenu (*(other.subMenu));
  55557. }
  55558. ~Item()
  55559. {
  55560. customComp = 0;
  55561. }
  55562. bool canBeTriggered() const throw()
  55563. {
  55564. return active && ! (isSeparator || (subMenu != 0));
  55565. }
  55566. bool hasActiveSubMenu() const throw()
  55567. {
  55568. return active && (subMenu != 0);
  55569. }
  55570. const int itemId;
  55571. String text;
  55572. const Colour textColour;
  55573. const bool active, isSeparator, isTicked, usesColour;
  55574. Image image;
  55575. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55576. ScopedPointer <PopupMenu> subMenu;
  55577. ApplicationCommandManager* const commandManager;
  55578. juce_UseDebuggingNewOperator
  55579. private:
  55580. Item& operator= (const Item&);
  55581. };
  55582. class PopupMenu::ItemComponent : public Component
  55583. {
  55584. public:
  55585. ItemComponent (const PopupMenu::Item& itemInfo_)
  55586. : itemInfo (itemInfo_),
  55587. isHighlighted (false)
  55588. {
  55589. if (itemInfo.customComp != 0)
  55590. addAndMakeVisible (itemInfo.customComp);
  55591. }
  55592. ~ItemComponent()
  55593. {
  55594. if (itemInfo.customComp != 0)
  55595. removeChildComponent (itemInfo.customComp);
  55596. }
  55597. void getIdealSize (int& idealWidth,
  55598. int& idealHeight,
  55599. const int standardItemHeight)
  55600. {
  55601. if (itemInfo.customComp != 0)
  55602. {
  55603. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55604. }
  55605. else
  55606. {
  55607. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55608. itemInfo.isSeparator,
  55609. standardItemHeight,
  55610. idealWidth,
  55611. idealHeight);
  55612. }
  55613. }
  55614. void paint (Graphics& g)
  55615. {
  55616. if (itemInfo.customComp == 0)
  55617. {
  55618. String mainText (itemInfo.text);
  55619. String endText;
  55620. const int endIndex = mainText.indexOf ("<end>");
  55621. if (endIndex >= 0)
  55622. {
  55623. endText = mainText.substring (endIndex + 5).trim();
  55624. mainText = mainText.substring (0, endIndex);
  55625. }
  55626. getLookAndFeel()
  55627. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55628. itemInfo.isSeparator,
  55629. itemInfo.active,
  55630. isHighlighted,
  55631. itemInfo.isTicked,
  55632. itemInfo.subMenu != 0,
  55633. mainText, endText,
  55634. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55635. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55636. }
  55637. }
  55638. void resized()
  55639. {
  55640. if (getNumChildComponents() > 0)
  55641. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55642. }
  55643. void setHighlighted (bool shouldBeHighlighted)
  55644. {
  55645. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55646. if (isHighlighted != shouldBeHighlighted)
  55647. {
  55648. isHighlighted = shouldBeHighlighted;
  55649. if (itemInfo.customComp != 0)
  55650. {
  55651. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55652. itemInfo.customComp->repaint();
  55653. }
  55654. repaint();
  55655. }
  55656. }
  55657. PopupMenu::Item itemInfo;
  55658. juce_UseDebuggingNewOperator
  55659. private:
  55660. bool isHighlighted;
  55661. ItemComponent (const ItemComponent&);
  55662. ItemComponent& operator= (const ItemComponent&);
  55663. };
  55664. namespace PopupMenuSettings
  55665. {
  55666. static const int scrollZone = 24;
  55667. static const int borderSize = 2;
  55668. static const int timerInterval = 50;
  55669. static const int dismissCommandId = 0x6287345f;
  55670. }
  55671. class PopupMenu::Window : public Component,
  55672. private Timer
  55673. {
  55674. public:
  55675. Window()
  55676. : Component ("menu"),
  55677. owner (0),
  55678. currentChild (0),
  55679. activeSubMenu (0),
  55680. managerOfChosenCommand (0),
  55681. minimumWidth (0),
  55682. maximumNumColumns (7),
  55683. standardItemHeight (0),
  55684. isOver (false),
  55685. hasBeenOver (false),
  55686. isDown (false),
  55687. needsToScroll (false),
  55688. hideOnExit (false),
  55689. disableMouseMoves (false),
  55690. hasAnyJuceCompHadFocus (false),
  55691. numColumns (0),
  55692. contentHeight (0),
  55693. childYOffset (0),
  55694. timeEnteredCurrentChildComp (0),
  55695. scrollAcceleration (1.0)
  55696. {
  55697. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55698. setWantsKeyboardFocus (true);
  55699. setMouseClickGrabsKeyboardFocus (false);
  55700. setOpaque (true);
  55701. setAlwaysOnTop (true);
  55702. Desktop::getInstance().addGlobalMouseListener (this);
  55703. getActiveWindows().add (this);
  55704. }
  55705. ~Window()
  55706. {
  55707. getActiveWindows().removeValue (this);
  55708. Desktop::getInstance().removeGlobalMouseListener (this);
  55709. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55710. activeSubMenu = 0;
  55711. deleteAllChildren();
  55712. }
  55713. static Window* create (const PopupMenu& menu,
  55714. const bool dismissOnMouseUp,
  55715. Window* const owner_,
  55716. const Rectangle<int>& target,
  55717. const int minimumWidth,
  55718. const int maximumNumColumns,
  55719. const int standardItemHeight,
  55720. const bool alignToRectangle,
  55721. const int itemIdThatMustBeVisible,
  55722. ApplicationCommandManager** managerOfChosenCommand,
  55723. Component* const componentAttachedTo)
  55724. {
  55725. if (menu.items.size() > 0)
  55726. {
  55727. int totalItems = 0;
  55728. ScopedPointer <Window> mw (new Window());
  55729. mw->setLookAndFeel (menu.lookAndFeel);
  55730. mw->setWantsKeyboardFocus (false);
  55731. mw->minimumWidth = minimumWidth;
  55732. mw->maximumNumColumns = maximumNumColumns;
  55733. mw->standardItemHeight = standardItemHeight;
  55734. mw->dismissOnMouseUp = dismissOnMouseUp;
  55735. for (int i = 0; i < menu.items.size(); ++i)
  55736. {
  55737. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55738. mw->addItem (*item);
  55739. ++totalItems;
  55740. }
  55741. if (totalItems > 0)
  55742. {
  55743. mw->owner = owner_;
  55744. mw->managerOfChosenCommand = managerOfChosenCommand;
  55745. mw->componentAttachedTo = componentAttachedTo;
  55746. mw->componentAttachedToOriginal = componentAttachedTo;
  55747. mw->calculateWindowPos (target, alignToRectangle);
  55748. mw->setTopLeftPosition (mw->windowPos.getX(),
  55749. mw->windowPos.getY());
  55750. mw->updateYPositions();
  55751. if (itemIdThatMustBeVisible != 0)
  55752. {
  55753. const int y = target.getY() - mw->windowPos.getY();
  55754. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55755. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55756. }
  55757. mw->resizeToBestWindowPos();
  55758. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55759. | mw->getLookAndFeel().getMenuWindowFlags());
  55760. return mw.release();
  55761. }
  55762. }
  55763. return 0;
  55764. }
  55765. void paint (Graphics& g)
  55766. {
  55767. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55768. }
  55769. void paintOverChildren (Graphics& g)
  55770. {
  55771. if (isScrolling())
  55772. {
  55773. LookAndFeel& lf = getLookAndFeel();
  55774. if (isScrollZoneActive (false))
  55775. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55776. if (isScrollZoneActive (true))
  55777. {
  55778. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55779. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55780. }
  55781. }
  55782. }
  55783. bool isScrollZoneActive (bool bottomOne) const
  55784. {
  55785. return isScrolling()
  55786. && (bottomOne
  55787. ? childYOffset < contentHeight - windowPos.getHeight()
  55788. : childYOffset > 0);
  55789. }
  55790. void addItem (const PopupMenu::Item& item)
  55791. {
  55792. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55793. addAndMakeVisible (mic);
  55794. int itemW = 80;
  55795. int itemH = 16;
  55796. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55797. mic->setSize (itemW, jlimit (2, 600, itemH));
  55798. mic->addMouseListener (this, false);
  55799. }
  55800. // hide this and all sub-comps
  55801. void hide (const PopupMenu::Item* const item)
  55802. {
  55803. if (isVisible())
  55804. {
  55805. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55806. activeSubMenu = 0;
  55807. currentChild = 0;
  55808. exitModalState (item != 0 ? item->itemId : 0);
  55809. setVisible (false);
  55810. if (item != 0
  55811. && item->commandManager != 0
  55812. && item->itemId != 0)
  55813. {
  55814. *managerOfChosenCommand = item->commandManager;
  55815. }
  55816. }
  55817. }
  55818. void dismissMenu (const PopupMenu::Item* const item)
  55819. {
  55820. if (owner != 0)
  55821. {
  55822. owner->dismissMenu (item);
  55823. }
  55824. else
  55825. {
  55826. if (item != 0)
  55827. {
  55828. // need a copy of this on the stack as the one passed in will get deleted during this call
  55829. const PopupMenu::Item mi (*item);
  55830. hide (&mi);
  55831. }
  55832. else
  55833. {
  55834. hide (0);
  55835. }
  55836. }
  55837. }
  55838. void mouseMove (const MouseEvent&)
  55839. {
  55840. timerCallback();
  55841. }
  55842. void mouseDown (const MouseEvent&)
  55843. {
  55844. timerCallback();
  55845. }
  55846. void mouseDrag (const MouseEvent&)
  55847. {
  55848. timerCallback();
  55849. }
  55850. void mouseUp (const MouseEvent&)
  55851. {
  55852. timerCallback();
  55853. }
  55854. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55855. {
  55856. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55857. lastMouse = Point<int> (-1, -1);
  55858. }
  55859. bool keyPressed (const KeyPress& key)
  55860. {
  55861. if (key.isKeyCode (KeyPress::downKey))
  55862. {
  55863. selectNextItem (1);
  55864. }
  55865. else if (key.isKeyCode (KeyPress::upKey))
  55866. {
  55867. selectNextItem (-1);
  55868. }
  55869. else if (key.isKeyCode (KeyPress::leftKey))
  55870. {
  55871. if (owner != 0)
  55872. {
  55873. Component::SafePointer<Window> parentWindow (owner);
  55874. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55875. hide (0);
  55876. if (parentWindow != 0)
  55877. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55878. disableTimerUntilMouseMoves();
  55879. }
  55880. else if (componentAttachedTo != 0)
  55881. {
  55882. componentAttachedTo->keyPressed (key);
  55883. }
  55884. }
  55885. else if (key.isKeyCode (KeyPress::rightKey))
  55886. {
  55887. disableTimerUntilMouseMoves();
  55888. if (showSubMenuFor (currentChild))
  55889. {
  55890. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55891. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55892. activeSubMenu->selectNextItem (1);
  55893. }
  55894. else if (componentAttachedTo != 0)
  55895. {
  55896. componentAttachedTo->keyPressed (key);
  55897. }
  55898. }
  55899. else if (key.isKeyCode (KeyPress::returnKey))
  55900. {
  55901. triggerCurrentlyHighlightedItem();
  55902. }
  55903. else if (key.isKeyCode (KeyPress::escapeKey))
  55904. {
  55905. dismissMenu (0);
  55906. }
  55907. else
  55908. {
  55909. return false;
  55910. }
  55911. return true;
  55912. }
  55913. void inputAttemptWhenModal()
  55914. {
  55915. Component::SafePointer<Component> deletionChecker (this);
  55916. timerCallback();
  55917. if (deletionChecker != 0 && ! isOverAnyMenu())
  55918. {
  55919. if (componentAttachedTo != 0)
  55920. {
  55921. // we want to dismiss the menu, but if we do it synchronously, then
  55922. // the mouse-click will be allowed to pass through. That's good, except
  55923. // when the user clicks on the button that orginally popped the menu up,
  55924. // as they'll expect the menu to go away, and in fact it'll just
  55925. // come back. So only dismiss synchronously if they're not on the original
  55926. // comp that we're attached to.
  55927. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55928. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55929. {
  55930. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55931. return;
  55932. }
  55933. }
  55934. dismissMenu (0);
  55935. }
  55936. }
  55937. void handleCommandMessage (int commandId)
  55938. {
  55939. Component::handleCommandMessage (commandId);
  55940. if (commandId == PopupMenuSettings::dismissCommandId)
  55941. dismissMenu (0);
  55942. }
  55943. void timerCallback()
  55944. {
  55945. if (! isVisible())
  55946. return;
  55947. if (componentAttachedTo != componentAttachedToOriginal)
  55948. {
  55949. dismissMenu (0);
  55950. return;
  55951. }
  55952. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55953. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55954. return;
  55955. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55956. // move rather than a real timer callback
  55957. const Point<int> globalMousePos (Desktop::getMousePosition());
  55958. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55959. const uint32 now = Time::getMillisecondCounter();
  55960. if (now > timeEnteredCurrentChildComp + 100
  55961. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55962. && currentChild->isValidComponent()
  55963. && (! disableMouseMoves)
  55964. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55965. {
  55966. showSubMenuFor (currentChild);
  55967. }
  55968. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55969. {
  55970. highlightItemUnderMouse (globalMousePos, localMousePos);
  55971. }
  55972. bool overScrollArea = false;
  55973. if (isScrolling()
  55974. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55975. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55976. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55977. {
  55978. if (now > lastScroll + 20)
  55979. {
  55980. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55981. int amount = 0;
  55982. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55983. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55984. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55985. lastScroll = now;
  55986. }
  55987. overScrollArea = true;
  55988. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55989. }
  55990. else
  55991. {
  55992. scrollAcceleration = 1.0;
  55993. }
  55994. const bool wasDown = isDown;
  55995. bool isOverAny = isOverAnyMenu();
  55996. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55997. {
  55998. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55999. isOverAny = isOverAnyMenu();
  56000. }
  56001. if (hideOnExit && hasBeenOver && ! isOverAny)
  56002. {
  56003. hide (0);
  56004. }
  56005. else
  56006. {
  56007. isDown = hasBeenOver
  56008. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56009. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56010. bool anyFocused = Process::isForegroundProcess();
  56011. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56012. {
  56013. // because no component at all may have focus, our test here will
  56014. // only be triggered when something has focus and then loses it.
  56015. anyFocused = ! hasAnyJuceCompHadFocus;
  56016. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56017. {
  56018. if (ComponentPeer::getPeer (i)->isFocused())
  56019. {
  56020. anyFocused = true;
  56021. hasAnyJuceCompHadFocus = true;
  56022. break;
  56023. }
  56024. }
  56025. }
  56026. if (! anyFocused)
  56027. {
  56028. if (now > lastFocused + 10)
  56029. {
  56030. wasHiddenBecauseOfAppChange() = true;
  56031. dismissMenu (0);
  56032. return; // may have been deleted by the previous call..
  56033. }
  56034. }
  56035. else if (wasDown && now > menuCreationTime + 250
  56036. && ! (isDown || overScrollArea))
  56037. {
  56038. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56039. if (isOver)
  56040. {
  56041. triggerCurrentlyHighlightedItem();
  56042. }
  56043. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56044. {
  56045. dismissMenu (0);
  56046. }
  56047. return; // may have been deleted by the previous calls..
  56048. }
  56049. else
  56050. {
  56051. lastFocused = now;
  56052. }
  56053. }
  56054. }
  56055. static Array<Window*>& getActiveWindows()
  56056. {
  56057. static Array<Window*> activeMenuWindows;
  56058. return activeMenuWindows;
  56059. }
  56060. static bool& wasHiddenBecauseOfAppChange() throw()
  56061. {
  56062. static bool b = false;
  56063. return b;
  56064. }
  56065. juce_UseDebuggingNewOperator
  56066. private:
  56067. Window* owner;
  56068. PopupMenu::ItemComponent* currentChild;
  56069. ScopedPointer <Window> activeSubMenu;
  56070. ApplicationCommandManager** managerOfChosenCommand;
  56071. Component::SafePointer<Component> componentAttachedTo;
  56072. Component* componentAttachedToOriginal;
  56073. Rectangle<int> windowPos;
  56074. Point<int> lastMouse;
  56075. int minimumWidth, maximumNumColumns, standardItemHeight;
  56076. bool isOver, hasBeenOver, isDown, needsToScroll;
  56077. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56078. int numColumns, contentHeight, childYOffset;
  56079. Array <int> columnWidths;
  56080. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56081. double scrollAcceleration;
  56082. bool overlaps (const Rectangle<int>& r) const
  56083. {
  56084. return r.intersects (getBounds())
  56085. || (owner != 0 && owner->overlaps (r));
  56086. }
  56087. bool isOverAnyMenu() const
  56088. {
  56089. return (owner != 0) ? owner->isOverAnyMenu()
  56090. : isOverChildren();
  56091. }
  56092. bool isOverChildren() const
  56093. {
  56094. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56095. return isVisible()
  56096. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56097. }
  56098. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56099. {
  56100. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56101. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56102. if (activeSubMenu != 0)
  56103. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56104. }
  56105. bool treeContains (const Window* const window) const throw()
  56106. {
  56107. const Window* mw = this;
  56108. while (mw->owner != 0)
  56109. mw = mw->owner;
  56110. while (mw != 0)
  56111. {
  56112. if (mw == window)
  56113. return true;
  56114. mw = mw->activeSubMenu;
  56115. }
  56116. return false;
  56117. }
  56118. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56119. {
  56120. const Rectangle<int> mon (Desktop::getInstance()
  56121. .getMonitorAreaContaining (target.getCentre(),
  56122. #if JUCE_MAC
  56123. true));
  56124. #else
  56125. false)); // on windows, don't stop the menu overlapping the taskbar
  56126. #endif
  56127. int x, y, widthToUse, heightToUse;
  56128. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56129. if (alignToRectangle)
  56130. {
  56131. x = target.getX();
  56132. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56133. const int spaceOver = target.getY() - mon.getY();
  56134. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56135. y = target.getBottom();
  56136. else
  56137. y = target.getY() - heightToUse;
  56138. }
  56139. else
  56140. {
  56141. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56142. if (owner != 0)
  56143. {
  56144. if (owner->owner != 0)
  56145. {
  56146. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56147. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56148. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56149. tendTowardsRight = true;
  56150. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56151. tendTowardsRight = false;
  56152. }
  56153. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56154. {
  56155. tendTowardsRight = true;
  56156. }
  56157. }
  56158. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56159. target.getX() - mon.getX()) - 32;
  56160. if (biggestSpace < widthToUse)
  56161. {
  56162. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56163. if (numColumns > 1)
  56164. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56165. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56166. }
  56167. if (tendTowardsRight)
  56168. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56169. else
  56170. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56171. y = target.getY();
  56172. if (target.getCentreY() > mon.getCentreY())
  56173. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56174. }
  56175. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56176. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56177. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56178. // sets this flag if it's big enough to obscure any of its parent menus
  56179. hideOnExit = (owner != 0)
  56180. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56181. }
  56182. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56183. {
  56184. numColumns = 0;
  56185. contentHeight = 0;
  56186. const int maxMenuH = getParentHeight() - 24;
  56187. int totalW;
  56188. do
  56189. {
  56190. ++numColumns;
  56191. totalW = workOutBestSize (maxMenuW);
  56192. if (totalW > maxMenuW)
  56193. {
  56194. numColumns = jmax (1, numColumns - 1);
  56195. totalW = workOutBestSize (maxMenuW); // to update col widths
  56196. break;
  56197. }
  56198. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56199. {
  56200. break;
  56201. }
  56202. } while (numColumns < maximumNumColumns);
  56203. const int actualH = jmin (contentHeight, maxMenuH);
  56204. needsToScroll = contentHeight > actualH;
  56205. width = updateYPositions();
  56206. height = actualH + PopupMenuSettings::borderSize * 2;
  56207. }
  56208. int workOutBestSize (const int maxMenuW)
  56209. {
  56210. int totalW = 0;
  56211. contentHeight = 0;
  56212. int childNum = 0;
  56213. for (int col = 0; col < numColumns; ++col)
  56214. {
  56215. int i, colW = 50, colH = 0;
  56216. const int numChildren = jmin (getNumChildComponents() - childNum,
  56217. (getNumChildComponents() + numColumns - 1) / numColumns);
  56218. for (i = numChildren; --i >= 0;)
  56219. {
  56220. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56221. colH += getChildComponent (childNum + i)->getHeight();
  56222. }
  56223. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56224. columnWidths.set (col, colW);
  56225. totalW += colW;
  56226. contentHeight = jmax (contentHeight, colH);
  56227. childNum += numChildren;
  56228. }
  56229. if (totalW < minimumWidth)
  56230. {
  56231. totalW = minimumWidth;
  56232. for (int col = 0; col < numColumns; ++col)
  56233. columnWidths.set (0, totalW / numColumns);
  56234. }
  56235. return totalW;
  56236. }
  56237. void ensureItemIsVisible (const int itemId, int wantedY)
  56238. {
  56239. jassert (itemId != 0)
  56240. for (int i = getNumChildComponents(); --i >= 0;)
  56241. {
  56242. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56243. if (m != 0
  56244. && m->itemInfo.itemId == itemId
  56245. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56246. {
  56247. const int currentY = m->getY();
  56248. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56249. {
  56250. if (wantedY < 0)
  56251. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56252. jmax (PopupMenuSettings::scrollZone,
  56253. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56254. currentY);
  56255. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56256. int deltaY = wantedY - currentY;
  56257. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56258. jmin (windowPos.getHeight(), mon.getHeight()));
  56259. const int newY = jlimit (mon.getY(),
  56260. mon.getBottom() - windowPos.getHeight(),
  56261. windowPos.getY() + deltaY);
  56262. deltaY -= newY - windowPos.getY();
  56263. childYOffset -= deltaY;
  56264. windowPos.setPosition (windowPos.getX(), newY);
  56265. updateYPositions();
  56266. }
  56267. break;
  56268. }
  56269. }
  56270. }
  56271. void resizeToBestWindowPos()
  56272. {
  56273. Rectangle<int> r (windowPos);
  56274. if (childYOffset < 0)
  56275. {
  56276. r.setBounds (r.getX(), r.getY() - childYOffset,
  56277. r.getWidth(), r.getHeight() + childYOffset);
  56278. }
  56279. else if (childYOffset > 0)
  56280. {
  56281. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56282. if (spaceAtBottom > 0)
  56283. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56284. }
  56285. setBounds (r);
  56286. updateYPositions();
  56287. }
  56288. void alterChildYPos (const int delta)
  56289. {
  56290. if (isScrolling())
  56291. {
  56292. childYOffset += delta;
  56293. if (delta < 0)
  56294. {
  56295. childYOffset = jmax (childYOffset, 0);
  56296. }
  56297. else if (delta > 0)
  56298. {
  56299. childYOffset = jmin (childYOffset,
  56300. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56301. }
  56302. updateYPositions();
  56303. }
  56304. else
  56305. {
  56306. childYOffset = 0;
  56307. }
  56308. resizeToBestWindowPos();
  56309. repaint();
  56310. }
  56311. int updateYPositions()
  56312. {
  56313. int x = 0;
  56314. int childNum = 0;
  56315. for (int col = 0; col < numColumns; ++col)
  56316. {
  56317. const int numChildren = jmin (getNumChildComponents() - childNum,
  56318. (getNumChildComponents() + numColumns - 1) / numColumns);
  56319. const int colW = columnWidths [col];
  56320. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56321. for (int i = 0; i < numChildren; ++i)
  56322. {
  56323. Component* const c = getChildComponent (childNum + i);
  56324. c->setBounds (x, y, colW, c->getHeight());
  56325. y += c->getHeight();
  56326. }
  56327. x += colW;
  56328. childNum += numChildren;
  56329. }
  56330. return x;
  56331. }
  56332. bool isScrolling() const throw()
  56333. {
  56334. return childYOffset != 0 || needsToScroll;
  56335. }
  56336. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56337. {
  56338. if (currentChild->isValidComponent())
  56339. currentChild->setHighlighted (false);
  56340. currentChild = child;
  56341. if (currentChild != 0)
  56342. {
  56343. currentChild->setHighlighted (true);
  56344. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56345. }
  56346. }
  56347. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56348. {
  56349. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56350. activeSubMenu = 0;
  56351. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56352. {
  56353. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56354. dismissOnMouseUp,
  56355. this,
  56356. childComp->getScreenBounds(),
  56357. 0, maximumNumColumns,
  56358. standardItemHeight,
  56359. false, 0, managerOfChosenCommand,
  56360. componentAttachedTo);
  56361. if (activeSubMenu != 0)
  56362. {
  56363. activeSubMenu->setVisible (true);
  56364. activeSubMenu->enterModalState (false);
  56365. activeSubMenu->toFront (false);
  56366. return true;
  56367. }
  56368. }
  56369. return false;
  56370. }
  56371. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56372. {
  56373. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56374. if (isOver)
  56375. hasBeenOver = true;
  56376. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56377. {
  56378. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56379. if (disableMouseMoves && isOver)
  56380. disableMouseMoves = false;
  56381. }
  56382. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56383. return;
  56384. bool isMovingTowardsMenu = false;
  56385. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56386. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56387. {
  56388. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56389. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56390. // extends from the last mouse pos to the submenu's rectangle..
  56391. float subX = (float) activeSubMenu->getScreenX();
  56392. if (activeSubMenu->getX() > getX())
  56393. {
  56394. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56395. }
  56396. else
  56397. {
  56398. lastMouse += Point<int> (2, 0);
  56399. subX += activeSubMenu->getWidth();
  56400. }
  56401. Path areaTowardsSubMenu;
  56402. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56403. (float) lastMouse.getY(),
  56404. subX,
  56405. (float) activeSubMenu->getScreenY(),
  56406. subX,
  56407. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56408. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56409. }
  56410. lastMouse = globalMousePos;
  56411. if (! isMovingTowardsMenu)
  56412. {
  56413. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56414. if (c == this)
  56415. c = 0;
  56416. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56417. if (mic == 0 && c != 0)
  56418. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56419. if (mic != currentChild
  56420. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56421. {
  56422. if (isOver && (c != 0) && (activeSubMenu != 0))
  56423. {
  56424. activeSubMenu->hide (0);
  56425. }
  56426. if (! isOver)
  56427. mic = 0;
  56428. setCurrentlyHighlightedChild (mic);
  56429. }
  56430. }
  56431. }
  56432. void triggerCurrentlyHighlightedItem()
  56433. {
  56434. if (currentChild->isValidComponent()
  56435. && currentChild->itemInfo.canBeTriggered()
  56436. && (currentChild->itemInfo.customComp == 0
  56437. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56438. {
  56439. dismissMenu (&currentChild->itemInfo);
  56440. }
  56441. }
  56442. void selectNextItem (const int delta)
  56443. {
  56444. disableTimerUntilMouseMoves();
  56445. PopupMenu::ItemComponent* mic = 0;
  56446. bool wasLastOne = (currentChild == 0);
  56447. const int numItems = getNumChildComponents();
  56448. for (int i = 0; i < numItems + 1; ++i)
  56449. {
  56450. int index = (delta > 0) ? i : (numItems - 1 - i);
  56451. index = (index + numItems) % numItems;
  56452. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56453. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56454. && wasLastOne)
  56455. break;
  56456. if (mic == currentChild)
  56457. wasLastOne = true;
  56458. }
  56459. setCurrentlyHighlightedChild (mic);
  56460. }
  56461. void disableTimerUntilMouseMoves()
  56462. {
  56463. disableMouseMoves = true;
  56464. if (owner != 0)
  56465. owner->disableTimerUntilMouseMoves();
  56466. }
  56467. Window (const Window&);
  56468. Window& operator= (const Window&);
  56469. };
  56470. PopupMenu::PopupMenu()
  56471. : lookAndFeel (0),
  56472. separatorPending (false)
  56473. {
  56474. }
  56475. PopupMenu::PopupMenu (const PopupMenu& other)
  56476. : lookAndFeel (other.lookAndFeel),
  56477. separatorPending (false)
  56478. {
  56479. items.addCopiesOf (other.items);
  56480. }
  56481. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56482. {
  56483. if (this != &other)
  56484. {
  56485. lookAndFeel = other.lookAndFeel;
  56486. clear();
  56487. items.addCopiesOf (other.items);
  56488. }
  56489. return *this;
  56490. }
  56491. PopupMenu::~PopupMenu()
  56492. {
  56493. clear();
  56494. }
  56495. void PopupMenu::clear()
  56496. {
  56497. items.clear();
  56498. separatorPending = false;
  56499. }
  56500. void PopupMenu::addSeparatorIfPending()
  56501. {
  56502. if (separatorPending)
  56503. {
  56504. separatorPending = false;
  56505. if (items.size() > 0)
  56506. items.add (new Item());
  56507. }
  56508. }
  56509. void PopupMenu::addItem (const int itemResultId,
  56510. const String& itemText,
  56511. const bool isActive,
  56512. const bool isTicked,
  56513. const Image& iconToUse)
  56514. {
  56515. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56516. // didn't pick anything, so you shouldn't use it as the id
  56517. // for an item..
  56518. addSeparatorIfPending();
  56519. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56520. Colours::black, false, 0, 0, 0));
  56521. }
  56522. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56523. const int commandID,
  56524. const String& displayName)
  56525. {
  56526. jassert (commandManager != 0 && commandID != 0);
  56527. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56528. if (registeredInfo != 0)
  56529. {
  56530. ApplicationCommandInfo info (*registeredInfo);
  56531. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56532. addSeparatorIfPending();
  56533. items.add (new Item (commandID,
  56534. displayName.isNotEmpty() ? displayName
  56535. : info.shortName,
  56536. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56537. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56538. Image::null,
  56539. Colours::black,
  56540. false,
  56541. 0, 0,
  56542. commandManager));
  56543. }
  56544. }
  56545. void PopupMenu::addColouredItem (const int itemResultId,
  56546. const String& itemText,
  56547. const Colour& itemTextColour,
  56548. const bool isActive,
  56549. const bool isTicked,
  56550. const Image& iconToUse)
  56551. {
  56552. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56553. // didn't pick anything, so you shouldn't use it as the id
  56554. // for an item..
  56555. addSeparatorIfPending();
  56556. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56557. itemTextColour, true, 0, 0, 0));
  56558. }
  56559. void PopupMenu::addCustomItem (const int itemResultId,
  56560. PopupMenuCustomComponent* const customComponent)
  56561. {
  56562. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56563. // didn't pick anything, so you shouldn't use it as the id
  56564. // for an item..
  56565. addSeparatorIfPending();
  56566. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56567. Colours::black, false, customComponent, 0, 0));
  56568. }
  56569. class NormalComponentWrapper : public PopupMenuCustomComponent
  56570. {
  56571. public:
  56572. NormalComponentWrapper (Component* const comp,
  56573. const int w, const int h,
  56574. const bool triggerMenuItemAutomaticallyWhenClicked)
  56575. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56576. width (w),
  56577. height (h)
  56578. {
  56579. addAndMakeVisible (comp);
  56580. }
  56581. ~NormalComponentWrapper() {}
  56582. void getIdealSize (int& idealWidth, int& idealHeight)
  56583. {
  56584. idealWidth = width;
  56585. idealHeight = height;
  56586. }
  56587. void resized()
  56588. {
  56589. if (getChildComponent(0) != 0)
  56590. getChildComponent(0)->setBounds (getLocalBounds());
  56591. }
  56592. juce_UseDebuggingNewOperator
  56593. private:
  56594. const int width, height;
  56595. NormalComponentWrapper (const NormalComponentWrapper&);
  56596. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56597. };
  56598. void PopupMenu::addCustomItem (const int itemResultId,
  56599. Component* customComponent,
  56600. int idealWidth, int idealHeight,
  56601. const bool triggerMenuItemAutomaticallyWhenClicked)
  56602. {
  56603. addCustomItem (itemResultId,
  56604. new NormalComponentWrapper (customComponent,
  56605. idealWidth, idealHeight,
  56606. triggerMenuItemAutomaticallyWhenClicked));
  56607. }
  56608. void PopupMenu::addSubMenu (const String& subMenuName,
  56609. const PopupMenu& subMenu,
  56610. const bool isActive,
  56611. const Image& iconToUse,
  56612. const bool isTicked)
  56613. {
  56614. addSeparatorIfPending();
  56615. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56616. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56617. }
  56618. void PopupMenu::addSeparator()
  56619. {
  56620. separatorPending = true;
  56621. }
  56622. class HeaderItemComponent : public PopupMenuCustomComponent
  56623. {
  56624. public:
  56625. HeaderItemComponent (const String& name)
  56626. : PopupMenuCustomComponent (false)
  56627. {
  56628. setName (name);
  56629. }
  56630. ~HeaderItemComponent()
  56631. {
  56632. }
  56633. void paint (Graphics& g)
  56634. {
  56635. Font f (getLookAndFeel().getPopupMenuFont());
  56636. f.setBold (true);
  56637. g.setFont (f);
  56638. g.setColour (findColour (PopupMenu::headerTextColourId));
  56639. g.drawFittedText (getName(),
  56640. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56641. Justification::bottomLeft, 1);
  56642. }
  56643. void getIdealSize (int& idealWidth,
  56644. int& idealHeight)
  56645. {
  56646. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56647. idealHeight += idealHeight / 2;
  56648. idealWidth += idealWidth / 4;
  56649. }
  56650. juce_UseDebuggingNewOperator
  56651. };
  56652. void PopupMenu::addSectionHeader (const String& title)
  56653. {
  56654. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56655. }
  56656. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56657. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56658. {
  56659. public:
  56660. PopupMenuCompletionCallback()
  56661. : managerOfChosenCommand (0)
  56662. {
  56663. }
  56664. ~PopupMenuCompletionCallback() {}
  56665. void modalStateFinished (int result)
  56666. {
  56667. if (managerOfChosenCommand != 0 && result != 0)
  56668. {
  56669. ApplicationCommandTarget::InvocationInfo info (result);
  56670. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56671. managerOfChosenCommand->invoke (info, true);
  56672. }
  56673. }
  56674. ApplicationCommandManager* managerOfChosenCommand;
  56675. ScopedPointer<Component> component;
  56676. private:
  56677. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56678. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56679. };
  56680. int PopupMenu::showMenu (const Rectangle<int>& target,
  56681. const int itemIdThatMustBeVisible,
  56682. const int minimumWidth,
  56683. const int maximumNumColumns,
  56684. const int standardItemHeight,
  56685. const bool alignToRectangle,
  56686. Component* const componentAttachedTo,
  56687. ModalComponentManager::Callback* userCallback)
  56688. {
  56689. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56690. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56691. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56692. Window::wasHiddenBecauseOfAppChange() = false;
  56693. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56694. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56695. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56696. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56697. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56698. &callback->managerOfChosenCommand, componentAttachedTo);
  56699. if (callback->component == 0)
  56700. return 0;
  56701. callbackDeleter.release();
  56702. callback->component->enterModalState (false, userCallbackDeleter.release());
  56703. callback->component->toFront (false); // need to do this after making it modal, or it could
  56704. // be stuck behind other comps that are already modal..
  56705. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56706. if (userCallback != 0)
  56707. return 0;
  56708. const int result = callback->component->runModalLoop();
  56709. if (! Window::wasHiddenBecauseOfAppChange())
  56710. {
  56711. if (prevTopLevel != 0)
  56712. prevTopLevel->toFront (true);
  56713. if (prevFocused != 0)
  56714. prevFocused->grabKeyboardFocus();
  56715. }
  56716. return result;
  56717. }
  56718. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56719. const int minimumWidth,
  56720. const int maximumNumColumns,
  56721. const int standardItemHeight,
  56722. ModalComponentManager::Callback* callback)
  56723. {
  56724. const Point<int> mousePos (Desktop::getMousePosition());
  56725. return showAt (mousePos.getX(), mousePos.getY(),
  56726. itemIdThatMustBeVisible,
  56727. minimumWidth,
  56728. maximumNumColumns,
  56729. standardItemHeight,
  56730. callback);
  56731. }
  56732. int PopupMenu::showAt (const int screenX,
  56733. const int screenY,
  56734. const int itemIdThatMustBeVisible,
  56735. const int minimumWidth,
  56736. const int maximumNumColumns,
  56737. const int standardItemHeight,
  56738. ModalComponentManager::Callback* callback)
  56739. {
  56740. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56741. itemIdThatMustBeVisible,
  56742. minimumWidth, maximumNumColumns,
  56743. standardItemHeight,
  56744. false, 0, callback);
  56745. }
  56746. int PopupMenu::showAt (Component* componentToAttachTo,
  56747. const int itemIdThatMustBeVisible,
  56748. const int minimumWidth,
  56749. const int maximumNumColumns,
  56750. const int standardItemHeight,
  56751. ModalComponentManager::Callback* callback)
  56752. {
  56753. if (componentToAttachTo != 0)
  56754. {
  56755. return showMenu (componentToAttachTo->getScreenBounds(),
  56756. itemIdThatMustBeVisible,
  56757. minimumWidth,
  56758. maximumNumColumns,
  56759. standardItemHeight,
  56760. true, componentToAttachTo, callback);
  56761. }
  56762. else
  56763. {
  56764. return show (itemIdThatMustBeVisible,
  56765. minimumWidth,
  56766. maximumNumColumns,
  56767. standardItemHeight,
  56768. callback);
  56769. }
  56770. }
  56771. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56772. {
  56773. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56774. {
  56775. Window* const pmw = Window::getActiveWindows()[i];
  56776. if (pmw != 0)
  56777. pmw->dismissMenu (0);
  56778. }
  56779. }
  56780. int PopupMenu::getNumItems() const throw()
  56781. {
  56782. int num = 0;
  56783. for (int i = items.size(); --i >= 0;)
  56784. if (! (items.getUnchecked(i))->isSeparator)
  56785. ++num;
  56786. return num;
  56787. }
  56788. bool PopupMenu::containsCommandItem (const int commandID) const
  56789. {
  56790. for (int i = items.size(); --i >= 0;)
  56791. {
  56792. const Item* mi = items.getUnchecked (i);
  56793. if ((mi->itemId == commandID && mi->commandManager != 0)
  56794. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56795. {
  56796. return true;
  56797. }
  56798. }
  56799. return false;
  56800. }
  56801. bool PopupMenu::containsAnyActiveItems() const throw()
  56802. {
  56803. for (int i = items.size(); --i >= 0;)
  56804. {
  56805. const Item* const mi = items.getUnchecked (i);
  56806. if (mi->subMenu != 0)
  56807. {
  56808. if (mi->subMenu->containsAnyActiveItems())
  56809. return true;
  56810. }
  56811. else if (mi->active)
  56812. {
  56813. return true;
  56814. }
  56815. }
  56816. return false;
  56817. }
  56818. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56819. {
  56820. lookAndFeel = newLookAndFeel;
  56821. }
  56822. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56823. : isHighlighted (false),
  56824. isTriggeredAutomatically (isTriggeredAutomatically_)
  56825. {
  56826. }
  56827. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56828. {
  56829. }
  56830. void PopupMenuCustomComponent::triggerMenuItem()
  56831. {
  56832. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56833. if (mic != 0)
  56834. {
  56835. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56836. if (pmw != 0)
  56837. {
  56838. pmw->dismissMenu (&mic->itemInfo);
  56839. }
  56840. else
  56841. {
  56842. // something must have gone wrong with the component hierarchy if this happens..
  56843. jassertfalse;
  56844. }
  56845. }
  56846. else
  56847. {
  56848. // why isn't this component inside a menu? Not much point triggering the item if
  56849. // there's no menu.
  56850. jassertfalse;
  56851. }
  56852. }
  56853. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56854. : subMenu (0),
  56855. itemId (0),
  56856. isSeparator (false),
  56857. isTicked (false),
  56858. isEnabled (false),
  56859. isCustomComponent (false),
  56860. isSectionHeader (false),
  56861. customColour (0),
  56862. customImage (0),
  56863. menu (menu_),
  56864. index (0)
  56865. {
  56866. }
  56867. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56868. {
  56869. }
  56870. bool PopupMenu::MenuItemIterator::next()
  56871. {
  56872. if (index >= menu.items.size())
  56873. return false;
  56874. const Item* const item = menu.items.getUnchecked (index);
  56875. ++index;
  56876. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56877. subMenu = item->subMenu;
  56878. itemId = item->itemId;
  56879. isSeparator = item->isSeparator;
  56880. isTicked = item->isTicked;
  56881. isEnabled = item->active;
  56882. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56883. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56884. customColour = item->usesColour ? &(item->textColour) : 0;
  56885. customImage = item->image;
  56886. commandManager = item->commandManager;
  56887. return true;
  56888. }
  56889. END_JUCE_NAMESPACE
  56890. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56891. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56892. BEGIN_JUCE_NAMESPACE
  56893. ComponentDragger::ComponentDragger()
  56894. : constrainer (0)
  56895. {
  56896. }
  56897. ComponentDragger::~ComponentDragger()
  56898. {
  56899. }
  56900. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56901. ComponentBoundsConstrainer* const constrainer_)
  56902. {
  56903. jassert (componentToDrag->isValidComponent());
  56904. if (componentToDrag != 0)
  56905. {
  56906. constrainer = constrainer_;
  56907. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56908. }
  56909. }
  56910. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56911. {
  56912. jassert (componentToDrag->isValidComponent());
  56913. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56914. if (componentToDrag != 0)
  56915. {
  56916. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56917. const Component* const parentComp = componentToDrag->getParentComponent();
  56918. if (parentComp != 0)
  56919. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56920. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56921. if (constrainer != 0)
  56922. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56923. else
  56924. componentToDrag->setBounds (bounds);
  56925. }
  56926. }
  56927. END_JUCE_NAMESPACE
  56928. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56929. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56930. BEGIN_JUCE_NAMESPACE
  56931. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56932. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56933. class DragImageComponent : public Component,
  56934. public Timer
  56935. {
  56936. public:
  56937. DragImageComponent (const Image& im,
  56938. const String& desc,
  56939. Component* const sourceComponent,
  56940. Component* const mouseDragSource_,
  56941. DragAndDropContainer* const o,
  56942. const Point<int>& imageOffset_)
  56943. : image (im),
  56944. source (sourceComponent),
  56945. mouseDragSource (mouseDragSource_),
  56946. owner (o),
  56947. dragDesc (desc),
  56948. imageOffset (imageOffset_),
  56949. hasCheckedForExternalDrag (false),
  56950. drawImage (true)
  56951. {
  56952. setSize (im.getWidth(), im.getHeight());
  56953. if (mouseDragSource == 0)
  56954. mouseDragSource = source;
  56955. mouseDragSource->addMouseListener (this, false);
  56956. startTimer (200);
  56957. setInterceptsMouseClicks (false, false);
  56958. setAlwaysOnTop (true);
  56959. }
  56960. ~DragImageComponent()
  56961. {
  56962. if (owner->dragImageComponent == this)
  56963. owner->dragImageComponent.release();
  56964. if (mouseDragSource != 0)
  56965. {
  56966. mouseDragSource->removeMouseListener (this);
  56967. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56968. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56969. }
  56970. }
  56971. void paint (Graphics& g)
  56972. {
  56973. if (isOpaque())
  56974. g.fillAll (Colours::white);
  56975. if (drawImage)
  56976. {
  56977. g.setOpacity (1.0f);
  56978. g.drawImageAt (image, 0, 0);
  56979. }
  56980. }
  56981. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56982. {
  56983. Component* hit = getParentComponent();
  56984. if (hit == 0)
  56985. {
  56986. hit = Desktop::getInstance().findComponentAt (screenPos);
  56987. }
  56988. else
  56989. {
  56990. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56991. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56992. }
  56993. // (note: use a local copy of the dragDesc member in case the callback runs
  56994. // a modal loop and deletes this object before the method completes)
  56995. const String dragDescLocal (dragDesc);
  56996. while (hit != 0)
  56997. {
  56998. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56999. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57000. {
  57001. relativePos = hit->globalPositionToRelative (screenPos);
  57002. return ddt;
  57003. }
  57004. hit = hit->getParentComponent();
  57005. }
  57006. return 0;
  57007. }
  57008. void mouseUp (const MouseEvent& e)
  57009. {
  57010. if (e.originalComponent != this)
  57011. {
  57012. if (mouseDragSource != 0)
  57013. mouseDragSource->removeMouseListener (this);
  57014. bool dropAccepted = false;
  57015. DragAndDropTarget* ddt = 0;
  57016. Point<int> relPos;
  57017. if (isVisible())
  57018. {
  57019. setVisible (false);
  57020. ddt = findTarget (e.getScreenPosition(), relPos);
  57021. // fade this component and remove it - it'll be deleted later by the timer callback
  57022. dropAccepted = ddt != 0;
  57023. setVisible (true);
  57024. if (dropAccepted || source == 0)
  57025. {
  57026. fadeOutComponent (120);
  57027. }
  57028. else
  57029. {
  57030. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57031. source->getHeight() / 2)));
  57032. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57033. getHeight() / 2)));
  57034. fadeOutComponent (120,
  57035. target.getX() - ourCentre.getX(),
  57036. target.getY() - ourCentre.getY());
  57037. }
  57038. }
  57039. if (getParentComponent() != 0)
  57040. getParentComponent()->removeChildComponent (this);
  57041. if (dropAccepted && ddt != 0)
  57042. {
  57043. // (note: use a local copy of the dragDesc member in case the callback runs
  57044. // a modal loop and deletes this object before the method completes)
  57045. const String dragDescLocal (dragDesc);
  57046. currentlyOverComp = 0;
  57047. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57048. }
  57049. // careful - this object could now be deleted..
  57050. }
  57051. }
  57052. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57053. {
  57054. // (note: use a local copy of the dragDesc member in case the callback runs
  57055. // a modal loop and deletes this object before it returns)
  57056. const String dragDescLocal (dragDesc);
  57057. Point<int> newPos (screenPos + imageOffset);
  57058. if (getParentComponent() != 0)
  57059. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57060. //if (newX != getX() || newY != getY())
  57061. {
  57062. setTopLeftPosition (newPos.getX(), newPos.getY());
  57063. Point<int> relPos;
  57064. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57065. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57066. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57067. if (ddtComp != currentlyOverComp)
  57068. {
  57069. if (currentlyOverComp != 0 && source != 0
  57070. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57071. {
  57072. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57073. }
  57074. currentlyOverComp = ddtComp;
  57075. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57076. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57077. }
  57078. DragAndDropTarget* target = getCurrentlyOver();
  57079. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57080. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57081. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57082. {
  57083. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57084. {
  57085. hasCheckedForExternalDrag = true;
  57086. StringArray files;
  57087. bool canMoveFiles = false;
  57088. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57089. && files.size() > 0)
  57090. {
  57091. Component::SafePointer<Component> cdw (this);
  57092. setVisible (false);
  57093. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57094. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57095. if (cdw != 0)
  57096. delete this;
  57097. return;
  57098. }
  57099. }
  57100. }
  57101. }
  57102. }
  57103. void mouseDrag (const MouseEvent& e)
  57104. {
  57105. if (e.originalComponent != this)
  57106. updateLocation (true, e.getScreenPosition());
  57107. }
  57108. void timerCallback()
  57109. {
  57110. if (source == 0)
  57111. {
  57112. delete this;
  57113. }
  57114. else if (! isMouseButtonDownAnywhere())
  57115. {
  57116. if (mouseDragSource != 0)
  57117. mouseDragSource->removeMouseListener (this);
  57118. delete this;
  57119. }
  57120. }
  57121. private:
  57122. Image image;
  57123. Component::SafePointer<Component> source;
  57124. Component::SafePointer<Component> mouseDragSource;
  57125. DragAndDropContainer* const owner;
  57126. Component::SafePointer<Component> currentlyOverComp;
  57127. DragAndDropTarget* getCurrentlyOver()
  57128. {
  57129. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57130. }
  57131. String dragDesc;
  57132. const Point<int> imageOffset;
  57133. bool hasCheckedForExternalDrag, drawImage;
  57134. DragImageComponent (const DragImageComponent&);
  57135. DragImageComponent& operator= (const DragImageComponent&);
  57136. };
  57137. DragAndDropContainer::DragAndDropContainer()
  57138. {
  57139. }
  57140. DragAndDropContainer::~DragAndDropContainer()
  57141. {
  57142. dragImageComponent = 0;
  57143. }
  57144. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57145. Component* sourceComponent,
  57146. const Image& dragImage_,
  57147. const bool allowDraggingToExternalWindows,
  57148. const Point<int>* imageOffsetFromMouse)
  57149. {
  57150. Image dragImage (dragImage_);
  57151. if (dragImageComponent == 0)
  57152. {
  57153. Component* const thisComp = dynamic_cast <Component*> (this);
  57154. if (thisComp == 0)
  57155. {
  57156. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57157. return;
  57158. }
  57159. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57160. if (draggingSource == 0 || ! draggingSource->isDragging())
  57161. {
  57162. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57163. return;
  57164. }
  57165. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57166. Point<int> imageOffset;
  57167. if (dragImage.isNull())
  57168. {
  57169. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57170. .convertedToFormat (Image::ARGB);
  57171. dragImage.multiplyAllAlphas (0.6f);
  57172. const int lo = 150;
  57173. const int hi = 400;
  57174. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57175. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57176. for (int y = dragImage.getHeight(); --y >= 0;)
  57177. {
  57178. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57179. for (int x = dragImage.getWidth(); --x >= 0;)
  57180. {
  57181. const int dx = x - clipped.getX();
  57182. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57183. if (distance > lo)
  57184. {
  57185. const float alpha = (distance > hi) ? 0
  57186. : (hi - distance) / (float) (hi - lo)
  57187. + Random::getSystemRandom().nextFloat() * 0.008f;
  57188. dragImage.multiplyAlphaAt (x, y, alpha);
  57189. }
  57190. }
  57191. }
  57192. imageOffset = -clipped;
  57193. }
  57194. else
  57195. {
  57196. if (imageOffsetFromMouse == 0)
  57197. imageOffset = -dragImage.getBounds().getCentre();
  57198. else
  57199. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57200. }
  57201. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57202. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57203. currentDragDesc = sourceDescription;
  57204. if (allowDraggingToExternalWindows)
  57205. {
  57206. if (! Desktop::canUseSemiTransparentWindows())
  57207. dragImageComponent->setOpaque (true);
  57208. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57209. | ComponentPeer::windowIsTemporary
  57210. | ComponentPeer::windowIgnoresKeyPresses);
  57211. }
  57212. else
  57213. thisComp->addChildComponent (dragImageComponent);
  57214. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57215. dragImageComponent->setVisible (true);
  57216. }
  57217. }
  57218. bool DragAndDropContainer::isDragAndDropActive() const
  57219. {
  57220. return dragImageComponent != 0;
  57221. }
  57222. const String DragAndDropContainer::getCurrentDragDescription() const
  57223. {
  57224. return (dragImageComponent != 0) ? currentDragDesc
  57225. : String::empty;
  57226. }
  57227. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57228. {
  57229. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57230. }
  57231. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57232. {
  57233. return false;
  57234. }
  57235. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57236. {
  57237. }
  57238. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57239. {
  57240. }
  57241. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57242. {
  57243. }
  57244. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57245. {
  57246. return true;
  57247. }
  57248. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57249. {
  57250. }
  57251. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57252. {
  57253. }
  57254. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57255. {
  57256. }
  57257. END_JUCE_NAMESPACE
  57258. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57259. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57260. BEGIN_JUCE_NAMESPACE
  57261. class MouseCursor::SharedCursorHandle
  57262. {
  57263. public:
  57264. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57265. : handle (createStandardMouseCursor (type)),
  57266. refCount (1),
  57267. standardType (type),
  57268. isStandard (true)
  57269. {
  57270. }
  57271. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57272. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57273. refCount (1),
  57274. standardType (MouseCursor::NormalCursor),
  57275. isStandard (false)
  57276. {
  57277. }
  57278. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57279. {
  57280. const ScopedLock sl (getLock());
  57281. for (int i = 0; i < getCursors().size(); ++i)
  57282. {
  57283. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57284. if (sc->standardType == type)
  57285. return sc->retain();
  57286. }
  57287. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57288. getCursors().add (sc);
  57289. return sc;
  57290. }
  57291. SharedCursorHandle* retain() throw()
  57292. {
  57293. ++refCount;
  57294. return this;
  57295. }
  57296. void release()
  57297. {
  57298. if (--refCount == 0)
  57299. {
  57300. if (isStandard)
  57301. {
  57302. const ScopedLock sl (getLock());
  57303. getCursors().removeValue (this);
  57304. }
  57305. delete this;
  57306. }
  57307. }
  57308. void* getHandle() const throw() { return handle; }
  57309. juce_UseDebuggingNewOperator
  57310. private:
  57311. void* const handle;
  57312. Atomic <int> refCount;
  57313. const MouseCursor::StandardCursorType standardType;
  57314. const bool isStandard;
  57315. static CriticalSection& getLock()
  57316. {
  57317. static CriticalSection lock;
  57318. return lock;
  57319. }
  57320. static Array <SharedCursorHandle*>& getCursors()
  57321. {
  57322. static Array <SharedCursorHandle*> cursors;
  57323. return cursors;
  57324. }
  57325. ~SharedCursorHandle()
  57326. {
  57327. deleteMouseCursor (handle, isStandard);
  57328. }
  57329. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57330. };
  57331. MouseCursor::MouseCursor()
  57332. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57333. {
  57334. jassert (cursorHandle != 0);
  57335. }
  57336. MouseCursor::MouseCursor (const StandardCursorType type)
  57337. : cursorHandle (SharedCursorHandle::createStandard (type))
  57338. {
  57339. jassert (cursorHandle != 0);
  57340. }
  57341. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57342. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57343. {
  57344. }
  57345. MouseCursor::MouseCursor (const MouseCursor& other)
  57346. : cursorHandle (other.cursorHandle->retain())
  57347. {
  57348. }
  57349. MouseCursor::~MouseCursor()
  57350. {
  57351. cursorHandle->release();
  57352. }
  57353. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57354. {
  57355. other.cursorHandle->retain();
  57356. cursorHandle->release();
  57357. cursorHandle = other.cursorHandle;
  57358. return *this;
  57359. }
  57360. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57361. {
  57362. return getHandle() == other.getHandle();
  57363. }
  57364. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57365. {
  57366. return getHandle() != other.getHandle();
  57367. }
  57368. void* MouseCursor::getHandle() const throw()
  57369. {
  57370. return cursorHandle->getHandle();
  57371. }
  57372. void MouseCursor::showWaitCursor()
  57373. {
  57374. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57375. }
  57376. void MouseCursor::hideWaitCursor()
  57377. {
  57378. Desktop::getInstance().getMainMouseSource().revealCursor();
  57379. }
  57380. END_JUCE_NAMESPACE
  57381. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57382. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57383. BEGIN_JUCE_NAMESPACE
  57384. MouseEvent::MouseEvent (MouseInputSource& source_,
  57385. const Point<int>& position,
  57386. const ModifierKeys& mods_,
  57387. Component* const eventComponent_,
  57388. Component* const originator,
  57389. const Time& eventTime_,
  57390. const Point<int> mouseDownPos_,
  57391. const Time& mouseDownTime_,
  57392. const int numberOfClicks_,
  57393. const bool mouseWasDragged) throw()
  57394. : x (position.getX()),
  57395. y (position.getY()),
  57396. mods (mods_),
  57397. eventComponent (eventComponent_),
  57398. originalComponent (originator),
  57399. eventTime (eventTime_),
  57400. source (source_),
  57401. mouseDownPos (mouseDownPos_),
  57402. mouseDownTime (mouseDownTime_),
  57403. numberOfClicks (numberOfClicks_),
  57404. wasMovedSinceMouseDown (mouseWasDragged)
  57405. {
  57406. }
  57407. MouseEvent::~MouseEvent() throw()
  57408. {
  57409. }
  57410. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57411. {
  57412. if (otherComponent == 0)
  57413. {
  57414. jassertfalse;
  57415. return *this;
  57416. }
  57417. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57418. mods, otherComponent, originalComponent, eventTime,
  57419. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57420. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57421. }
  57422. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57423. {
  57424. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57425. eventTime, mouseDownPos, mouseDownTime,
  57426. numberOfClicks, wasMovedSinceMouseDown);
  57427. }
  57428. bool MouseEvent::mouseWasClicked() const throw()
  57429. {
  57430. return ! wasMovedSinceMouseDown;
  57431. }
  57432. int MouseEvent::getMouseDownX() const throw()
  57433. {
  57434. return mouseDownPos.getX();
  57435. }
  57436. int MouseEvent::getMouseDownY() const throw()
  57437. {
  57438. return mouseDownPos.getY();
  57439. }
  57440. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57441. {
  57442. return mouseDownPos;
  57443. }
  57444. int MouseEvent::getDistanceFromDragStartX() const throw()
  57445. {
  57446. return x - mouseDownPos.getX();
  57447. }
  57448. int MouseEvent::getDistanceFromDragStartY() const throw()
  57449. {
  57450. return y - mouseDownPos.getY();
  57451. }
  57452. int MouseEvent::getDistanceFromDragStart() const throw()
  57453. {
  57454. return mouseDownPos.getDistanceFrom (getPosition());
  57455. }
  57456. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57457. {
  57458. return getPosition() - mouseDownPos;
  57459. }
  57460. int MouseEvent::getLengthOfMousePress() const throw()
  57461. {
  57462. if (mouseDownTime.toMilliseconds() > 0)
  57463. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57464. return 0;
  57465. }
  57466. const Point<int> MouseEvent::getPosition() const throw()
  57467. {
  57468. return Point<int> (x, y);
  57469. }
  57470. int MouseEvent::getScreenX() const
  57471. {
  57472. return getScreenPosition().getX();
  57473. }
  57474. int MouseEvent::getScreenY() const
  57475. {
  57476. return getScreenPosition().getY();
  57477. }
  57478. const Point<int> MouseEvent::getScreenPosition() const
  57479. {
  57480. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57481. }
  57482. int MouseEvent::getMouseDownScreenX() const
  57483. {
  57484. return getMouseDownScreenPosition().getX();
  57485. }
  57486. int MouseEvent::getMouseDownScreenY() const
  57487. {
  57488. return getMouseDownScreenPosition().getY();
  57489. }
  57490. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57491. {
  57492. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57493. }
  57494. int MouseEvent::doubleClickTimeOutMs = 400;
  57495. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57496. {
  57497. doubleClickTimeOutMs = newTime;
  57498. }
  57499. int MouseEvent::getDoubleClickTimeout() throw()
  57500. {
  57501. return doubleClickTimeOutMs;
  57502. }
  57503. END_JUCE_NAMESPACE
  57504. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57505. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57506. BEGIN_JUCE_NAMESPACE
  57507. class MouseInputSourceInternal : public AsyncUpdater
  57508. {
  57509. public:
  57510. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57511. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57512. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57513. mouseEventCounter (0)
  57514. {
  57515. zerostruct (mouseDowns);
  57516. }
  57517. ~MouseInputSourceInternal()
  57518. {
  57519. }
  57520. bool isDragging() const throw()
  57521. {
  57522. return buttonState.isAnyMouseButtonDown();
  57523. }
  57524. Component* getComponentUnderMouse() const
  57525. {
  57526. return static_cast <Component*> (componentUnderMouse);
  57527. }
  57528. const ModifierKeys getCurrentModifiers() const
  57529. {
  57530. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57531. }
  57532. ComponentPeer* getPeer()
  57533. {
  57534. if (! ComponentPeer::isValidPeer (lastPeer))
  57535. lastPeer = 0;
  57536. return lastPeer;
  57537. }
  57538. Component* findComponentAt (const Point<int>& screenPos)
  57539. {
  57540. ComponentPeer* const peer = getPeer();
  57541. if (peer != 0)
  57542. {
  57543. Component* const comp = peer->getComponent();
  57544. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57545. // (the contains() call is needed to test for overlapping desktop windows)
  57546. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57547. return comp->getComponentAt (relativePos);
  57548. }
  57549. return 0;
  57550. }
  57551. const Point<int> getScreenPosition() const throw()
  57552. {
  57553. return lastScreenPos + unboundedMouseOffset;
  57554. }
  57555. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57556. {
  57557. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57558. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57559. }
  57560. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57561. {
  57562. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57563. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57564. }
  57565. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57566. {
  57567. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57568. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57569. }
  57570. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57571. {
  57572. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57573. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57574. }
  57575. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57576. {
  57577. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57578. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57579. }
  57580. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57581. {
  57582. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57583. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57584. }
  57585. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57586. {
  57587. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57588. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57589. }
  57590. // (returns true if the button change caused a modal event loop)
  57591. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57592. {
  57593. if (buttonState == newButtonState)
  57594. return false;
  57595. setScreenPos (screenPos, time, false);
  57596. // (ignore secondary clicks when there's already a button down)
  57597. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57598. {
  57599. buttonState = newButtonState;
  57600. return false;
  57601. }
  57602. const int lastCounter = mouseEventCounter;
  57603. if (buttonState.isAnyMouseButtonDown())
  57604. {
  57605. Component* const current = getComponentUnderMouse();
  57606. if (current != 0)
  57607. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57608. enableUnboundedMouseMovement (false, false);
  57609. }
  57610. buttonState = newButtonState;
  57611. if (buttonState.isAnyMouseButtonDown())
  57612. {
  57613. Desktop::getInstance().incrementMouseClickCounter();
  57614. Component* const current = getComponentUnderMouse();
  57615. if (current != 0)
  57616. {
  57617. registerMouseDown (screenPos, time, current);
  57618. sendMouseDown (current, screenPos, time);
  57619. }
  57620. }
  57621. return lastCounter != mouseEventCounter;
  57622. }
  57623. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57624. {
  57625. Component* current = getComponentUnderMouse();
  57626. if (newComponent != current)
  57627. {
  57628. Component::SafePointer<Component> safeNewComp (newComponent);
  57629. const ModifierKeys originalButtonState (buttonState);
  57630. if (current != 0)
  57631. {
  57632. setButtons (screenPos, time, ModifierKeys());
  57633. sendMouseExit (current, screenPos, time);
  57634. buttonState = originalButtonState;
  57635. }
  57636. componentUnderMouse = safeNewComp;
  57637. current = getComponentUnderMouse();
  57638. if (current != 0)
  57639. sendMouseEnter (current, screenPos, time);
  57640. revealCursor (false);
  57641. setButtons (screenPos, time, originalButtonState);
  57642. }
  57643. }
  57644. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57645. {
  57646. ModifierKeys::updateCurrentModifiers();
  57647. if (newPeer != lastPeer)
  57648. {
  57649. setComponentUnderMouse (0, screenPos, time);
  57650. lastPeer = newPeer;
  57651. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57652. }
  57653. }
  57654. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57655. {
  57656. if (! isDragging())
  57657. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57658. if (newScreenPos != lastScreenPos || forceUpdate)
  57659. {
  57660. cancelPendingUpdate();
  57661. lastScreenPos = newScreenPos;
  57662. Component* const current = getComponentUnderMouse();
  57663. if (current != 0)
  57664. {
  57665. if (isDragging())
  57666. {
  57667. registerMouseDrag (newScreenPos);
  57668. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57669. if (isUnboundedMouseModeOn)
  57670. handleUnboundedDrag (current);
  57671. }
  57672. else
  57673. {
  57674. sendMouseMove (current, newScreenPos, time);
  57675. }
  57676. }
  57677. revealCursor (false);
  57678. }
  57679. }
  57680. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57681. {
  57682. jassert (newPeer != 0);
  57683. lastTime = time;
  57684. ++mouseEventCounter;
  57685. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57686. if (isDragging() && newMods.isAnyMouseButtonDown())
  57687. {
  57688. setScreenPos (screenPos, time, false);
  57689. }
  57690. else
  57691. {
  57692. setPeer (newPeer, screenPos, time);
  57693. ComponentPeer* peer = getPeer();
  57694. if (peer != 0)
  57695. {
  57696. if (setButtons (screenPos, time, newMods))
  57697. return; // some modal events have been dispatched, so the current event is now out-of-date
  57698. peer = getPeer();
  57699. if (peer != 0)
  57700. setScreenPos (screenPos, time, false);
  57701. }
  57702. }
  57703. }
  57704. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57705. {
  57706. jassert (peer != 0);
  57707. lastTime = time;
  57708. ++mouseEventCounter;
  57709. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57710. setPeer (peer, screenPos, time);
  57711. setScreenPos (screenPos, time, false);
  57712. triggerFakeMove();
  57713. if (! isDragging())
  57714. {
  57715. Component* current = getComponentUnderMouse();
  57716. if (current != 0)
  57717. sendMouseWheel (current, screenPos, time, x, y);
  57718. }
  57719. }
  57720. const Time getLastMouseDownTime() const throw()
  57721. {
  57722. return Time (mouseDowns[0].time);
  57723. }
  57724. const Point<int> getLastMouseDownPosition() const throw()
  57725. {
  57726. return mouseDowns[0].position;
  57727. }
  57728. int getNumberOfMultipleClicks() const throw()
  57729. {
  57730. int numClicks = 0;
  57731. if (mouseDowns[0].time != 0)
  57732. {
  57733. if (! mouseMovedSignificantlySincePressed)
  57734. ++numClicks;
  57735. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57736. {
  57737. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57738. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57739. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57740. {
  57741. ++numClicks;
  57742. }
  57743. else
  57744. {
  57745. break;
  57746. }
  57747. }
  57748. }
  57749. return numClicks;
  57750. }
  57751. bool hasMouseMovedSignificantlySincePressed() const throw()
  57752. {
  57753. return mouseMovedSignificantlySincePressed
  57754. || lastTime > mouseDowns[0].time + 300;
  57755. }
  57756. void triggerFakeMove()
  57757. {
  57758. triggerAsyncUpdate();
  57759. }
  57760. void handleAsyncUpdate()
  57761. {
  57762. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57763. }
  57764. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57765. {
  57766. enable = enable && isDragging();
  57767. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57768. if (enable != isUnboundedMouseModeOn)
  57769. {
  57770. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57771. {
  57772. // when released, return the mouse to within the component's bounds
  57773. Component* current = getComponentUnderMouse();
  57774. if (current != 0)
  57775. Desktop::setMousePosition (current->getScreenBounds()
  57776. .getConstrainedPoint (lastScreenPos));
  57777. }
  57778. isUnboundedMouseModeOn = enable;
  57779. unboundedMouseOffset = Point<int>();
  57780. revealCursor (true);
  57781. }
  57782. }
  57783. void handleUnboundedDrag (Component* current)
  57784. {
  57785. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57786. if (! screenArea.contains (lastScreenPos))
  57787. {
  57788. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57789. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57790. Desktop::setMousePosition (componentCentre);
  57791. }
  57792. else if (isCursorVisibleUntilOffscreen
  57793. && (! unboundedMouseOffset.isOrigin())
  57794. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57795. {
  57796. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57797. unboundedMouseOffset = Point<int>();
  57798. }
  57799. }
  57800. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57801. {
  57802. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57803. {
  57804. cursor = MouseCursor::NoCursor;
  57805. forcedUpdate = true;
  57806. }
  57807. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57808. {
  57809. currentCursorHandle = cursor.getHandle();
  57810. cursor.showInWindow (getPeer());
  57811. }
  57812. }
  57813. void hideCursor()
  57814. {
  57815. showMouseCursor (MouseCursor::NoCursor, true);
  57816. }
  57817. void revealCursor (bool forcedUpdate)
  57818. {
  57819. MouseCursor mc (MouseCursor::NormalCursor);
  57820. Component* current = getComponentUnderMouse();
  57821. if (current != 0)
  57822. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57823. showMouseCursor (mc, forcedUpdate);
  57824. }
  57825. int index;
  57826. bool isMouseDevice;
  57827. Point<int> lastScreenPos;
  57828. ModifierKeys buttonState;
  57829. private:
  57830. MouseInputSource& source;
  57831. Component::SafePointer<Component> componentUnderMouse;
  57832. ComponentPeer* lastPeer;
  57833. Point<int> unboundedMouseOffset;
  57834. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57835. void* currentCursorHandle;
  57836. int mouseEventCounter;
  57837. struct RecentMouseDown
  57838. {
  57839. Point<int> position;
  57840. int64 time;
  57841. Component* component;
  57842. };
  57843. RecentMouseDown mouseDowns[4];
  57844. bool mouseMovedSignificantlySincePressed;
  57845. int64 lastTime;
  57846. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57847. {
  57848. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57849. mouseDowns[i] = mouseDowns[i - 1];
  57850. mouseDowns[0].position = screenPos;
  57851. mouseDowns[0].time = time;
  57852. mouseDowns[0].component = component;
  57853. mouseMovedSignificantlySincePressed = false;
  57854. }
  57855. void registerMouseDrag (const Point<int>& screenPos) throw()
  57856. {
  57857. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57858. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57859. }
  57860. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57861. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57862. };
  57863. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57864. {
  57865. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57866. }
  57867. MouseInputSource::~MouseInputSource()
  57868. {
  57869. }
  57870. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57871. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57872. bool MouseInputSource::canHover() const { return isMouse(); }
  57873. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57874. int MouseInputSource::getIndex() const { return pimpl->index; }
  57875. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57876. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57877. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57878. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57879. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57880. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57881. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57882. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57883. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57884. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57885. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57886. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57887. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57888. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57889. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57890. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57891. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57892. {
  57893. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57894. }
  57895. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57896. {
  57897. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57898. }
  57899. END_JUCE_NAMESPACE
  57900. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57901. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57902. BEGIN_JUCE_NAMESPACE
  57903. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57904. : source (0),
  57905. hoverTimeMillisecs (hoverTimeMillisecs_),
  57906. hasJustHovered (false)
  57907. {
  57908. internalTimer.owner = this;
  57909. }
  57910. MouseHoverDetector::~MouseHoverDetector()
  57911. {
  57912. setHoverComponent (0);
  57913. }
  57914. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57915. {
  57916. hoverTimeMillisecs = newTimeInMillisecs;
  57917. }
  57918. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57919. {
  57920. if (source != newSourceComponent)
  57921. {
  57922. internalTimer.stopTimer();
  57923. hasJustHovered = false;
  57924. if (source != 0)
  57925. {
  57926. // ! you need to delete the hover detector before deleting its component
  57927. jassert (source->isValidComponent());
  57928. source->removeMouseListener (&internalTimer);
  57929. }
  57930. source = newSourceComponent;
  57931. if (newSourceComponent != 0)
  57932. newSourceComponent->addMouseListener (&internalTimer, false);
  57933. }
  57934. }
  57935. void MouseHoverDetector::hoverTimerCallback()
  57936. {
  57937. internalTimer.stopTimer();
  57938. if (source != 0)
  57939. {
  57940. const Point<int> pos (source->getMouseXYRelative());
  57941. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57942. {
  57943. hasJustHovered = true;
  57944. mouseHovered (pos.getX(), pos.getY());
  57945. }
  57946. }
  57947. }
  57948. void MouseHoverDetector::checkJustHoveredCallback()
  57949. {
  57950. if (hasJustHovered)
  57951. {
  57952. hasJustHovered = false;
  57953. mouseMovedAfterHover();
  57954. }
  57955. }
  57956. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57957. {
  57958. owner->hoverTimerCallback();
  57959. }
  57960. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57961. {
  57962. stopTimer();
  57963. owner->checkJustHoveredCallback();
  57964. }
  57965. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57966. {
  57967. stopTimer();
  57968. owner->checkJustHoveredCallback();
  57969. }
  57970. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57971. {
  57972. stopTimer();
  57973. owner->checkJustHoveredCallback();
  57974. }
  57975. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57976. {
  57977. stopTimer();
  57978. owner->checkJustHoveredCallback();
  57979. }
  57980. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57981. {
  57982. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57983. {
  57984. lastX = e.x;
  57985. lastY = e.y;
  57986. if (owner->source != 0)
  57987. startTimer (owner->hoverTimeMillisecs);
  57988. owner->checkJustHoveredCallback();
  57989. }
  57990. }
  57991. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57992. {
  57993. stopTimer();
  57994. owner->checkJustHoveredCallback();
  57995. }
  57996. END_JUCE_NAMESPACE
  57997. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57998. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57999. BEGIN_JUCE_NAMESPACE
  58000. void MouseListener::mouseEnter (const MouseEvent&)
  58001. {
  58002. }
  58003. void MouseListener::mouseExit (const MouseEvent&)
  58004. {
  58005. }
  58006. void MouseListener::mouseDown (const MouseEvent&)
  58007. {
  58008. }
  58009. void MouseListener::mouseUp (const MouseEvent&)
  58010. {
  58011. }
  58012. void MouseListener::mouseDrag (const MouseEvent&)
  58013. {
  58014. }
  58015. void MouseListener::mouseMove (const MouseEvent&)
  58016. {
  58017. }
  58018. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58019. {
  58020. }
  58021. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58022. {
  58023. }
  58024. END_JUCE_NAMESPACE
  58025. /*** End of inlined file: juce_MouseListener.cpp ***/
  58026. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58027. BEGIN_JUCE_NAMESPACE
  58028. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58029. const String& buttonTextWhenTrue,
  58030. const String& buttonTextWhenFalse)
  58031. : PropertyComponent (name),
  58032. onText (buttonTextWhenTrue),
  58033. offText (buttonTextWhenFalse)
  58034. {
  58035. addAndMakeVisible (&button);
  58036. button.setClickingTogglesState (false);
  58037. button.addButtonListener (this);
  58038. }
  58039. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58040. const String& name,
  58041. const String& buttonText)
  58042. : PropertyComponent (name),
  58043. onText (buttonText),
  58044. offText (buttonText)
  58045. {
  58046. addAndMakeVisible (&button);
  58047. button.setClickingTogglesState (false);
  58048. button.setButtonText (buttonText);
  58049. button.getToggleStateValue().referTo (valueToControl);
  58050. button.setClickingTogglesState (true);
  58051. }
  58052. BooleanPropertyComponent::~BooleanPropertyComponent()
  58053. {
  58054. }
  58055. void BooleanPropertyComponent::setState (const bool newState)
  58056. {
  58057. button.setToggleState (newState, true);
  58058. }
  58059. bool BooleanPropertyComponent::getState() const
  58060. {
  58061. return button.getToggleState();
  58062. }
  58063. void BooleanPropertyComponent::paint (Graphics& g)
  58064. {
  58065. PropertyComponent::paint (g);
  58066. g.setColour (Colours::white);
  58067. g.fillRect (button.getBounds());
  58068. g.setColour (findColour (ComboBox::outlineColourId));
  58069. g.drawRect (button.getBounds());
  58070. }
  58071. void BooleanPropertyComponent::refresh()
  58072. {
  58073. button.setToggleState (getState(), false);
  58074. button.setButtonText (button.getToggleState() ? onText : offText);
  58075. }
  58076. void BooleanPropertyComponent::buttonClicked (Button*)
  58077. {
  58078. setState (! getState());
  58079. }
  58080. END_JUCE_NAMESPACE
  58081. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58082. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58083. BEGIN_JUCE_NAMESPACE
  58084. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58085. const bool triggerOnMouseDown)
  58086. : PropertyComponent (name)
  58087. {
  58088. addAndMakeVisible (&button);
  58089. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58090. button.addButtonListener (this);
  58091. }
  58092. ButtonPropertyComponent::~ButtonPropertyComponent()
  58093. {
  58094. }
  58095. void ButtonPropertyComponent::refresh()
  58096. {
  58097. button.setButtonText (getButtonText());
  58098. }
  58099. void ButtonPropertyComponent::buttonClicked (Button*)
  58100. {
  58101. buttonClicked();
  58102. }
  58103. END_JUCE_NAMESPACE
  58104. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58105. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58106. BEGIN_JUCE_NAMESPACE
  58107. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58108. public Value::Listener
  58109. {
  58110. public:
  58111. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58112. : sourceValue (sourceValue_),
  58113. mappings (mappings_)
  58114. {
  58115. sourceValue.addListener (this);
  58116. }
  58117. ~RemapperValueSource() {}
  58118. const var getValue() const
  58119. {
  58120. return mappings.indexOf (sourceValue.getValue()) + 1;
  58121. }
  58122. void setValue (const var& newValue)
  58123. {
  58124. const var remappedVal (mappings [(int) newValue - 1]);
  58125. if (remappedVal != sourceValue)
  58126. sourceValue = remappedVal;
  58127. }
  58128. void valueChanged (Value&)
  58129. {
  58130. sendChangeMessage (true);
  58131. }
  58132. juce_UseDebuggingNewOperator
  58133. protected:
  58134. Value sourceValue;
  58135. Array<var> mappings;
  58136. RemapperValueSource (const RemapperValueSource&);
  58137. const RemapperValueSource& operator= (const RemapperValueSource&);
  58138. };
  58139. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58140. : PropertyComponent (name),
  58141. isCustomClass (true)
  58142. {
  58143. }
  58144. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58145. const String& name,
  58146. const StringArray& choices_,
  58147. const Array <var>& correspondingValues)
  58148. : PropertyComponent (name),
  58149. choices (choices_),
  58150. isCustomClass (false)
  58151. {
  58152. // The array of corresponding values must contain one value for each of the items in
  58153. // the choices array!
  58154. jassert (correspondingValues.size() == choices.size());
  58155. createComboBox();
  58156. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58157. }
  58158. ChoicePropertyComponent::~ChoicePropertyComponent()
  58159. {
  58160. }
  58161. void ChoicePropertyComponent::createComboBox()
  58162. {
  58163. addAndMakeVisible (&comboBox);
  58164. for (int i = 0; i < choices.size(); ++i)
  58165. {
  58166. if (choices[i].isNotEmpty())
  58167. comboBox.addItem (choices[i], i + 1);
  58168. else
  58169. comboBox.addSeparator();
  58170. }
  58171. comboBox.setEditableText (false);
  58172. }
  58173. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58174. {
  58175. jassertfalse; // you need to override this method in your subclass!
  58176. }
  58177. int ChoicePropertyComponent::getIndex() const
  58178. {
  58179. jassertfalse; // you need to override this method in your subclass!
  58180. return -1;
  58181. }
  58182. const StringArray& ChoicePropertyComponent::getChoices() const
  58183. {
  58184. return choices;
  58185. }
  58186. void ChoicePropertyComponent::refresh()
  58187. {
  58188. if (isCustomClass)
  58189. {
  58190. if (! comboBox.isVisible())
  58191. {
  58192. createComboBox();
  58193. comboBox.addListener (this);
  58194. }
  58195. comboBox.setSelectedId (getIndex() + 1, true);
  58196. }
  58197. }
  58198. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58199. {
  58200. if (isCustomClass)
  58201. {
  58202. const int newIndex = comboBox.getSelectedId() - 1;
  58203. if (newIndex != getIndex())
  58204. setIndex (newIndex);
  58205. }
  58206. }
  58207. END_JUCE_NAMESPACE
  58208. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58209. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58210. BEGIN_JUCE_NAMESPACE
  58211. PropertyComponent::PropertyComponent (const String& name,
  58212. const int preferredHeight_)
  58213. : Component (name),
  58214. preferredHeight (preferredHeight_)
  58215. {
  58216. jassert (name.isNotEmpty());
  58217. }
  58218. PropertyComponent::~PropertyComponent()
  58219. {
  58220. }
  58221. void PropertyComponent::paint (Graphics& g)
  58222. {
  58223. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58224. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58225. }
  58226. void PropertyComponent::resized()
  58227. {
  58228. if (getNumChildComponents() > 0)
  58229. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58230. }
  58231. void PropertyComponent::enablementChanged()
  58232. {
  58233. repaint();
  58234. }
  58235. END_JUCE_NAMESPACE
  58236. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58237. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58238. BEGIN_JUCE_NAMESPACE
  58239. class PropertyPanel::PropertyHolderComponent : public Component
  58240. {
  58241. public:
  58242. PropertyHolderComponent()
  58243. {
  58244. }
  58245. ~PropertyHolderComponent()
  58246. {
  58247. deleteAllChildren();
  58248. }
  58249. void paint (Graphics&)
  58250. {
  58251. }
  58252. void updateLayout (int width);
  58253. void refreshAll() const;
  58254. private:
  58255. PropertyHolderComponent (const PropertyHolderComponent&);
  58256. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58257. };
  58258. class PropertySectionComponent : public Component
  58259. {
  58260. public:
  58261. PropertySectionComponent (const String& sectionTitle,
  58262. const Array <PropertyComponent*>& newProperties,
  58263. const bool open)
  58264. : Component (sectionTitle),
  58265. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58266. isOpen_ (open)
  58267. {
  58268. for (int i = newProperties.size(); --i >= 0;)
  58269. {
  58270. addAndMakeVisible (newProperties.getUnchecked(i));
  58271. newProperties.getUnchecked(i)->refresh();
  58272. }
  58273. }
  58274. ~PropertySectionComponent()
  58275. {
  58276. deleteAllChildren();
  58277. }
  58278. void paint (Graphics& g)
  58279. {
  58280. if (titleHeight > 0)
  58281. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58282. }
  58283. void resized()
  58284. {
  58285. int y = titleHeight;
  58286. for (int i = getNumChildComponents(); --i >= 0;)
  58287. {
  58288. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58289. if (pec != 0)
  58290. {
  58291. const int prefH = pec->getPreferredHeight();
  58292. pec->setBounds (1, y, getWidth() - 2, prefH);
  58293. y += prefH;
  58294. }
  58295. }
  58296. }
  58297. int getPreferredHeight() const
  58298. {
  58299. int y = titleHeight;
  58300. if (isOpen())
  58301. {
  58302. for (int i = 0; i < getNumChildComponents(); ++i)
  58303. {
  58304. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58305. if (pec != 0)
  58306. y += pec->getPreferredHeight();
  58307. }
  58308. }
  58309. return y;
  58310. }
  58311. void setOpen (const bool open)
  58312. {
  58313. if (isOpen_ != open)
  58314. {
  58315. isOpen_ = open;
  58316. for (int i = 0; i < getNumChildComponents(); ++i)
  58317. {
  58318. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58319. if (pec != 0)
  58320. pec->setVisible (open);
  58321. }
  58322. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58323. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58324. if (pp != 0)
  58325. pp->resized();
  58326. }
  58327. }
  58328. bool isOpen() const
  58329. {
  58330. return isOpen_;
  58331. }
  58332. void refreshAll() const
  58333. {
  58334. for (int i = 0; i < getNumChildComponents(); ++i)
  58335. {
  58336. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58337. if (pec != 0)
  58338. pec->refresh();
  58339. }
  58340. }
  58341. void mouseDown (const MouseEvent&)
  58342. {
  58343. }
  58344. void mouseUp (const MouseEvent& e)
  58345. {
  58346. if (e.getMouseDownX() < titleHeight
  58347. && e.x < titleHeight
  58348. && e.y < titleHeight
  58349. && e.getNumberOfClicks() != 2)
  58350. {
  58351. setOpen (! isOpen());
  58352. }
  58353. }
  58354. void mouseDoubleClick (const MouseEvent& e)
  58355. {
  58356. if (e.y < titleHeight)
  58357. setOpen (! isOpen());
  58358. }
  58359. private:
  58360. int titleHeight;
  58361. bool isOpen_;
  58362. PropertySectionComponent (const PropertySectionComponent&);
  58363. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58364. };
  58365. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58366. {
  58367. int y = 0;
  58368. for (int i = getNumChildComponents(); --i >= 0;)
  58369. {
  58370. PropertySectionComponent* const section
  58371. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58372. if (section != 0)
  58373. {
  58374. const int prefH = section->getPreferredHeight();
  58375. section->setBounds (0, y, width, prefH);
  58376. y += prefH;
  58377. }
  58378. }
  58379. setSize (width, y);
  58380. repaint();
  58381. }
  58382. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58383. {
  58384. for (int i = getNumChildComponents(); --i >= 0;)
  58385. {
  58386. PropertySectionComponent* const section
  58387. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58388. if (section != 0)
  58389. section->refreshAll();
  58390. }
  58391. }
  58392. PropertyPanel::PropertyPanel()
  58393. {
  58394. messageWhenEmpty = TRANS("(nothing selected)");
  58395. addAndMakeVisible (&viewport);
  58396. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58397. viewport.setFocusContainer (true);
  58398. }
  58399. PropertyPanel::~PropertyPanel()
  58400. {
  58401. clear();
  58402. }
  58403. void PropertyPanel::paint (Graphics& g)
  58404. {
  58405. if (propertyHolderComponent->getNumChildComponents() == 0)
  58406. {
  58407. g.setColour (Colours::black.withAlpha (0.5f));
  58408. g.setFont (14.0f);
  58409. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58410. Justification::centred, true);
  58411. }
  58412. }
  58413. void PropertyPanel::resized()
  58414. {
  58415. viewport.setBounds (getLocalBounds());
  58416. updatePropHolderLayout();
  58417. }
  58418. void PropertyPanel::clear()
  58419. {
  58420. if (propertyHolderComponent->getNumChildComponents() > 0)
  58421. {
  58422. propertyHolderComponent->deleteAllChildren();
  58423. repaint();
  58424. }
  58425. }
  58426. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58427. {
  58428. if (propertyHolderComponent->getNumChildComponents() == 0)
  58429. repaint();
  58430. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58431. newProperties,
  58432. true), 0);
  58433. updatePropHolderLayout();
  58434. }
  58435. void PropertyPanel::addSection (const String& sectionTitle,
  58436. const Array <PropertyComponent*>& newProperties,
  58437. const bool shouldBeOpen)
  58438. {
  58439. jassert (sectionTitle.isNotEmpty());
  58440. if (propertyHolderComponent->getNumChildComponents() == 0)
  58441. repaint();
  58442. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58443. newProperties,
  58444. shouldBeOpen), 0);
  58445. updatePropHolderLayout();
  58446. }
  58447. void PropertyPanel::updatePropHolderLayout() const
  58448. {
  58449. const int maxWidth = viewport.getMaximumVisibleWidth();
  58450. propertyHolderComponent->updateLayout (maxWidth);
  58451. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58452. if (maxWidth != newMaxWidth)
  58453. {
  58454. // need to do this twice because of scrollbars changing the size, etc.
  58455. propertyHolderComponent->updateLayout (newMaxWidth);
  58456. }
  58457. }
  58458. void PropertyPanel::refreshAll() const
  58459. {
  58460. propertyHolderComponent->refreshAll();
  58461. }
  58462. const StringArray PropertyPanel::getSectionNames() const
  58463. {
  58464. StringArray s;
  58465. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58466. {
  58467. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58468. if (section != 0 && section->getName().isNotEmpty())
  58469. s.add (section->getName());
  58470. }
  58471. return s;
  58472. }
  58473. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58474. {
  58475. int index = 0;
  58476. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58477. {
  58478. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58479. if (section != 0 && section->getName().isNotEmpty())
  58480. {
  58481. if (index == sectionIndex)
  58482. return section->isOpen();
  58483. ++index;
  58484. }
  58485. }
  58486. return false;
  58487. }
  58488. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58489. {
  58490. int index = 0;
  58491. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58492. {
  58493. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58494. if (section != 0 && section->getName().isNotEmpty())
  58495. {
  58496. if (index == sectionIndex)
  58497. {
  58498. section->setOpen (shouldBeOpen);
  58499. break;
  58500. }
  58501. ++index;
  58502. }
  58503. }
  58504. }
  58505. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58506. {
  58507. int index = 0;
  58508. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58509. {
  58510. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58511. if (section != 0 && section->getName().isNotEmpty())
  58512. {
  58513. if (index == sectionIndex)
  58514. {
  58515. section->setEnabled (shouldBeEnabled);
  58516. break;
  58517. }
  58518. ++index;
  58519. }
  58520. }
  58521. }
  58522. XmlElement* PropertyPanel::getOpennessState() const
  58523. {
  58524. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58525. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58526. const StringArray sections (getSectionNames());
  58527. for (int i = 0; i < sections.size(); ++i)
  58528. {
  58529. if (sections[i].isNotEmpty())
  58530. {
  58531. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58532. e->setAttribute ("name", sections[i]);
  58533. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58534. }
  58535. }
  58536. return xml;
  58537. }
  58538. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58539. {
  58540. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58541. {
  58542. const StringArray sections (getSectionNames());
  58543. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58544. {
  58545. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58546. e->getBoolAttribute ("open"));
  58547. }
  58548. viewport.setViewPosition (viewport.getViewPositionX(),
  58549. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58550. }
  58551. }
  58552. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58553. {
  58554. if (messageWhenEmpty != newMessage)
  58555. {
  58556. messageWhenEmpty = newMessage;
  58557. repaint();
  58558. }
  58559. }
  58560. const String& PropertyPanel::getMessageWhenEmpty() const
  58561. {
  58562. return messageWhenEmpty;
  58563. }
  58564. END_JUCE_NAMESPACE
  58565. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58566. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58567. BEGIN_JUCE_NAMESPACE
  58568. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58569. const double rangeMin,
  58570. const double rangeMax,
  58571. const double interval,
  58572. const double skewFactor)
  58573. : PropertyComponent (name)
  58574. {
  58575. addAndMakeVisible (&slider);
  58576. slider.setRange (rangeMin, rangeMax, interval);
  58577. slider.setSkewFactor (skewFactor);
  58578. slider.setSliderStyle (Slider::LinearBar);
  58579. slider.addListener (this);
  58580. }
  58581. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58582. const String& name,
  58583. const double rangeMin,
  58584. const double rangeMax,
  58585. const double interval,
  58586. const double skewFactor)
  58587. : PropertyComponent (name)
  58588. {
  58589. addAndMakeVisible (&slider);
  58590. slider.setRange (rangeMin, rangeMax, interval);
  58591. slider.setSkewFactor (skewFactor);
  58592. slider.setSliderStyle (Slider::LinearBar);
  58593. slider.getValueObject().referTo (valueToControl);
  58594. }
  58595. SliderPropertyComponent::~SliderPropertyComponent()
  58596. {
  58597. }
  58598. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58599. {
  58600. }
  58601. double SliderPropertyComponent::getValue() const
  58602. {
  58603. return slider.getValue();
  58604. }
  58605. void SliderPropertyComponent::refresh()
  58606. {
  58607. slider.setValue (getValue(), false);
  58608. }
  58609. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58610. {
  58611. if (getValue() != slider.getValue())
  58612. setValue (slider.getValue());
  58613. }
  58614. END_JUCE_NAMESPACE
  58615. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58616. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58617. BEGIN_JUCE_NAMESPACE
  58618. class TextPropLabel : public Label
  58619. {
  58620. TextPropertyComponent& owner;
  58621. int maxChars;
  58622. bool isMultiline;
  58623. public:
  58624. TextPropLabel (TextPropertyComponent& owner_,
  58625. const int maxChars_, const bool isMultiline_)
  58626. : Label (String::empty, String::empty),
  58627. owner (owner_),
  58628. maxChars (maxChars_),
  58629. isMultiline (isMultiline_)
  58630. {
  58631. setEditable (true, true, false);
  58632. setColour (backgroundColourId, Colours::white);
  58633. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58634. }
  58635. ~TextPropLabel()
  58636. {
  58637. }
  58638. TextEditor* createEditorComponent()
  58639. {
  58640. TextEditor* const textEditor = Label::createEditorComponent();
  58641. textEditor->setInputRestrictions (maxChars);
  58642. if (isMultiline)
  58643. {
  58644. textEditor->setMultiLine (true, true);
  58645. textEditor->setReturnKeyStartsNewLine (true);
  58646. }
  58647. return textEditor;
  58648. }
  58649. void textWasEdited()
  58650. {
  58651. owner.textWasEdited();
  58652. }
  58653. };
  58654. TextPropertyComponent::TextPropertyComponent (const String& name,
  58655. const int maxNumChars,
  58656. const bool isMultiLine)
  58657. : PropertyComponent (name)
  58658. {
  58659. createEditor (maxNumChars, isMultiLine);
  58660. }
  58661. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58662. const String& name,
  58663. const int maxNumChars,
  58664. const bool isMultiLine)
  58665. : PropertyComponent (name)
  58666. {
  58667. createEditor (maxNumChars, isMultiLine);
  58668. textEditor->getTextValue().referTo (valueToControl);
  58669. }
  58670. TextPropertyComponent::~TextPropertyComponent()
  58671. {
  58672. deleteAllChildren();
  58673. }
  58674. void TextPropertyComponent::setText (const String& newText)
  58675. {
  58676. textEditor->setText (newText, true);
  58677. }
  58678. const String TextPropertyComponent::getText() const
  58679. {
  58680. return textEditor->getText();
  58681. }
  58682. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58683. {
  58684. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58685. if (isMultiLine)
  58686. {
  58687. textEditor->setJustificationType (Justification::topLeft);
  58688. preferredHeight = 120;
  58689. }
  58690. }
  58691. void TextPropertyComponent::refresh()
  58692. {
  58693. textEditor->setText (getText(), false);
  58694. }
  58695. void TextPropertyComponent::textWasEdited()
  58696. {
  58697. const String newText (textEditor->getText());
  58698. if (getText() != newText)
  58699. setText (newText);
  58700. }
  58701. END_JUCE_NAMESPACE
  58702. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58703. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58704. BEGIN_JUCE_NAMESPACE
  58705. class SimpleDeviceManagerInputLevelMeter : public Component,
  58706. public Timer
  58707. {
  58708. public:
  58709. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58710. : manager (manager_),
  58711. level (0)
  58712. {
  58713. startTimer (50);
  58714. manager->enableInputLevelMeasurement (true);
  58715. }
  58716. ~SimpleDeviceManagerInputLevelMeter()
  58717. {
  58718. manager->enableInputLevelMeasurement (false);
  58719. }
  58720. void timerCallback()
  58721. {
  58722. const float newLevel = (float) manager->getCurrentInputLevel();
  58723. if (std::abs (level - newLevel) > 0.005f)
  58724. {
  58725. level = newLevel;
  58726. repaint();
  58727. }
  58728. }
  58729. void paint (Graphics& g)
  58730. {
  58731. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58732. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58733. }
  58734. private:
  58735. AudioDeviceManager* const manager;
  58736. float level;
  58737. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58738. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58739. };
  58740. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58741. public ListBoxModel
  58742. {
  58743. public:
  58744. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58745. const String& noItemsMessage_,
  58746. const int minNumber_,
  58747. const int maxNumber_)
  58748. : ListBox (String::empty, 0),
  58749. deviceManager (deviceManager_),
  58750. noItemsMessage (noItemsMessage_),
  58751. minNumber (minNumber_),
  58752. maxNumber (maxNumber_)
  58753. {
  58754. items = MidiInput::getDevices();
  58755. setModel (this);
  58756. setOutlineThickness (1);
  58757. }
  58758. ~MidiInputSelectorComponentListBox()
  58759. {
  58760. }
  58761. int getNumRows()
  58762. {
  58763. return items.size();
  58764. }
  58765. void paintListBoxItem (int row,
  58766. Graphics& g,
  58767. int width, int height,
  58768. bool rowIsSelected)
  58769. {
  58770. if (((unsigned int) row) < (unsigned int) items.size())
  58771. {
  58772. if (rowIsSelected)
  58773. g.fillAll (findColour (TextEditor::highlightColourId)
  58774. .withMultipliedAlpha (0.3f));
  58775. const String item (items [row]);
  58776. bool enabled = deviceManager.isMidiInputEnabled (item);
  58777. const int x = getTickX();
  58778. const float tickW = height * 0.75f;
  58779. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58780. enabled, true, true, false);
  58781. g.setFont (height * 0.6f);
  58782. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58783. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58784. }
  58785. }
  58786. void listBoxItemClicked (int row, const MouseEvent& e)
  58787. {
  58788. selectRow (row);
  58789. if (e.x < getTickX())
  58790. flipEnablement (row);
  58791. }
  58792. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58793. {
  58794. flipEnablement (row);
  58795. }
  58796. void returnKeyPressed (int row)
  58797. {
  58798. flipEnablement (row);
  58799. }
  58800. void paint (Graphics& g)
  58801. {
  58802. ListBox::paint (g);
  58803. if (items.size() == 0)
  58804. {
  58805. g.setColour (Colours::grey);
  58806. g.setFont (13.0f);
  58807. g.drawText (noItemsMessage,
  58808. 0, 0, getWidth(), getHeight() / 2,
  58809. Justification::centred, true);
  58810. }
  58811. }
  58812. int getBestHeight (const int preferredHeight)
  58813. {
  58814. const int extra = getOutlineThickness() * 2;
  58815. return jmax (getRowHeight() * 2 + extra,
  58816. jmin (getRowHeight() * getNumRows() + extra,
  58817. preferredHeight));
  58818. }
  58819. juce_UseDebuggingNewOperator
  58820. private:
  58821. AudioDeviceManager& deviceManager;
  58822. const String noItemsMessage;
  58823. StringArray items;
  58824. int minNumber, maxNumber;
  58825. void flipEnablement (const int row)
  58826. {
  58827. if (((unsigned int) row) < (unsigned int) items.size())
  58828. {
  58829. const String item (items [row]);
  58830. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58831. }
  58832. }
  58833. int getTickX() const
  58834. {
  58835. return getRowHeight() + 5;
  58836. }
  58837. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58838. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58839. };
  58840. class AudioDeviceSettingsPanel : public Component,
  58841. public ChangeListener,
  58842. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58843. public ButtonListener
  58844. {
  58845. public:
  58846. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58847. AudioIODeviceType::DeviceSetupDetails& setup_,
  58848. const bool hideAdvancedOptionsWithButton)
  58849. : type (type_),
  58850. setup (setup_)
  58851. {
  58852. if (hideAdvancedOptionsWithButton)
  58853. {
  58854. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58855. showAdvancedSettingsButton->addButtonListener (this);
  58856. }
  58857. type->scanForDevices();
  58858. setup.manager->addChangeListener (this);
  58859. changeListenerCallback (0);
  58860. }
  58861. ~AudioDeviceSettingsPanel()
  58862. {
  58863. setup.manager->removeChangeListener (this);
  58864. }
  58865. void resized()
  58866. {
  58867. const int lx = proportionOfWidth (0.35f);
  58868. const int w = proportionOfWidth (0.4f);
  58869. const int h = 24;
  58870. const int space = 6;
  58871. const int dh = h + space;
  58872. int y = 0;
  58873. if (outputDeviceDropDown != 0)
  58874. {
  58875. outputDeviceDropDown->setBounds (lx, y, w, h);
  58876. if (testButton != 0)
  58877. testButton->setBounds (proportionOfWidth (0.77f),
  58878. outputDeviceDropDown->getY(),
  58879. proportionOfWidth (0.18f),
  58880. h);
  58881. y += dh;
  58882. }
  58883. if (inputDeviceDropDown != 0)
  58884. {
  58885. inputDeviceDropDown->setBounds (lx, y, w, h);
  58886. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58887. inputDeviceDropDown->getY(),
  58888. proportionOfWidth (0.18f),
  58889. h);
  58890. y += dh;
  58891. }
  58892. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58893. if (outputChanList != 0)
  58894. {
  58895. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58896. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58897. y += bh + space;
  58898. }
  58899. if (inputChanList != 0)
  58900. {
  58901. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58902. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58903. y += bh + space;
  58904. }
  58905. y += space * 2;
  58906. if (showAdvancedSettingsButton != 0)
  58907. {
  58908. showAdvancedSettingsButton->changeWidthToFitText (h);
  58909. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58910. }
  58911. if (sampleRateDropDown != 0)
  58912. {
  58913. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58914. || ! showAdvancedSettingsButton->isVisible());
  58915. sampleRateDropDown->setBounds (lx, y, w, h);
  58916. y += dh;
  58917. }
  58918. if (bufferSizeDropDown != 0)
  58919. {
  58920. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58921. || ! showAdvancedSettingsButton->isVisible());
  58922. bufferSizeDropDown->setBounds (lx, y, w, h);
  58923. y += dh;
  58924. }
  58925. if (showUIButton != 0)
  58926. {
  58927. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58928. || ! showAdvancedSettingsButton->isVisible());
  58929. showUIButton->changeWidthToFitText (h);
  58930. showUIButton->setTopLeftPosition (lx, y);
  58931. }
  58932. }
  58933. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58934. {
  58935. if (comboBoxThatHasChanged == 0)
  58936. return;
  58937. AudioDeviceManager::AudioDeviceSetup config;
  58938. setup.manager->getAudioDeviceSetup (config);
  58939. String error;
  58940. if (comboBoxThatHasChanged == outputDeviceDropDown
  58941. || comboBoxThatHasChanged == inputDeviceDropDown)
  58942. {
  58943. if (outputDeviceDropDown != 0)
  58944. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58945. : outputDeviceDropDown->getText();
  58946. if (inputDeviceDropDown != 0)
  58947. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58948. : inputDeviceDropDown->getText();
  58949. if (! type->hasSeparateInputsAndOutputs())
  58950. config.inputDeviceName = config.outputDeviceName;
  58951. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58952. config.useDefaultInputChannels = true;
  58953. else
  58954. config.useDefaultOutputChannels = true;
  58955. error = setup.manager->setAudioDeviceSetup (config, true);
  58956. showCorrectDeviceName (inputDeviceDropDown, true);
  58957. showCorrectDeviceName (outputDeviceDropDown, false);
  58958. updateControlPanelButton();
  58959. resized();
  58960. }
  58961. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58962. {
  58963. if (sampleRateDropDown->getSelectedId() > 0)
  58964. {
  58965. config.sampleRate = sampleRateDropDown->getSelectedId();
  58966. error = setup.manager->setAudioDeviceSetup (config, true);
  58967. }
  58968. }
  58969. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58970. {
  58971. if (bufferSizeDropDown->getSelectedId() > 0)
  58972. {
  58973. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58974. error = setup.manager->setAudioDeviceSetup (config, true);
  58975. }
  58976. }
  58977. if (error.isNotEmpty())
  58978. {
  58979. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58980. "Error when trying to open audio device!",
  58981. error);
  58982. }
  58983. }
  58984. void buttonClicked (Button* button)
  58985. {
  58986. if (button == showAdvancedSettingsButton)
  58987. {
  58988. showAdvancedSettingsButton->setVisible (false);
  58989. resized();
  58990. }
  58991. else if (button == showUIButton)
  58992. {
  58993. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58994. if (device != 0 && device->showControlPanel())
  58995. {
  58996. setup.manager->closeAudioDevice();
  58997. setup.manager->restartLastAudioDevice();
  58998. getTopLevelComponent()->toFront (true);
  58999. }
  59000. }
  59001. else if (button == testButton && testButton != 0)
  59002. {
  59003. setup.manager->playTestSound();
  59004. }
  59005. }
  59006. void updateControlPanelButton()
  59007. {
  59008. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59009. showUIButton = 0;
  59010. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59011. {
  59012. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59013. TRANS ("opens the device's own control panel")));
  59014. showUIButton->addButtonListener (this);
  59015. }
  59016. resized();
  59017. }
  59018. void changeListenerCallback (void*)
  59019. {
  59020. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59021. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59022. {
  59023. if (outputDeviceDropDown == 0)
  59024. {
  59025. outputDeviceDropDown = new ComboBox (String::empty);
  59026. outputDeviceDropDown->addListener (this);
  59027. addAndMakeVisible (outputDeviceDropDown);
  59028. outputDeviceLabel = new Label (String::empty,
  59029. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59030. : TRANS ("device:"));
  59031. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59032. if (setup.maxNumOutputChannels > 0)
  59033. {
  59034. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59035. testButton->addButtonListener (this);
  59036. }
  59037. }
  59038. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59039. }
  59040. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59041. {
  59042. if (inputDeviceDropDown == 0)
  59043. {
  59044. inputDeviceDropDown = new ComboBox (String::empty);
  59045. inputDeviceDropDown->addListener (this);
  59046. addAndMakeVisible (inputDeviceDropDown);
  59047. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59048. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59049. addAndMakeVisible (inputLevelMeter
  59050. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59051. }
  59052. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59053. }
  59054. updateControlPanelButton();
  59055. showCorrectDeviceName (inputDeviceDropDown, true);
  59056. showCorrectDeviceName (outputDeviceDropDown, false);
  59057. if (currentDevice != 0)
  59058. {
  59059. if (setup.maxNumOutputChannels > 0
  59060. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59061. {
  59062. if (outputChanList == 0)
  59063. {
  59064. addAndMakeVisible (outputChanList
  59065. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59066. TRANS ("(no audio output channels found)")));
  59067. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59068. outputChanLabel->attachToComponent (outputChanList, true);
  59069. }
  59070. outputChanList->refresh();
  59071. }
  59072. else
  59073. {
  59074. outputChanLabel = 0;
  59075. outputChanList = 0;
  59076. }
  59077. if (setup.maxNumInputChannels > 0
  59078. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59079. {
  59080. if (inputChanList == 0)
  59081. {
  59082. addAndMakeVisible (inputChanList
  59083. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59084. TRANS ("(no audio input channels found)")));
  59085. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59086. inputChanLabel->attachToComponent (inputChanList, true);
  59087. }
  59088. inputChanList->refresh();
  59089. }
  59090. else
  59091. {
  59092. inputChanLabel = 0;
  59093. inputChanList = 0;
  59094. }
  59095. // sample rate..
  59096. {
  59097. if (sampleRateDropDown == 0)
  59098. {
  59099. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59100. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59101. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59102. }
  59103. else
  59104. {
  59105. sampleRateDropDown->clear();
  59106. sampleRateDropDown->removeListener (this);
  59107. }
  59108. const int numRates = currentDevice->getNumSampleRates();
  59109. for (int i = 0; i < numRates; ++i)
  59110. {
  59111. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59112. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59113. }
  59114. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59115. sampleRateDropDown->addListener (this);
  59116. }
  59117. // buffer size
  59118. {
  59119. if (bufferSizeDropDown == 0)
  59120. {
  59121. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59122. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59123. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59124. }
  59125. else
  59126. {
  59127. bufferSizeDropDown->clear();
  59128. bufferSizeDropDown->removeListener (this);
  59129. }
  59130. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59131. double currentRate = currentDevice->getCurrentSampleRate();
  59132. if (currentRate == 0)
  59133. currentRate = 48000.0;
  59134. for (int i = 0; i < numBufferSizes; ++i)
  59135. {
  59136. const int bs = currentDevice->getBufferSizeSamples (i);
  59137. bufferSizeDropDown->addItem (String (bs)
  59138. + " samples ("
  59139. + String (bs * 1000.0 / currentRate, 1)
  59140. + " ms)",
  59141. bs);
  59142. }
  59143. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59144. bufferSizeDropDown->addListener (this);
  59145. }
  59146. }
  59147. else
  59148. {
  59149. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59150. sampleRateLabel = 0;
  59151. bufferSizeLabel = 0;
  59152. sampleRateDropDown = 0;
  59153. bufferSizeDropDown = 0;
  59154. if (outputDeviceDropDown != 0)
  59155. outputDeviceDropDown->setSelectedId (-1, true);
  59156. if (inputDeviceDropDown != 0)
  59157. inputDeviceDropDown->setSelectedId (-1, true);
  59158. }
  59159. resized();
  59160. setSize (getWidth(), getLowestY() + 4);
  59161. }
  59162. private:
  59163. AudioIODeviceType* const type;
  59164. const AudioIODeviceType::DeviceSetupDetails setup;
  59165. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59166. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59167. ScopedPointer<TextButton> testButton;
  59168. ScopedPointer<Component> inputLevelMeter;
  59169. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59170. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59171. {
  59172. if (box != 0)
  59173. {
  59174. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59175. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59176. box->setSelectedId (index + 1, true);
  59177. if (testButton != 0 && ! isInput)
  59178. testButton->setEnabled (index >= 0);
  59179. }
  59180. }
  59181. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59182. {
  59183. const StringArray devs (type->getDeviceNames (isInputs));
  59184. combo.clear (true);
  59185. for (int i = 0; i < devs.size(); ++i)
  59186. combo.addItem (devs[i], i + 1);
  59187. combo.addItem (TRANS("<< none >>"), -1);
  59188. combo.setSelectedId (-1, true);
  59189. }
  59190. int getLowestY() const
  59191. {
  59192. int y = 0;
  59193. for (int i = getNumChildComponents(); --i >= 0;)
  59194. y = jmax (y, getChildComponent (i)->getBottom());
  59195. return y;
  59196. }
  59197. public:
  59198. class ChannelSelectorListBox : public ListBox,
  59199. public ListBoxModel
  59200. {
  59201. public:
  59202. enum BoxType
  59203. {
  59204. audioInputType,
  59205. audioOutputType
  59206. };
  59207. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59208. const BoxType type_,
  59209. const String& noItemsMessage_)
  59210. : ListBox (String::empty, 0),
  59211. setup (setup_),
  59212. type (type_),
  59213. noItemsMessage (noItemsMessage_)
  59214. {
  59215. refresh();
  59216. setModel (this);
  59217. setOutlineThickness (1);
  59218. }
  59219. ~ChannelSelectorListBox()
  59220. {
  59221. }
  59222. void refresh()
  59223. {
  59224. items.clear();
  59225. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59226. if (currentDevice != 0)
  59227. {
  59228. if (type == audioInputType)
  59229. items = currentDevice->getInputChannelNames();
  59230. else if (type == audioOutputType)
  59231. items = currentDevice->getOutputChannelNames();
  59232. if (setup.useStereoPairs)
  59233. {
  59234. StringArray pairs;
  59235. for (int i = 0; i < items.size(); i += 2)
  59236. {
  59237. const String name (items[i]);
  59238. const String name2 (items[i + 1]);
  59239. String commonBit;
  59240. for (int j = 0; j < name.length(); ++j)
  59241. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59242. commonBit = name.substring (0, j);
  59243. // Make sure we only split the name at a space, because otherwise, things
  59244. // like "input 11" + "input 12" would become "input 11 + 2"
  59245. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59246. commonBit = commonBit.dropLastCharacters (1);
  59247. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59248. }
  59249. items = pairs;
  59250. }
  59251. }
  59252. updateContent();
  59253. repaint();
  59254. }
  59255. int getNumRows()
  59256. {
  59257. return items.size();
  59258. }
  59259. void paintListBoxItem (int row,
  59260. Graphics& g,
  59261. int width, int height,
  59262. bool rowIsSelected)
  59263. {
  59264. if (((unsigned int) row) < (unsigned int) items.size())
  59265. {
  59266. if (rowIsSelected)
  59267. g.fillAll (findColour (TextEditor::highlightColourId)
  59268. .withMultipliedAlpha (0.3f));
  59269. const String item (items [row]);
  59270. bool enabled = false;
  59271. AudioDeviceManager::AudioDeviceSetup config;
  59272. setup.manager->getAudioDeviceSetup (config);
  59273. if (setup.useStereoPairs)
  59274. {
  59275. if (type == audioInputType)
  59276. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59277. else if (type == audioOutputType)
  59278. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59279. }
  59280. else
  59281. {
  59282. if (type == audioInputType)
  59283. enabled = config.inputChannels [row];
  59284. else if (type == audioOutputType)
  59285. enabled = config.outputChannels [row];
  59286. }
  59287. const int x = getTickX();
  59288. const float tickW = height * 0.75f;
  59289. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59290. enabled, true, true, false);
  59291. g.setFont (height * 0.6f);
  59292. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59293. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59294. }
  59295. }
  59296. void listBoxItemClicked (int row, const MouseEvent& e)
  59297. {
  59298. selectRow (row);
  59299. if (e.x < getTickX())
  59300. flipEnablement (row);
  59301. }
  59302. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59303. {
  59304. flipEnablement (row);
  59305. }
  59306. void returnKeyPressed (int row)
  59307. {
  59308. flipEnablement (row);
  59309. }
  59310. void paint (Graphics& g)
  59311. {
  59312. ListBox::paint (g);
  59313. if (items.size() == 0)
  59314. {
  59315. g.setColour (Colours::grey);
  59316. g.setFont (13.0f);
  59317. g.drawText (noItemsMessage,
  59318. 0, 0, getWidth(), getHeight() / 2,
  59319. Justification::centred, true);
  59320. }
  59321. }
  59322. int getBestHeight (int maxHeight)
  59323. {
  59324. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59325. getNumRows())
  59326. + getOutlineThickness() * 2;
  59327. }
  59328. juce_UseDebuggingNewOperator
  59329. private:
  59330. const AudioIODeviceType::DeviceSetupDetails setup;
  59331. const BoxType type;
  59332. const String noItemsMessage;
  59333. StringArray items;
  59334. void flipEnablement (const int row)
  59335. {
  59336. jassert (type == audioInputType || type == audioOutputType);
  59337. if (((unsigned int) row) < (unsigned int) items.size())
  59338. {
  59339. AudioDeviceManager::AudioDeviceSetup config;
  59340. setup.manager->getAudioDeviceSetup (config);
  59341. if (setup.useStereoPairs)
  59342. {
  59343. BigInteger bits;
  59344. BigInteger& original = (type == audioInputType ? config.inputChannels
  59345. : config.outputChannels);
  59346. int i;
  59347. for (i = 0; i < 256; i += 2)
  59348. bits.setBit (i / 2, original [i] || original [i + 1]);
  59349. if (type == audioInputType)
  59350. {
  59351. config.useDefaultInputChannels = false;
  59352. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59353. }
  59354. else
  59355. {
  59356. config.useDefaultOutputChannels = false;
  59357. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59358. }
  59359. for (i = 0; i < 256; ++i)
  59360. original.setBit (i, bits [i / 2]);
  59361. }
  59362. else
  59363. {
  59364. if (type == audioInputType)
  59365. {
  59366. config.useDefaultInputChannels = false;
  59367. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59368. }
  59369. else
  59370. {
  59371. config.useDefaultOutputChannels = false;
  59372. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59373. }
  59374. }
  59375. String error (setup.manager->setAudioDeviceSetup (config, true));
  59376. if (! error.isEmpty())
  59377. {
  59378. //xxx
  59379. }
  59380. }
  59381. }
  59382. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59383. {
  59384. const int numActive = chans.countNumberOfSetBits();
  59385. if (chans [index])
  59386. {
  59387. if (numActive > minNumber)
  59388. chans.setBit (index, false);
  59389. }
  59390. else
  59391. {
  59392. if (numActive >= maxNumber)
  59393. {
  59394. const int firstActiveChan = chans.findNextSetBit();
  59395. chans.setBit (index > firstActiveChan
  59396. ? firstActiveChan : chans.getHighestBit(),
  59397. false);
  59398. }
  59399. chans.setBit (index, true);
  59400. }
  59401. }
  59402. int getTickX() const
  59403. {
  59404. return getRowHeight() + 5;
  59405. }
  59406. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59407. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59408. };
  59409. private:
  59410. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59411. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59412. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59413. };
  59414. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59415. const int minInputChannels_,
  59416. const int maxInputChannels_,
  59417. const int minOutputChannels_,
  59418. const int maxOutputChannels_,
  59419. const bool showMidiInputOptions,
  59420. const bool showMidiOutputSelector,
  59421. const bool showChannelsAsStereoPairs_,
  59422. const bool hideAdvancedOptionsWithButton_)
  59423. : deviceManager (deviceManager_),
  59424. deviceTypeDropDown (0),
  59425. deviceTypeDropDownLabel (0),
  59426. minOutputChannels (minOutputChannels_),
  59427. maxOutputChannels (maxOutputChannels_),
  59428. minInputChannels (minInputChannels_),
  59429. maxInputChannels (maxInputChannels_),
  59430. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59431. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59432. {
  59433. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59434. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59435. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59436. {
  59437. deviceTypeDropDown = new ComboBox (String::empty);
  59438. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59439. {
  59440. deviceTypeDropDown
  59441. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59442. i + 1);
  59443. }
  59444. addAndMakeVisible (deviceTypeDropDown);
  59445. deviceTypeDropDown->addListener (this);
  59446. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59447. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59448. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59449. }
  59450. if (showMidiInputOptions)
  59451. {
  59452. addAndMakeVisible (midiInputsList
  59453. = new MidiInputSelectorComponentListBox (deviceManager,
  59454. TRANS("(no midi inputs available)"),
  59455. 0, 0));
  59456. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59457. midiInputsLabel->setJustificationType (Justification::topRight);
  59458. midiInputsLabel->attachToComponent (midiInputsList, true);
  59459. }
  59460. else
  59461. {
  59462. midiInputsList = 0;
  59463. midiInputsLabel = 0;
  59464. }
  59465. if (showMidiOutputSelector)
  59466. {
  59467. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59468. midiOutputSelector->addListener (this);
  59469. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59470. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59471. }
  59472. else
  59473. {
  59474. midiOutputSelector = 0;
  59475. midiOutputLabel = 0;
  59476. }
  59477. deviceManager_.addChangeListener (this);
  59478. changeListenerCallback (0);
  59479. }
  59480. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59481. {
  59482. deviceManager.removeChangeListener (this);
  59483. }
  59484. void AudioDeviceSelectorComponent::resized()
  59485. {
  59486. const int lx = proportionOfWidth (0.35f);
  59487. const int w = proportionOfWidth (0.4f);
  59488. const int h = 24;
  59489. const int space = 6;
  59490. const int dh = h + space;
  59491. int y = 15;
  59492. if (deviceTypeDropDown != 0)
  59493. {
  59494. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59495. y += dh + space * 2;
  59496. }
  59497. if (audioDeviceSettingsComp != 0)
  59498. {
  59499. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59500. y += audioDeviceSettingsComp->getHeight() + space;
  59501. }
  59502. if (midiInputsList != 0)
  59503. {
  59504. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59505. midiInputsList->setBounds (lx, y, w, bh);
  59506. y += bh + space;
  59507. }
  59508. if (midiOutputSelector != 0)
  59509. midiOutputSelector->setBounds (lx, y, w, h);
  59510. }
  59511. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59512. {
  59513. if (child == audioDeviceSettingsComp)
  59514. resized();
  59515. }
  59516. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59517. {
  59518. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59519. if (device != 0 && device->hasControlPanel())
  59520. {
  59521. if (device->showControlPanel())
  59522. deviceManager.restartLastAudioDevice();
  59523. getTopLevelComponent()->toFront (true);
  59524. }
  59525. }
  59526. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59527. {
  59528. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59529. {
  59530. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59531. if (type != 0)
  59532. {
  59533. audioDeviceSettingsComp = 0;
  59534. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59535. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59536. }
  59537. }
  59538. else if (comboBoxThatHasChanged == midiOutputSelector)
  59539. {
  59540. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59541. }
  59542. }
  59543. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59544. {
  59545. if (deviceTypeDropDown != 0)
  59546. {
  59547. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59548. }
  59549. if (audioDeviceSettingsComp == 0
  59550. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59551. {
  59552. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59553. audioDeviceSettingsComp = 0;
  59554. AudioIODeviceType* const type
  59555. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59556. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59557. if (type != 0)
  59558. {
  59559. AudioIODeviceType::DeviceSetupDetails details;
  59560. details.manager = &deviceManager;
  59561. details.minNumInputChannels = minInputChannels;
  59562. details.maxNumInputChannels = maxInputChannels;
  59563. details.minNumOutputChannels = minOutputChannels;
  59564. details.maxNumOutputChannels = maxOutputChannels;
  59565. details.useStereoPairs = showChannelsAsStereoPairs;
  59566. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59567. if (audioDeviceSettingsComp != 0)
  59568. {
  59569. addAndMakeVisible (audioDeviceSettingsComp);
  59570. audioDeviceSettingsComp->resized();
  59571. }
  59572. }
  59573. }
  59574. if (midiInputsList != 0)
  59575. {
  59576. midiInputsList->updateContent();
  59577. midiInputsList->repaint();
  59578. }
  59579. if (midiOutputSelector != 0)
  59580. {
  59581. midiOutputSelector->clear();
  59582. const StringArray midiOuts (MidiOutput::getDevices());
  59583. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59584. midiOutputSelector->addSeparator();
  59585. for (int i = 0; i < midiOuts.size(); ++i)
  59586. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59587. int current = -1;
  59588. if (deviceManager.getDefaultMidiOutput() != 0)
  59589. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59590. midiOutputSelector->setSelectedId (current, true);
  59591. }
  59592. resized();
  59593. }
  59594. END_JUCE_NAMESPACE
  59595. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59596. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59597. BEGIN_JUCE_NAMESPACE
  59598. BubbleComponent::BubbleComponent()
  59599. : side (0),
  59600. allowablePlacements (above | below | left | right),
  59601. arrowTipX (0.0f),
  59602. arrowTipY (0.0f)
  59603. {
  59604. setInterceptsMouseClicks (false, false);
  59605. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59606. setComponentEffect (&shadow);
  59607. }
  59608. BubbleComponent::~BubbleComponent()
  59609. {
  59610. }
  59611. void BubbleComponent::paint (Graphics& g)
  59612. {
  59613. int x = content.getX();
  59614. int y = content.getY();
  59615. int w = content.getWidth();
  59616. int h = content.getHeight();
  59617. int cw, ch;
  59618. getContentSize (cw, ch);
  59619. if (side == 3)
  59620. x += w - cw;
  59621. else if (side != 1)
  59622. x += (w - cw) / 2;
  59623. w = cw;
  59624. if (side == 2)
  59625. y += h - ch;
  59626. else if (side != 0)
  59627. y += (h - ch) / 2;
  59628. h = ch;
  59629. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59630. (float) x, (float) y,
  59631. (float) w, (float) h);
  59632. const int cx = x + (w - cw) / 2;
  59633. const int cy = y + (h - ch) / 2;
  59634. const int indent = 3;
  59635. g.setOrigin (cx + indent, cy + indent);
  59636. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59637. paintContent (g, cw - indent * 2, ch - indent * 2);
  59638. }
  59639. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59640. {
  59641. allowablePlacements = newPlacement;
  59642. }
  59643. void BubbleComponent::setPosition (Component* componentToPointTo)
  59644. {
  59645. jassert (componentToPointTo->isValidComponent());
  59646. Point<int> pos;
  59647. if (getParentComponent() != 0)
  59648. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59649. else
  59650. pos = componentToPointTo->relativePositionToGlobal (pos);
  59651. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59652. }
  59653. void BubbleComponent::setPosition (const int arrowTipX_,
  59654. const int arrowTipY_)
  59655. {
  59656. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59657. }
  59658. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59659. {
  59660. Rectangle<int> availableSpace;
  59661. if (getParentComponent() != 0)
  59662. {
  59663. availableSpace.setSize (getParentComponent()->getWidth(),
  59664. getParentComponent()->getHeight());
  59665. }
  59666. else
  59667. {
  59668. availableSpace = getParentMonitorArea();
  59669. }
  59670. int x = 0;
  59671. int y = 0;
  59672. int w = 150;
  59673. int h = 30;
  59674. getContentSize (w, h);
  59675. w += 30;
  59676. h += 30;
  59677. const float edgeIndent = 2.0f;
  59678. const int arrowLength = jmin (10, h / 3, w / 3);
  59679. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59680. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59681. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59682. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59683. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59684. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59685. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59686. {
  59687. spaceLeft = spaceRight = 0;
  59688. }
  59689. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59690. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59691. {
  59692. spaceAbove = spaceBelow = 0;
  59693. }
  59694. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59695. {
  59696. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59697. arrowTipX = w * 0.5f;
  59698. content.setSize (w, h - arrowLength);
  59699. if (spaceAbove >= spaceBelow)
  59700. {
  59701. // above
  59702. y = rectangleToPointTo.getY() - h;
  59703. content.setPosition (0, 0);
  59704. arrowTipY = h - edgeIndent;
  59705. side = 2;
  59706. }
  59707. else
  59708. {
  59709. // below
  59710. y = rectangleToPointTo.getBottom();
  59711. content.setPosition (0, arrowLength);
  59712. arrowTipY = edgeIndent;
  59713. side = 0;
  59714. }
  59715. }
  59716. else
  59717. {
  59718. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59719. arrowTipY = h * 0.5f;
  59720. content.setSize (w - arrowLength, h);
  59721. if (spaceLeft > spaceRight)
  59722. {
  59723. // on the left
  59724. x = rectangleToPointTo.getX() - w;
  59725. content.setPosition (0, 0);
  59726. arrowTipX = w - edgeIndent;
  59727. side = 3;
  59728. }
  59729. else
  59730. {
  59731. // on the right
  59732. x = rectangleToPointTo.getRight();
  59733. content.setPosition (arrowLength, 0);
  59734. arrowTipX = edgeIndent;
  59735. side = 1;
  59736. }
  59737. }
  59738. setBounds (x, y, w, h);
  59739. }
  59740. END_JUCE_NAMESPACE
  59741. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59742. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59743. BEGIN_JUCE_NAMESPACE
  59744. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59745. : fadeOutLength (fadeOutLengthMs),
  59746. deleteAfterUse (false)
  59747. {
  59748. }
  59749. BubbleMessageComponent::~BubbleMessageComponent()
  59750. {
  59751. fadeOutComponent (fadeOutLength);
  59752. }
  59753. void BubbleMessageComponent::showAt (int x, int y,
  59754. const String& text,
  59755. const int numMillisecondsBeforeRemoving,
  59756. const bool removeWhenMouseClicked,
  59757. const bool deleteSelfAfterUse)
  59758. {
  59759. textLayout.clear();
  59760. textLayout.setText (text, Font (14.0f));
  59761. textLayout.layout (256, Justification::centredLeft, true);
  59762. setPosition (x, y);
  59763. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59764. }
  59765. void BubbleMessageComponent::showAt (Component* const component,
  59766. const String& text,
  59767. const int numMillisecondsBeforeRemoving,
  59768. const bool removeWhenMouseClicked,
  59769. const bool deleteSelfAfterUse)
  59770. {
  59771. textLayout.clear();
  59772. textLayout.setText (text, Font (14.0f));
  59773. textLayout.layout (256, Justification::centredLeft, true);
  59774. setPosition (component);
  59775. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59776. }
  59777. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59778. const bool removeWhenMouseClicked,
  59779. const bool deleteSelfAfterUse)
  59780. {
  59781. setVisible (true);
  59782. deleteAfterUse = deleteSelfAfterUse;
  59783. if (numMillisecondsBeforeRemoving > 0)
  59784. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59785. else
  59786. expiryTime = 0;
  59787. startTimer (77);
  59788. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59789. if (! (removeWhenMouseClicked && isShowing()))
  59790. mouseClickCounter += 0xfffff;
  59791. repaint();
  59792. }
  59793. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59794. {
  59795. w = textLayout.getWidth() + 16;
  59796. h = textLayout.getHeight() + 16;
  59797. }
  59798. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59799. {
  59800. g.setColour (findColour (TooltipWindow::textColourId));
  59801. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59802. }
  59803. void BubbleMessageComponent::timerCallback()
  59804. {
  59805. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59806. {
  59807. stopTimer();
  59808. setVisible (false);
  59809. if (deleteAfterUse)
  59810. delete this;
  59811. }
  59812. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59813. {
  59814. stopTimer();
  59815. fadeOutComponent (fadeOutLength);
  59816. if (deleteAfterUse)
  59817. delete this;
  59818. }
  59819. }
  59820. END_JUCE_NAMESPACE
  59821. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59822. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59823. BEGIN_JUCE_NAMESPACE
  59824. class ColourComponentSlider : public Slider
  59825. {
  59826. public:
  59827. ColourComponentSlider (const String& name)
  59828. : Slider (name)
  59829. {
  59830. setRange (0.0, 255.0, 1.0);
  59831. }
  59832. ~ColourComponentSlider()
  59833. {
  59834. }
  59835. const String getTextFromValue (double value)
  59836. {
  59837. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59838. }
  59839. double getValueFromText (const String& text)
  59840. {
  59841. return (double) text.getHexValue32();
  59842. }
  59843. private:
  59844. ColourComponentSlider (const ColourComponentSlider&);
  59845. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59846. };
  59847. class ColourSpaceMarker : public Component
  59848. {
  59849. public:
  59850. ColourSpaceMarker()
  59851. {
  59852. setInterceptsMouseClicks (false, false);
  59853. }
  59854. ~ColourSpaceMarker()
  59855. {
  59856. }
  59857. void paint (Graphics& g)
  59858. {
  59859. g.setColour (Colour::greyLevel (0.1f));
  59860. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59861. g.setColour (Colour::greyLevel (0.9f));
  59862. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59863. }
  59864. private:
  59865. ColourSpaceMarker (const ColourSpaceMarker&);
  59866. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59867. };
  59868. class ColourSelector::ColourSpaceView : public Component
  59869. {
  59870. public:
  59871. ColourSpaceView (ColourSelector* owner_,
  59872. float& h_, float& s_, float& v_,
  59873. const int edgeSize)
  59874. : owner (owner_),
  59875. h (h_), s (s_), v (v_),
  59876. lastHue (0.0f),
  59877. edge (edgeSize)
  59878. {
  59879. addAndMakeVisible (&marker);
  59880. setMouseCursor (MouseCursor::CrosshairCursor);
  59881. }
  59882. ~ColourSpaceView()
  59883. {
  59884. }
  59885. void paint (Graphics& g)
  59886. {
  59887. if (colours.isNull())
  59888. {
  59889. const int width = getWidth() / 2;
  59890. const int height = getHeight() / 2;
  59891. colours = Image (Image::RGB, width, height, false);
  59892. Image::BitmapData pixels (colours, true);
  59893. for (int y = 0; y < height; ++y)
  59894. {
  59895. const float val = 1.0f - y / (float) height;
  59896. for (int x = 0; x < width; ++x)
  59897. {
  59898. const float sat = x / (float) width;
  59899. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59900. }
  59901. }
  59902. }
  59903. g.setOpacity (1.0f);
  59904. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59905. 0, 0, colours.getWidth(), colours.getHeight());
  59906. }
  59907. void mouseDown (const MouseEvent& e)
  59908. {
  59909. mouseDrag (e);
  59910. }
  59911. void mouseDrag (const MouseEvent& e)
  59912. {
  59913. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59914. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59915. owner->setSV (sat, val);
  59916. }
  59917. void updateIfNeeded()
  59918. {
  59919. if (lastHue != h)
  59920. {
  59921. lastHue = h;
  59922. colours = Image::null;
  59923. repaint();
  59924. }
  59925. updateMarker();
  59926. }
  59927. void resized()
  59928. {
  59929. colours = Image::null;
  59930. updateMarker();
  59931. }
  59932. private:
  59933. ColourSelector* const owner;
  59934. float& h;
  59935. float& s;
  59936. float& v;
  59937. float lastHue;
  59938. ColourSpaceMarker marker;
  59939. const int edge;
  59940. Image colours;
  59941. void updateMarker()
  59942. {
  59943. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59944. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59945. edge * 2, edge * 2);
  59946. }
  59947. ColourSpaceView (const ColourSpaceView&);
  59948. ColourSpaceView& operator= (const ColourSpaceView&);
  59949. };
  59950. class HueSelectorMarker : public Component
  59951. {
  59952. public:
  59953. HueSelectorMarker()
  59954. {
  59955. setInterceptsMouseClicks (false, false);
  59956. }
  59957. ~HueSelectorMarker()
  59958. {
  59959. }
  59960. void paint (Graphics& g)
  59961. {
  59962. Path p;
  59963. p.addTriangle (1.0f, 1.0f,
  59964. getWidth() * 0.3f, getHeight() * 0.5f,
  59965. 1.0f, getHeight() - 1.0f);
  59966. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59967. getWidth() * 0.7f, getHeight() * 0.5f,
  59968. getWidth() - 1.0f, getHeight() - 1.0f);
  59969. g.setColour (Colours::white.withAlpha (0.75f));
  59970. g.fillPath (p);
  59971. g.setColour (Colours::black.withAlpha (0.75f));
  59972. g.strokePath (p, PathStrokeType (1.2f));
  59973. }
  59974. private:
  59975. HueSelectorMarker (const HueSelectorMarker&);
  59976. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59977. };
  59978. class ColourSelector::HueSelectorComp : public Component
  59979. {
  59980. public:
  59981. HueSelectorComp (ColourSelector* owner_,
  59982. float& h_, float& s_, float& v_,
  59983. const int edgeSize)
  59984. : owner (owner_),
  59985. h (h_), s (s_), v (v_),
  59986. lastHue (0.0f),
  59987. edge (edgeSize)
  59988. {
  59989. addAndMakeVisible (&marker);
  59990. }
  59991. ~HueSelectorComp()
  59992. {
  59993. }
  59994. void paint (Graphics& g)
  59995. {
  59996. const float yScale = 1.0f / (getHeight() - edge * 2);
  59997. const Rectangle<int> clip (g.getClipBounds());
  59998. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59999. {
  60000. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60001. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60002. }
  60003. }
  60004. void resized()
  60005. {
  60006. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60007. getWidth(), edge * 2);
  60008. }
  60009. void mouseDown (const MouseEvent& e)
  60010. {
  60011. mouseDrag (e);
  60012. }
  60013. void mouseDrag (const MouseEvent& e)
  60014. {
  60015. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60016. owner->setHue (hue);
  60017. }
  60018. void updateIfNeeded()
  60019. {
  60020. resized();
  60021. }
  60022. private:
  60023. ColourSelector* const owner;
  60024. float& h;
  60025. float& s;
  60026. float& v;
  60027. float lastHue;
  60028. HueSelectorMarker marker;
  60029. const int edge;
  60030. HueSelectorComp (const HueSelectorComp&);
  60031. HueSelectorComp& operator= (const HueSelectorComp&);
  60032. };
  60033. class ColourSelector::SwatchComponent : public Component
  60034. {
  60035. public:
  60036. SwatchComponent (ColourSelector* owner_, int index_)
  60037. : owner (owner_),
  60038. index (index_)
  60039. {
  60040. }
  60041. ~SwatchComponent()
  60042. {
  60043. }
  60044. void paint (Graphics& g)
  60045. {
  60046. const Colour colour (owner->getSwatchColour (index));
  60047. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60048. Colour (0xffdddddd).overlaidWith (colour),
  60049. Colour (0xffffffff).overlaidWith (colour));
  60050. }
  60051. void mouseDown (const MouseEvent&)
  60052. {
  60053. PopupMenu m;
  60054. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60055. m.addSeparator();
  60056. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60057. const int r = m.showAt (this);
  60058. if (r == 1)
  60059. {
  60060. owner->setCurrentColour (owner->getSwatchColour (index));
  60061. }
  60062. else if (r == 2)
  60063. {
  60064. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60065. {
  60066. owner->setSwatchColour (index, owner->getCurrentColour());
  60067. repaint();
  60068. }
  60069. }
  60070. }
  60071. private:
  60072. ColourSelector* const owner;
  60073. const int index;
  60074. SwatchComponent (const SwatchComponent&);
  60075. SwatchComponent& operator= (const SwatchComponent&);
  60076. };
  60077. ColourSelector::ColourSelector (const int flags_,
  60078. const int edgeGap_,
  60079. const int gapAroundColourSpaceComponent)
  60080. : colour (Colours::white),
  60081. colourSpace (0),
  60082. hueSelector (0),
  60083. flags (flags_),
  60084. edgeGap (edgeGap_)
  60085. {
  60086. // not much point having a selector with no components in it!
  60087. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60088. updateHSV();
  60089. if ((flags & showSliders) != 0)
  60090. {
  60091. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60092. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60093. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60094. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60095. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60096. for (int i = 4; --i >= 0;)
  60097. sliders[i]->addListener (this);
  60098. }
  60099. else
  60100. {
  60101. zeromem (sliders, sizeof (sliders));
  60102. }
  60103. if ((flags & showColourspace) != 0)
  60104. {
  60105. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60106. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60107. }
  60108. update();
  60109. }
  60110. ColourSelector::~ColourSelector()
  60111. {
  60112. dispatchPendingMessages();
  60113. swatchComponents.clear();
  60114. deleteAllChildren();
  60115. }
  60116. const Colour ColourSelector::getCurrentColour() const
  60117. {
  60118. return ((flags & showAlphaChannel) != 0) ? colour
  60119. : colour.withAlpha ((uint8) 0xff);
  60120. }
  60121. void ColourSelector::setCurrentColour (const Colour& c)
  60122. {
  60123. if (c != colour)
  60124. {
  60125. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60126. updateHSV();
  60127. update();
  60128. }
  60129. }
  60130. void ColourSelector::setHue (float newH)
  60131. {
  60132. newH = jlimit (0.0f, 1.0f, newH);
  60133. if (h != newH)
  60134. {
  60135. h = newH;
  60136. colour = Colour (h, s, v, colour.getFloatAlpha());
  60137. update();
  60138. }
  60139. }
  60140. void ColourSelector::setSV (float newS, float newV)
  60141. {
  60142. newS = jlimit (0.0f, 1.0f, newS);
  60143. newV = jlimit (0.0f, 1.0f, newV);
  60144. if (s != newS || v != newV)
  60145. {
  60146. s = newS;
  60147. v = newV;
  60148. colour = Colour (h, s, v, colour.getFloatAlpha());
  60149. update();
  60150. }
  60151. }
  60152. void ColourSelector::updateHSV()
  60153. {
  60154. colour.getHSB (h, s, v);
  60155. }
  60156. void ColourSelector::update()
  60157. {
  60158. if (sliders[0] != 0)
  60159. {
  60160. sliders[0]->setValue ((int) colour.getRed());
  60161. sliders[1]->setValue ((int) colour.getGreen());
  60162. sliders[2]->setValue ((int) colour.getBlue());
  60163. sliders[3]->setValue ((int) colour.getAlpha());
  60164. }
  60165. if (colourSpace != 0)
  60166. {
  60167. colourSpace->updateIfNeeded();
  60168. hueSelector->updateIfNeeded();
  60169. }
  60170. if ((flags & showColourAtTop) != 0)
  60171. repaint (previewArea);
  60172. sendChangeMessage (this);
  60173. }
  60174. void ColourSelector::paint (Graphics& g)
  60175. {
  60176. g.fillAll (findColour (backgroundColourId));
  60177. if ((flags & showColourAtTop) != 0)
  60178. {
  60179. const Colour currentColour (getCurrentColour());
  60180. g.fillCheckerBoard (previewArea, 10, 10,
  60181. Colour (0xffdddddd).overlaidWith (currentColour),
  60182. Colour (0xffffffff).overlaidWith (currentColour));
  60183. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60184. g.setFont (14.0f, true);
  60185. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60186. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60187. Justification::centred, false);
  60188. }
  60189. if ((flags & showSliders) != 0)
  60190. {
  60191. g.setColour (findColour (labelTextColourId));
  60192. g.setFont (11.0f);
  60193. for (int i = 4; --i >= 0;)
  60194. {
  60195. if (sliders[i]->isVisible())
  60196. g.drawText (sliders[i]->getName() + ":",
  60197. 0, sliders[i]->getY(),
  60198. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60199. Justification::centredRight, false);
  60200. }
  60201. }
  60202. }
  60203. void ColourSelector::resized()
  60204. {
  60205. const int swatchesPerRow = 8;
  60206. const int swatchHeight = 22;
  60207. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60208. const int numSwatches = getNumSwatches();
  60209. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60210. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60211. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60212. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60213. int y = topSpace;
  60214. if ((flags & showColourspace) != 0)
  60215. {
  60216. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60217. colourSpace->setBounds (edgeGap, y,
  60218. getWidth() - hueWidth - edgeGap - 4,
  60219. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60220. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60221. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60222. colourSpace->getHeight());
  60223. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60224. }
  60225. if ((flags & showSliders) != 0)
  60226. {
  60227. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60228. for (int i = 0; i < numSliders; ++i)
  60229. {
  60230. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60231. proportionOfWidth (0.72f), sliderHeight - 2);
  60232. y += sliderHeight;
  60233. }
  60234. }
  60235. if (numSwatches > 0)
  60236. {
  60237. const int startX = 8;
  60238. const int xGap = 4;
  60239. const int yGap = 4;
  60240. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60241. y += edgeGap;
  60242. if (swatchComponents.size() != numSwatches)
  60243. {
  60244. swatchComponents.clear();
  60245. for (int i = 0; i < numSwatches; ++i)
  60246. {
  60247. SwatchComponent* const sc = new SwatchComponent (this, i);
  60248. swatchComponents.add (sc);
  60249. addAndMakeVisible (sc);
  60250. }
  60251. }
  60252. int x = startX;
  60253. for (int i = 0; i < swatchComponents.size(); ++i)
  60254. {
  60255. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60256. sc->setBounds (x + xGap / 2,
  60257. y + yGap / 2,
  60258. swatchWidth - xGap,
  60259. swatchHeight - yGap);
  60260. if (((i + 1) % swatchesPerRow) == 0)
  60261. {
  60262. x = startX;
  60263. y += swatchHeight;
  60264. }
  60265. else
  60266. {
  60267. x += swatchWidth;
  60268. }
  60269. }
  60270. }
  60271. }
  60272. void ColourSelector::sliderValueChanged (Slider*)
  60273. {
  60274. if (sliders[0] != 0)
  60275. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60276. (uint8) sliders[1]->getValue(),
  60277. (uint8) sliders[2]->getValue(),
  60278. (uint8) sliders[3]->getValue()));
  60279. }
  60280. int ColourSelector::getNumSwatches() const
  60281. {
  60282. return 0;
  60283. }
  60284. const Colour ColourSelector::getSwatchColour (const int) const
  60285. {
  60286. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60287. return Colours::black;
  60288. }
  60289. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60290. {
  60291. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60292. }
  60293. END_JUCE_NAMESPACE
  60294. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60295. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60296. BEGIN_JUCE_NAMESPACE
  60297. class ShadowWindow : public Component
  60298. {
  60299. Component* owner;
  60300. Image shadowImageSections [12];
  60301. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60302. public:
  60303. ShadowWindow (Component* const owner_,
  60304. const int type_,
  60305. const Image shadowImageSections_ [12])
  60306. : owner (owner_),
  60307. type (type_)
  60308. {
  60309. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60310. shadowImageSections [i] = shadowImageSections_ [i];
  60311. setInterceptsMouseClicks (false, false);
  60312. if (owner_->isOnDesktop())
  60313. {
  60314. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60315. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60316. | ComponentPeer::windowIsTemporary
  60317. | ComponentPeer::windowIgnoresKeyPresses);
  60318. }
  60319. else if (owner_->getParentComponent() != 0)
  60320. {
  60321. owner_->getParentComponent()->addChildComponent (this);
  60322. }
  60323. }
  60324. ~ShadowWindow()
  60325. {
  60326. }
  60327. void paint (Graphics& g)
  60328. {
  60329. const Image& topLeft = shadowImageSections [type * 3];
  60330. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60331. const Image& filler = shadowImageSections [type * 3 + 2];
  60332. g.setOpacity (1.0f);
  60333. if (type < 2)
  60334. {
  60335. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60336. g.drawImage (topLeft,
  60337. 0, 0, topLeft.getWidth(), imH,
  60338. 0, 0, topLeft.getWidth(), imH);
  60339. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60340. g.drawImage (bottomRight,
  60341. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60342. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60343. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60344. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60345. }
  60346. else
  60347. {
  60348. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60349. g.drawImage (topLeft,
  60350. 0, 0, imW, topLeft.getHeight(),
  60351. 0, 0, imW, topLeft.getHeight());
  60352. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60353. g.drawImage (bottomRight,
  60354. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60355. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60356. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60357. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60358. }
  60359. }
  60360. void resized()
  60361. {
  60362. repaint(); // (needed for correct repainting)
  60363. }
  60364. private:
  60365. ShadowWindow (const ShadowWindow&);
  60366. ShadowWindow& operator= (const ShadowWindow&);
  60367. };
  60368. DropShadower::DropShadower (const float alpha_,
  60369. const int xOffset_,
  60370. const int yOffset_,
  60371. const float blurRadius_)
  60372. : owner (0),
  60373. numShadows (0),
  60374. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60375. xOffset (xOffset_),
  60376. yOffset (yOffset_),
  60377. alpha (alpha_),
  60378. blurRadius (blurRadius_),
  60379. inDestructor (false),
  60380. reentrant (false)
  60381. {
  60382. }
  60383. DropShadower::~DropShadower()
  60384. {
  60385. if (owner != 0)
  60386. owner->removeComponentListener (this);
  60387. inDestructor = true;
  60388. deleteShadowWindows();
  60389. }
  60390. void DropShadower::deleteShadowWindows()
  60391. {
  60392. if (numShadows > 0)
  60393. {
  60394. int i;
  60395. for (i = numShadows; --i >= 0;)
  60396. delete shadowWindows[i];
  60397. numShadows = 0;
  60398. }
  60399. }
  60400. void DropShadower::setOwner (Component* componentToFollow)
  60401. {
  60402. if (componentToFollow != owner)
  60403. {
  60404. if (owner != 0)
  60405. owner->removeComponentListener (this);
  60406. // (the component can't be null)
  60407. jassert (componentToFollow != 0);
  60408. owner = componentToFollow;
  60409. jassert (owner != 0);
  60410. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60411. owner->addComponentListener (this);
  60412. updateShadows();
  60413. }
  60414. }
  60415. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60416. {
  60417. updateShadows();
  60418. }
  60419. void DropShadower::componentBroughtToFront (Component&)
  60420. {
  60421. bringShadowWindowsToFront();
  60422. }
  60423. void DropShadower::componentChildrenChanged (Component&)
  60424. {
  60425. }
  60426. void DropShadower::componentParentHierarchyChanged (Component&)
  60427. {
  60428. deleteShadowWindows();
  60429. updateShadows();
  60430. }
  60431. void DropShadower::componentVisibilityChanged (Component&)
  60432. {
  60433. updateShadows();
  60434. }
  60435. void DropShadower::updateShadows()
  60436. {
  60437. if (reentrant || inDestructor || (owner == 0))
  60438. return;
  60439. reentrant = true;
  60440. ComponentPeer* const nw = owner->getPeer();
  60441. const bool isOwnerVisible = owner->isVisible()
  60442. && (nw == 0 || ! nw->isMinimised());
  60443. const bool createShadowWindows = numShadows == 0
  60444. && owner->getWidth() > 0
  60445. && owner->getHeight() > 0
  60446. && isOwnerVisible
  60447. && (Desktop::canUseSemiTransparentWindows()
  60448. || owner->getParentComponent() != 0);
  60449. if (createShadowWindows)
  60450. {
  60451. // keep a cached version of the image to save doing the gaussian too often
  60452. String imageId;
  60453. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60454. const int hash = imageId.hashCode();
  60455. Image bigIm (ImageCache::getFromHashCode (hash));
  60456. if (bigIm.isNull())
  60457. {
  60458. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60459. Graphics bigG (bigIm);
  60460. bigG.setColour (Colours::black.withAlpha (alpha));
  60461. bigG.fillRect (shadowEdge + xOffset,
  60462. shadowEdge + yOffset,
  60463. bigIm.getWidth() - (shadowEdge * 2),
  60464. bigIm.getHeight() - (shadowEdge * 2));
  60465. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60466. blurKernel.createGaussianBlur (blurRadius);
  60467. blurKernel.applyToImage (bigIm, bigIm,
  60468. Rectangle<int> (xOffset, yOffset,
  60469. bigIm.getWidth(), bigIm.getHeight()));
  60470. ImageCache::addImageToCache (bigIm, hash);
  60471. }
  60472. const int iw = bigIm.getWidth();
  60473. const int ih = bigIm.getHeight();
  60474. const int shadowEdge2 = shadowEdge * 2;
  60475. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60476. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60477. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60478. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60479. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60480. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60481. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60482. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60483. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60484. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60485. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60486. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60487. for (int i = 0; i < 4; ++i)
  60488. {
  60489. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60490. ++numShadows;
  60491. }
  60492. }
  60493. if (numShadows > 0)
  60494. {
  60495. for (int i = numShadows; --i >= 0;)
  60496. {
  60497. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60498. shadowWindows[i]->setVisible (isOwnerVisible);
  60499. }
  60500. const int x = owner->getX();
  60501. const int y = owner->getY() - shadowEdge;
  60502. const int w = owner->getWidth();
  60503. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60504. shadowWindows[0]->setBounds (x - shadowEdge,
  60505. y,
  60506. shadowEdge,
  60507. h);
  60508. shadowWindows[1]->setBounds (x + w,
  60509. y,
  60510. shadowEdge,
  60511. h);
  60512. shadowWindows[2]->setBounds (x,
  60513. y,
  60514. w,
  60515. shadowEdge);
  60516. shadowWindows[3]->setBounds (x,
  60517. owner->getBottom(),
  60518. w,
  60519. shadowEdge);
  60520. }
  60521. reentrant = false;
  60522. if (createShadowWindows)
  60523. bringShadowWindowsToFront();
  60524. }
  60525. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60526. const int sx, const int sy)
  60527. {
  60528. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60529. Graphics g (shadowImageSections[num]);
  60530. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60531. }
  60532. void DropShadower::bringShadowWindowsToFront()
  60533. {
  60534. if (! (inDestructor || reentrant))
  60535. {
  60536. updateShadows();
  60537. reentrant = true;
  60538. for (int i = numShadows; --i >= 0;)
  60539. shadowWindows[i]->toBehind (owner);
  60540. reentrant = false;
  60541. }
  60542. }
  60543. END_JUCE_NAMESPACE
  60544. /*** End of inlined file: juce_DropShadower.cpp ***/
  60545. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60546. BEGIN_JUCE_NAMESPACE
  60547. class MagnifyingPeer : public ComponentPeer
  60548. {
  60549. public:
  60550. MagnifyingPeer (Component* const component_,
  60551. MagnifierComponent* const magnifierComp_)
  60552. : ComponentPeer (component_, 0),
  60553. magnifierComp (magnifierComp_)
  60554. {
  60555. }
  60556. ~MagnifyingPeer()
  60557. {
  60558. }
  60559. void* getNativeHandle() const { return 0; }
  60560. void setVisible (bool) {}
  60561. void setTitle (const String&) {}
  60562. void setPosition (int, int) {}
  60563. void setSize (int, int) {}
  60564. void setBounds (int, int, int, int, bool) {}
  60565. void setMinimised (bool) {}
  60566. bool isMinimised() const { return false; }
  60567. void setFullScreen (bool) {}
  60568. bool isFullScreen() const { return false; }
  60569. const BorderSize getFrameSize() const { return BorderSize (0); }
  60570. bool setAlwaysOnTop (bool) { return true; }
  60571. void toFront (bool) {}
  60572. void toBehind (ComponentPeer*) {}
  60573. void setIcon (const Image&) {}
  60574. bool isFocused() const
  60575. {
  60576. return magnifierComp->hasKeyboardFocus (true);
  60577. }
  60578. void grabFocus()
  60579. {
  60580. ComponentPeer* peer = magnifierComp->getPeer();
  60581. if (peer != 0)
  60582. peer->grabFocus();
  60583. }
  60584. void textInputRequired (const Point<int>& position)
  60585. {
  60586. ComponentPeer* peer = magnifierComp->getPeer();
  60587. if (peer != 0)
  60588. peer->textInputRequired (position);
  60589. }
  60590. const Rectangle<int> getBounds() const
  60591. {
  60592. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60593. component->getWidth(), component->getHeight());
  60594. }
  60595. const Point<int> getScreenPosition() const
  60596. {
  60597. return magnifierComp->getScreenPosition();
  60598. }
  60599. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60600. {
  60601. const double zoom = magnifierComp->getScaleFactor();
  60602. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60603. roundToInt (relativePosition.getY() * zoom)));
  60604. }
  60605. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60606. {
  60607. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60608. const double zoom = magnifierComp->getScaleFactor();
  60609. return Point<int> (roundToInt (p.getX() / zoom),
  60610. roundToInt (p.getY() / zoom));
  60611. }
  60612. bool contains (const Point<int>& position, bool) const
  60613. {
  60614. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60615. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60616. }
  60617. void repaint (const Rectangle<int>& area)
  60618. {
  60619. const double zoom = magnifierComp->getScaleFactor();
  60620. magnifierComp->repaint ((int) (area.getX() * zoom),
  60621. (int) (area.getY() * zoom),
  60622. roundToInt (area.getWidth() * zoom) + 1,
  60623. roundToInt (area.getHeight() * zoom) + 1);
  60624. }
  60625. void performAnyPendingRepaintsNow()
  60626. {
  60627. }
  60628. juce_UseDebuggingNewOperator
  60629. private:
  60630. MagnifierComponent* const magnifierComp;
  60631. MagnifyingPeer (const MagnifyingPeer&);
  60632. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60633. };
  60634. class PeerHolderComp : public Component
  60635. {
  60636. public:
  60637. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60638. : magnifierComp (magnifierComp_)
  60639. {
  60640. setVisible (true);
  60641. }
  60642. ~PeerHolderComp()
  60643. {
  60644. }
  60645. ComponentPeer* createNewPeer (int, void*)
  60646. {
  60647. return new MagnifyingPeer (this, magnifierComp);
  60648. }
  60649. void childBoundsChanged (Component* c)
  60650. {
  60651. if (c != 0)
  60652. {
  60653. setSize (c->getWidth(), c->getHeight());
  60654. magnifierComp->childBoundsChanged (this);
  60655. }
  60656. }
  60657. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60658. {
  60659. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60660. Component* const p = magnifierComp->getParentComponent();
  60661. if (p != 0)
  60662. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60663. }
  60664. private:
  60665. MagnifierComponent* const magnifierComp;
  60666. PeerHolderComp (const PeerHolderComp&);
  60667. PeerHolderComp& operator= (const PeerHolderComp&);
  60668. };
  60669. MagnifierComponent::MagnifierComponent (Component* const content_,
  60670. const bool deleteContentCompWhenNoLongerNeeded)
  60671. : content (content_),
  60672. scaleFactor (0.0),
  60673. peer (0),
  60674. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60675. quality (Graphics::lowResamplingQuality),
  60676. mouseSource (0, true)
  60677. {
  60678. holderComp = new PeerHolderComp (this);
  60679. setScaleFactor (1.0);
  60680. }
  60681. MagnifierComponent::~MagnifierComponent()
  60682. {
  60683. delete holderComp;
  60684. if (deleteContent)
  60685. delete content;
  60686. }
  60687. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60688. {
  60689. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60690. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60691. if (scaleFactor != newScaleFactor)
  60692. {
  60693. scaleFactor = newScaleFactor;
  60694. if (scaleFactor == 1.0)
  60695. {
  60696. holderComp->removeFromDesktop();
  60697. peer = 0;
  60698. addChildComponent (content);
  60699. childBoundsChanged (content);
  60700. }
  60701. else
  60702. {
  60703. holderComp->addAndMakeVisible (content);
  60704. holderComp->childBoundsChanged (content);
  60705. childBoundsChanged (holderComp);
  60706. holderComp->addToDesktop (0);
  60707. peer = holderComp->getPeer();
  60708. }
  60709. repaint();
  60710. }
  60711. }
  60712. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60713. {
  60714. quality = newQuality;
  60715. }
  60716. void MagnifierComponent::paint (Graphics& g)
  60717. {
  60718. const int w = holderComp->getWidth();
  60719. const int h = holderComp->getHeight();
  60720. if (w == 0 || h == 0)
  60721. return;
  60722. const Rectangle<int> r (g.getClipBounds());
  60723. const int srcX = (int) (r.getX() / scaleFactor);
  60724. const int srcY = (int) (r.getY() / scaleFactor);
  60725. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60726. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60727. if (scaleFactor >= 1.0)
  60728. {
  60729. ++srcW;
  60730. ++srcH;
  60731. }
  60732. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60733. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60734. {
  60735. Graphics g2 (temp);
  60736. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60737. holderComp->paintEntireComponent (g2);
  60738. }
  60739. g.setImageResamplingQuality (quality);
  60740. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60741. }
  60742. void MagnifierComponent::childBoundsChanged (Component* c)
  60743. {
  60744. if (c != 0)
  60745. setSize (roundToInt (c->getWidth() * scaleFactor),
  60746. roundToInt (c->getHeight() * scaleFactor));
  60747. }
  60748. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60749. {
  60750. if (peer != 0)
  60751. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60752. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60753. }
  60754. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60755. {
  60756. passOnMouseEventToPeer (e);
  60757. }
  60758. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60759. {
  60760. passOnMouseEventToPeer (e);
  60761. }
  60762. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60763. {
  60764. passOnMouseEventToPeer (e);
  60765. }
  60766. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60767. {
  60768. passOnMouseEventToPeer (e);
  60769. }
  60770. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60771. {
  60772. passOnMouseEventToPeer (e);
  60773. }
  60774. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60775. {
  60776. passOnMouseEventToPeer (e);
  60777. }
  60778. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60779. {
  60780. if (peer != 0)
  60781. peer->handleMouseWheel (e.source.getIndex(),
  60782. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60783. ix * 256.0f, iy * 256.0f);
  60784. else
  60785. Component::mouseWheelMove (e, ix, iy);
  60786. }
  60787. int MagnifierComponent::scaleInt (const int n) const
  60788. {
  60789. return roundToInt (n / scaleFactor);
  60790. }
  60791. END_JUCE_NAMESPACE
  60792. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60793. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60794. BEGIN_JUCE_NAMESPACE
  60795. class MidiKeyboardUpDownButton : public Button
  60796. {
  60797. public:
  60798. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60799. const int delta_)
  60800. : Button (String::empty),
  60801. owner (owner_),
  60802. delta (delta_)
  60803. {
  60804. setOpaque (true);
  60805. }
  60806. ~MidiKeyboardUpDownButton()
  60807. {
  60808. }
  60809. void clicked()
  60810. {
  60811. int note = owner->getLowestVisibleKey();
  60812. if (delta < 0)
  60813. note = (note - 1) / 12;
  60814. else
  60815. note = note / 12 + 1;
  60816. owner->setLowestVisibleKey (note * 12);
  60817. }
  60818. void paintButton (Graphics& g,
  60819. bool isMouseOverButton,
  60820. bool isButtonDown)
  60821. {
  60822. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60823. isMouseOverButton, isButtonDown,
  60824. delta > 0);
  60825. }
  60826. private:
  60827. MidiKeyboardComponent* const owner;
  60828. const int delta;
  60829. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60830. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60831. };
  60832. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60833. const Orientation orientation_)
  60834. : state (state_),
  60835. xOffset (0),
  60836. blackNoteLength (1),
  60837. keyWidth (16.0f),
  60838. orientation (orientation_),
  60839. midiChannel (1),
  60840. midiInChannelMask (0xffff),
  60841. velocity (1.0f),
  60842. noteUnderMouse (-1),
  60843. mouseDownNote (-1),
  60844. rangeStart (0),
  60845. rangeEnd (127),
  60846. firstKey (12 * 4),
  60847. canScroll (true),
  60848. mouseDragging (false),
  60849. useMousePositionForVelocity (true),
  60850. keyMappingOctave (6),
  60851. octaveNumForMiddleC (3)
  60852. {
  60853. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60854. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60855. // initialise with a default set of querty key-mappings..
  60856. const char* const keymap = "awsedftgyhujkolp;";
  60857. for (int i = String (keymap).length(); --i >= 0;)
  60858. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60859. setOpaque (true);
  60860. setWantsKeyboardFocus (true);
  60861. state.addListener (this);
  60862. }
  60863. MidiKeyboardComponent::~MidiKeyboardComponent()
  60864. {
  60865. state.removeListener (this);
  60866. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60867. deleteAllChildren();
  60868. }
  60869. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60870. {
  60871. keyWidth = widthInPixels;
  60872. resized();
  60873. }
  60874. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60875. {
  60876. if (orientation != newOrientation)
  60877. {
  60878. orientation = newOrientation;
  60879. resized();
  60880. }
  60881. }
  60882. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60883. const int highestNote)
  60884. {
  60885. jassert (lowestNote >= 0 && lowestNote <= 127);
  60886. jassert (highestNote >= 0 && highestNote <= 127);
  60887. jassert (lowestNote <= highestNote);
  60888. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60889. {
  60890. rangeStart = jlimit (0, 127, lowestNote);
  60891. rangeEnd = jlimit (0, 127, highestNote);
  60892. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60893. resized();
  60894. }
  60895. }
  60896. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60897. {
  60898. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60899. if (noteNumber != firstKey)
  60900. {
  60901. firstKey = noteNumber;
  60902. sendChangeMessage (this);
  60903. resized();
  60904. }
  60905. }
  60906. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60907. {
  60908. if (canScroll != canScroll_)
  60909. {
  60910. canScroll = canScroll_;
  60911. resized();
  60912. }
  60913. }
  60914. void MidiKeyboardComponent::colourChanged()
  60915. {
  60916. repaint();
  60917. }
  60918. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60919. {
  60920. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60921. if (midiChannel != midiChannelNumber)
  60922. {
  60923. resetAnyKeysInUse();
  60924. midiChannel = jlimit (1, 16, midiChannelNumber);
  60925. }
  60926. }
  60927. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60928. {
  60929. midiInChannelMask = midiChannelMask;
  60930. triggerAsyncUpdate();
  60931. }
  60932. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60933. {
  60934. velocity = jlimit (0.0f, 1.0f, velocity_);
  60935. useMousePositionForVelocity = useMousePositionForVelocity_;
  60936. }
  60937. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60938. {
  60939. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60940. static const float blackNoteWidth = 0.7f;
  60941. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60942. 1.0f, 2 - blackNoteWidth * 0.4f,
  60943. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60944. 4.0f, 5 - blackNoteWidth * 0.5f,
  60945. 5.0f, 6 - blackNoteWidth * 0.3f,
  60946. 6.0f };
  60947. static const float widths[] = { 1.0f, blackNoteWidth,
  60948. 1.0f, blackNoteWidth,
  60949. 1.0f, 1.0f, blackNoteWidth,
  60950. 1.0f, blackNoteWidth,
  60951. 1.0f, blackNoteWidth,
  60952. 1.0f };
  60953. const int octave = midiNoteNumber / 12;
  60954. const int note = midiNoteNumber % 12;
  60955. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60956. w = roundToInt (widths [note] * keyWidth_);
  60957. }
  60958. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60959. {
  60960. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60961. int rx, rw;
  60962. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60963. x -= xOffset + rx;
  60964. }
  60965. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60966. {
  60967. int x, y;
  60968. getKeyPos (midiNoteNumber, x, y);
  60969. return x;
  60970. }
  60971. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60972. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60973. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60974. {
  60975. if (! reallyContains (pos.getX(), pos.getY(), false))
  60976. return -1;
  60977. Point<int> p (pos);
  60978. if (orientation != horizontalKeyboard)
  60979. {
  60980. p = Point<int> (p.getY(), p.getX());
  60981. if (orientation == verticalKeyboardFacingLeft)
  60982. p = Point<int> (p.getX(), getWidth() - p.getY());
  60983. else
  60984. p = Point<int> (getHeight() - p.getX(), p.getY());
  60985. }
  60986. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60987. }
  60988. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60989. {
  60990. if (pos.getY() < blackNoteLength)
  60991. {
  60992. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60993. {
  60994. for (int i = 0; i < 5; ++i)
  60995. {
  60996. const int note = octaveStart + blackNotes [i];
  60997. if (note >= rangeStart && note <= rangeEnd)
  60998. {
  60999. int kx, kw;
  61000. getKeyPos (note, kx, kw);
  61001. kx += xOffset;
  61002. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61003. {
  61004. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61005. return note;
  61006. }
  61007. }
  61008. }
  61009. }
  61010. }
  61011. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61012. {
  61013. for (int i = 0; i < 7; ++i)
  61014. {
  61015. const int note = octaveStart + whiteNotes [i];
  61016. if (note >= rangeStart && note <= rangeEnd)
  61017. {
  61018. int kx, kw;
  61019. getKeyPos (note, kx, kw);
  61020. kx += xOffset;
  61021. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61022. {
  61023. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61024. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61025. return note;
  61026. }
  61027. }
  61028. }
  61029. }
  61030. mousePositionVelocity = 0;
  61031. return -1;
  61032. }
  61033. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61034. {
  61035. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61036. {
  61037. int x, w;
  61038. getKeyPos (noteNum, x, w);
  61039. if (orientation == horizontalKeyboard)
  61040. repaint (x, 0, w, getHeight());
  61041. else if (orientation == verticalKeyboardFacingLeft)
  61042. repaint (0, x, getWidth(), w);
  61043. else if (orientation == verticalKeyboardFacingRight)
  61044. repaint (0, getHeight() - x - w, getWidth(), w);
  61045. }
  61046. }
  61047. void MidiKeyboardComponent::paint (Graphics& g)
  61048. {
  61049. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61050. const Colour lineColour (findColour (keySeparatorLineColourId));
  61051. const Colour textColour (findColour (textLabelColourId));
  61052. int x, w, octave;
  61053. for (octave = 0; octave < 128; octave += 12)
  61054. {
  61055. for (int white = 0; white < 7; ++white)
  61056. {
  61057. const int noteNum = octave + whiteNotes [white];
  61058. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61059. {
  61060. getKeyPos (noteNum, x, w);
  61061. if (orientation == horizontalKeyboard)
  61062. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61063. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61064. noteUnderMouse == noteNum,
  61065. lineColour, textColour);
  61066. else if (orientation == verticalKeyboardFacingLeft)
  61067. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61068. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61069. noteUnderMouse == noteNum,
  61070. lineColour, textColour);
  61071. else if (orientation == verticalKeyboardFacingRight)
  61072. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61073. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61074. noteUnderMouse == noteNum,
  61075. lineColour, textColour);
  61076. }
  61077. }
  61078. }
  61079. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61080. if (orientation == verticalKeyboardFacingLeft)
  61081. {
  61082. x1 = getWidth() - 1.0f;
  61083. x2 = getWidth() - 5.0f;
  61084. }
  61085. else if (orientation == verticalKeyboardFacingRight)
  61086. x2 = 5.0f;
  61087. else
  61088. y2 = 5.0f;
  61089. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61090. Colours::transparentBlack, x2, y2, false));
  61091. getKeyPos (rangeEnd, x, w);
  61092. x += w;
  61093. if (orientation == verticalKeyboardFacingLeft)
  61094. g.fillRect (getWidth() - 5, 0, 5, x);
  61095. else if (orientation == verticalKeyboardFacingRight)
  61096. g.fillRect (0, 0, 5, x);
  61097. else
  61098. g.fillRect (0, 0, x, 5);
  61099. g.setColour (lineColour);
  61100. if (orientation == verticalKeyboardFacingLeft)
  61101. g.fillRect (0, 0, 1, x);
  61102. else if (orientation == verticalKeyboardFacingRight)
  61103. g.fillRect (getWidth() - 1, 0, 1, x);
  61104. else
  61105. g.fillRect (0, getHeight() - 1, x, 1);
  61106. const Colour blackNoteColour (findColour (blackNoteColourId));
  61107. for (octave = 0; octave < 128; octave += 12)
  61108. {
  61109. for (int black = 0; black < 5; ++black)
  61110. {
  61111. const int noteNum = octave + blackNotes [black];
  61112. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61113. {
  61114. getKeyPos (noteNum, x, w);
  61115. if (orientation == horizontalKeyboard)
  61116. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61117. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61118. noteUnderMouse == noteNum,
  61119. blackNoteColour);
  61120. else if (orientation == verticalKeyboardFacingLeft)
  61121. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61122. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61123. noteUnderMouse == noteNum,
  61124. blackNoteColour);
  61125. else if (orientation == verticalKeyboardFacingRight)
  61126. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61127. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61128. noteUnderMouse == noteNum,
  61129. blackNoteColour);
  61130. }
  61131. }
  61132. }
  61133. }
  61134. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61135. Graphics& g, int x, int y, int w, int h,
  61136. bool isDown, bool isOver,
  61137. const Colour& lineColour,
  61138. const Colour& textColour)
  61139. {
  61140. Colour c (Colours::transparentWhite);
  61141. if (isDown)
  61142. c = findColour (keyDownOverlayColourId);
  61143. if (isOver)
  61144. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61145. g.setColour (c);
  61146. g.fillRect (x, y, w, h);
  61147. const String text (getWhiteNoteText (midiNoteNumber));
  61148. if (! text.isEmpty())
  61149. {
  61150. g.setColour (textColour);
  61151. Font f (jmin (12.0f, keyWidth * 0.9f));
  61152. f.setHorizontalScale (0.8f);
  61153. g.setFont (f);
  61154. Justification justification (Justification::centredBottom);
  61155. if (orientation == verticalKeyboardFacingLeft)
  61156. justification = Justification::centredLeft;
  61157. else if (orientation == verticalKeyboardFacingRight)
  61158. justification = Justification::centredRight;
  61159. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61160. }
  61161. g.setColour (lineColour);
  61162. if (orientation == horizontalKeyboard)
  61163. g.fillRect (x, y, 1, h);
  61164. else if (orientation == verticalKeyboardFacingLeft)
  61165. g.fillRect (x, y, w, 1);
  61166. else if (orientation == verticalKeyboardFacingRight)
  61167. g.fillRect (x, y + h - 1, w, 1);
  61168. if (midiNoteNumber == rangeEnd)
  61169. {
  61170. if (orientation == horizontalKeyboard)
  61171. g.fillRect (x + w, y, 1, h);
  61172. else if (orientation == verticalKeyboardFacingLeft)
  61173. g.fillRect (x, y + h, w, 1);
  61174. else if (orientation == verticalKeyboardFacingRight)
  61175. g.fillRect (x, y - 1, w, 1);
  61176. }
  61177. }
  61178. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61179. Graphics& g, int x, int y, int w, int h,
  61180. bool isDown, bool isOver,
  61181. const Colour& noteFillColour)
  61182. {
  61183. Colour c (noteFillColour);
  61184. if (isDown)
  61185. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61186. if (isOver)
  61187. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61188. g.setColour (c);
  61189. g.fillRect (x, y, w, h);
  61190. if (isDown)
  61191. {
  61192. g.setColour (noteFillColour);
  61193. g.drawRect (x, y, w, h);
  61194. }
  61195. else
  61196. {
  61197. const int xIndent = jmax (1, jmin (w, h) / 8);
  61198. g.setColour (c.brighter());
  61199. if (orientation == horizontalKeyboard)
  61200. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61201. else if (orientation == verticalKeyboardFacingLeft)
  61202. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61203. else if (orientation == verticalKeyboardFacingRight)
  61204. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61205. }
  61206. }
  61207. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61208. {
  61209. octaveNumForMiddleC = octaveNumForMiddleC_;
  61210. repaint();
  61211. }
  61212. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61213. {
  61214. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61215. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61216. return String::empty;
  61217. }
  61218. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61219. const bool isMouseOver_,
  61220. const bool isButtonDown,
  61221. const bool movesOctavesUp)
  61222. {
  61223. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61224. float angle;
  61225. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61226. angle = movesOctavesUp ? 0.0f : 0.5f;
  61227. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61228. angle = movesOctavesUp ? 0.25f : 0.75f;
  61229. else
  61230. angle = movesOctavesUp ? 0.75f : 0.25f;
  61231. Path path;
  61232. path.lineTo (0.0f, 1.0f);
  61233. path.lineTo (1.0f, 0.5f);
  61234. path.closeSubPath();
  61235. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61236. g.setColour (findColour (upDownButtonArrowColourId)
  61237. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61238. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61239. w - 2.0f,
  61240. h - 2.0f,
  61241. true));
  61242. }
  61243. void MidiKeyboardComponent::resized()
  61244. {
  61245. int w = getWidth();
  61246. int h = getHeight();
  61247. if (w > 0 && h > 0)
  61248. {
  61249. if (orientation != horizontalKeyboard)
  61250. swapVariables (w, h);
  61251. blackNoteLength = roundToInt (h * 0.7f);
  61252. int kx2, kw2;
  61253. getKeyPos (rangeEnd, kx2, kw2);
  61254. kx2 += kw2;
  61255. if (firstKey != rangeStart)
  61256. {
  61257. int kx1, kw1;
  61258. getKeyPos (rangeStart, kx1, kw1);
  61259. if (kx2 - kx1 <= w)
  61260. {
  61261. firstKey = rangeStart;
  61262. sendChangeMessage (this);
  61263. repaint();
  61264. }
  61265. }
  61266. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61267. scrollDown->setVisible (showScrollButtons);
  61268. scrollUp->setVisible (showScrollButtons);
  61269. xOffset = 0;
  61270. if (showScrollButtons)
  61271. {
  61272. const int scrollButtonW = jmin (12, w / 2);
  61273. if (orientation == horizontalKeyboard)
  61274. {
  61275. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61276. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61277. }
  61278. else if (orientation == verticalKeyboardFacingLeft)
  61279. {
  61280. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61281. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61282. }
  61283. else if (orientation == verticalKeyboardFacingRight)
  61284. {
  61285. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61286. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61287. }
  61288. int endOfLastKey, kw;
  61289. getKeyPos (rangeEnd, endOfLastKey, kw);
  61290. endOfLastKey += kw;
  61291. float mousePositionVelocity;
  61292. const int spaceAvailable = w - scrollButtonW * 2;
  61293. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61294. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61295. {
  61296. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61297. sendChangeMessage (this);
  61298. }
  61299. int newOffset = 0;
  61300. getKeyPos (firstKey, newOffset, kw);
  61301. xOffset = newOffset - scrollButtonW;
  61302. }
  61303. else
  61304. {
  61305. firstKey = rangeStart;
  61306. }
  61307. timerCallback();
  61308. repaint();
  61309. }
  61310. }
  61311. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61312. {
  61313. triggerAsyncUpdate();
  61314. }
  61315. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61316. {
  61317. triggerAsyncUpdate();
  61318. }
  61319. void MidiKeyboardComponent::handleAsyncUpdate()
  61320. {
  61321. for (int i = rangeStart; i <= rangeEnd; ++i)
  61322. {
  61323. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61324. {
  61325. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61326. repaintNote (i);
  61327. }
  61328. }
  61329. }
  61330. void MidiKeyboardComponent::resetAnyKeysInUse()
  61331. {
  61332. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61333. {
  61334. state.allNotesOff (midiChannel);
  61335. keysPressed.clear();
  61336. mouseDownNote = -1;
  61337. }
  61338. }
  61339. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61340. {
  61341. float mousePositionVelocity = 0.0f;
  61342. const int newNote = (mouseDragging || isMouseOver())
  61343. ? xyToNote (pos, mousePositionVelocity) : -1;
  61344. if (noteUnderMouse != newNote)
  61345. {
  61346. if (mouseDownNote >= 0)
  61347. {
  61348. state.noteOff (midiChannel, mouseDownNote);
  61349. mouseDownNote = -1;
  61350. }
  61351. if (mouseDragging && newNote >= 0)
  61352. {
  61353. if (! useMousePositionForVelocity)
  61354. mousePositionVelocity = 1.0f;
  61355. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61356. mouseDownNote = newNote;
  61357. }
  61358. repaintNote (noteUnderMouse);
  61359. noteUnderMouse = newNote;
  61360. repaintNote (noteUnderMouse);
  61361. }
  61362. else if (mouseDownNote >= 0 && ! mouseDragging)
  61363. {
  61364. state.noteOff (midiChannel, mouseDownNote);
  61365. mouseDownNote = -1;
  61366. }
  61367. }
  61368. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61369. {
  61370. updateNoteUnderMouse (e.getPosition());
  61371. stopTimer();
  61372. }
  61373. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61374. {
  61375. float mousePositionVelocity;
  61376. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61377. if (newNote >= 0)
  61378. mouseDraggedToKey (newNote, e);
  61379. updateNoteUnderMouse (e.getPosition());
  61380. }
  61381. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61382. {
  61383. return true;
  61384. }
  61385. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61386. {
  61387. }
  61388. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61389. {
  61390. float mousePositionVelocity;
  61391. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61392. mouseDragging = false;
  61393. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61394. {
  61395. repaintNote (noteUnderMouse);
  61396. noteUnderMouse = -1;
  61397. mouseDragging = true;
  61398. updateNoteUnderMouse (e.getPosition());
  61399. startTimer (500);
  61400. }
  61401. }
  61402. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61403. {
  61404. mouseDragging = false;
  61405. updateNoteUnderMouse (e.getPosition());
  61406. stopTimer();
  61407. }
  61408. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61409. {
  61410. updateNoteUnderMouse (e.getPosition());
  61411. }
  61412. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61413. {
  61414. updateNoteUnderMouse (e.getPosition());
  61415. }
  61416. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61417. {
  61418. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61419. }
  61420. void MidiKeyboardComponent::timerCallback()
  61421. {
  61422. updateNoteUnderMouse (getMouseXYRelative());
  61423. }
  61424. void MidiKeyboardComponent::clearKeyMappings()
  61425. {
  61426. resetAnyKeysInUse();
  61427. keyPressNotes.clear();
  61428. keyPresses.clear();
  61429. }
  61430. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61431. const int midiNoteOffsetFromC)
  61432. {
  61433. removeKeyPressForNote (midiNoteOffsetFromC);
  61434. keyPressNotes.add (midiNoteOffsetFromC);
  61435. keyPresses.add (key);
  61436. }
  61437. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61438. {
  61439. for (int i = keyPressNotes.size(); --i >= 0;)
  61440. {
  61441. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61442. {
  61443. keyPressNotes.remove (i);
  61444. keyPresses.remove (i);
  61445. }
  61446. }
  61447. }
  61448. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61449. {
  61450. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61451. keyMappingOctave = newOctaveNumber;
  61452. }
  61453. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61454. {
  61455. bool keyPressUsed = false;
  61456. for (int i = keyPresses.size(); --i >= 0;)
  61457. {
  61458. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61459. if (keyPresses.getReference(i).isCurrentlyDown())
  61460. {
  61461. if (! keysPressed [note])
  61462. {
  61463. keysPressed.setBit (note);
  61464. state.noteOn (midiChannel, note, velocity);
  61465. keyPressUsed = true;
  61466. }
  61467. }
  61468. else
  61469. {
  61470. if (keysPressed [note])
  61471. {
  61472. keysPressed.clearBit (note);
  61473. state.noteOff (midiChannel, note);
  61474. keyPressUsed = true;
  61475. }
  61476. }
  61477. }
  61478. return keyPressUsed;
  61479. }
  61480. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61481. {
  61482. resetAnyKeysInUse();
  61483. }
  61484. END_JUCE_NAMESPACE
  61485. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61486. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61487. #if JUCE_OPENGL
  61488. BEGIN_JUCE_NAMESPACE
  61489. extern void juce_glViewport (const int w, const int h);
  61490. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61491. const int alphaBits_,
  61492. const int depthBufferBits_,
  61493. const int stencilBufferBits_)
  61494. : redBits (bitsPerRGBComponent),
  61495. greenBits (bitsPerRGBComponent),
  61496. blueBits (bitsPerRGBComponent),
  61497. alphaBits (alphaBits_),
  61498. depthBufferBits (depthBufferBits_),
  61499. stencilBufferBits (stencilBufferBits_),
  61500. accumulationBufferRedBits (0),
  61501. accumulationBufferGreenBits (0),
  61502. accumulationBufferBlueBits (0),
  61503. accumulationBufferAlphaBits (0),
  61504. fullSceneAntiAliasingNumSamples (0)
  61505. {
  61506. }
  61507. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61508. : redBits (other.redBits),
  61509. greenBits (other.greenBits),
  61510. blueBits (other.blueBits),
  61511. alphaBits (other.alphaBits),
  61512. depthBufferBits (other.depthBufferBits),
  61513. stencilBufferBits (other.stencilBufferBits),
  61514. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61515. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61516. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61517. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61518. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61519. {
  61520. }
  61521. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61522. {
  61523. redBits = other.redBits;
  61524. greenBits = other.greenBits;
  61525. blueBits = other.blueBits;
  61526. alphaBits = other.alphaBits;
  61527. depthBufferBits = other.depthBufferBits;
  61528. stencilBufferBits = other.stencilBufferBits;
  61529. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61530. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61531. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61532. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61533. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61534. return *this;
  61535. }
  61536. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61537. {
  61538. return redBits == other.redBits
  61539. && greenBits == other.greenBits
  61540. && blueBits == other.blueBits
  61541. && alphaBits == other.alphaBits
  61542. && depthBufferBits == other.depthBufferBits
  61543. && stencilBufferBits == other.stencilBufferBits
  61544. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61545. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61546. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61547. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61548. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61549. }
  61550. static Array<OpenGLContext*> knownContexts;
  61551. OpenGLContext::OpenGLContext() throw()
  61552. {
  61553. knownContexts.add (this);
  61554. }
  61555. OpenGLContext::~OpenGLContext()
  61556. {
  61557. knownContexts.removeValue (this);
  61558. }
  61559. OpenGLContext* OpenGLContext::getCurrentContext()
  61560. {
  61561. for (int i = knownContexts.size(); --i >= 0;)
  61562. {
  61563. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61564. if (oglc->isActive())
  61565. return oglc;
  61566. }
  61567. return 0;
  61568. }
  61569. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61570. {
  61571. public:
  61572. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61573. : ComponentMovementWatcher (owner_),
  61574. owner (owner_),
  61575. wasShowing (false)
  61576. {
  61577. }
  61578. ~OpenGLComponentWatcher() {}
  61579. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61580. {
  61581. owner->updateContextPosition();
  61582. }
  61583. void componentPeerChanged()
  61584. {
  61585. const ScopedLock sl (owner->getContextLock());
  61586. owner->deleteContext();
  61587. }
  61588. void componentVisibilityChanged (Component&)
  61589. {
  61590. const bool isShowingNow = owner->isShowing();
  61591. if (wasShowing != isShowingNow)
  61592. {
  61593. wasShowing = isShowingNow;
  61594. if (! isShowingNow)
  61595. {
  61596. const ScopedLock sl (owner->getContextLock());
  61597. owner->deleteContext();
  61598. }
  61599. }
  61600. }
  61601. juce_UseDebuggingNewOperator
  61602. private:
  61603. OpenGLComponent* const owner;
  61604. bool wasShowing;
  61605. };
  61606. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61607. : type (type_),
  61608. contextToShareListsWith (0),
  61609. needToUpdateViewport (true)
  61610. {
  61611. setOpaque (true);
  61612. componentWatcher = new OpenGLComponentWatcher (this);
  61613. }
  61614. OpenGLComponent::~OpenGLComponent()
  61615. {
  61616. deleteContext();
  61617. componentWatcher = 0;
  61618. }
  61619. void OpenGLComponent::deleteContext()
  61620. {
  61621. const ScopedLock sl (contextLock);
  61622. context = 0;
  61623. }
  61624. void OpenGLComponent::updateContextPosition()
  61625. {
  61626. needToUpdateViewport = true;
  61627. if (getWidth() > 0 && getHeight() > 0)
  61628. {
  61629. Component* const topComp = getTopLevelComponent();
  61630. if (topComp->getPeer() != 0)
  61631. {
  61632. const ScopedLock sl (contextLock);
  61633. if (context != 0)
  61634. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61635. getScreenY() - topComp->getScreenY(),
  61636. getWidth(),
  61637. getHeight(),
  61638. topComp->getHeight());
  61639. }
  61640. }
  61641. }
  61642. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61643. {
  61644. OpenGLPixelFormat pf;
  61645. const ScopedLock sl (contextLock);
  61646. if (context != 0)
  61647. pf = context->getPixelFormat();
  61648. return pf;
  61649. }
  61650. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61651. {
  61652. if (! (preferredPixelFormat == formatToUse))
  61653. {
  61654. const ScopedLock sl (contextLock);
  61655. deleteContext();
  61656. preferredPixelFormat = formatToUse;
  61657. }
  61658. }
  61659. void OpenGLComponent::shareWith (OpenGLContext* c)
  61660. {
  61661. if (contextToShareListsWith != c)
  61662. {
  61663. const ScopedLock sl (contextLock);
  61664. deleteContext();
  61665. contextToShareListsWith = c;
  61666. }
  61667. }
  61668. bool OpenGLComponent::makeCurrentContextActive()
  61669. {
  61670. if (context == 0)
  61671. {
  61672. const ScopedLock sl (contextLock);
  61673. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61674. {
  61675. context = createContext();
  61676. if (context != 0)
  61677. {
  61678. updateContextPosition();
  61679. if (context->makeActive())
  61680. newOpenGLContextCreated();
  61681. }
  61682. }
  61683. }
  61684. return context != 0 && context->makeActive();
  61685. }
  61686. void OpenGLComponent::makeCurrentContextInactive()
  61687. {
  61688. if (context != 0)
  61689. context->makeInactive();
  61690. }
  61691. bool OpenGLComponent::isActiveContext() const throw()
  61692. {
  61693. return context != 0 && context->isActive();
  61694. }
  61695. void OpenGLComponent::swapBuffers()
  61696. {
  61697. if (context != 0)
  61698. context->swapBuffers();
  61699. }
  61700. void OpenGLComponent::paint (Graphics&)
  61701. {
  61702. if (renderAndSwapBuffers())
  61703. {
  61704. ComponentPeer* const peer = getPeer();
  61705. if (peer != 0)
  61706. {
  61707. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61708. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61709. }
  61710. }
  61711. }
  61712. bool OpenGLComponent::renderAndSwapBuffers()
  61713. {
  61714. const ScopedLock sl (contextLock);
  61715. if (! makeCurrentContextActive())
  61716. return false;
  61717. if (needToUpdateViewport)
  61718. {
  61719. needToUpdateViewport = false;
  61720. juce_glViewport (getWidth(), getHeight());
  61721. }
  61722. renderOpenGL();
  61723. swapBuffers();
  61724. return true;
  61725. }
  61726. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61727. {
  61728. Component::internalRepaint (x, y, w, h);
  61729. if (context != 0)
  61730. context->repaint();
  61731. }
  61732. END_JUCE_NAMESPACE
  61733. #endif
  61734. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61735. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61736. BEGIN_JUCE_NAMESPACE
  61737. PreferencesPanel::PreferencesPanel()
  61738. : buttonSize (70)
  61739. {
  61740. }
  61741. PreferencesPanel::~PreferencesPanel()
  61742. {
  61743. currentPage = 0;
  61744. deleteAllChildren();
  61745. }
  61746. void PreferencesPanel::addSettingsPage (const String& title,
  61747. const Drawable* icon,
  61748. const Drawable* overIcon,
  61749. const Drawable* downIcon)
  61750. {
  61751. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61752. button->setImages (icon, overIcon, downIcon);
  61753. button->setRadioGroupId (1);
  61754. button->addButtonListener (this);
  61755. button->setClickingTogglesState (true);
  61756. button->setWantsKeyboardFocus (false);
  61757. addAndMakeVisible (button);
  61758. resized();
  61759. if (currentPage == 0)
  61760. setCurrentPage (title);
  61761. }
  61762. void PreferencesPanel::addSettingsPage (const String& title,
  61763. const void* imageData,
  61764. const int imageDataSize)
  61765. {
  61766. DrawableImage icon, iconOver, iconDown;
  61767. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61768. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61769. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61770. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61771. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61772. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61773. }
  61774. class PrefsDialogWindow : public DialogWindow
  61775. {
  61776. public:
  61777. PrefsDialogWindow (const String& dialogtitle,
  61778. const Colour& backgroundColour)
  61779. : DialogWindow (dialogtitle, backgroundColour, true)
  61780. {
  61781. }
  61782. ~PrefsDialogWindow()
  61783. {
  61784. }
  61785. void closeButtonPressed()
  61786. {
  61787. exitModalState (0);
  61788. }
  61789. private:
  61790. PrefsDialogWindow (const PrefsDialogWindow&);
  61791. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61792. };
  61793. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61794. int dialogWidth,
  61795. int dialogHeight,
  61796. const Colour& backgroundColour)
  61797. {
  61798. setSize (dialogWidth, dialogHeight);
  61799. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61800. dw.setContentComponent (this, true, true);
  61801. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61802. dw.runModalLoop();
  61803. dw.setContentComponent (0, false, false);
  61804. }
  61805. void PreferencesPanel::resized()
  61806. {
  61807. int x = 0;
  61808. for (int i = 0; i < getNumChildComponents(); ++i)
  61809. {
  61810. Component* c = getChildComponent (i);
  61811. if (dynamic_cast <DrawableButton*> (c) == 0)
  61812. {
  61813. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61814. }
  61815. else
  61816. {
  61817. c->setBounds (x, 0, buttonSize, buttonSize);
  61818. x += buttonSize;
  61819. }
  61820. }
  61821. }
  61822. void PreferencesPanel::paint (Graphics& g)
  61823. {
  61824. g.setColour (Colours::grey);
  61825. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61826. }
  61827. void PreferencesPanel::setCurrentPage (const String& pageName)
  61828. {
  61829. if (currentPageName != pageName)
  61830. {
  61831. currentPageName = pageName;
  61832. currentPage = 0;
  61833. currentPage = createComponentForPage (pageName);
  61834. if (currentPage != 0)
  61835. {
  61836. addAndMakeVisible (currentPage);
  61837. currentPage->toBack();
  61838. resized();
  61839. }
  61840. for (int i = 0; i < getNumChildComponents(); ++i)
  61841. {
  61842. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61843. if (db != 0 && db->getName() == pageName)
  61844. {
  61845. db->setToggleState (true, false);
  61846. break;
  61847. }
  61848. }
  61849. }
  61850. }
  61851. void PreferencesPanel::buttonClicked (Button*)
  61852. {
  61853. for (int i = 0; i < getNumChildComponents(); ++i)
  61854. {
  61855. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61856. if (db != 0 && db->getToggleState())
  61857. {
  61858. setCurrentPage (db->getName());
  61859. break;
  61860. }
  61861. }
  61862. }
  61863. END_JUCE_NAMESPACE
  61864. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61865. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61866. #if JUCE_WINDOWS || JUCE_LINUX
  61867. BEGIN_JUCE_NAMESPACE
  61868. SystemTrayIconComponent::SystemTrayIconComponent()
  61869. {
  61870. addToDesktop (0);
  61871. }
  61872. SystemTrayIconComponent::~SystemTrayIconComponent()
  61873. {
  61874. }
  61875. END_JUCE_NAMESPACE
  61876. #endif
  61877. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61878. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61879. BEGIN_JUCE_NAMESPACE
  61880. class AlertWindowTextEditor : public TextEditor
  61881. {
  61882. public:
  61883. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61884. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61885. {
  61886. setSelectAllWhenFocused (true);
  61887. }
  61888. ~AlertWindowTextEditor()
  61889. {
  61890. }
  61891. void returnPressed()
  61892. {
  61893. // pass these up the component hierarchy to be trigger the buttons
  61894. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61895. }
  61896. void escapePressed()
  61897. {
  61898. // pass these up the component hierarchy to be trigger the buttons
  61899. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61900. }
  61901. private:
  61902. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61903. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61904. static juce_wchar getDefaultPasswordChar() throw()
  61905. {
  61906. #if JUCE_LINUX
  61907. return 0x2022;
  61908. #else
  61909. return 0x25cf;
  61910. #endif
  61911. }
  61912. };
  61913. AlertWindow::AlertWindow (const String& title,
  61914. const String& message,
  61915. AlertIconType iconType,
  61916. Component* associatedComponent_)
  61917. : TopLevelWindow (title, true),
  61918. alertIconType (iconType),
  61919. associatedComponent (associatedComponent_)
  61920. {
  61921. if (message.isEmpty())
  61922. text = " "; // to force an update if the message is empty
  61923. setMessage (message);
  61924. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61925. {
  61926. Component* const c = Desktop::getInstance().getComponent (i);
  61927. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61928. {
  61929. setAlwaysOnTop (true);
  61930. break;
  61931. }
  61932. }
  61933. if (! JUCEApplication::isStandaloneApp())
  61934. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61935. lookAndFeelChanged();
  61936. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61937. }
  61938. AlertWindow::~AlertWindow()
  61939. {
  61940. for (int i = customComps.size(); --i >= 0;)
  61941. removeChildComponent ((Component*) customComps[i]);
  61942. deleteAllChildren();
  61943. }
  61944. void AlertWindow::userTriedToCloseWindow()
  61945. {
  61946. exitModalState (0);
  61947. }
  61948. void AlertWindow::setMessage (const String& message)
  61949. {
  61950. const String newMessage (message.substring (0, 2048));
  61951. if (text != newMessage)
  61952. {
  61953. text = newMessage;
  61954. font.setHeight (15.0f);
  61955. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61956. textLayout.setText (getName() + "\n\n", titleFont);
  61957. textLayout.appendText (text, font);
  61958. updateLayout (true);
  61959. repaint();
  61960. }
  61961. }
  61962. void AlertWindow::buttonClicked (Button* button)
  61963. {
  61964. for (int i = 0; i < buttons.size(); i++)
  61965. {
  61966. TextButton* const c = (TextButton*) buttons[i];
  61967. if (button->getName() == c->getName())
  61968. {
  61969. if (c->getParentComponent() != 0)
  61970. c->getParentComponent()->exitModalState (c->getCommandID());
  61971. break;
  61972. }
  61973. }
  61974. }
  61975. void AlertWindow::addButton (const String& name,
  61976. const int returnValue,
  61977. const KeyPress& shortcutKey1,
  61978. const KeyPress& shortcutKey2)
  61979. {
  61980. TextButton* const b = new TextButton (name, String::empty);
  61981. b->setWantsKeyboardFocus (true);
  61982. b->setMouseClickGrabsKeyboardFocus (false);
  61983. b->setCommandToTrigger (0, returnValue, false);
  61984. b->addShortcut (shortcutKey1);
  61985. b->addShortcut (shortcutKey2);
  61986. b->addButtonListener (this);
  61987. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61988. addAndMakeVisible (b, 0);
  61989. buttons.add (b);
  61990. updateLayout (false);
  61991. }
  61992. int AlertWindow::getNumButtons() const
  61993. {
  61994. return buttons.size();
  61995. }
  61996. void AlertWindow::triggerButtonClick (const String& buttonName)
  61997. {
  61998. for (int i = buttons.size(); --i >= 0;)
  61999. {
  62000. TextButton* const b = (TextButton*) buttons[i];
  62001. if (buttonName == b->getName())
  62002. {
  62003. b->triggerClick();
  62004. break;
  62005. }
  62006. }
  62007. }
  62008. void AlertWindow::addTextEditor (const String& name,
  62009. const String& initialContents,
  62010. const String& onScreenLabel,
  62011. const bool isPasswordBox)
  62012. {
  62013. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62014. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62015. tc->setFont (font);
  62016. tc->setText (initialContents);
  62017. tc->setCaretPosition (initialContents.length());
  62018. addAndMakeVisible (tc);
  62019. textBoxes.add (tc);
  62020. allComps.add (tc);
  62021. textboxNames.add (onScreenLabel);
  62022. updateLayout (false);
  62023. }
  62024. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62025. {
  62026. for (int i = textBoxes.size(); --i >= 0;)
  62027. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  62028. return ((TextEditor*)textBoxes[i])->getText();
  62029. return String::empty;
  62030. }
  62031. void AlertWindow::addComboBox (const String& name,
  62032. const StringArray& items,
  62033. const String& onScreenLabel)
  62034. {
  62035. ComboBox* const cb = new ComboBox (name);
  62036. for (int i = 0; i < items.size(); ++i)
  62037. cb->addItem (items[i], i + 1);
  62038. addAndMakeVisible (cb);
  62039. cb->setSelectedItemIndex (0);
  62040. comboBoxes.add (cb);
  62041. allComps.add (cb);
  62042. comboBoxNames.add (onScreenLabel);
  62043. updateLayout (false);
  62044. }
  62045. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62046. {
  62047. for (int i = comboBoxes.size(); --i >= 0;)
  62048. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62049. return (ComboBox*) comboBoxes[i];
  62050. return 0;
  62051. }
  62052. class AlertTextComp : public TextEditor
  62053. {
  62054. public:
  62055. AlertTextComp (const String& message,
  62056. const Font& font)
  62057. {
  62058. setReadOnly (true);
  62059. setMultiLine (true, true);
  62060. setCaretVisible (false);
  62061. setScrollbarsShown (true);
  62062. lookAndFeelChanged();
  62063. setWantsKeyboardFocus (false);
  62064. setFont (font);
  62065. setText (message, false);
  62066. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62067. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62068. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62069. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62070. }
  62071. ~AlertTextComp()
  62072. {
  62073. }
  62074. int getPreferredWidth() const throw() { return bestWidth; }
  62075. void updateLayout (const int width)
  62076. {
  62077. TextLayout text;
  62078. text.appendText (getText(), getFont());
  62079. text.layout (width - 8, Justification::topLeft, true);
  62080. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62081. }
  62082. private:
  62083. int bestWidth;
  62084. AlertTextComp (const AlertTextComp&);
  62085. AlertTextComp& operator= (const AlertTextComp&);
  62086. };
  62087. void AlertWindow::addTextBlock (const String& textBlock)
  62088. {
  62089. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62090. textBlocks.add (c);
  62091. allComps.add (c);
  62092. addAndMakeVisible (c);
  62093. updateLayout (false);
  62094. }
  62095. void AlertWindow::addProgressBarComponent (double& progressValue)
  62096. {
  62097. ProgressBar* const pb = new ProgressBar (progressValue);
  62098. progressBars.add (pb);
  62099. allComps.add (pb);
  62100. addAndMakeVisible (pb);
  62101. updateLayout (false);
  62102. }
  62103. void AlertWindow::addCustomComponent (Component* const component)
  62104. {
  62105. customComps.add (component);
  62106. allComps.add (component);
  62107. addAndMakeVisible (component);
  62108. updateLayout (false);
  62109. }
  62110. int AlertWindow::getNumCustomComponents() const
  62111. {
  62112. return customComps.size();
  62113. }
  62114. Component* AlertWindow::getCustomComponent (const int index) const
  62115. {
  62116. return (Component*) customComps [index];
  62117. }
  62118. Component* AlertWindow::removeCustomComponent (const int index)
  62119. {
  62120. Component* const c = getCustomComponent (index);
  62121. if (c != 0)
  62122. {
  62123. customComps.removeValue (c);
  62124. allComps.removeValue (c);
  62125. removeChildComponent (c);
  62126. updateLayout (false);
  62127. }
  62128. return c;
  62129. }
  62130. void AlertWindow::paint (Graphics& g)
  62131. {
  62132. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62133. g.setColour (findColour (textColourId));
  62134. g.setFont (getLookAndFeel().getAlertWindowFont());
  62135. int i;
  62136. for (i = textBoxes.size(); --i >= 0;)
  62137. {
  62138. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62139. g.drawFittedText (textboxNames[i],
  62140. te->getX(), te->getY() - 14,
  62141. te->getWidth(), 14,
  62142. Justification::centredLeft, 1);
  62143. }
  62144. for (i = comboBoxNames.size(); --i >= 0;)
  62145. {
  62146. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62147. g.drawFittedText (comboBoxNames[i],
  62148. cb->getX(), cb->getY() - 14,
  62149. cb->getWidth(), 14,
  62150. Justification::centredLeft, 1);
  62151. }
  62152. for (i = customComps.size(); --i >= 0;)
  62153. {
  62154. const Component* const c = (Component*) customComps[i];
  62155. g.drawFittedText (c->getName(),
  62156. c->getX(), c->getY() - 14,
  62157. c->getWidth(), 14,
  62158. Justification::centredLeft, 1);
  62159. }
  62160. }
  62161. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62162. {
  62163. const int titleH = 24;
  62164. const int iconWidth = 80;
  62165. const int wid = jmax (font.getStringWidth (text),
  62166. font.getStringWidth (getName()));
  62167. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62168. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62169. const int edgeGap = 10;
  62170. const int labelHeight = 18;
  62171. int iconSpace;
  62172. if (alertIconType == NoIcon)
  62173. {
  62174. textLayout.layout (w, Justification::horizontallyCentred, true);
  62175. iconSpace = 0;
  62176. }
  62177. else
  62178. {
  62179. textLayout.layout (w, Justification::left, true);
  62180. iconSpace = iconWidth;
  62181. }
  62182. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62183. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62184. const int textLayoutH = textLayout.getHeight();
  62185. const int textBottom = 16 + titleH + textLayoutH;
  62186. int h = textBottom;
  62187. int buttonW = 40;
  62188. int i;
  62189. for (i = 0; i < buttons.size(); ++i)
  62190. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62191. w = jmax (buttonW, w);
  62192. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62193. if (buttons.size() > 0)
  62194. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62195. for (i = customComps.size(); --i >= 0;)
  62196. {
  62197. Component* c = (Component*) customComps[i];
  62198. w = jmax (w, (c->getWidth() * 100) / 80);
  62199. h += 10 + c->getHeight();
  62200. if (c->getName().isNotEmpty())
  62201. h += labelHeight;
  62202. }
  62203. for (i = textBlocks.size(); --i >= 0;)
  62204. {
  62205. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62206. w = jmax (w, ac->getPreferredWidth());
  62207. }
  62208. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62209. for (i = textBlocks.size(); --i >= 0;)
  62210. {
  62211. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62212. ac->updateLayout ((int) (w * 0.8f));
  62213. h += ac->getHeight() + 10;
  62214. }
  62215. h = jmin (getParentHeight() - 50, h);
  62216. if (onlyIncreaseSize)
  62217. {
  62218. w = jmax (w, getWidth());
  62219. h = jmax (h, getHeight());
  62220. }
  62221. if (! isVisible())
  62222. {
  62223. centreAroundComponent (associatedComponent, w, h);
  62224. }
  62225. else
  62226. {
  62227. const int cx = getX() + getWidth() / 2;
  62228. const int cy = getY() + getHeight() / 2;
  62229. setBounds (cx - w / 2,
  62230. cy - h / 2,
  62231. w, h);
  62232. }
  62233. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62234. const int spacer = 16;
  62235. int totalWidth = -spacer;
  62236. for (i = buttons.size(); --i >= 0;)
  62237. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62238. int x = (w - totalWidth) / 2;
  62239. int y = (int) (getHeight() * 0.95f);
  62240. for (i = 0; i < buttons.size(); ++i)
  62241. {
  62242. TextButton* const c = (TextButton*) buttons[i];
  62243. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62244. c->setTopLeftPosition (x, ny);
  62245. if (ny < y)
  62246. y = ny;
  62247. x += c->getWidth() + spacer;
  62248. c->toFront (false);
  62249. }
  62250. y = textBottom;
  62251. for (i = 0; i < allComps.size(); ++i)
  62252. {
  62253. Component* const c = (Component*) allComps[i];
  62254. h = 22;
  62255. const int comboIndex = comboBoxes.indexOf (c);
  62256. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62257. y += labelHeight;
  62258. const int tbIndex = textBoxes.indexOf (c);
  62259. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62260. y += labelHeight;
  62261. if (customComps.contains (c))
  62262. {
  62263. if (c->getName().isNotEmpty())
  62264. y += labelHeight;
  62265. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62266. h = c->getHeight();
  62267. }
  62268. else if (textBlocks.contains (c))
  62269. {
  62270. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62271. h = c->getHeight();
  62272. }
  62273. else
  62274. {
  62275. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62276. }
  62277. y += h + 10;
  62278. }
  62279. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62280. }
  62281. bool AlertWindow::containsAnyExtraComponents() const
  62282. {
  62283. return textBoxes.size()
  62284. + comboBoxes.size()
  62285. + progressBars.size()
  62286. + customComps.size() > 0;
  62287. }
  62288. void AlertWindow::mouseDown (const MouseEvent&)
  62289. {
  62290. dragger.startDraggingComponent (this, &constrainer);
  62291. }
  62292. void AlertWindow::mouseDrag (const MouseEvent& e)
  62293. {
  62294. dragger.dragComponent (this, e);
  62295. }
  62296. bool AlertWindow::keyPressed (const KeyPress& key)
  62297. {
  62298. for (int i = buttons.size(); --i >= 0;)
  62299. {
  62300. TextButton* const b = (TextButton*) buttons[i];
  62301. if (b->isRegisteredForShortcut (key))
  62302. {
  62303. b->triggerClick();
  62304. return true;
  62305. }
  62306. }
  62307. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62308. {
  62309. exitModalState (0);
  62310. return true;
  62311. }
  62312. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62313. {
  62314. ((TextButton*) buttons.getFirst())->triggerClick();
  62315. return true;
  62316. }
  62317. return false;
  62318. }
  62319. void AlertWindow::lookAndFeelChanged()
  62320. {
  62321. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62322. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62323. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62324. }
  62325. int AlertWindow::getDesktopWindowStyleFlags() const
  62326. {
  62327. return getLookAndFeel().getAlertBoxWindowFlags();
  62328. }
  62329. struct AlertWindowInfo
  62330. {
  62331. String title, message, button1, button2, button3;
  62332. AlertWindow::AlertIconType iconType;
  62333. int numButtons;
  62334. Component::SafePointer<Component> associatedComponent;
  62335. int run() const
  62336. {
  62337. return (int) (pointer_sized_int)
  62338. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62339. }
  62340. private:
  62341. int show() const
  62342. {
  62343. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62344. : LookAndFeel::getDefaultLookAndFeel();
  62345. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62346. iconType, numButtons, associatedComponent));
  62347. jassert (alertBox != 0); // you have to return one of these!
  62348. return alertBox->runModalLoop();
  62349. }
  62350. static void* showCallback (void* userData)
  62351. {
  62352. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62353. }
  62354. };
  62355. void AlertWindow::showMessageBox (AlertIconType iconType,
  62356. const String& title,
  62357. const String& message,
  62358. const String& buttonText,
  62359. Component* associatedComponent)
  62360. {
  62361. AlertWindowInfo info;
  62362. info.title = title;
  62363. info.message = message;
  62364. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62365. info.iconType = iconType;
  62366. info.numButtons = 1;
  62367. info.associatedComponent = associatedComponent;
  62368. info.run();
  62369. }
  62370. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62371. const String& title,
  62372. const String& message,
  62373. const String& button1Text,
  62374. const String& button2Text,
  62375. Component* associatedComponent)
  62376. {
  62377. AlertWindowInfo info;
  62378. info.title = title;
  62379. info.message = message;
  62380. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62381. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62382. info.iconType = iconType;
  62383. info.numButtons = 2;
  62384. info.associatedComponent = associatedComponent;
  62385. return info.run() != 0;
  62386. }
  62387. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62388. const String& title,
  62389. const String& message,
  62390. const String& button1Text,
  62391. const String& button2Text,
  62392. const String& button3Text,
  62393. Component* associatedComponent)
  62394. {
  62395. AlertWindowInfo info;
  62396. info.title = title;
  62397. info.message = message;
  62398. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62399. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62400. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62401. info.iconType = iconType;
  62402. info.numButtons = 3;
  62403. info.associatedComponent = associatedComponent;
  62404. return info.run();
  62405. }
  62406. END_JUCE_NAMESPACE
  62407. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62408. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62409. BEGIN_JUCE_NAMESPACE
  62410. CallOutBox::CallOutBox (Component& contentComponent,
  62411. Component& componentToPointTo,
  62412. Component* const parentComponent)
  62413. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62414. {
  62415. addAndMakeVisible (&content);
  62416. if (parentComponent != 0)
  62417. {
  62418. updatePosition (parentComponent->getLocalBounds(),
  62419. componentToPointTo.getLocalBounds()
  62420. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62421. parentComponent->addAndMakeVisible (this);
  62422. }
  62423. else
  62424. {
  62425. if (! JUCEApplication::isStandaloneApp())
  62426. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62427. updatePosition (componentToPointTo.getScreenBounds(),
  62428. componentToPointTo.getParentMonitorArea());
  62429. addToDesktop (ComponentPeer::windowIsTemporary);
  62430. }
  62431. }
  62432. CallOutBox::~CallOutBox()
  62433. {
  62434. }
  62435. void CallOutBox::setArrowSize (const float newSize)
  62436. {
  62437. arrowSize = newSize;
  62438. borderSpace = jmax (20, (int) arrowSize);
  62439. refreshPath();
  62440. }
  62441. void CallOutBox::paint (Graphics& g)
  62442. {
  62443. if (background.isNull())
  62444. {
  62445. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62446. Graphics g (background);
  62447. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62448. }
  62449. g.setColour (Colours::black);
  62450. g.drawImageAt (background, 0, 0);
  62451. }
  62452. void CallOutBox::resized()
  62453. {
  62454. content.setTopLeftPosition (borderSpace, borderSpace);
  62455. refreshPath();
  62456. }
  62457. void CallOutBox::moved()
  62458. {
  62459. refreshPath();
  62460. }
  62461. void CallOutBox::childBoundsChanged (Component*)
  62462. {
  62463. updatePosition (targetArea, availableArea);
  62464. }
  62465. bool CallOutBox::hitTest (int x, int y)
  62466. {
  62467. return outline.contains ((float) x, (float) y);
  62468. }
  62469. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62470. void CallOutBox::inputAttemptWhenModal()
  62471. {
  62472. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62473. if (targetArea.contains (mousePos))
  62474. {
  62475. // if you click on the area that originally popped-up the callout, you expect it
  62476. // to get rid of the box, but deleting the box here allows the click to pass through and
  62477. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62478. postCommandMessage (callOutBoxDismissCommandId);
  62479. }
  62480. else
  62481. {
  62482. exitModalState (0);
  62483. setVisible (false);
  62484. }
  62485. }
  62486. void CallOutBox::handleCommandMessage (int commandId)
  62487. {
  62488. Component::handleCommandMessage (commandId);
  62489. if (commandId == callOutBoxDismissCommandId)
  62490. {
  62491. exitModalState (0);
  62492. setVisible (false);
  62493. }
  62494. }
  62495. bool CallOutBox::keyPressed (const KeyPress& key)
  62496. {
  62497. if (key.isKeyCode (KeyPress::escapeKey))
  62498. {
  62499. inputAttemptWhenModal();
  62500. return true;
  62501. }
  62502. return false;
  62503. }
  62504. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62505. {
  62506. targetArea = newAreaToPointTo;
  62507. availableArea = newAreaToFitIn;
  62508. Rectangle<int> bounds (0, 0,
  62509. content.getWidth() + borderSpace * 2,
  62510. content.getHeight() + borderSpace * 2);
  62511. const int hw = bounds.getWidth() / 2;
  62512. const int hh = bounds.getHeight() / 2;
  62513. const float hwReduced = (float) (hw - borderSpace * 3);
  62514. const float hhReduced = (float) (hh - borderSpace * 3);
  62515. const float arrowIndent = borderSpace - arrowSize;
  62516. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62517. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62518. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62519. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62520. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62521. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62522. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62523. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62524. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62525. float nearest = 1.0e9f;
  62526. for (int i = 0; i < 4; ++i)
  62527. {
  62528. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62529. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62530. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62531. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62532. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62533. distanceFromCentre *= 2.0f;
  62534. if (distanceFromCentre < nearest)
  62535. {
  62536. nearest = distanceFromCentre;
  62537. targetPoint = targets[i];
  62538. bounds.setPosition ((int) (centre.getX() - hw),
  62539. (int) (centre.getY() - hh));
  62540. }
  62541. }
  62542. setBounds (bounds);
  62543. }
  62544. void CallOutBox::refreshPath()
  62545. {
  62546. repaint();
  62547. background = Image::null;
  62548. outline.clear();
  62549. const float gap = 4.5f;
  62550. const float cornerSize = 9.0f;
  62551. const float cornerSize2 = 2.0f * cornerSize;
  62552. const float arrowBaseWidth = arrowSize * 0.7f;
  62553. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62554. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62555. outline.startNewSubPath (left + cornerSize, top);
  62556. if (targetY <= top)
  62557. {
  62558. outline.lineTo (targetX - arrowBaseWidth, top);
  62559. outline.lineTo (targetX, targetY);
  62560. outline.lineTo (targetX + arrowBaseWidth, top);
  62561. }
  62562. outline.lineTo (right - cornerSize, top);
  62563. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62564. if (targetX >= right)
  62565. {
  62566. outline.lineTo (right, targetY - arrowBaseWidth);
  62567. outline.lineTo (targetX, targetY);
  62568. outline.lineTo (right, targetY + arrowBaseWidth);
  62569. }
  62570. outline.lineTo (right, bottom - cornerSize);
  62571. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62572. if (targetY >= bottom)
  62573. {
  62574. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62575. outline.lineTo (targetX, targetY);
  62576. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62577. }
  62578. outline.lineTo (left + cornerSize, bottom);
  62579. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62580. if (targetX <= left)
  62581. {
  62582. outline.lineTo (left, targetY + arrowBaseWidth);
  62583. outline.lineTo (targetX, targetY);
  62584. outline.lineTo (left, targetY - arrowBaseWidth);
  62585. }
  62586. outline.lineTo (left, top + cornerSize);
  62587. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62588. outline.closeSubPath();
  62589. }
  62590. END_JUCE_NAMESPACE
  62591. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62592. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62593. BEGIN_JUCE_NAMESPACE
  62594. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62595. static Array <ComponentPeer*> heavyweightPeers;
  62596. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62597. : component (component_),
  62598. styleFlags (styleFlags_),
  62599. lastPaintTime (0),
  62600. constrainer (0),
  62601. lastDragAndDropCompUnderMouse (0),
  62602. fakeMouseMessageSent (false),
  62603. isWindowMinimised (false)
  62604. {
  62605. heavyweightPeers.add (this);
  62606. }
  62607. ComponentPeer::~ComponentPeer()
  62608. {
  62609. heavyweightPeers.removeValue (this);
  62610. Desktop::getInstance().triggerFocusCallback();
  62611. }
  62612. int ComponentPeer::getNumPeers() throw()
  62613. {
  62614. return heavyweightPeers.size();
  62615. }
  62616. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62617. {
  62618. return heavyweightPeers [index];
  62619. }
  62620. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62621. {
  62622. for (int i = heavyweightPeers.size(); --i >= 0;)
  62623. {
  62624. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62625. if (peer->getComponent() == component)
  62626. return peer;
  62627. }
  62628. return 0;
  62629. }
  62630. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62631. {
  62632. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62633. }
  62634. void ComponentPeer::updateCurrentModifiers() throw()
  62635. {
  62636. ModifierKeys::updateCurrentModifiers();
  62637. }
  62638. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62639. {
  62640. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62641. jassert (mouse != 0); // not enough sources!
  62642. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62643. }
  62644. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62645. {
  62646. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62647. jassert (mouse != 0); // not enough sources!
  62648. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62649. }
  62650. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62651. {
  62652. Graphics g (&contextToPaintTo);
  62653. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62654. g.saveState();
  62655. #endif
  62656. JUCE_TRY
  62657. {
  62658. component->paintEntireComponent (g);
  62659. }
  62660. JUCE_CATCH_EXCEPTION
  62661. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62662. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62663. // clearly when things are being repainted.
  62664. {
  62665. g.restoreState();
  62666. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62667. (uint8) Random::getSystemRandom().nextInt (255),
  62668. (uint8) Random::getSystemRandom().nextInt (255),
  62669. (uint8) 0x50));
  62670. }
  62671. #endif
  62672. }
  62673. bool ComponentPeer::handleKeyPress (const int keyCode,
  62674. const juce_wchar textCharacter)
  62675. {
  62676. updateCurrentModifiers();
  62677. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62678. ? Component::getCurrentlyFocusedComponent()
  62679. : component;
  62680. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62681. {
  62682. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62683. if (currentModalComp != 0)
  62684. target = currentModalComp;
  62685. }
  62686. const KeyPress keyInfo (keyCode,
  62687. ModifierKeys::getCurrentModifiers().getRawFlags()
  62688. & ModifierKeys::allKeyboardModifiers,
  62689. textCharacter);
  62690. bool keyWasUsed = false;
  62691. while (target != 0)
  62692. {
  62693. const Component::SafePointer<Component> deletionChecker (target);
  62694. if (target->keyListeners_ != 0)
  62695. {
  62696. for (int i = target->keyListeners_->size(); --i >= 0;)
  62697. {
  62698. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62699. if (keyWasUsed || deletionChecker == 0)
  62700. return keyWasUsed;
  62701. i = jmin (i, target->keyListeners_->size());
  62702. }
  62703. }
  62704. keyWasUsed = target->keyPressed (keyInfo);
  62705. if (keyWasUsed || deletionChecker == 0)
  62706. break;
  62707. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62708. {
  62709. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62710. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62711. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62712. break;
  62713. }
  62714. target = target->parentComponent_;
  62715. }
  62716. return keyWasUsed;
  62717. }
  62718. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62719. {
  62720. updateCurrentModifiers();
  62721. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62722. ? Component::getCurrentlyFocusedComponent()
  62723. : component;
  62724. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62725. {
  62726. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62727. if (currentModalComp != 0)
  62728. target = currentModalComp;
  62729. }
  62730. bool keyWasUsed = false;
  62731. while (target != 0)
  62732. {
  62733. const Component::SafePointer<Component> deletionChecker (target);
  62734. keyWasUsed = target->keyStateChanged (isKeyDown);
  62735. if (keyWasUsed || deletionChecker == 0)
  62736. break;
  62737. if (target->keyListeners_ != 0)
  62738. {
  62739. for (int i = target->keyListeners_->size(); --i >= 0;)
  62740. {
  62741. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62742. if (keyWasUsed || deletionChecker == 0)
  62743. return keyWasUsed;
  62744. i = jmin (i, target->keyListeners_->size());
  62745. }
  62746. }
  62747. target = target->parentComponent_;
  62748. }
  62749. return keyWasUsed;
  62750. }
  62751. void ComponentPeer::handleModifierKeysChange()
  62752. {
  62753. updateCurrentModifiers();
  62754. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62755. if (target == 0)
  62756. target = Component::getCurrentlyFocusedComponent();
  62757. if (target == 0)
  62758. target = component;
  62759. if (target != 0)
  62760. target->internalModifierKeysChanged();
  62761. }
  62762. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62763. {
  62764. Component* const c = Component::getCurrentlyFocusedComponent();
  62765. if (component->isParentOf (c))
  62766. {
  62767. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62768. if (ti != 0 && ti->isTextInputActive())
  62769. return ti;
  62770. }
  62771. return 0;
  62772. }
  62773. void ComponentPeer::handleBroughtToFront()
  62774. {
  62775. updateCurrentModifiers();
  62776. if (component != 0)
  62777. component->internalBroughtToFront();
  62778. }
  62779. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62780. {
  62781. constrainer = newConstrainer;
  62782. }
  62783. void ComponentPeer::handleMovedOrResized()
  62784. {
  62785. jassert (component->isValidComponent());
  62786. updateCurrentModifiers();
  62787. const bool nowMinimised = isMinimised();
  62788. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62789. {
  62790. const Component::SafePointer<Component> deletionChecker (component);
  62791. const Rectangle<int> newBounds (getBounds());
  62792. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62793. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62794. if (wasMoved || wasResized)
  62795. {
  62796. component->bounds_ = newBounds;
  62797. if (wasResized)
  62798. component->repaint();
  62799. component->sendMovedResizedMessages (wasMoved, wasResized);
  62800. if (deletionChecker == 0)
  62801. return;
  62802. }
  62803. }
  62804. if (isWindowMinimised != nowMinimised)
  62805. {
  62806. isWindowMinimised = nowMinimised;
  62807. component->minimisationStateChanged (nowMinimised);
  62808. component->sendVisibilityChangeMessage();
  62809. }
  62810. if (! isFullScreen())
  62811. lastNonFullscreenBounds = component->getBounds();
  62812. }
  62813. void ComponentPeer::handleFocusGain()
  62814. {
  62815. updateCurrentModifiers();
  62816. if (component->isParentOf (lastFocusedComponent))
  62817. {
  62818. Component::currentlyFocusedComponent = lastFocusedComponent;
  62819. Desktop::getInstance().triggerFocusCallback();
  62820. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62821. }
  62822. else
  62823. {
  62824. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62825. component->grabKeyboardFocus();
  62826. else
  62827. Component::bringModalComponentToFront();
  62828. }
  62829. }
  62830. void ComponentPeer::handleFocusLoss()
  62831. {
  62832. updateCurrentModifiers();
  62833. if (component->hasKeyboardFocus (true))
  62834. {
  62835. lastFocusedComponent = Component::currentlyFocusedComponent;
  62836. if (lastFocusedComponent != 0)
  62837. {
  62838. Component::currentlyFocusedComponent = 0;
  62839. Desktop::getInstance().triggerFocusCallback();
  62840. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62841. }
  62842. }
  62843. }
  62844. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62845. {
  62846. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62847. ? static_cast <Component*> (lastFocusedComponent)
  62848. : component;
  62849. }
  62850. void ComponentPeer::handleScreenSizeChange()
  62851. {
  62852. updateCurrentModifiers();
  62853. component->parentSizeChanged();
  62854. handleMovedOrResized();
  62855. }
  62856. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62857. {
  62858. lastNonFullscreenBounds = newBounds;
  62859. }
  62860. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62861. {
  62862. return lastNonFullscreenBounds;
  62863. }
  62864. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62865. const StringArray& files,
  62866. FileDragAndDropTarget* const lastOne)
  62867. {
  62868. while (c != 0)
  62869. {
  62870. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62871. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62872. return t;
  62873. c = c->getParentComponent();
  62874. }
  62875. return 0;
  62876. }
  62877. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62878. {
  62879. updateCurrentModifiers();
  62880. FileDragAndDropTarget* lastTarget
  62881. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62882. FileDragAndDropTarget* newTarget = 0;
  62883. Component* const compUnderMouse = component->getComponentAt (position);
  62884. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62885. {
  62886. lastDragAndDropCompUnderMouse = compUnderMouse;
  62887. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62888. if (newTarget != lastTarget)
  62889. {
  62890. if (lastTarget != 0)
  62891. lastTarget->fileDragExit (files);
  62892. dragAndDropTargetComponent = 0;
  62893. if (newTarget != 0)
  62894. {
  62895. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62896. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62897. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62898. }
  62899. }
  62900. }
  62901. else
  62902. {
  62903. newTarget = lastTarget;
  62904. }
  62905. if (newTarget != 0)
  62906. {
  62907. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62908. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62909. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62910. }
  62911. }
  62912. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62913. {
  62914. handleFileDragMove (files, Point<int> (-1, -1));
  62915. jassert (dragAndDropTargetComponent == 0);
  62916. lastDragAndDropCompUnderMouse = 0;
  62917. }
  62918. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62919. {
  62920. handleFileDragMove (files, position);
  62921. if (dragAndDropTargetComponent != 0)
  62922. {
  62923. FileDragAndDropTarget* const target
  62924. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62925. dragAndDropTargetComponent = 0;
  62926. lastDragAndDropCompUnderMouse = 0;
  62927. if (target != 0)
  62928. {
  62929. Component* const targetComp = dynamic_cast <Component*> (target);
  62930. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62931. {
  62932. targetComp->internalModalInputAttempt();
  62933. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62934. return;
  62935. }
  62936. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62937. target->filesDropped (files, pos.getX(), pos.getY());
  62938. }
  62939. }
  62940. }
  62941. void ComponentPeer::handleUserClosingWindow()
  62942. {
  62943. updateCurrentModifiers();
  62944. component->userTriedToCloseWindow();
  62945. }
  62946. void ComponentPeer::bringModalComponentToFront()
  62947. {
  62948. Component::bringModalComponentToFront();
  62949. }
  62950. void ComponentPeer::clearMaskedRegion()
  62951. {
  62952. maskedRegion.clear();
  62953. }
  62954. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62955. {
  62956. maskedRegion.add (x, y, w, h);
  62957. }
  62958. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62959. {
  62960. StringArray s;
  62961. s.add ("Software Renderer");
  62962. return s;
  62963. }
  62964. int ComponentPeer::getCurrentRenderingEngine() throw()
  62965. {
  62966. return 0;
  62967. }
  62968. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62969. {
  62970. }
  62971. END_JUCE_NAMESPACE
  62972. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62973. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62974. BEGIN_JUCE_NAMESPACE
  62975. DialogWindow::DialogWindow (const String& name,
  62976. const Colour& backgroundColour_,
  62977. const bool escapeKeyTriggersCloseButton_,
  62978. const bool addToDesktop_)
  62979. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62980. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62981. {
  62982. }
  62983. DialogWindow::~DialogWindow()
  62984. {
  62985. }
  62986. void DialogWindow::resized()
  62987. {
  62988. DocumentWindow::resized();
  62989. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62990. if (escapeKeyTriggersCloseButton
  62991. && getCloseButton() != 0
  62992. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62993. {
  62994. getCloseButton()->addShortcut (esc);
  62995. }
  62996. }
  62997. class TempDialogWindow : public DialogWindow
  62998. {
  62999. public:
  63000. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63001. : DialogWindow (title, colour, escapeCloses, true)
  63002. {
  63003. if (! JUCEApplication::isStandaloneApp())
  63004. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63005. }
  63006. ~TempDialogWindow()
  63007. {
  63008. }
  63009. void closeButtonPressed()
  63010. {
  63011. setVisible (false);
  63012. }
  63013. private:
  63014. TempDialogWindow (const TempDialogWindow&);
  63015. TempDialogWindow& operator= (const TempDialogWindow&);
  63016. };
  63017. int DialogWindow::showModalDialog (const String& dialogTitle,
  63018. Component* contentComponent,
  63019. Component* componentToCentreAround,
  63020. const Colour& colour,
  63021. const bool escapeKeyTriggersCloseButton,
  63022. const bool shouldBeResizable,
  63023. const bool useBottomRightCornerResizer)
  63024. {
  63025. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63026. dw.setContentComponent (contentComponent, true, true);
  63027. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63028. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63029. const int result = dw.runModalLoop();
  63030. dw.setContentComponent (0, false);
  63031. return result;
  63032. }
  63033. END_JUCE_NAMESPACE
  63034. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63035. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63036. BEGIN_JUCE_NAMESPACE
  63037. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63038. {
  63039. public:
  63040. ButtonListenerProxy (DocumentWindow& owner_)
  63041. : owner (owner_)
  63042. {
  63043. }
  63044. void buttonClicked (Button* button)
  63045. {
  63046. if (button == owner.getMinimiseButton())
  63047. owner.minimiseButtonPressed();
  63048. else if (button == owner.getMaximiseButton())
  63049. owner.maximiseButtonPressed();
  63050. else if (button == owner.getCloseButton())
  63051. owner.closeButtonPressed();
  63052. }
  63053. juce_UseDebuggingNewOperator
  63054. private:
  63055. DocumentWindow& owner;
  63056. ButtonListenerProxy (const ButtonListenerProxy&);
  63057. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63058. };
  63059. DocumentWindow::DocumentWindow (const String& title,
  63060. const Colour& backgroundColour,
  63061. const int requiredButtons_,
  63062. const bool addToDesktop_)
  63063. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63064. titleBarHeight (26),
  63065. menuBarHeight (24),
  63066. requiredButtons (requiredButtons_),
  63067. #if JUCE_MAC
  63068. positionTitleBarButtonsOnLeft (true),
  63069. #else
  63070. positionTitleBarButtonsOnLeft (false),
  63071. #endif
  63072. drawTitleTextCentred (true),
  63073. menuBarModel (0)
  63074. {
  63075. setResizeLimits (128, 128, 32768, 32768);
  63076. lookAndFeelChanged();
  63077. }
  63078. DocumentWindow::~DocumentWindow()
  63079. {
  63080. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63081. titleBarButtons[i] = 0;
  63082. menuBar = 0;
  63083. }
  63084. void DocumentWindow::repaintTitleBar()
  63085. {
  63086. repaint (getTitleBarArea());
  63087. }
  63088. void DocumentWindow::setName (const String& newName)
  63089. {
  63090. if (newName != getName())
  63091. {
  63092. Component::setName (newName);
  63093. repaintTitleBar();
  63094. }
  63095. }
  63096. void DocumentWindow::setIcon (const Image& imageToUse)
  63097. {
  63098. titleBarIcon = imageToUse;
  63099. repaintTitleBar();
  63100. }
  63101. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63102. {
  63103. titleBarHeight = newHeight;
  63104. resized();
  63105. repaintTitleBar();
  63106. }
  63107. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63108. const bool positionTitleBarButtonsOnLeft_)
  63109. {
  63110. requiredButtons = requiredButtons_;
  63111. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63112. lookAndFeelChanged();
  63113. }
  63114. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63115. {
  63116. drawTitleTextCentred = textShouldBeCentred;
  63117. repaintTitleBar();
  63118. }
  63119. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63120. const int menuBarHeight_)
  63121. {
  63122. if (menuBarModel != menuBarModel_)
  63123. {
  63124. menuBar = 0;
  63125. menuBarModel = menuBarModel_;
  63126. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63127. : getLookAndFeel().getDefaultMenuBarHeight();
  63128. if (menuBarModel != 0)
  63129. {
  63130. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63131. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63132. menuBar->setEnabled (isActiveWindow());
  63133. }
  63134. resized();
  63135. }
  63136. }
  63137. void DocumentWindow::closeButtonPressed()
  63138. {
  63139. /* If you've got a close button, you have to override this method to get
  63140. rid of your window!
  63141. If the window is just a pop-up, you should override this method and make
  63142. it delete the window in whatever way is appropriate for your app. E.g. you
  63143. might just want to call "delete this".
  63144. If your app is centred around this window such that the whole app should quit when
  63145. the window is closed, then you will probably want to use this method as an opportunity
  63146. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63147. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63148. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63149. or closing it via the taskbar icon on Windows).
  63150. */
  63151. jassertfalse;
  63152. }
  63153. void DocumentWindow::minimiseButtonPressed()
  63154. {
  63155. setMinimised (true);
  63156. }
  63157. void DocumentWindow::maximiseButtonPressed()
  63158. {
  63159. setFullScreen (! isFullScreen());
  63160. }
  63161. void DocumentWindow::paint (Graphics& g)
  63162. {
  63163. ResizableWindow::paint (g);
  63164. if (resizableBorder == 0)
  63165. {
  63166. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63167. const BorderSize border (getBorderThickness());
  63168. g.fillRect (0, 0, getWidth(), border.getTop());
  63169. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63170. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63171. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63172. }
  63173. const Rectangle<int> titleBarArea (getTitleBarArea());
  63174. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63175. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63176. int titleSpaceX1 = 6;
  63177. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63178. for (int i = 0; i < 3; ++i)
  63179. {
  63180. if (titleBarButtons[i] != 0)
  63181. {
  63182. if (positionTitleBarButtonsOnLeft)
  63183. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63184. else
  63185. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63186. }
  63187. }
  63188. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63189. titleBarArea.getWidth(),
  63190. titleBarArea.getHeight(),
  63191. titleSpaceX1,
  63192. jmax (1, titleSpaceX2 - titleSpaceX1),
  63193. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63194. ! drawTitleTextCentred);
  63195. }
  63196. void DocumentWindow::resized()
  63197. {
  63198. ResizableWindow::resized();
  63199. if (titleBarButtons[1] != 0)
  63200. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63201. const Rectangle<int> titleBarArea (getTitleBarArea());
  63202. getLookAndFeel()
  63203. .positionDocumentWindowButtons (*this,
  63204. titleBarArea.getX(), titleBarArea.getY(),
  63205. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63206. titleBarButtons[0],
  63207. titleBarButtons[1],
  63208. titleBarButtons[2],
  63209. positionTitleBarButtonsOnLeft);
  63210. if (menuBar != 0)
  63211. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63212. titleBarArea.getWidth(), menuBarHeight);
  63213. }
  63214. const BorderSize DocumentWindow::getBorderThickness()
  63215. {
  63216. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63217. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63218. }
  63219. const BorderSize DocumentWindow::getContentComponentBorder()
  63220. {
  63221. BorderSize border (getBorderThickness());
  63222. border.setTop (border.getTop()
  63223. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63224. + (menuBar != 0 ? menuBarHeight : 0));
  63225. return border;
  63226. }
  63227. int DocumentWindow::getTitleBarHeight() const
  63228. {
  63229. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63230. }
  63231. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63232. {
  63233. const BorderSize border (getBorderThickness());
  63234. return Rectangle<int> (border.getLeft(), border.getTop(),
  63235. getWidth() - border.getLeftAndRight(),
  63236. getTitleBarHeight());
  63237. }
  63238. Button* DocumentWindow::getCloseButton() const throw()
  63239. {
  63240. return titleBarButtons[2];
  63241. }
  63242. Button* DocumentWindow::getMinimiseButton() const throw()
  63243. {
  63244. return titleBarButtons[0];
  63245. }
  63246. Button* DocumentWindow::getMaximiseButton() const throw()
  63247. {
  63248. return titleBarButtons[1];
  63249. }
  63250. int DocumentWindow::getDesktopWindowStyleFlags() const
  63251. {
  63252. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63253. if ((requiredButtons & minimiseButton) != 0)
  63254. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63255. if ((requiredButtons & maximiseButton) != 0)
  63256. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63257. if ((requiredButtons & closeButton) != 0)
  63258. styleFlags |= ComponentPeer::windowHasCloseButton;
  63259. return styleFlags;
  63260. }
  63261. void DocumentWindow::lookAndFeelChanged()
  63262. {
  63263. int i;
  63264. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63265. titleBarButtons[i] = 0;
  63266. if (! isUsingNativeTitleBar())
  63267. {
  63268. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63269. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63270. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63271. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63272. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63273. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63274. for (i = 0; i < 3; ++i)
  63275. {
  63276. if (titleBarButtons[i] != 0)
  63277. {
  63278. if (buttonListener == 0)
  63279. buttonListener = new ButtonListenerProxy (*this);
  63280. titleBarButtons[i]->addButtonListener (buttonListener);
  63281. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63282. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63283. Component::addAndMakeVisible (titleBarButtons[i]);
  63284. }
  63285. }
  63286. if (getCloseButton() != 0)
  63287. {
  63288. #if JUCE_MAC
  63289. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63290. #else
  63291. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63292. #endif
  63293. }
  63294. }
  63295. activeWindowStatusChanged();
  63296. ResizableWindow::lookAndFeelChanged();
  63297. }
  63298. void DocumentWindow::parentHierarchyChanged()
  63299. {
  63300. lookAndFeelChanged();
  63301. }
  63302. void DocumentWindow::activeWindowStatusChanged()
  63303. {
  63304. ResizableWindow::activeWindowStatusChanged();
  63305. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63306. if (titleBarButtons[i] != 0)
  63307. titleBarButtons[i]->setEnabled (isActiveWindow());
  63308. if (menuBar != 0)
  63309. menuBar->setEnabled (isActiveWindow());
  63310. }
  63311. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63312. {
  63313. if (getTitleBarArea().contains (e.x, e.y)
  63314. && getMaximiseButton() != 0)
  63315. {
  63316. getMaximiseButton()->triggerClick();
  63317. }
  63318. }
  63319. void DocumentWindow::userTriedToCloseWindow()
  63320. {
  63321. closeButtonPressed();
  63322. }
  63323. END_JUCE_NAMESPACE
  63324. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63325. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63326. BEGIN_JUCE_NAMESPACE
  63327. ResizableWindow::ResizableWindow (const String& name,
  63328. const bool addToDesktop_)
  63329. : TopLevelWindow (name, addToDesktop_),
  63330. resizeToFitContent (false),
  63331. fullscreen (false),
  63332. lastNonFullScreenPos (50, 50, 256, 256),
  63333. constrainer (0)
  63334. #if JUCE_DEBUG
  63335. , hasBeenResized (false)
  63336. #endif
  63337. {
  63338. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63339. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63340. if (addToDesktop_)
  63341. Component::addToDesktop (getDesktopWindowStyleFlags());
  63342. }
  63343. ResizableWindow::ResizableWindow (const String& name,
  63344. const Colour& backgroundColour_,
  63345. const bool addToDesktop_)
  63346. : TopLevelWindow (name, addToDesktop_),
  63347. resizeToFitContent (false),
  63348. fullscreen (false),
  63349. lastNonFullScreenPos (50, 50, 256, 256),
  63350. constrainer (0)
  63351. #if JUCE_DEBUG
  63352. , hasBeenResized (false)
  63353. #endif
  63354. {
  63355. setBackgroundColour (backgroundColour_);
  63356. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63357. if (addToDesktop_)
  63358. Component::addToDesktop (getDesktopWindowStyleFlags());
  63359. }
  63360. ResizableWindow::~ResizableWindow()
  63361. {
  63362. resizableCorner = 0;
  63363. resizableBorder = 0;
  63364. contentComponent.deleteAndZero();
  63365. // have you been adding your own components directly to this window..? tut tut tut.
  63366. // Read the instructions for using a ResizableWindow!
  63367. jassert (getNumChildComponents() == 0);
  63368. }
  63369. int ResizableWindow::getDesktopWindowStyleFlags() const
  63370. {
  63371. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63372. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63373. styleFlags |= ComponentPeer::windowIsResizable;
  63374. return styleFlags;
  63375. }
  63376. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63377. const bool deleteOldOne,
  63378. const bool resizeToFit)
  63379. {
  63380. resizeToFitContent = resizeToFit;
  63381. if (newContentComponent != static_cast <Component*> (contentComponent))
  63382. {
  63383. if (deleteOldOne)
  63384. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63385. // external deletion of the content comp)
  63386. else
  63387. removeChildComponent (contentComponent);
  63388. contentComponent = newContentComponent;
  63389. Component::addAndMakeVisible (contentComponent);
  63390. }
  63391. if (resizeToFit)
  63392. childBoundsChanged (contentComponent);
  63393. resized(); // must always be called to position the new content comp
  63394. }
  63395. void ResizableWindow::setContentComponentSize (int width, int height)
  63396. {
  63397. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63398. const BorderSize border (getContentComponentBorder());
  63399. setSize (width + border.getLeftAndRight(),
  63400. height + border.getTopAndBottom());
  63401. }
  63402. const BorderSize ResizableWindow::getBorderThickness()
  63403. {
  63404. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63405. }
  63406. const BorderSize ResizableWindow::getContentComponentBorder()
  63407. {
  63408. return getBorderThickness();
  63409. }
  63410. void ResizableWindow::moved()
  63411. {
  63412. updateLastPos();
  63413. }
  63414. void ResizableWindow::visibilityChanged()
  63415. {
  63416. TopLevelWindow::visibilityChanged();
  63417. updateLastPos();
  63418. }
  63419. void ResizableWindow::resized()
  63420. {
  63421. if (resizableBorder != 0)
  63422. {
  63423. resizableBorder->setVisible (! isFullScreen());
  63424. resizableBorder->setBorderThickness (getBorderThickness());
  63425. resizableBorder->setSize (getWidth(), getHeight());
  63426. resizableBorder->toBack();
  63427. }
  63428. if (resizableCorner != 0)
  63429. {
  63430. resizableCorner->setVisible (! isFullScreen());
  63431. const int resizerSize = 18;
  63432. resizableCorner->setBounds (getWidth() - resizerSize,
  63433. getHeight() - resizerSize,
  63434. resizerSize, resizerSize);
  63435. }
  63436. if (contentComponent != 0)
  63437. contentComponent->setBoundsInset (getContentComponentBorder());
  63438. updateLastPos();
  63439. #if JUCE_DEBUG
  63440. hasBeenResized = true;
  63441. #endif
  63442. }
  63443. void ResizableWindow::childBoundsChanged (Component* child)
  63444. {
  63445. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63446. {
  63447. // not going to look very good if this component has a zero size..
  63448. jassert (child->getWidth() > 0);
  63449. jassert (child->getHeight() > 0);
  63450. const BorderSize borders (getContentComponentBorder());
  63451. setSize (child->getWidth() + borders.getLeftAndRight(),
  63452. child->getHeight() + borders.getTopAndBottom());
  63453. }
  63454. }
  63455. void ResizableWindow::activeWindowStatusChanged()
  63456. {
  63457. const BorderSize border (getContentComponentBorder());
  63458. Rectangle<int> area (getLocalBounds());
  63459. repaint (area.removeFromTop (border.getTop()));
  63460. repaint (area.removeFromLeft (border.getLeft()));
  63461. repaint (area.removeFromRight (border.getRight()));
  63462. repaint (area.removeFromBottom (border.getBottom()));
  63463. }
  63464. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63465. const bool useBottomRightCornerResizer)
  63466. {
  63467. if (shouldBeResizable)
  63468. {
  63469. if (useBottomRightCornerResizer)
  63470. {
  63471. resizableBorder = 0;
  63472. if (resizableCorner == 0)
  63473. {
  63474. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63475. resizableCorner->setAlwaysOnTop (true);
  63476. }
  63477. }
  63478. else
  63479. {
  63480. resizableCorner = 0;
  63481. if (resizableBorder == 0)
  63482. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63483. }
  63484. }
  63485. else
  63486. {
  63487. resizableCorner = 0;
  63488. resizableBorder = 0;
  63489. }
  63490. if (isUsingNativeTitleBar())
  63491. recreateDesktopWindow();
  63492. childBoundsChanged (contentComponent);
  63493. resized();
  63494. }
  63495. bool ResizableWindow::isResizable() const throw()
  63496. {
  63497. return resizableCorner != 0
  63498. || resizableBorder != 0;
  63499. }
  63500. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63501. const int newMinimumHeight,
  63502. const int newMaximumWidth,
  63503. const int newMaximumHeight) throw()
  63504. {
  63505. // if you've set up a custom constrainer then these settings won't have any effect..
  63506. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63507. if (constrainer == 0)
  63508. setConstrainer (&defaultConstrainer);
  63509. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63510. newMaximumWidth, newMaximumHeight);
  63511. setBoundsConstrained (getBounds());
  63512. }
  63513. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63514. {
  63515. if (constrainer != newConstrainer)
  63516. {
  63517. constrainer = newConstrainer;
  63518. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63519. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63520. resizableCorner = 0;
  63521. resizableBorder = 0;
  63522. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63523. ComponentPeer* const peer = getPeer();
  63524. if (peer != 0)
  63525. peer->setConstrainer (newConstrainer);
  63526. }
  63527. }
  63528. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63529. {
  63530. if (constrainer != 0)
  63531. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63532. else
  63533. setBounds (bounds);
  63534. }
  63535. void ResizableWindow::paint (Graphics& g)
  63536. {
  63537. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63538. getBorderThickness(), *this);
  63539. if (! isFullScreen())
  63540. {
  63541. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63542. getBorderThickness(), *this);
  63543. }
  63544. #if JUCE_DEBUG
  63545. /* If this fails, then you've probably written a subclass with a resized()
  63546. callback but forgotten to make it call its parent class's resized() method.
  63547. It's important when you override methods like resized(), moved(),
  63548. etc., that you make sure the base class methods also get called.
  63549. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63550. because your content should all be inside the content component - and it's the
  63551. content component's resized() method that you should be using to do your
  63552. layout.
  63553. */
  63554. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63555. #endif
  63556. }
  63557. void ResizableWindow::lookAndFeelChanged()
  63558. {
  63559. resized();
  63560. if (isOnDesktop())
  63561. {
  63562. Component::addToDesktop (getDesktopWindowStyleFlags());
  63563. ComponentPeer* const peer = getPeer();
  63564. if (peer != 0)
  63565. peer->setConstrainer (constrainer);
  63566. }
  63567. }
  63568. const Colour ResizableWindow::getBackgroundColour() const throw()
  63569. {
  63570. return findColour (backgroundColourId, false);
  63571. }
  63572. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63573. {
  63574. Colour backgroundColour (newColour);
  63575. if (! Desktop::canUseSemiTransparentWindows())
  63576. backgroundColour = newColour.withAlpha (1.0f);
  63577. setColour (backgroundColourId, backgroundColour);
  63578. setOpaque (backgroundColour.isOpaque());
  63579. repaint();
  63580. }
  63581. bool ResizableWindow::isFullScreen() const
  63582. {
  63583. if (isOnDesktop())
  63584. {
  63585. ComponentPeer* const peer = getPeer();
  63586. return peer != 0 && peer->isFullScreen();
  63587. }
  63588. return fullscreen;
  63589. }
  63590. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63591. {
  63592. if (shouldBeFullScreen != isFullScreen())
  63593. {
  63594. updateLastPos();
  63595. fullscreen = shouldBeFullScreen;
  63596. if (isOnDesktop())
  63597. {
  63598. ComponentPeer* const peer = getPeer();
  63599. if (peer != 0)
  63600. {
  63601. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63602. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63603. peer->setFullScreen (shouldBeFullScreen);
  63604. if (! shouldBeFullScreen)
  63605. setBounds (lastPos);
  63606. }
  63607. else
  63608. {
  63609. jassertfalse;
  63610. }
  63611. }
  63612. else
  63613. {
  63614. if (shouldBeFullScreen)
  63615. setBounds (0, 0, getParentWidth(), getParentHeight());
  63616. else
  63617. setBounds (lastNonFullScreenPos);
  63618. }
  63619. resized();
  63620. }
  63621. }
  63622. bool ResizableWindow::isMinimised() const
  63623. {
  63624. ComponentPeer* const peer = getPeer();
  63625. return (peer != 0) && peer->isMinimised();
  63626. }
  63627. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63628. {
  63629. if (shouldMinimise != isMinimised())
  63630. {
  63631. ComponentPeer* const peer = getPeer();
  63632. if (peer != 0)
  63633. {
  63634. updateLastPos();
  63635. peer->setMinimised (shouldMinimise);
  63636. }
  63637. else
  63638. {
  63639. jassertfalse;
  63640. }
  63641. }
  63642. }
  63643. void ResizableWindow::updateLastPos()
  63644. {
  63645. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63646. {
  63647. lastNonFullScreenPos = getBounds();
  63648. }
  63649. }
  63650. void ResizableWindow::parentSizeChanged()
  63651. {
  63652. if (isFullScreen() && getParentComponent() != 0)
  63653. {
  63654. setBounds (0, 0, getParentWidth(), getParentHeight());
  63655. }
  63656. }
  63657. const String ResizableWindow::getWindowStateAsString()
  63658. {
  63659. updateLastPos();
  63660. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63661. }
  63662. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63663. {
  63664. StringArray tokens;
  63665. tokens.addTokens (s, false);
  63666. tokens.removeEmptyStrings();
  63667. tokens.trim();
  63668. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63669. const int firstCoord = fs ? 1 : 0;
  63670. if (tokens.size() != firstCoord + 4)
  63671. return false;
  63672. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63673. tokens[firstCoord + 1].getIntValue(),
  63674. tokens[firstCoord + 2].getIntValue(),
  63675. tokens[firstCoord + 3].getIntValue());
  63676. if (newPos.isEmpty())
  63677. return false;
  63678. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63679. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63680. if (peer != 0)
  63681. peer->getFrameSize().addTo (newPos);
  63682. if (! screen.contains (newPos))
  63683. {
  63684. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63685. jmin (newPos.getHeight(), screen.getHeight()));
  63686. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63687. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63688. }
  63689. if (peer != 0)
  63690. {
  63691. peer->getFrameSize().subtractFrom (newPos);
  63692. peer->setNonFullScreenBounds (newPos);
  63693. }
  63694. lastNonFullScreenPos = newPos;
  63695. setFullScreen (fs);
  63696. if (! fs)
  63697. setBoundsConstrained (newPos);
  63698. return true;
  63699. }
  63700. void ResizableWindow::mouseDown (const MouseEvent&)
  63701. {
  63702. if (! isFullScreen())
  63703. dragger.startDraggingComponent (this, constrainer);
  63704. }
  63705. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63706. {
  63707. if (! isFullScreen())
  63708. dragger.dragComponent (this, e);
  63709. }
  63710. #if JUCE_DEBUG
  63711. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63712. {
  63713. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63714. manages its child components automatically, and if you add your own it'll cause
  63715. trouble. Instead, use setContentComponent() to give it a component which
  63716. will be automatically resized and kept in the right place - then you can add
  63717. subcomponents to the content comp. See the notes for the ResizableWindow class
  63718. for more info.
  63719. If you really know what you're doing and want to avoid this assertion, just call
  63720. Component::addChildComponent directly.
  63721. */
  63722. jassertfalse;
  63723. Component::addChildComponent (child, zOrder);
  63724. }
  63725. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63726. {
  63727. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63728. manages its child components automatically, and if you add your own it'll cause
  63729. trouble. Instead, use setContentComponent() to give it a component which
  63730. will be automatically resized and kept in the right place - then you can add
  63731. subcomponents to the content comp. See the notes for the ResizableWindow class
  63732. for more info.
  63733. If you really know what you're doing and want to avoid this assertion, just call
  63734. Component::addAndMakeVisible directly.
  63735. */
  63736. jassertfalse;
  63737. Component::addAndMakeVisible (child, zOrder);
  63738. }
  63739. #endif
  63740. END_JUCE_NAMESPACE
  63741. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63742. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63743. BEGIN_JUCE_NAMESPACE
  63744. SplashScreen::SplashScreen()
  63745. {
  63746. setOpaque (true);
  63747. }
  63748. SplashScreen::~SplashScreen()
  63749. {
  63750. }
  63751. void SplashScreen::show (const String& title,
  63752. const Image& backgroundImage_,
  63753. const int minimumTimeToDisplayFor,
  63754. const bool useDropShadow,
  63755. const bool removeOnMouseClick)
  63756. {
  63757. backgroundImage = backgroundImage_;
  63758. jassert (backgroundImage_.isValid());
  63759. if (backgroundImage_.isValid())
  63760. {
  63761. setOpaque (! backgroundImage_.hasAlphaChannel());
  63762. show (title,
  63763. backgroundImage_.getWidth(),
  63764. backgroundImage_.getHeight(),
  63765. minimumTimeToDisplayFor,
  63766. useDropShadow,
  63767. removeOnMouseClick);
  63768. }
  63769. }
  63770. void SplashScreen::show (const String& title,
  63771. const int width,
  63772. const int height,
  63773. const int minimumTimeToDisplayFor,
  63774. const bool useDropShadow,
  63775. const bool removeOnMouseClick)
  63776. {
  63777. setName (title);
  63778. setAlwaysOnTop (true);
  63779. setVisible (true);
  63780. centreWithSize (width, height);
  63781. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63782. toFront (false);
  63783. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63784. repaint();
  63785. originalClickCounter = removeOnMouseClick
  63786. ? Desktop::getMouseButtonClickCounter()
  63787. : std::numeric_limits<int>::max();
  63788. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63789. startTimer (50);
  63790. }
  63791. void SplashScreen::paint (Graphics& g)
  63792. {
  63793. g.setOpacity (1.0f);
  63794. g.drawImage (backgroundImage,
  63795. 0, 0, getWidth(), getHeight(),
  63796. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63797. }
  63798. void SplashScreen::timerCallback()
  63799. {
  63800. if (Time::getCurrentTime() > earliestTimeToDelete
  63801. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63802. {
  63803. delete this;
  63804. }
  63805. }
  63806. END_JUCE_NAMESPACE
  63807. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63808. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63809. BEGIN_JUCE_NAMESPACE
  63810. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63811. const bool hasProgressBar,
  63812. const bool hasCancelButton,
  63813. const int timeOutMsWhenCancelling_,
  63814. const String& cancelButtonText)
  63815. : Thread ("Juce Progress Window"),
  63816. progress (0.0),
  63817. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63818. {
  63819. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63820. .createAlertWindow (title, String::empty, cancelButtonText,
  63821. String::empty, String::empty,
  63822. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63823. if (hasProgressBar)
  63824. alertWindow->addProgressBarComponent (progress);
  63825. }
  63826. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63827. {
  63828. stopThread (timeOutMsWhenCancelling);
  63829. }
  63830. bool ThreadWithProgressWindow::runThread (const int priority)
  63831. {
  63832. startThread (priority);
  63833. startTimer (100);
  63834. {
  63835. const ScopedLock sl (messageLock);
  63836. alertWindow->setMessage (message);
  63837. }
  63838. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63839. stopThread (timeOutMsWhenCancelling);
  63840. alertWindow->setVisible (false);
  63841. return finishedNaturally;
  63842. }
  63843. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63844. {
  63845. progress = newProgress;
  63846. }
  63847. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63848. {
  63849. const ScopedLock sl (messageLock);
  63850. message = newStatusMessage;
  63851. }
  63852. void ThreadWithProgressWindow::timerCallback()
  63853. {
  63854. if (! isThreadRunning())
  63855. {
  63856. // thread has finished normally..
  63857. alertWindow->exitModalState (1);
  63858. alertWindow->setVisible (false);
  63859. }
  63860. else
  63861. {
  63862. const ScopedLock sl (messageLock);
  63863. alertWindow->setMessage (message);
  63864. }
  63865. }
  63866. END_JUCE_NAMESPACE
  63867. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63868. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63869. BEGIN_JUCE_NAMESPACE
  63870. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63871. const int millisecondsBeforeTipAppears_)
  63872. : Component ("tooltip"),
  63873. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63874. mouseClicks (0),
  63875. lastHideTime (0),
  63876. lastComponentUnderMouse (0),
  63877. changedCompsSinceShown (true)
  63878. {
  63879. if (Desktop::getInstance().getMainMouseSource().canHover())
  63880. startTimer (123);
  63881. setAlwaysOnTop (true);
  63882. setOpaque (true);
  63883. if (parentComponent != 0)
  63884. parentComponent->addChildComponent (this);
  63885. }
  63886. TooltipWindow::~TooltipWindow()
  63887. {
  63888. hide();
  63889. }
  63890. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63891. {
  63892. millisecondsBeforeTipAppears = newTimeMs;
  63893. }
  63894. void TooltipWindow::paint (Graphics& g)
  63895. {
  63896. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63897. }
  63898. void TooltipWindow::mouseEnter (const MouseEvent&)
  63899. {
  63900. hide();
  63901. }
  63902. void TooltipWindow::showFor (const String& tip)
  63903. {
  63904. jassert (tip.isNotEmpty());
  63905. if (tipShowing != tip)
  63906. repaint();
  63907. tipShowing = tip;
  63908. Point<int> mousePos (Desktop::getMousePosition());
  63909. if (getParentComponent() != 0)
  63910. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63911. int x, y, w, h;
  63912. getLookAndFeel().getTooltipSize (tip, w, h);
  63913. if (mousePos.getX() > getParentWidth() / 2)
  63914. x = mousePos.getX() - (w + 12);
  63915. else
  63916. x = mousePos.getX() + 24;
  63917. if (mousePos.getY() > getParentHeight() / 2)
  63918. y = mousePos.getY() - (h + 6);
  63919. else
  63920. y = mousePos.getY() + 6;
  63921. setBounds (x, y, w, h);
  63922. setVisible (true);
  63923. if (getParentComponent() == 0)
  63924. {
  63925. addToDesktop (ComponentPeer::windowHasDropShadow
  63926. | ComponentPeer::windowIsTemporary
  63927. | ComponentPeer::windowIgnoresKeyPresses);
  63928. }
  63929. toFront (false);
  63930. }
  63931. const String TooltipWindow::getTipFor (Component* const c)
  63932. {
  63933. if (c != 0
  63934. && Process::isForegroundProcess()
  63935. && ! Component::isMouseButtonDownAnywhere())
  63936. {
  63937. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63938. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63939. return ttc->getTooltip();
  63940. }
  63941. return String::empty;
  63942. }
  63943. void TooltipWindow::hide()
  63944. {
  63945. tipShowing = String::empty;
  63946. removeFromDesktop();
  63947. setVisible (false);
  63948. }
  63949. void TooltipWindow::timerCallback()
  63950. {
  63951. const unsigned int now = Time::getApproximateMillisecondCounter();
  63952. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63953. const String newTip (getTipFor (newComp));
  63954. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63955. lastComponentUnderMouse = newComp;
  63956. lastTipUnderMouse = newTip;
  63957. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63958. const bool mouseWasClicked = clickCount > mouseClicks;
  63959. mouseClicks = clickCount;
  63960. const Point<int> mousePos (Desktop::getMousePosition());
  63961. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63962. lastMousePos = mousePos;
  63963. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63964. lastCompChangeTime = now;
  63965. if (isVisible() || now < lastHideTime + 500)
  63966. {
  63967. // if a tip is currently visible (or has just disappeared), update to a new one
  63968. // immediately if needed..
  63969. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63970. {
  63971. if (isVisible())
  63972. {
  63973. lastHideTime = now;
  63974. hide();
  63975. }
  63976. }
  63977. else if (tipChanged)
  63978. {
  63979. showFor (newTip);
  63980. }
  63981. }
  63982. else
  63983. {
  63984. // if there isn't currently a tip, but one is needed, only let it
  63985. // appear after a timeout..
  63986. if (newTip.isNotEmpty()
  63987. && newTip != tipShowing
  63988. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63989. {
  63990. showFor (newTip);
  63991. }
  63992. }
  63993. }
  63994. END_JUCE_NAMESPACE
  63995. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63996. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63997. BEGIN_JUCE_NAMESPACE
  63998. /** Keeps track of the active top level window.
  63999. */
  64000. class TopLevelWindowManager : public Timer,
  64001. public DeletedAtShutdown
  64002. {
  64003. public:
  64004. TopLevelWindowManager()
  64005. : currentActive (0)
  64006. {
  64007. }
  64008. ~TopLevelWindowManager()
  64009. {
  64010. clearSingletonInstance();
  64011. }
  64012. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64013. void timerCallback()
  64014. {
  64015. startTimer (jmin (1731, getTimerInterval() * 2));
  64016. TopLevelWindow* active = 0;
  64017. if (Process::isForegroundProcess())
  64018. {
  64019. active = currentActive;
  64020. Component* const c = Component::getCurrentlyFocusedComponent();
  64021. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64022. if (tlw == 0 && c != 0)
  64023. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64024. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64025. if (tlw != 0)
  64026. active = tlw;
  64027. }
  64028. if (active != currentActive)
  64029. {
  64030. currentActive = active;
  64031. for (int i = windows.size(); --i >= 0;)
  64032. {
  64033. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64034. tlw->setWindowActive (isWindowActive (tlw));
  64035. i = jmin (i, windows.size() - 1);
  64036. }
  64037. Desktop::getInstance().triggerFocusCallback();
  64038. }
  64039. }
  64040. bool addWindow (TopLevelWindow* const w)
  64041. {
  64042. windows.add (w);
  64043. startTimer (10);
  64044. return isWindowActive (w);
  64045. }
  64046. void removeWindow (TopLevelWindow* const w)
  64047. {
  64048. startTimer (10);
  64049. if (currentActive == w)
  64050. currentActive = 0;
  64051. windows.removeValue (w);
  64052. if (windows.size() == 0)
  64053. deleteInstance();
  64054. }
  64055. Array <TopLevelWindow*> windows;
  64056. private:
  64057. TopLevelWindow* currentActive;
  64058. bool isWindowActive (TopLevelWindow* const tlw) const
  64059. {
  64060. return (tlw == currentActive
  64061. || tlw->isParentOf (currentActive)
  64062. || tlw->hasKeyboardFocus (true))
  64063. && tlw->isShowing();
  64064. }
  64065. TopLevelWindowManager (const TopLevelWindowManager&);
  64066. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64067. };
  64068. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64069. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64070. {
  64071. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64072. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64073. }
  64074. TopLevelWindow::TopLevelWindow (const String& name,
  64075. const bool addToDesktop_)
  64076. : Component (name),
  64077. useDropShadow (true),
  64078. useNativeTitleBar (false),
  64079. windowIsActive_ (false)
  64080. {
  64081. setOpaque (true);
  64082. if (addToDesktop_)
  64083. Component::addToDesktop (getDesktopWindowStyleFlags());
  64084. else
  64085. setDropShadowEnabled (true);
  64086. setWantsKeyboardFocus (true);
  64087. setBroughtToFrontOnMouseClick (true);
  64088. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64089. }
  64090. TopLevelWindow::~TopLevelWindow()
  64091. {
  64092. shadower = 0;
  64093. TopLevelWindowManager::getInstance()->removeWindow (this);
  64094. }
  64095. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64096. {
  64097. if (hasKeyboardFocus (true))
  64098. TopLevelWindowManager::getInstance()->timerCallback();
  64099. else
  64100. TopLevelWindowManager::getInstance()->startTimer (10);
  64101. }
  64102. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64103. {
  64104. if (windowIsActive_ != isNowActive)
  64105. {
  64106. windowIsActive_ = isNowActive;
  64107. activeWindowStatusChanged();
  64108. }
  64109. }
  64110. void TopLevelWindow::activeWindowStatusChanged()
  64111. {
  64112. }
  64113. void TopLevelWindow::parentHierarchyChanged()
  64114. {
  64115. setDropShadowEnabled (useDropShadow);
  64116. }
  64117. void TopLevelWindow::visibilityChanged()
  64118. {
  64119. if (isShowing())
  64120. toFront (true);
  64121. }
  64122. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64123. {
  64124. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64125. if (useDropShadow)
  64126. styleFlags |= ComponentPeer::windowHasDropShadow;
  64127. if (useNativeTitleBar)
  64128. styleFlags |= ComponentPeer::windowHasTitleBar;
  64129. return styleFlags;
  64130. }
  64131. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64132. {
  64133. useDropShadow = useShadow;
  64134. if (isOnDesktop())
  64135. {
  64136. shadower = 0;
  64137. Component::addToDesktop (getDesktopWindowStyleFlags());
  64138. }
  64139. else
  64140. {
  64141. if (useShadow && isOpaque())
  64142. {
  64143. if (shadower == 0)
  64144. {
  64145. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64146. if (shadower != 0)
  64147. shadower->setOwner (this);
  64148. }
  64149. }
  64150. else
  64151. {
  64152. shadower = 0;
  64153. }
  64154. }
  64155. }
  64156. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64157. {
  64158. if (useNativeTitleBar != useNativeTitleBar_)
  64159. {
  64160. useNativeTitleBar = useNativeTitleBar_;
  64161. recreateDesktopWindow();
  64162. sendLookAndFeelChange();
  64163. }
  64164. }
  64165. void TopLevelWindow::recreateDesktopWindow()
  64166. {
  64167. if (isOnDesktop())
  64168. {
  64169. Component::addToDesktop (getDesktopWindowStyleFlags());
  64170. toFront (true);
  64171. }
  64172. }
  64173. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64174. {
  64175. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64176. because this class needs to make sure its layout corresponds with settings like whether
  64177. it's got a native title bar or not.
  64178. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64179. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64180. method, then add or remove whatever flags are necessary from this value before returning it.
  64181. */
  64182. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64183. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64184. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64185. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64186. sendLookAndFeelChange();
  64187. }
  64188. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64189. {
  64190. if (c == 0)
  64191. c = TopLevelWindow::getActiveTopLevelWindow();
  64192. if (c == 0)
  64193. {
  64194. centreWithSize (width, height);
  64195. }
  64196. else
  64197. {
  64198. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64199. (c->getHeight() - height) / 2)));
  64200. Rectangle<int> parentArea (c->getParentMonitorArea());
  64201. if (getParentComponent() != 0)
  64202. {
  64203. p = getParentComponent()->globalPositionToRelative (p);
  64204. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64205. }
  64206. parentArea.reduce (12, 12);
  64207. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64208. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64209. width, height);
  64210. }
  64211. }
  64212. int TopLevelWindow::getNumTopLevelWindows() throw()
  64213. {
  64214. return TopLevelWindowManager::getInstance()->windows.size();
  64215. }
  64216. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64217. {
  64218. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64219. }
  64220. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64221. {
  64222. TopLevelWindow* best = 0;
  64223. int bestNumTWLParents = -1;
  64224. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64225. {
  64226. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64227. if (tlw->isActiveWindow())
  64228. {
  64229. int numTWLParents = 0;
  64230. const Component* c = tlw->getParentComponent();
  64231. while (c != 0)
  64232. {
  64233. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64234. ++numTWLParents;
  64235. c = c->getParentComponent();
  64236. }
  64237. if (bestNumTWLParents < numTWLParents)
  64238. {
  64239. best = tlw;
  64240. bestNumTWLParents = numTWLParents;
  64241. }
  64242. }
  64243. }
  64244. return best;
  64245. }
  64246. END_JUCE_NAMESPACE
  64247. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64248. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64249. BEGIN_JUCE_NAMESPACE
  64250. namespace RelativeCoordinateHelpers
  64251. {
  64252. static void skipComma (const juce_wchar* const s, int& i)
  64253. {
  64254. while (CharacterFunctions::isWhitespace (s[i]))
  64255. ++i;
  64256. if (s[i] == ',')
  64257. ++i;
  64258. }
  64259. }
  64260. const String RelativeCoordinate::Strings::parent ("parent");
  64261. const String RelativeCoordinate::Strings::left ("left");
  64262. const String RelativeCoordinate::Strings::right ("right");
  64263. const String RelativeCoordinate::Strings::top ("top");
  64264. const String RelativeCoordinate::Strings::bottom ("bottom");
  64265. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64266. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64267. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64268. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64269. RelativeCoordinate::RelativeCoordinate()
  64270. {
  64271. }
  64272. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64273. : term (term_)
  64274. {
  64275. }
  64276. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64277. : term (other.term)
  64278. {
  64279. }
  64280. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64281. {
  64282. term = other.term;
  64283. return *this;
  64284. }
  64285. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64286. : term (absoluteDistanceFromOrigin)
  64287. {
  64288. }
  64289. RelativeCoordinate::RelativeCoordinate (const String& s)
  64290. {
  64291. try
  64292. {
  64293. term = Expression (s);
  64294. }
  64295. catch (...)
  64296. {}
  64297. }
  64298. RelativeCoordinate::~RelativeCoordinate()
  64299. {
  64300. }
  64301. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64302. {
  64303. return term.toString() == other.term.toString();
  64304. }
  64305. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64306. {
  64307. return ! operator== (other);
  64308. }
  64309. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64310. {
  64311. try
  64312. {
  64313. if (context != 0)
  64314. return term.evaluate (*context);
  64315. else
  64316. return term.evaluate();
  64317. }
  64318. catch (...)
  64319. {}
  64320. return 0.0;
  64321. }
  64322. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64323. {
  64324. try
  64325. {
  64326. if (context != 0)
  64327. term.evaluate (*context);
  64328. else
  64329. term.evaluate();
  64330. }
  64331. catch (...)
  64332. {
  64333. return true;
  64334. }
  64335. return false;
  64336. }
  64337. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64338. {
  64339. try
  64340. {
  64341. if (context != 0)
  64342. {
  64343. term = term.adjustedToGiveNewResult (newPos, *context);
  64344. }
  64345. else
  64346. {
  64347. Expression::EvaluationContext defaultContext;
  64348. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64349. }
  64350. }
  64351. catch (...)
  64352. {}
  64353. }
  64354. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64355. {
  64356. try
  64357. {
  64358. if (context != 0)
  64359. return term.referencesSymbol (coordName, *context);
  64360. Expression::EvaluationContext defaultContext;
  64361. return term.referencesSymbol (coordName, defaultContext);
  64362. }
  64363. catch (...)
  64364. {}
  64365. return false;
  64366. }
  64367. bool RelativeCoordinate::isDynamic() const
  64368. {
  64369. return term.usesAnySymbols();
  64370. }
  64371. const String RelativeCoordinate::toString() const
  64372. {
  64373. return term.toString();
  64374. }
  64375. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName,
  64376. const Expression::EvaluationContext* context)
  64377. {
  64378. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64379. if (term.referencesSymbol (oldName, *context))
  64380. {
  64381. const double oldValue = resolve (context);
  64382. term = term.withRenamedSymbol (oldName, newName);
  64383. moveToAbsolute (oldValue, context);
  64384. }
  64385. }
  64386. RelativePoint::RelativePoint()
  64387. {
  64388. }
  64389. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64390. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64391. {
  64392. }
  64393. RelativePoint::RelativePoint (const float x_, const float y_)
  64394. : x (x_), y (y_)
  64395. {
  64396. }
  64397. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64398. : x (x_), y (y_)
  64399. {
  64400. }
  64401. RelativePoint::RelativePoint (const String& s)
  64402. {
  64403. int i = 0;
  64404. x = RelativeCoordinate (Expression::parse (s, i));
  64405. RelativeCoordinateHelpers::skipComma (s, i);
  64406. y = RelativeCoordinate (Expression::parse (s, i));
  64407. }
  64408. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64409. {
  64410. return x == other.x && y == other.y;
  64411. }
  64412. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64413. {
  64414. return ! operator== (other);
  64415. }
  64416. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64417. {
  64418. return Point<float> ((float) x.resolve (context),
  64419. (float) y.resolve (context));
  64420. }
  64421. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64422. {
  64423. x.moveToAbsolute (newPos.getX(), context);
  64424. y.moveToAbsolute (newPos.getY(), context);
  64425. }
  64426. const String RelativePoint::toString() const
  64427. {
  64428. return x.toString() + ", " + y.toString();
  64429. }
  64430. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName, const Expression::EvaluationContext* context)
  64431. {
  64432. x.renameSymbolIfUsed (oldName, newName, context);
  64433. y.renameSymbolIfUsed (oldName, newName, context);
  64434. }
  64435. bool RelativePoint::isDynamic() const
  64436. {
  64437. return x.isDynamic() || y.isDynamic();
  64438. }
  64439. RelativeRectangle::RelativeRectangle()
  64440. {
  64441. }
  64442. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64443. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64444. : left (left_), right (right_), top (top_), bottom (bottom_)
  64445. {
  64446. }
  64447. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64448. : left (rect.getX()),
  64449. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64450. top (rect.getY()),
  64451. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64452. {
  64453. }
  64454. RelativeRectangle::RelativeRectangle (const String& s)
  64455. {
  64456. int i = 0;
  64457. left = RelativeCoordinate (Expression::parse (s, i));
  64458. RelativeCoordinateHelpers::skipComma (s, i);
  64459. top = RelativeCoordinate (Expression::parse (s, i));
  64460. RelativeCoordinateHelpers::skipComma (s, i);
  64461. right = RelativeCoordinate (Expression::parse (s, i));
  64462. RelativeCoordinateHelpers::skipComma (s, i);
  64463. bottom = RelativeCoordinate (Expression::parse (s, i));
  64464. }
  64465. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64466. {
  64467. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64468. }
  64469. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64470. {
  64471. return ! operator== (other);
  64472. }
  64473. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64474. {
  64475. const double l = left.resolve (context);
  64476. const double r = right.resolve (context);
  64477. const double t = top.resolve (context);
  64478. const double b = bottom.resolve (context);
  64479. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64480. }
  64481. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64482. {
  64483. left.moveToAbsolute (newPos.getX(), context);
  64484. right.moveToAbsolute (newPos.getRight(), context);
  64485. top.moveToAbsolute (newPos.getY(), context);
  64486. bottom.moveToAbsolute (newPos.getBottom(), context);
  64487. }
  64488. const String RelativeRectangle::toString() const
  64489. {
  64490. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64491. }
  64492. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName,
  64493. const Expression::EvaluationContext* context)
  64494. {
  64495. left.renameSymbolIfUsed (oldName, newName, context);
  64496. right.renameSymbolIfUsed (oldName, newName, context);
  64497. top.renameSymbolIfUsed (oldName, newName, context);
  64498. bottom.renameSymbolIfUsed (oldName, newName, context);
  64499. }
  64500. RelativePointPath::RelativePointPath()
  64501. : usesNonZeroWinding (true),
  64502. containsDynamicPoints (false)
  64503. {
  64504. }
  64505. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64506. : usesNonZeroWinding (true),
  64507. containsDynamicPoints (false)
  64508. {
  64509. ValueTree state (DrawablePath::valueTreeType);
  64510. other.writeTo (state, 0);
  64511. parse (state);
  64512. }
  64513. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64514. : usesNonZeroWinding (true),
  64515. containsDynamicPoints (false)
  64516. {
  64517. parse (drawable);
  64518. }
  64519. RelativePointPath::RelativePointPath (const Path& path)
  64520. {
  64521. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64522. Path::Iterator i (path);
  64523. while (i.next())
  64524. {
  64525. switch (i.elementType)
  64526. {
  64527. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64528. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64529. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64530. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64531. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64532. default: jassertfalse; break;
  64533. }
  64534. }
  64535. }
  64536. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64537. {
  64538. DrawablePath::ValueTreeWrapper wrapper (state);
  64539. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64540. ValueTree pathTree (wrapper.getPathState());
  64541. pathTree.removeAllChildren (undoManager);
  64542. for (int i = 0; i < elements.size(); ++i)
  64543. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64544. }
  64545. void RelativePointPath::parse (const ValueTree& state)
  64546. {
  64547. DrawablePath::ValueTreeWrapper wrapper (state);
  64548. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64549. RelativePoint points[3];
  64550. const ValueTree pathTree (wrapper.getPathState());
  64551. const int num = pathTree.getNumChildren();
  64552. for (int i = 0; i < num; ++i)
  64553. {
  64554. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64555. const int numCps = e.getNumControlPoints();
  64556. for (int j = 0; j < numCps; ++j)
  64557. {
  64558. points[j] = e.getControlPoint (j);
  64559. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64560. }
  64561. const Identifier type (e.getType());
  64562. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64563. elements.add (new StartSubPath (points[0]));
  64564. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64565. elements.add (new CloseSubPath());
  64566. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64567. elements.add (new LineTo (points[0]));
  64568. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64569. elements.add (new QuadraticTo (points[0], points[1]));
  64570. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64571. elements.add (new CubicTo (points[0], points[1], points[2]));
  64572. else
  64573. jassertfalse;
  64574. }
  64575. }
  64576. RelativePointPath::~RelativePointPath()
  64577. {
  64578. }
  64579. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64580. {
  64581. elements.swapWithArray (other.elements);
  64582. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64583. }
  64584. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64585. {
  64586. for (int i = 0; i < elements.size(); ++i)
  64587. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64588. }
  64589. bool RelativePointPath::containsAnyDynamicPoints() const
  64590. {
  64591. return containsDynamicPoints;
  64592. }
  64593. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64594. {
  64595. }
  64596. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64597. : ElementBase (startSubPathElement), startPos (pos)
  64598. {
  64599. }
  64600. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64601. {
  64602. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64603. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64604. return v;
  64605. }
  64606. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64607. {
  64608. path.startNewSubPath (startPos.resolve (coordFinder));
  64609. }
  64610. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64611. {
  64612. numPoints = 1;
  64613. return &startPos;
  64614. }
  64615. RelativePointPath::CloseSubPath::CloseSubPath()
  64616. : ElementBase (closeSubPathElement)
  64617. {
  64618. }
  64619. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64620. {
  64621. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64622. }
  64623. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64624. {
  64625. path.closeSubPath();
  64626. }
  64627. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64628. {
  64629. numPoints = 0;
  64630. return 0;
  64631. }
  64632. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64633. : ElementBase (lineToElement), endPoint (endPoint_)
  64634. {
  64635. }
  64636. const ValueTree RelativePointPath::LineTo::createTree() const
  64637. {
  64638. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64639. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64640. return v;
  64641. }
  64642. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64643. {
  64644. path.lineTo (endPoint.resolve (coordFinder));
  64645. }
  64646. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64647. {
  64648. numPoints = 1;
  64649. return &endPoint;
  64650. }
  64651. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64652. : ElementBase (quadraticToElement)
  64653. {
  64654. controlPoints[0] = controlPoint;
  64655. controlPoints[1] = endPoint;
  64656. }
  64657. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64658. {
  64659. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64660. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64661. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64662. return v;
  64663. }
  64664. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64665. {
  64666. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64667. controlPoints[1].resolve (coordFinder));
  64668. }
  64669. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64670. {
  64671. numPoints = 2;
  64672. return controlPoints;
  64673. }
  64674. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64675. : ElementBase (cubicToElement)
  64676. {
  64677. controlPoints[0] = controlPoint1;
  64678. controlPoints[1] = controlPoint2;
  64679. controlPoints[2] = endPoint;
  64680. }
  64681. const ValueTree RelativePointPath::CubicTo::createTree() const
  64682. {
  64683. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64684. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64685. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64686. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64687. return v;
  64688. }
  64689. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64690. {
  64691. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64692. controlPoints[1].resolve (coordFinder),
  64693. controlPoints[2].resolve (coordFinder));
  64694. }
  64695. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64696. {
  64697. numPoints = 3;
  64698. return controlPoints;
  64699. }
  64700. RelativeParallelogram::RelativeParallelogram()
  64701. {
  64702. }
  64703. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64704. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64705. {
  64706. }
  64707. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64708. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64709. {
  64710. }
  64711. RelativeParallelogram::~RelativeParallelogram()
  64712. {
  64713. }
  64714. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64715. {
  64716. points[0] = topLeft.resolve (coordFinder);
  64717. points[1] = topRight.resolve (coordFinder);
  64718. points[2] = bottomLeft.resolve (coordFinder);
  64719. }
  64720. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64721. {
  64722. resolveThreePoints (points, coordFinder);
  64723. points[3] = points[1] + (points[2] - points[0]);
  64724. }
  64725. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64726. {
  64727. Point<float> points[4];
  64728. resolveFourCorners (points, coordFinder);
  64729. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64730. }
  64731. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64732. {
  64733. Point<float> points[4];
  64734. resolveFourCorners (points, coordFinder);
  64735. path.startNewSubPath (points[0]);
  64736. path.lineTo (points[1]);
  64737. path.lineTo (points[3]);
  64738. path.lineTo (points[2]);
  64739. path.closeSubPath();
  64740. }
  64741. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64742. {
  64743. Point<float> corners[3];
  64744. resolveThreePoints (corners, coordFinder);
  64745. const Line<float> top (corners[0], corners[1]);
  64746. const Line<float> left (corners[0], corners[2]);
  64747. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64748. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64749. topRight.moveToAbsolute (newTopRight, coordFinder);
  64750. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64751. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64752. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64753. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64754. }
  64755. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64756. {
  64757. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64758. }
  64759. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64760. {
  64761. return ! operator== (other);
  64762. }
  64763. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64764. {
  64765. const Point<float> tr (corners[1] - corners[0]);
  64766. const Point<float> bl (corners[2] - corners[0]);
  64767. target -= corners[0];
  64768. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64769. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64770. }
  64771. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64772. {
  64773. return corners[0]
  64774. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64775. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64776. }
  64777. END_JUCE_NAMESPACE
  64778. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64779. #endif
  64780. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64781. /*** Start of inlined file: juce_Colour.cpp ***/
  64782. BEGIN_JUCE_NAMESPACE
  64783. namespace ColourHelpers
  64784. {
  64785. static uint8 floatAlphaToInt (const float alpha) throw()
  64786. {
  64787. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64788. }
  64789. static void convertHSBtoRGB (float h, float s, float v,
  64790. uint8& r, uint8& g, uint8& b) throw()
  64791. {
  64792. v = jlimit (0.0f, 1.0f, v);
  64793. v *= 255.0f;
  64794. const uint8 intV = (uint8) roundToInt (v);
  64795. if (s <= 0)
  64796. {
  64797. r = intV;
  64798. g = intV;
  64799. b = intV;
  64800. }
  64801. else
  64802. {
  64803. s = jmin (1.0f, s);
  64804. h = jlimit (0.0f, 1.0f, h);
  64805. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64806. const float f = h - std::floor (h);
  64807. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64808. const float y = v * (1.0f - s * f);
  64809. const float z = v * (1.0f - (s * (1.0f - f)));
  64810. if (h < 1.0f)
  64811. {
  64812. r = intV;
  64813. g = (uint8) roundToInt (z);
  64814. b = x;
  64815. }
  64816. else if (h < 2.0f)
  64817. {
  64818. r = (uint8) roundToInt (y);
  64819. g = intV;
  64820. b = x;
  64821. }
  64822. else if (h < 3.0f)
  64823. {
  64824. r = x;
  64825. g = intV;
  64826. b = (uint8) roundToInt (z);
  64827. }
  64828. else if (h < 4.0f)
  64829. {
  64830. r = x;
  64831. g = (uint8) roundToInt (y);
  64832. b = intV;
  64833. }
  64834. else if (h < 5.0f)
  64835. {
  64836. r = (uint8) roundToInt (z);
  64837. g = x;
  64838. b = intV;
  64839. }
  64840. else if (h < 6.0f)
  64841. {
  64842. r = intV;
  64843. g = x;
  64844. b = (uint8) roundToInt (y);
  64845. }
  64846. else
  64847. {
  64848. r = 0;
  64849. g = 0;
  64850. b = 0;
  64851. }
  64852. }
  64853. }
  64854. }
  64855. Colour::Colour() throw()
  64856. : argb (0)
  64857. {
  64858. }
  64859. Colour::Colour (const Colour& other) throw()
  64860. : argb (other.argb)
  64861. {
  64862. }
  64863. Colour& Colour::operator= (const Colour& other) throw()
  64864. {
  64865. argb = other.argb;
  64866. return *this;
  64867. }
  64868. bool Colour::operator== (const Colour& other) const throw()
  64869. {
  64870. return argb.getARGB() == other.argb.getARGB();
  64871. }
  64872. bool Colour::operator!= (const Colour& other) const throw()
  64873. {
  64874. return argb.getARGB() != other.argb.getARGB();
  64875. }
  64876. Colour::Colour (const uint32 argb_) throw()
  64877. : argb (argb_)
  64878. {
  64879. }
  64880. Colour::Colour (const uint8 red,
  64881. const uint8 green,
  64882. const uint8 blue) throw()
  64883. {
  64884. argb.setARGB (0xff, red, green, blue);
  64885. }
  64886. const Colour Colour::fromRGB (const uint8 red,
  64887. const uint8 green,
  64888. const uint8 blue) throw()
  64889. {
  64890. return Colour (red, green, blue);
  64891. }
  64892. Colour::Colour (const uint8 red,
  64893. const uint8 green,
  64894. const uint8 blue,
  64895. const uint8 alpha) throw()
  64896. {
  64897. argb.setARGB (alpha, red, green, blue);
  64898. }
  64899. const Colour Colour::fromRGBA (const uint8 red,
  64900. const uint8 green,
  64901. const uint8 blue,
  64902. const uint8 alpha) throw()
  64903. {
  64904. return Colour (red, green, blue, alpha);
  64905. }
  64906. Colour::Colour (const uint8 red,
  64907. const uint8 green,
  64908. const uint8 blue,
  64909. const float alpha) throw()
  64910. {
  64911. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64912. }
  64913. const Colour Colour::fromRGBAFloat (const uint8 red,
  64914. const uint8 green,
  64915. const uint8 blue,
  64916. const float alpha) throw()
  64917. {
  64918. return Colour (red, green, blue, alpha);
  64919. }
  64920. Colour::Colour (const float hue,
  64921. const float saturation,
  64922. const float brightness,
  64923. const float alpha) throw()
  64924. {
  64925. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64926. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64927. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64928. }
  64929. const Colour Colour::fromHSV (const float hue,
  64930. const float saturation,
  64931. const float brightness,
  64932. const float alpha) throw()
  64933. {
  64934. return Colour (hue, saturation, brightness, alpha);
  64935. }
  64936. Colour::Colour (const float hue,
  64937. const float saturation,
  64938. const float brightness,
  64939. const uint8 alpha) throw()
  64940. {
  64941. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64942. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64943. argb.setARGB (alpha, r, g, b);
  64944. }
  64945. Colour::~Colour() throw()
  64946. {
  64947. }
  64948. const PixelARGB Colour::getPixelARGB() const throw()
  64949. {
  64950. PixelARGB p (argb);
  64951. p.premultiply();
  64952. return p;
  64953. }
  64954. uint32 Colour::getARGB() const throw()
  64955. {
  64956. return argb.getARGB();
  64957. }
  64958. bool Colour::isTransparent() const throw()
  64959. {
  64960. return getAlpha() == 0;
  64961. }
  64962. bool Colour::isOpaque() const throw()
  64963. {
  64964. return getAlpha() == 0xff;
  64965. }
  64966. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64967. {
  64968. PixelARGB newCol (argb);
  64969. newCol.setAlpha (newAlpha);
  64970. return Colour (newCol.getARGB());
  64971. }
  64972. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64973. {
  64974. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64975. PixelARGB newCol (argb);
  64976. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64977. return Colour (newCol.getARGB());
  64978. }
  64979. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64980. {
  64981. jassert (alphaMultiplier >= 0);
  64982. PixelARGB newCol (argb);
  64983. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64984. return Colour (newCol.getARGB());
  64985. }
  64986. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64987. {
  64988. const int destAlpha = getAlpha();
  64989. if (destAlpha > 0)
  64990. {
  64991. const int invA = 0xff - (int) src.getAlpha();
  64992. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64993. if (resA > 0)
  64994. {
  64995. const int da = (invA * destAlpha) / resA;
  64996. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64997. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64998. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64999. (uint8) resA);
  65000. }
  65001. return *this;
  65002. }
  65003. else
  65004. {
  65005. return src;
  65006. }
  65007. }
  65008. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65009. {
  65010. if (proportionOfOther <= 0)
  65011. return *this;
  65012. if (proportionOfOther >= 1.0f)
  65013. return other;
  65014. PixelARGB c1 (getPixelARGB());
  65015. const PixelARGB c2 (other.getPixelARGB());
  65016. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65017. c1.unpremultiply();
  65018. return Colour (c1.getARGB());
  65019. }
  65020. float Colour::getFloatRed() const throw()
  65021. {
  65022. return getRed() / 255.0f;
  65023. }
  65024. float Colour::getFloatGreen() const throw()
  65025. {
  65026. return getGreen() / 255.0f;
  65027. }
  65028. float Colour::getFloatBlue() const throw()
  65029. {
  65030. return getBlue() / 255.0f;
  65031. }
  65032. float Colour::getFloatAlpha() const throw()
  65033. {
  65034. return getAlpha() / 255.0f;
  65035. }
  65036. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65037. {
  65038. const int r = getRed();
  65039. const int g = getGreen();
  65040. const int b = getBlue();
  65041. const int hi = jmax (r, g, b);
  65042. const int lo = jmin (r, g, b);
  65043. if (hi != 0)
  65044. {
  65045. s = (hi - lo) / (float) hi;
  65046. if (s != 0)
  65047. {
  65048. const float invDiff = 1.0f / (hi - lo);
  65049. const float red = (hi - r) * invDiff;
  65050. const float green = (hi - g) * invDiff;
  65051. const float blue = (hi - b) * invDiff;
  65052. if (r == hi)
  65053. h = blue - green;
  65054. else if (g == hi)
  65055. h = 2.0f + red - blue;
  65056. else
  65057. h = 4.0f + green - red;
  65058. h *= 1.0f / 6.0f;
  65059. if (h < 0)
  65060. ++h;
  65061. }
  65062. else
  65063. {
  65064. h = 0;
  65065. }
  65066. }
  65067. else
  65068. {
  65069. s = 0;
  65070. h = 0;
  65071. }
  65072. v = hi / 255.0f;
  65073. }
  65074. float Colour::getHue() const throw()
  65075. {
  65076. float h, s, b;
  65077. getHSB (h, s, b);
  65078. return h;
  65079. }
  65080. const Colour Colour::withHue (const float hue) const throw()
  65081. {
  65082. float h, s, b;
  65083. getHSB (h, s, b);
  65084. return Colour (hue, s, b, getAlpha());
  65085. }
  65086. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65087. {
  65088. float h, s, b;
  65089. getHSB (h, s, b);
  65090. h += amountToRotate;
  65091. h -= std::floor (h);
  65092. return Colour (h, s, b, getAlpha());
  65093. }
  65094. float Colour::getSaturation() const throw()
  65095. {
  65096. float h, s, b;
  65097. getHSB (h, s, b);
  65098. return s;
  65099. }
  65100. const Colour Colour::withSaturation (const float saturation) const throw()
  65101. {
  65102. float h, s, b;
  65103. getHSB (h, s, b);
  65104. return Colour (h, saturation, b, getAlpha());
  65105. }
  65106. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65107. {
  65108. float h, s, b;
  65109. getHSB (h, s, b);
  65110. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65111. }
  65112. float Colour::getBrightness() const throw()
  65113. {
  65114. float h, s, b;
  65115. getHSB (h, s, b);
  65116. return b;
  65117. }
  65118. const Colour Colour::withBrightness (const float brightness) const throw()
  65119. {
  65120. float h, s, b;
  65121. getHSB (h, s, b);
  65122. return Colour (h, s, brightness, getAlpha());
  65123. }
  65124. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65125. {
  65126. float h, s, b;
  65127. getHSB (h, s, b);
  65128. b *= amount;
  65129. if (b > 1.0f)
  65130. b = 1.0f;
  65131. return Colour (h, s, b, getAlpha());
  65132. }
  65133. const Colour Colour::brighter (float amount) const throw()
  65134. {
  65135. amount = 1.0f / (1.0f + amount);
  65136. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65137. (uint8) (255 - (amount * (255 - getGreen()))),
  65138. (uint8) (255 - (amount * (255 - getBlue()))),
  65139. getAlpha());
  65140. }
  65141. const Colour Colour::darker (float amount) const throw()
  65142. {
  65143. amount = 1.0f / (1.0f + amount);
  65144. return Colour ((uint8) (amount * getRed()),
  65145. (uint8) (amount * getGreen()),
  65146. (uint8) (amount * getBlue()),
  65147. getAlpha());
  65148. }
  65149. const Colour Colour::greyLevel (const float brightness) throw()
  65150. {
  65151. const uint8 level
  65152. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65153. return Colour (level, level, level);
  65154. }
  65155. const Colour Colour::contrasting (const float amount) const throw()
  65156. {
  65157. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65158. ? Colours::black
  65159. : Colours::white).withAlpha (amount));
  65160. }
  65161. const Colour Colour::contrasting (const Colour& colour1,
  65162. const Colour& colour2) throw()
  65163. {
  65164. const float b1 = colour1.getBrightness();
  65165. const float b2 = colour2.getBrightness();
  65166. float best = 0.0f;
  65167. float bestDist = 0.0f;
  65168. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65169. {
  65170. const float d1 = std::abs (i - b1);
  65171. const float d2 = std::abs (i - b2);
  65172. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65173. if (dist > bestDist)
  65174. {
  65175. best = i;
  65176. bestDist = dist;
  65177. }
  65178. }
  65179. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65180. .withBrightness (best);
  65181. }
  65182. const String Colour::toString() const
  65183. {
  65184. return String::toHexString ((int) argb.getARGB());
  65185. }
  65186. const Colour Colour::fromString (const String& encodedColourString)
  65187. {
  65188. return Colour ((uint32) encodedColourString.getHexValue32());
  65189. }
  65190. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65191. {
  65192. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65193. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65194. .toUpperCase();
  65195. }
  65196. END_JUCE_NAMESPACE
  65197. /*** End of inlined file: juce_Colour.cpp ***/
  65198. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65199. BEGIN_JUCE_NAMESPACE
  65200. ColourGradient::ColourGradient() throw()
  65201. {
  65202. #if JUCE_DEBUG
  65203. point1.setX (987654.0f);
  65204. #endif
  65205. }
  65206. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65207. const Colour& colour2, const float x2_, const float y2_,
  65208. const bool isRadial_)
  65209. : point1 (x1_, y1_),
  65210. point2 (x2_, y2_),
  65211. isRadial (isRadial_)
  65212. {
  65213. colours.add (ColourPoint (0.0, colour1));
  65214. colours.add (ColourPoint (1.0, colour2));
  65215. }
  65216. ColourGradient::~ColourGradient()
  65217. {
  65218. }
  65219. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65220. {
  65221. return point1 == other.point1 && point2 == other.point2
  65222. && isRadial == other.isRadial
  65223. && colours == other.colours;
  65224. }
  65225. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65226. {
  65227. return ! operator== (other);
  65228. }
  65229. void ColourGradient::clearColours()
  65230. {
  65231. colours.clear();
  65232. }
  65233. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65234. {
  65235. // must be within the two end-points
  65236. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65237. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65238. int i;
  65239. for (i = 0; i < colours.size(); ++i)
  65240. if (colours.getReference(i).position > pos)
  65241. break;
  65242. colours.insert (i, ColourPoint (pos, colour));
  65243. return i;
  65244. }
  65245. void ColourGradient::removeColour (int index)
  65246. {
  65247. jassert (index > 0 && index < colours.size() - 1);
  65248. colours.remove (index);
  65249. }
  65250. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65251. {
  65252. for (int i = 0; i < colours.size(); ++i)
  65253. {
  65254. Colour& c = colours.getReference(i).colour;
  65255. c = c.withMultipliedAlpha (multiplier);
  65256. }
  65257. }
  65258. int ColourGradient::getNumColours() const throw()
  65259. {
  65260. return colours.size();
  65261. }
  65262. double ColourGradient::getColourPosition (const int index) const throw()
  65263. {
  65264. if (((unsigned int) index) < (unsigned int) colours.size())
  65265. return colours.getReference (index).position;
  65266. return 0;
  65267. }
  65268. const Colour ColourGradient::getColour (const int index) const throw()
  65269. {
  65270. if (((unsigned int) index) < (unsigned int) colours.size())
  65271. return colours.getReference (index).colour;
  65272. return Colour();
  65273. }
  65274. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65275. {
  65276. if (((unsigned int) index) < (unsigned int) colours.size())
  65277. colours.getReference (index).colour = newColour;
  65278. }
  65279. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65280. {
  65281. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65282. if (position <= 0 || colours.size() <= 1)
  65283. return colours.getReference(0).colour;
  65284. int i = colours.size() - 1;
  65285. while (position < colours.getReference(i).position)
  65286. --i;
  65287. const ColourPoint& p1 = colours.getReference (i);
  65288. if (i >= colours.size() - 1)
  65289. return p1.colour;
  65290. const ColourPoint& p2 = colours.getReference (i + 1);
  65291. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65292. }
  65293. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65294. {
  65295. #if JUCE_DEBUG
  65296. // trying to use the object without setting its co-ordinates? Have a careful read of
  65297. // the comments for the constructors.
  65298. jassert (point1.getX() != 987654.0f);
  65299. #endif
  65300. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65301. 3 * (int) point1.transformedBy (transform)
  65302. .getDistanceFrom (point2.transformedBy (transform)));
  65303. lookupTable.malloc (numEntries);
  65304. if (colours.size() >= 2)
  65305. {
  65306. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65307. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65308. int index = 0;
  65309. for (int j = 1; j < colours.size(); ++j)
  65310. {
  65311. const ColourPoint& p = colours.getReference (j);
  65312. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65313. const PixelARGB pix2 (p.colour.getPixelARGB());
  65314. for (int i = 0; i < numToDo; ++i)
  65315. {
  65316. jassert (index >= 0 && index < numEntries);
  65317. lookupTable[index] = pix1;
  65318. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65319. ++index;
  65320. }
  65321. pix1 = pix2;
  65322. }
  65323. while (index < numEntries)
  65324. lookupTable [index++] = pix1;
  65325. }
  65326. else
  65327. {
  65328. jassertfalse; // no colours specified!
  65329. }
  65330. return numEntries;
  65331. }
  65332. bool ColourGradient::isOpaque() const throw()
  65333. {
  65334. for (int i = 0; i < colours.size(); ++i)
  65335. if (! colours.getReference(i).colour.isOpaque())
  65336. return false;
  65337. return true;
  65338. }
  65339. bool ColourGradient::isInvisible() const throw()
  65340. {
  65341. for (int i = 0; i < colours.size(); ++i)
  65342. if (! colours.getReference(i).colour.isTransparent())
  65343. return false;
  65344. return true;
  65345. }
  65346. END_JUCE_NAMESPACE
  65347. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65348. /*** Start of inlined file: juce_Colours.cpp ***/
  65349. BEGIN_JUCE_NAMESPACE
  65350. const Colour Colours::transparentBlack (0);
  65351. const Colour Colours::transparentWhite (0x00ffffff);
  65352. const Colour Colours::aliceblue (0xfff0f8ff);
  65353. const Colour Colours::antiquewhite (0xfffaebd7);
  65354. const Colour Colours::aqua (0xff00ffff);
  65355. const Colour Colours::aquamarine (0xff7fffd4);
  65356. const Colour Colours::azure (0xfff0ffff);
  65357. const Colour Colours::beige (0xfff5f5dc);
  65358. const Colour Colours::bisque (0xffffe4c4);
  65359. const Colour Colours::black (0xff000000);
  65360. const Colour Colours::blanchedalmond (0xffffebcd);
  65361. const Colour Colours::blue (0xff0000ff);
  65362. const Colour Colours::blueviolet (0xff8a2be2);
  65363. const Colour Colours::brown (0xffa52a2a);
  65364. const Colour Colours::burlywood (0xffdeb887);
  65365. const Colour Colours::cadetblue (0xff5f9ea0);
  65366. const Colour Colours::chartreuse (0xff7fff00);
  65367. const Colour Colours::chocolate (0xffd2691e);
  65368. const Colour Colours::coral (0xffff7f50);
  65369. const Colour Colours::cornflowerblue (0xff6495ed);
  65370. const Colour Colours::cornsilk (0xfffff8dc);
  65371. const Colour Colours::crimson (0xffdc143c);
  65372. const Colour Colours::cyan (0xff00ffff);
  65373. const Colour Colours::darkblue (0xff00008b);
  65374. const Colour Colours::darkcyan (0xff008b8b);
  65375. const Colour Colours::darkgoldenrod (0xffb8860b);
  65376. const Colour Colours::darkgrey (0xff555555);
  65377. const Colour Colours::darkgreen (0xff006400);
  65378. const Colour Colours::darkkhaki (0xffbdb76b);
  65379. const Colour Colours::darkmagenta (0xff8b008b);
  65380. const Colour Colours::darkolivegreen (0xff556b2f);
  65381. const Colour Colours::darkorange (0xffff8c00);
  65382. const Colour Colours::darkorchid (0xff9932cc);
  65383. const Colour Colours::darkred (0xff8b0000);
  65384. const Colour Colours::darksalmon (0xffe9967a);
  65385. const Colour Colours::darkseagreen (0xff8fbc8f);
  65386. const Colour Colours::darkslateblue (0xff483d8b);
  65387. const Colour Colours::darkslategrey (0xff2f4f4f);
  65388. const Colour Colours::darkturquoise (0xff00ced1);
  65389. const Colour Colours::darkviolet (0xff9400d3);
  65390. const Colour Colours::deeppink (0xffff1493);
  65391. const Colour Colours::deepskyblue (0xff00bfff);
  65392. const Colour Colours::dimgrey (0xff696969);
  65393. const Colour Colours::dodgerblue (0xff1e90ff);
  65394. const Colour Colours::firebrick (0xffb22222);
  65395. const Colour Colours::floralwhite (0xfffffaf0);
  65396. const Colour Colours::forestgreen (0xff228b22);
  65397. const Colour Colours::fuchsia (0xffff00ff);
  65398. const Colour Colours::gainsboro (0xffdcdcdc);
  65399. const Colour Colours::gold (0xffffd700);
  65400. const Colour Colours::goldenrod (0xffdaa520);
  65401. const Colour Colours::grey (0xff808080);
  65402. const Colour Colours::green (0xff008000);
  65403. const Colour Colours::greenyellow (0xffadff2f);
  65404. const Colour Colours::honeydew (0xfff0fff0);
  65405. const Colour Colours::hotpink (0xffff69b4);
  65406. const Colour Colours::indianred (0xffcd5c5c);
  65407. const Colour Colours::indigo (0xff4b0082);
  65408. const Colour Colours::ivory (0xfffffff0);
  65409. const Colour Colours::khaki (0xfff0e68c);
  65410. const Colour Colours::lavender (0xffe6e6fa);
  65411. const Colour Colours::lavenderblush (0xfffff0f5);
  65412. const Colour Colours::lemonchiffon (0xfffffacd);
  65413. const Colour Colours::lightblue (0xffadd8e6);
  65414. const Colour Colours::lightcoral (0xfff08080);
  65415. const Colour Colours::lightcyan (0xffe0ffff);
  65416. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65417. const Colour Colours::lightgreen (0xff90ee90);
  65418. const Colour Colours::lightgrey (0xffd3d3d3);
  65419. const Colour Colours::lightpink (0xffffb6c1);
  65420. const Colour Colours::lightsalmon (0xffffa07a);
  65421. const Colour Colours::lightseagreen (0xff20b2aa);
  65422. const Colour Colours::lightskyblue (0xff87cefa);
  65423. const Colour Colours::lightslategrey (0xff778899);
  65424. const Colour Colours::lightsteelblue (0xffb0c4de);
  65425. const Colour Colours::lightyellow (0xffffffe0);
  65426. const Colour Colours::lime (0xff00ff00);
  65427. const Colour Colours::limegreen (0xff32cd32);
  65428. const Colour Colours::linen (0xfffaf0e6);
  65429. const Colour Colours::magenta (0xffff00ff);
  65430. const Colour Colours::maroon (0xff800000);
  65431. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65432. const Colour Colours::mediumblue (0xff0000cd);
  65433. const Colour Colours::mediumorchid (0xffba55d3);
  65434. const Colour Colours::mediumpurple (0xff9370db);
  65435. const Colour Colours::mediumseagreen (0xff3cb371);
  65436. const Colour Colours::mediumslateblue (0xff7b68ee);
  65437. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65438. const Colour Colours::mediumturquoise (0xff48d1cc);
  65439. const Colour Colours::mediumvioletred (0xffc71585);
  65440. const Colour Colours::midnightblue (0xff191970);
  65441. const Colour Colours::mintcream (0xfff5fffa);
  65442. const Colour Colours::mistyrose (0xffffe4e1);
  65443. const Colour Colours::navajowhite (0xffffdead);
  65444. const Colour Colours::navy (0xff000080);
  65445. const Colour Colours::oldlace (0xfffdf5e6);
  65446. const Colour Colours::olive (0xff808000);
  65447. const Colour Colours::olivedrab (0xff6b8e23);
  65448. const Colour Colours::orange (0xffffa500);
  65449. const Colour Colours::orangered (0xffff4500);
  65450. const Colour Colours::orchid (0xffda70d6);
  65451. const Colour Colours::palegoldenrod (0xffeee8aa);
  65452. const Colour Colours::palegreen (0xff98fb98);
  65453. const Colour Colours::paleturquoise (0xffafeeee);
  65454. const Colour Colours::palevioletred (0xffdb7093);
  65455. const Colour Colours::papayawhip (0xffffefd5);
  65456. const Colour Colours::peachpuff (0xffffdab9);
  65457. const Colour Colours::peru (0xffcd853f);
  65458. const Colour Colours::pink (0xffffc0cb);
  65459. const Colour Colours::plum (0xffdda0dd);
  65460. const Colour Colours::powderblue (0xffb0e0e6);
  65461. const Colour Colours::purple (0xff800080);
  65462. const Colour Colours::red (0xffff0000);
  65463. const Colour Colours::rosybrown (0xffbc8f8f);
  65464. const Colour Colours::royalblue (0xff4169e1);
  65465. const Colour Colours::saddlebrown (0xff8b4513);
  65466. const Colour Colours::salmon (0xfffa8072);
  65467. const Colour Colours::sandybrown (0xfff4a460);
  65468. const Colour Colours::seagreen (0xff2e8b57);
  65469. const Colour Colours::seashell (0xfffff5ee);
  65470. const Colour Colours::sienna (0xffa0522d);
  65471. const Colour Colours::silver (0xffc0c0c0);
  65472. const Colour Colours::skyblue (0xff87ceeb);
  65473. const Colour Colours::slateblue (0xff6a5acd);
  65474. const Colour Colours::slategrey (0xff708090);
  65475. const Colour Colours::snow (0xfffffafa);
  65476. const Colour Colours::springgreen (0xff00ff7f);
  65477. const Colour Colours::steelblue (0xff4682b4);
  65478. const Colour Colours::tan (0xffd2b48c);
  65479. const Colour Colours::teal (0xff008080);
  65480. const Colour Colours::thistle (0xffd8bfd8);
  65481. const Colour Colours::tomato (0xffff6347);
  65482. const Colour Colours::turquoise (0xff40e0d0);
  65483. const Colour Colours::violet (0xffee82ee);
  65484. const Colour Colours::wheat (0xfff5deb3);
  65485. const Colour Colours::white (0xffffffff);
  65486. const Colour Colours::whitesmoke (0xfff5f5f5);
  65487. const Colour Colours::yellow (0xffffff00);
  65488. const Colour Colours::yellowgreen (0xff9acd32);
  65489. const Colour Colours::findColourForName (const String& colourName,
  65490. const Colour& defaultColour)
  65491. {
  65492. static const int presets[] =
  65493. {
  65494. // (first value is the string's hashcode, second is ARGB)
  65495. 0x05978fff, 0xff000000, /* black */
  65496. 0x06bdcc29, 0xffffffff, /* white */
  65497. 0x002e305a, 0xff0000ff, /* blue */
  65498. 0x00308adf, 0xff808080, /* grey */
  65499. 0x05e0cf03, 0xff008000, /* green */
  65500. 0x0001b891, 0xffff0000, /* red */
  65501. 0xd43c6474, 0xffffff00, /* yellow */
  65502. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65503. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65504. 0x002dcebc, 0xff00ffff, /* aqua */
  65505. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65506. 0x0590228f, 0xfff0ffff, /* azure */
  65507. 0x05947fe4, 0xfff5f5dc, /* beige */
  65508. 0xad388e35, 0xffffe4c4, /* bisque */
  65509. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65510. 0x39129959, 0xff8a2be2, /* blueviolet */
  65511. 0x059a8136, 0xffa52a2a, /* brown */
  65512. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65513. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65514. 0x6b748956, 0xff7fff00, /* chartreuse */
  65515. 0x2903623c, 0xffd2691e, /* chocolate */
  65516. 0x05a74431, 0xffff7f50, /* coral */
  65517. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65518. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65519. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65520. 0x002ed323, 0xff00ffff, /* cyan */
  65521. 0x67cc74d0, 0xff00008b, /* darkblue */
  65522. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65523. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65524. 0x67cecf55, 0xff555555, /* darkgrey */
  65525. 0x920b194d, 0xff006400, /* darkgreen */
  65526. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65527. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65528. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65529. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65530. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65531. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65532. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65533. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65534. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65535. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65536. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65537. 0xc8769375, 0xff9400d3, /* darkviolet */
  65538. 0x25832862, 0xffff1493, /* deeppink */
  65539. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65540. 0x634c8b67, 0xff696969, /* dimgrey */
  65541. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65542. 0xef19e3cb, 0xffb22222, /* firebrick */
  65543. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65544. 0xd086fd06, 0xff228b22, /* forestgreen */
  65545. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65546. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65547. 0x00308060, 0xffffd700, /* gold */
  65548. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65549. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65550. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65551. 0x41892743, 0xffff69b4, /* hotpink */
  65552. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65553. 0xb969fed2, 0xff4b0082, /* indigo */
  65554. 0x05fef6a9, 0xfffffff0, /* ivory */
  65555. 0x06149302, 0xfff0e68c, /* khaki */
  65556. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65557. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65558. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65559. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65560. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65561. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65562. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65563. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65564. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65565. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65566. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65567. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65568. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65569. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65570. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65571. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65572. 0x0032afd5, 0xff00ff00, /* lime */
  65573. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65574. 0x06234efa, 0xfffaf0e6, /* linen */
  65575. 0x316858a9, 0xffff00ff, /* magenta */
  65576. 0xbf8ca470, 0xff800000, /* maroon */
  65577. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65578. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65579. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65580. 0x07556b71, 0xff9370db, /* mediumpurple */
  65581. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65582. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65583. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65584. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65585. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65586. 0x168eb32a, 0xff191970, /* midnightblue */
  65587. 0x4306b960, 0xfff5fffa, /* mintcream */
  65588. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65589. 0xe97218a6, 0xffffdead, /* navajowhite */
  65590. 0x00337bb6, 0xff000080, /* navy */
  65591. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65592. 0x064ee1db, 0xff808000, /* olive */
  65593. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65594. 0xc3de262e, 0xffffa500, /* orange */
  65595. 0x58bebba3, 0xffff4500, /* orangered */
  65596. 0xc3def8a3, 0xffda70d6, /* orchid */
  65597. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65598. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65599. 0x74022737, 0xffafeeee, /* paleturquoise */
  65600. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65601. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65602. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65603. 0x003472f8, 0xffcd853f, /* peru */
  65604. 0x00348176, 0xffffc0cb, /* pink */
  65605. 0x00348d94, 0xffdda0dd, /* plum */
  65606. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65607. 0xc5c507bc, 0xff800080, /* purple */
  65608. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65609. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65610. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65611. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65612. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65613. 0x34636c14, 0xff2e8b57, /* seagreen */
  65614. 0x3507fb41, 0xfffff5ee, /* seashell */
  65615. 0xca348772, 0xffa0522d, /* sienna */
  65616. 0xca37d30d, 0xffc0c0c0, /* silver */
  65617. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65618. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65619. 0x44ab37f8, 0xff708090, /* slategrey */
  65620. 0x0035f183, 0xfffffafa, /* snow */
  65621. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65622. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65623. 0x0001bfa1, 0xffd2b48c, /* tan */
  65624. 0x0036425c, 0xff008080, /* teal */
  65625. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65626. 0xcc41600a, 0xffff6347, /* tomato */
  65627. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65628. 0xcf57947f, 0xffee82ee, /* violet */
  65629. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65630. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65631. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65632. };
  65633. const int hash = colourName.trim().toLowerCase().hashCode();
  65634. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65635. if (presets [i] == hash)
  65636. return Colour (presets [i + 1]);
  65637. return defaultColour;
  65638. }
  65639. END_JUCE_NAMESPACE
  65640. /*** End of inlined file: juce_Colours.cpp ***/
  65641. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65642. BEGIN_JUCE_NAMESPACE
  65643. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65644. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65645. const Path& path, const AffineTransform& transform)
  65646. : bounds (bounds_),
  65647. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65648. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65649. needToCheckEmptinesss (true)
  65650. {
  65651. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65652. int* t = table;
  65653. for (int i = bounds.getHeight(); --i >= 0;)
  65654. {
  65655. *t = 0;
  65656. t += lineStrideElements;
  65657. }
  65658. const int topLimit = bounds.getY() << 8;
  65659. const int heightLimit = bounds.getHeight() << 8;
  65660. const int leftLimit = bounds.getX() << 8;
  65661. const int rightLimit = bounds.getRight() << 8;
  65662. PathFlatteningIterator iter (path, transform);
  65663. while (iter.next())
  65664. {
  65665. int y1 = roundToInt (iter.y1 * 256.0f);
  65666. int y2 = roundToInt (iter.y2 * 256.0f);
  65667. if (y1 != y2)
  65668. {
  65669. y1 -= topLimit;
  65670. y2 -= topLimit;
  65671. const int startY = y1;
  65672. int direction = -1;
  65673. if (y1 > y2)
  65674. {
  65675. swapVariables (y1, y2);
  65676. direction = 1;
  65677. }
  65678. if (y1 < 0)
  65679. y1 = 0;
  65680. if (y2 > heightLimit)
  65681. y2 = heightLimit;
  65682. if (y1 < y2)
  65683. {
  65684. const double startX = 256.0f * iter.x1;
  65685. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65686. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65687. do
  65688. {
  65689. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65690. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65691. if (x < leftLimit)
  65692. x = leftLimit;
  65693. else if (x >= rightLimit)
  65694. x = rightLimit - 1;
  65695. addEdgePoint (x, y1 >> 8, direction * step);
  65696. y1 += step;
  65697. }
  65698. while (y1 < y2);
  65699. }
  65700. }
  65701. }
  65702. sanitiseLevels (path.isUsingNonZeroWinding());
  65703. }
  65704. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65705. : bounds (rectangleToAdd),
  65706. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65707. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65708. needToCheckEmptinesss (true)
  65709. {
  65710. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65711. table[0] = 0;
  65712. const int x1 = rectangleToAdd.getX() << 8;
  65713. const int x2 = rectangleToAdd.getRight() << 8;
  65714. int* t = table;
  65715. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65716. {
  65717. t[0] = 2;
  65718. t[1] = x1;
  65719. t[2] = 255;
  65720. t[3] = x2;
  65721. t[4] = 0;
  65722. t += lineStrideElements;
  65723. }
  65724. }
  65725. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65726. : bounds (rectanglesToAdd.getBounds()),
  65727. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65728. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65729. needToCheckEmptinesss (true)
  65730. {
  65731. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65732. int* t = table;
  65733. for (int i = bounds.getHeight(); --i >= 0;)
  65734. {
  65735. *t = 0;
  65736. t += lineStrideElements;
  65737. }
  65738. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65739. {
  65740. const Rectangle<int>* const r = iter.getRectangle();
  65741. const int x1 = r->getX() << 8;
  65742. const int x2 = r->getRight() << 8;
  65743. int y = r->getY() - bounds.getY();
  65744. for (int j = r->getHeight(); --j >= 0;)
  65745. {
  65746. addEdgePoint (x1, y, 255);
  65747. addEdgePoint (x2, y, -255);
  65748. ++y;
  65749. }
  65750. }
  65751. sanitiseLevels (true);
  65752. }
  65753. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65754. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65755. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65756. 2 + (int) rectangleToAdd.getWidth(),
  65757. 2 + (int) rectangleToAdd.getHeight())),
  65758. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65759. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65760. needToCheckEmptinesss (true)
  65761. {
  65762. jassert (! rectangleToAdd.isEmpty());
  65763. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65764. table[0] = 0;
  65765. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65766. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65767. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65768. jassert (y1 < 256);
  65769. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65770. if (x2 <= x1 || y2 <= y1)
  65771. {
  65772. bounds.setHeight (0);
  65773. return;
  65774. }
  65775. int lineY = 0;
  65776. int* t = table;
  65777. if ((y1 >> 8) == (y2 >> 8))
  65778. {
  65779. t[0] = 2;
  65780. t[1] = x1;
  65781. t[2] = y2 - y1;
  65782. t[3] = x2;
  65783. t[4] = 0;
  65784. ++lineY;
  65785. t += lineStrideElements;
  65786. }
  65787. else
  65788. {
  65789. t[0] = 2;
  65790. t[1] = x1;
  65791. t[2] = 255 - (y1 & 255);
  65792. t[3] = x2;
  65793. t[4] = 0;
  65794. ++lineY;
  65795. t += lineStrideElements;
  65796. while (lineY < (y2 >> 8))
  65797. {
  65798. t[0] = 2;
  65799. t[1] = x1;
  65800. t[2] = 255;
  65801. t[3] = x2;
  65802. t[4] = 0;
  65803. ++lineY;
  65804. t += lineStrideElements;
  65805. }
  65806. jassert (lineY < bounds.getHeight());
  65807. t[0] = 2;
  65808. t[1] = x1;
  65809. t[2] = y2 & 255;
  65810. t[3] = x2;
  65811. t[4] = 0;
  65812. ++lineY;
  65813. t += lineStrideElements;
  65814. }
  65815. while (lineY < bounds.getHeight())
  65816. {
  65817. t[0] = 0;
  65818. t += lineStrideElements;
  65819. ++lineY;
  65820. }
  65821. }
  65822. EdgeTable::EdgeTable (const EdgeTable& other)
  65823. {
  65824. operator= (other);
  65825. }
  65826. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65827. {
  65828. bounds = other.bounds;
  65829. maxEdgesPerLine = other.maxEdgesPerLine;
  65830. lineStrideElements = other.lineStrideElements;
  65831. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65832. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65833. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65834. return *this;
  65835. }
  65836. EdgeTable::~EdgeTable()
  65837. {
  65838. }
  65839. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65840. {
  65841. while (--numLines >= 0)
  65842. {
  65843. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65844. src += srcLineStride;
  65845. dest += destLineStride;
  65846. }
  65847. }
  65848. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65849. {
  65850. // Convert the table from relative windings to absolute levels..
  65851. int* lineStart = table;
  65852. for (int i = bounds.getHeight(); --i >= 0;)
  65853. {
  65854. int* line = lineStart;
  65855. lineStart += lineStrideElements;
  65856. int num = *line;
  65857. if (num == 0)
  65858. continue;
  65859. int level = 0;
  65860. if (useNonZeroWinding)
  65861. {
  65862. while (--num > 0)
  65863. {
  65864. line += 2;
  65865. level += *line;
  65866. int corrected = abs (level);
  65867. if (corrected >> 8)
  65868. corrected = 255;
  65869. *line = corrected;
  65870. }
  65871. }
  65872. else
  65873. {
  65874. while (--num > 0)
  65875. {
  65876. line += 2;
  65877. level += *line;
  65878. int corrected = abs (level);
  65879. if (corrected >> 8)
  65880. {
  65881. corrected &= 511;
  65882. if (corrected >> 8)
  65883. corrected = 511 - corrected;
  65884. }
  65885. *line = corrected;
  65886. }
  65887. }
  65888. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65889. }
  65890. }
  65891. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65892. {
  65893. if (newNumEdgesPerLine != maxEdgesPerLine)
  65894. {
  65895. maxEdgesPerLine = newNumEdgesPerLine;
  65896. jassert (bounds.getHeight() > 0);
  65897. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65898. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65899. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65900. table.swapWith (newTable);
  65901. lineStrideElements = newLineStrideElements;
  65902. }
  65903. }
  65904. void EdgeTable::optimiseTable() throw()
  65905. {
  65906. int maxLineElements = 0;
  65907. for (int i = bounds.getHeight(); --i >= 0;)
  65908. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65909. remapTableForNumEdges (maxLineElements);
  65910. }
  65911. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65912. {
  65913. jassert (y >= 0 && y < bounds.getHeight());
  65914. int* line = table + lineStrideElements * y;
  65915. const int numPoints = line[0];
  65916. int n = numPoints << 1;
  65917. if (n > 0)
  65918. {
  65919. while (n > 0)
  65920. {
  65921. const int cx = line [n - 1];
  65922. if (cx <= x)
  65923. {
  65924. if (cx == x)
  65925. {
  65926. line [n] += winding;
  65927. return;
  65928. }
  65929. break;
  65930. }
  65931. n -= 2;
  65932. }
  65933. if (numPoints >= maxEdgesPerLine)
  65934. {
  65935. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65936. jassert (numPoints < maxEdgesPerLine);
  65937. line = table + lineStrideElements * y;
  65938. }
  65939. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65940. }
  65941. line [n + 1] = x;
  65942. line [n + 2] = winding;
  65943. line[0]++;
  65944. }
  65945. void EdgeTable::translate (float dx, const int dy) throw()
  65946. {
  65947. bounds.translate ((int) std::floor (dx), dy);
  65948. int* lineStart = table;
  65949. const int intDx = (int) (dx * 256.0f);
  65950. for (int i = bounds.getHeight(); --i >= 0;)
  65951. {
  65952. int* line = lineStart;
  65953. lineStart += lineStrideElements;
  65954. int num = *line++;
  65955. while (--num >= 0)
  65956. {
  65957. *line += intDx;
  65958. line += 2;
  65959. }
  65960. }
  65961. }
  65962. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65963. {
  65964. jassert (y >= 0 && y < bounds.getHeight());
  65965. int* dest = table + lineStrideElements * y;
  65966. if (dest[0] == 0)
  65967. return;
  65968. int otherNumPoints = *otherLine;
  65969. if (otherNumPoints == 0)
  65970. {
  65971. *dest = 0;
  65972. return;
  65973. }
  65974. const int right = bounds.getRight() << 8;
  65975. // optimise for the common case where our line lies entirely within a
  65976. // single pair of points, as happens when clipping to a simple rect.
  65977. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65978. {
  65979. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65980. return;
  65981. }
  65982. ++otherLine;
  65983. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65984. int* temp = (int*) alloca (lineSizeBytes);
  65985. memcpy (temp, dest, lineSizeBytes);
  65986. const int* src1 = temp;
  65987. int srcNum1 = *src1++;
  65988. int x1 = *src1++;
  65989. const int* src2 = otherLine;
  65990. int srcNum2 = otherNumPoints;
  65991. int x2 = *src2++;
  65992. int destIndex = 0, destTotal = 0;
  65993. int level1 = 0, level2 = 0;
  65994. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65995. while (srcNum1 > 0 && srcNum2 > 0)
  65996. {
  65997. int nextX;
  65998. if (x1 < x2)
  65999. {
  66000. nextX = x1;
  66001. level1 = *src1++;
  66002. x1 = *src1++;
  66003. --srcNum1;
  66004. }
  66005. else if (x1 == x2)
  66006. {
  66007. nextX = x1;
  66008. level1 = *src1++;
  66009. level2 = *src2++;
  66010. x1 = *src1++;
  66011. x2 = *src2++;
  66012. --srcNum1;
  66013. --srcNum2;
  66014. }
  66015. else
  66016. {
  66017. nextX = x2;
  66018. level2 = *src2++;
  66019. x2 = *src2++;
  66020. --srcNum2;
  66021. }
  66022. if (nextX > lastX)
  66023. {
  66024. if (nextX >= right)
  66025. break;
  66026. lastX = nextX;
  66027. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66028. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66029. if (nextLevel != lastLevel)
  66030. {
  66031. if (destTotal >= maxEdgesPerLine)
  66032. {
  66033. dest[0] = destTotal;
  66034. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66035. dest = table + lineStrideElements * y;
  66036. }
  66037. ++destTotal;
  66038. lastLevel = nextLevel;
  66039. dest[++destIndex] = nextX;
  66040. dest[++destIndex] = nextLevel;
  66041. }
  66042. }
  66043. }
  66044. if (lastLevel > 0)
  66045. {
  66046. if (destTotal >= maxEdgesPerLine)
  66047. {
  66048. dest[0] = destTotal;
  66049. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66050. dest = table + lineStrideElements * y;
  66051. }
  66052. ++destTotal;
  66053. dest[++destIndex] = right;
  66054. dest[++destIndex] = 0;
  66055. }
  66056. dest[0] = destTotal;
  66057. #if JUCE_DEBUG
  66058. int last = std::numeric_limits<int>::min();
  66059. for (int i = 0; i < dest[0]; ++i)
  66060. {
  66061. jassert (dest[i * 2 + 1] > last);
  66062. last = dest[i * 2 + 1];
  66063. }
  66064. jassert (dest [dest[0] * 2] == 0);
  66065. #endif
  66066. }
  66067. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66068. {
  66069. int* lastItem = dest + (dest[0] * 2 - 1);
  66070. if (x2 < lastItem[0])
  66071. {
  66072. if (x2 <= dest[1])
  66073. {
  66074. dest[0] = 0;
  66075. return;
  66076. }
  66077. while (x2 < lastItem[-2])
  66078. {
  66079. --(dest[0]);
  66080. lastItem -= 2;
  66081. }
  66082. lastItem[0] = x2;
  66083. lastItem[1] = 0;
  66084. }
  66085. if (x1 > dest[1])
  66086. {
  66087. while (lastItem[0] > x1)
  66088. lastItem -= 2;
  66089. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66090. if (itemsRemoved > 0)
  66091. {
  66092. dest[0] -= itemsRemoved;
  66093. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66094. }
  66095. dest[1] = x1;
  66096. }
  66097. }
  66098. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66099. {
  66100. const Rectangle<int> clipped (r.getIntersection (bounds));
  66101. if (clipped.isEmpty())
  66102. {
  66103. needToCheckEmptinesss = false;
  66104. bounds.setHeight (0);
  66105. }
  66106. else
  66107. {
  66108. const int top = clipped.getY() - bounds.getY();
  66109. const int bottom = clipped.getBottom() - bounds.getY();
  66110. if (bottom < bounds.getHeight())
  66111. bounds.setHeight (bottom);
  66112. if (clipped.getRight() < bounds.getRight())
  66113. bounds.setRight (clipped.getRight());
  66114. for (int i = top; --i >= 0;)
  66115. table [lineStrideElements * i] = 0;
  66116. if (clipped.getX() > bounds.getX())
  66117. {
  66118. const int x1 = clipped.getX() << 8;
  66119. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66120. int* line = table + lineStrideElements * top;
  66121. for (int i = bottom - top; --i >= 0;)
  66122. {
  66123. if (line[0] != 0)
  66124. clipEdgeTableLineToRange (line, x1, x2);
  66125. line += lineStrideElements;
  66126. }
  66127. }
  66128. needToCheckEmptinesss = true;
  66129. }
  66130. }
  66131. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66132. {
  66133. const Rectangle<int> clipped (r.getIntersection (bounds));
  66134. if (! clipped.isEmpty())
  66135. {
  66136. const int top = clipped.getY() - bounds.getY();
  66137. const int bottom = clipped.getBottom() - bounds.getY();
  66138. //XXX optimise here by shortening the table if it fills top or bottom
  66139. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66140. clipped.getX() << 8, 0,
  66141. clipped.getRight() << 8, 255,
  66142. std::numeric_limits<int>::max(), 0 };
  66143. for (int i = top; i < bottom; ++i)
  66144. intersectWithEdgeTableLine (i, rectLine);
  66145. needToCheckEmptinesss = true;
  66146. }
  66147. }
  66148. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66149. {
  66150. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66151. if (clipped.isEmpty())
  66152. {
  66153. needToCheckEmptinesss = false;
  66154. bounds.setHeight (0);
  66155. }
  66156. else
  66157. {
  66158. const int top = clipped.getY() - bounds.getY();
  66159. const int bottom = clipped.getBottom() - bounds.getY();
  66160. if (bottom < bounds.getHeight())
  66161. bounds.setHeight (bottom);
  66162. if (clipped.getRight() < bounds.getRight())
  66163. bounds.setRight (clipped.getRight());
  66164. int i = 0;
  66165. for (i = top; --i >= 0;)
  66166. table [lineStrideElements * i] = 0;
  66167. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66168. for (i = top; i < bottom; ++i)
  66169. {
  66170. intersectWithEdgeTableLine (i, otherLine);
  66171. otherLine += other.lineStrideElements;
  66172. }
  66173. needToCheckEmptinesss = true;
  66174. }
  66175. }
  66176. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66177. {
  66178. y -= bounds.getY();
  66179. if (y < 0 || y >= bounds.getHeight())
  66180. return;
  66181. needToCheckEmptinesss = true;
  66182. if (numPixels <= 0)
  66183. {
  66184. table [lineStrideElements * y] = 0;
  66185. return;
  66186. }
  66187. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  66188. int destIndex = 0, lastLevel = 0;
  66189. while (--numPixels >= 0)
  66190. {
  66191. const int alpha = *mask;
  66192. mask += maskStride;
  66193. if (alpha != lastLevel)
  66194. {
  66195. tempLine[++destIndex] = (x << 8);
  66196. tempLine[++destIndex] = alpha;
  66197. lastLevel = alpha;
  66198. }
  66199. ++x;
  66200. }
  66201. if (lastLevel > 0)
  66202. {
  66203. tempLine[++destIndex] = (x << 8);
  66204. tempLine[++destIndex] = 0;
  66205. }
  66206. tempLine[0] = destIndex >> 1;
  66207. intersectWithEdgeTableLine (y, tempLine);
  66208. }
  66209. bool EdgeTable::isEmpty() throw()
  66210. {
  66211. if (needToCheckEmptinesss)
  66212. {
  66213. needToCheckEmptinesss = false;
  66214. int* t = table;
  66215. for (int i = bounds.getHeight(); --i >= 0;)
  66216. {
  66217. if (t[0] > 1)
  66218. return false;
  66219. t += lineStrideElements;
  66220. }
  66221. bounds.setHeight (0);
  66222. }
  66223. return bounds.getHeight() == 0;
  66224. }
  66225. END_JUCE_NAMESPACE
  66226. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66227. /*** Start of inlined file: juce_FillType.cpp ***/
  66228. BEGIN_JUCE_NAMESPACE
  66229. FillType::FillType() throw()
  66230. : colour (0xff000000), image (0)
  66231. {
  66232. }
  66233. FillType::FillType (const Colour& colour_) throw()
  66234. : colour (colour_), image (0)
  66235. {
  66236. }
  66237. FillType::FillType (const ColourGradient& gradient_)
  66238. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66239. {
  66240. }
  66241. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66242. : colour (0xff000000), image (image_), transform (transform_)
  66243. {
  66244. }
  66245. FillType::FillType (const FillType& other)
  66246. : colour (other.colour),
  66247. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66248. image (other.image), transform (other.transform)
  66249. {
  66250. }
  66251. FillType& FillType::operator= (const FillType& other)
  66252. {
  66253. if (this != &other)
  66254. {
  66255. colour = other.colour;
  66256. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66257. image = other.image;
  66258. transform = other.transform;
  66259. }
  66260. return *this;
  66261. }
  66262. FillType::~FillType() throw()
  66263. {
  66264. }
  66265. bool FillType::operator== (const FillType& other) const
  66266. {
  66267. return colour == other.colour && image == other.image
  66268. && transform == other.transform
  66269. && (gradient == other.gradient
  66270. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66271. }
  66272. bool FillType::operator!= (const FillType& other) const
  66273. {
  66274. return ! operator== (other);
  66275. }
  66276. void FillType::setColour (const Colour& newColour) throw()
  66277. {
  66278. gradient = 0;
  66279. image = Image::null;
  66280. colour = newColour;
  66281. }
  66282. void FillType::setGradient (const ColourGradient& newGradient)
  66283. {
  66284. if (gradient != 0)
  66285. {
  66286. *gradient = newGradient;
  66287. }
  66288. else
  66289. {
  66290. image = Image::null;
  66291. gradient = new ColourGradient (newGradient);
  66292. colour = Colours::black;
  66293. }
  66294. }
  66295. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66296. {
  66297. gradient = 0;
  66298. image = image_;
  66299. transform = transform_;
  66300. colour = Colours::black;
  66301. }
  66302. void FillType::setOpacity (const float newOpacity) throw()
  66303. {
  66304. colour = colour.withAlpha (newOpacity);
  66305. }
  66306. bool FillType::isInvisible() const throw()
  66307. {
  66308. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66309. }
  66310. END_JUCE_NAMESPACE
  66311. /*** End of inlined file: juce_FillType.cpp ***/
  66312. /*** Start of inlined file: juce_Graphics.cpp ***/
  66313. BEGIN_JUCE_NAMESPACE
  66314. template <typename Type>
  66315. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66316. {
  66317. const int maxVal = 0x3fffffff;
  66318. return (int) x >= -maxVal && (int) x <= maxVal
  66319. && (int) y >= -maxVal && (int) y <= maxVal
  66320. && (int) w >= -maxVal && (int) w <= maxVal
  66321. && (int) h >= -maxVal && (int) h <= maxVal;
  66322. }
  66323. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66324. {
  66325. }
  66326. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66327. {
  66328. }
  66329. Graphics::Graphics (const Image& imageToDrawOnto)
  66330. : context (imageToDrawOnto.createLowLevelContext()),
  66331. contextToDelete (context),
  66332. saveStatePending (false)
  66333. {
  66334. }
  66335. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66336. : context (internalContext),
  66337. saveStatePending (false)
  66338. {
  66339. }
  66340. Graphics::~Graphics()
  66341. {
  66342. }
  66343. void Graphics::resetToDefaultState()
  66344. {
  66345. saveStateIfPending();
  66346. context->setFill (FillType());
  66347. context->setFont (Font());
  66348. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66349. }
  66350. bool Graphics::isVectorDevice() const
  66351. {
  66352. return context->isVectorDevice();
  66353. }
  66354. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66355. {
  66356. saveStateIfPending();
  66357. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66358. }
  66359. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66360. {
  66361. saveStateIfPending();
  66362. return context->clipToRectangleList (clipRegion);
  66363. }
  66364. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66365. {
  66366. saveStateIfPending();
  66367. context->clipToPath (path, transform);
  66368. return ! context->isClipEmpty();
  66369. }
  66370. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66371. {
  66372. saveStateIfPending();
  66373. context->clipToImageAlpha (image, transform);
  66374. return ! context->isClipEmpty();
  66375. }
  66376. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66377. {
  66378. saveStateIfPending();
  66379. context->excludeClipRectangle (rectangleToExclude);
  66380. }
  66381. bool Graphics::isClipEmpty() const
  66382. {
  66383. return context->isClipEmpty();
  66384. }
  66385. const Rectangle<int> Graphics::getClipBounds() const
  66386. {
  66387. return context->getClipBounds();
  66388. }
  66389. void Graphics::saveState()
  66390. {
  66391. saveStateIfPending();
  66392. saveStatePending = true;
  66393. }
  66394. void Graphics::restoreState()
  66395. {
  66396. if (saveStatePending)
  66397. saveStatePending = false;
  66398. else
  66399. context->restoreState();
  66400. }
  66401. void Graphics::saveStateIfPending()
  66402. {
  66403. if (saveStatePending)
  66404. {
  66405. saveStatePending = false;
  66406. context->saveState();
  66407. }
  66408. }
  66409. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66410. {
  66411. saveStateIfPending();
  66412. context->setOrigin (newOriginX, newOriginY);
  66413. }
  66414. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66415. {
  66416. return context->clipRegionIntersects (area);
  66417. }
  66418. void Graphics::setColour (const Colour& newColour)
  66419. {
  66420. saveStateIfPending();
  66421. context->setFill (newColour);
  66422. }
  66423. void Graphics::setOpacity (const float newOpacity)
  66424. {
  66425. saveStateIfPending();
  66426. context->setOpacity (newOpacity);
  66427. }
  66428. void Graphics::setGradientFill (const ColourGradient& gradient)
  66429. {
  66430. setFillType (gradient);
  66431. }
  66432. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66433. {
  66434. saveStateIfPending();
  66435. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66436. context->setOpacity (opacity);
  66437. }
  66438. void Graphics::setFillType (const FillType& newFill)
  66439. {
  66440. saveStateIfPending();
  66441. context->setFill (newFill);
  66442. }
  66443. void Graphics::setFont (const Font& newFont)
  66444. {
  66445. saveStateIfPending();
  66446. context->setFont (newFont);
  66447. }
  66448. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66449. {
  66450. saveStateIfPending();
  66451. Font f (context->getFont());
  66452. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66453. context->setFont (f);
  66454. }
  66455. const Font Graphics::getCurrentFont() const
  66456. {
  66457. return context->getFont();
  66458. }
  66459. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66460. {
  66461. if (text.isNotEmpty()
  66462. && startX < context->getClipBounds().getRight())
  66463. {
  66464. GlyphArrangement arr;
  66465. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66466. arr.draw (*this);
  66467. }
  66468. }
  66469. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66470. {
  66471. if (text.isNotEmpty())
  66472. {
  66473. GlyphArrangement arr;
  66474. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66475. arr.draw (*this, transform);
  66476. }
  66477. }
  66478. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66479. {
  66480. if (text.isNotEmpty()
  66481. && startX < context->getClipBounds().getRight())
  66482. {
  66483. GlyphArrangement arr;
  66484. arr.addJustifiedText (context->getFont(), text,
  66485. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66486. Justification::left);
  66487. arr.draw (*this);
  66488. }
  66489. }
  66490. void Graphics::drawText (const String& text,
  66491. const int x, const int y, const int width, const int height,
  66492. const Justification& justificationType,
  66493. const bool useEllipsesIfTooBig) const
  66494. {
  66495. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66496. {
  66497. GlyphArrangement arr;
  66498. arr.addCurtailedLineOfText (context->getFont(), text,
  66499. 0.0f, 0.0f, (float) width,
  66500. useEllipsesIfTooBig);
  66501. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66502. (float) x, (float) y, (float) width, (float) height,
  66503. justificationType);
  66504. arr.draw (*this);
  66505. }
  66506. }
  66507. void Graphics::drawFittedText (const String& text,
  66508. const int x, const int y, const int width, const int height,
  66509. const Justification& justification,
  66510. const int maximumNumberOfLines,
  66511. const float minimumHorizontalScale) const
  66512. {
  66513. if (text.isNotEmpty()
  66514. && width > 0 && height > 0
  66515. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66516. {
  66517. GlyphArrangement arr;
  66518. arr.addFittedText (context->getFont(), text,
  66519. (float) x, (float) y, (float) width, (float) height,
  66520. justification,
  66521. maximumNumberOfLines,
  66522. minimumHorizontalScale);
  66523. arr.draw (*this);
  66524. }
  66525. }
  66526. void Graphics::fillRect (int x, int y, int width, int height) const
  66527. {
  66528. // passing in a silly number can cause maths problems in rendering!
  66529. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66530. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66531. }
  66532. void Graphics::fillRect (const Rectangle<int>& r) const
  66533. {
  66534. context->fillRect (r, false);
  66535. }
  66536. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66537. {
  66538. // passing in a silly number can cause maths problems in rendering!
  66539. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66540. Path p;
  66541. p.addRectangle (x, y, width, height);
  66542. fillPath (p);
  66543. }
  66544. void Graphics::setPixel (int x, int y) const
  66545. {
  66546. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66547. }
  66548. void Graphics::fillAll() const
  66549. {
  66550. fillRect (context->getClipBounds());
  66551. }
  66552. void Graphics::fillAll (const Colour& colourToUse) const
  66553. {
  66554. if (! colourToUse.isTransparent())
  66555. {
  66556. const Rectangle<int> clip (context->getClipBounds());
  66557. context->saveState();
  66558. context->setFill (colourToUse);
  66559. context->fillRect (clip, false);
  66560. context->restoreState();
  66561. }
  66562. }
  66563. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66564. {
  66565. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66566. context->fillPath (path, transform);
  66567. }
  66568. void Graphics::strokePath (const Path& path,
  66569. const PathStrokeType& strokeType,
  66570. const AffineTransform& transform) const
  66571. {
  66572. Path stroke;
  66573. strokeType.createStrokedPath (stroke, path, transform);
  66574. fillPath (stroke);
  66575. }
  66576. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66577. const int lineThickness) const
  66578. {
  66579. // passing in a silly number can cause maths problems in rendering!
  66580. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66581. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66582. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66583. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66584. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66585. }
  66586. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66587. {
  66588. // passing in a silly number can cause maths problems in rendering!
  66589. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66590. Path p;
  66591. p.addRectangle (x, y, width, lineThickness);
  66592. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66593. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66594. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66595. fillPath (p);
  66596. }
  66597. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66598. {
  66599. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66600. }
  66601. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66602. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66603. const bool useGradient, const bool sharpEdgeOnOutside) const
  66604. {
  66605. // passing in a silly number can cause maths problems in rendering!
  66606. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66607. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66608. {
  66609. context->saveState();
  66610. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66611. const float ramp = oldOpacity / bevelThickness;
  66612. for (int i = bevelThickness; --i >= 0;)
  66613. {
  66614. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66615. : oldOpacity;
  66616. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66617. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66618. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66619. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66620. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66621. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66622. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66623. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66624. }
  66625. context->restoreState();
  66626. }
  66627. }
  66628. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66629. {
  66630. // passing in a silly number can cause maths problems in rendering!
  66631. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66632. Path p;
  66633. p.addEllipse (x, y, width, height);
  66634. fillPath (p);
  66635. }
  66636. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66637. const float lineThickness) const
  66638. {
  66639. // passing in a silly number can cause maths problems in rendering!
  66640. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66641. Path p;
  66642. p.addEllipse (x, y, width, height);
  66643. strokePath (p, PathStrokeType (lineThickness));
  66644. }
  66645. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66646. {
  66647. // passing in a silly number can cause maths problems in rendering!
  66648. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66649. Path p;
  66650. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66651. fillPath (p);
  66652. }
  66653. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66654. {
  66655. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66656. }
  66657. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66658. const float cornerSize, const float lineThickness) const
  66659. {
  66660. // passing in a silly number can cause maths problems in rendering!
  66661. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66662. Path p;
  66663. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66664. strokePath (p, PathStrokeType (lineThickness));
  66665. }
  66666. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66667. {
  66668. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66669. }
  66670. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66671. {
  66672. Path p;
  66673. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66674. fillPath (p);
  66675. }
  66676. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66677. const int checkWidth, const int checkHeight,
  66678. const Colour& colour1, const Colour& colour2) const
  66679. {
  66680. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66681. if (checkWidth > 0 && checkHeight > 0)
  66682. {
  66683. context->saveState();
  66684. if (colour1 == colour2)
  66685. {
  66686. context->setFill (colour1);
  66687. context->fillRect (area, false);
  66688. }
  66689. else
  66690. {
  66691. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66692. if (! clipped.isEmpty())
  66693. {
  66694. context->clipToRectangle (clipped);
  66695. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66696. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66697. const int startX = area.getX() + checkNumX * checkWidth;
  66698. const int startY = area.getY() + checkNumY * checkHeight;
  66699. const int right = clipped.getRight();
  66700. const int bottom = clipped.getBottom();
  66701. for (int i = 0; i < 2; ++i)
  66702. {
  66703. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66704. int cy = i;
  66705. for (int y = startY; y < bottom; y += checkHeight)
  66706. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66707. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66708. }
  66709. }
  66710. }
  66711. context->restoreState();
  66712. }
  66713. }
  66714. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66715. {
  66716. context->drawVerticalLine (x, top, bottom);
  66717. }
  66718. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66719. {
  66720. context->drawHorizontalLine (y, left, right);
  66721. }
  66722. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66723. {
  66724. context->drawLine (Line<float> (x1, y1, x2, y2));
  66725. }
  66726. void Graphics::drawLine (const float startX, const float startY,
  66727. const float endX, const float endY,
  66728. const float lineThickness) const
  66729. {
  66730. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66731. }
  66732. void Graphics::drawLine (const Line<float>& line) const
  66733. {
  66734. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66735. }
  66736. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66737. {
  66738. Path p;
  66739. p.addLineSegment (line, lineThickness);
  66740. fillPath (p);
  66741. }
  66742. void Graphics::drawDashedLine (const float startX, const float startY,
  66743. const float endX, const float endY,
  66744. const float* const dashLengths,
  66745. const int numDashLengths,
  66746. const float lineThickness) const
  66747. {
  66748. const double dx = endX - startX;
  66749. const double dy = endY - startY;
  66750. const double totalLen = juce_hypot (dx, dy);
  66751. if (totalLen >= 0.5)
  66752. {
  66753. const double onePixAlpha = 1.0 / totalLen;
  66754. double alpha = 0.0;
  66755. float x = startX;
  66756. float y = startY;
  66757. int n = 0;
  66758. while (alpha < 1.0f)
  66759. {
  66760. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66761. n = n % numDashLengths;
  66762. const float oldX = x;
  66763. const float oldY = y;
  66764. x = (float) (startX + dx * alpha);
  66765. y = (float) (startY + dy * alpha);
  66766. if ((n & 1) != 0)
  66767. {
  66768. if (lineThickness != 1.0f)
  66769. drawLine (oldX, oldY, x, y, lineThickness);
  66770. else
  66771. drawLine (oldX, oldY, x, y);
  66772. }
  66773. }
  66774. }
  66775. }
  66776. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66777. {
  66778. saveStateIfPending();
  66779. context->setInterpolationQuality (newQuality);
  66780. }
  66781. void Graphics::drawImageAt (const Image& imageToDraw,
  66782. const int topLeftX, const int topLeftY,
  66783. const bool fillAlphaChannelWithCurrentBrush) const
  66784. {
  66785. const int imageW = imageToDraw.getWidth();
  66786. const int imageH = imageToDraw.getHeight();
  66787. drawImage (imageToDraw,
  66788. topLeftX, topLeftY, imageW, imageH,
  66789. 0, 0, imageW, imageH,
  66790. fillAlphaChannelWithCurrentBrush);
  66791. }
  66792. void Graphics::drawImageWithin (const Image& imageToDraw,
  66793. const int destX, const int destY,
  66794. const int destW, const int destH,
  66795. const RectanglePlacement& placementWithinTarget,
  66796. const bool fillAlphaChannelWithCurrentBrush) const
  66797. {
  66798. // passing in a silly number can cause maths problems in rendering!
  66799. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66800. if (imageToDraw.isValid())
  66801. {
  66802. const int imageW = imageToDraw.getWidth();
  66803. const int imageH = imageToDraw.getHeight();
  66804. if (imageW > 0 && imageH > 0)
  66805. {
  66806. double newX = 0.0, newY = 0.0;
  66807. double newW = imageW;
  66808. double newH = imageH;
  66809. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66810. destX, destY, destW, destH);
  66811. if (newW > 0 && newH > 0)
  66812. {
  66813. drawImage (imageToDraw,
  66814. roundToInt (newX), roundToInt (newY),
  66815. roundToInt (newW), roundToInt (newH),
  66816. 0, 0, imageW, imageH,
  66817. fillAlphaChannelWithCurrentBrush);
  66818. }
  66819. }
  66820. }
  66821. }
  66822. void Graphics::drawImage (const Image& imageToDraw,
  66823. int dx, int dy, int dw, int dh,
  66824. int sx, int sy, int sw, int sh,
  66825. const bool fillAlphaChannelWithCurrentBrush) const
  66826. {
  66827. // passing in a silly number can cause maths problems in rendering!
  66828. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66829. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66830. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66831. {
  66832. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66833. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66834. .translated ((float) dx, (float) dy),
  66835. fillAlphaChannelWithCurrentBrush);
  66836. }
  66837. }
  66838. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66839. const AffineTransform& transform,
  66840. const bool fillAlphaChannelWithCurrentBrush) const
  66841. {
  66842. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66843. {
  66844. if (fillAlphaChannelWithCurrentBrush)
  66845. {
  66846. context->saveState();
  66847. context->clipToImageAlpha (imageToDraw, transform);
  66848. fillAll();
  66849. context->restoreState();
  66850. }
  66851. else
  66852. {
  66853. context->drawImage (imageToDraw, transform, false);
  66854. }
  66855. }
  66856. }
  66857. END_JUCE_NAMESPACE
  66858. /*** End of inlined file: juce_Graphics.cpp ***/
  66859. /*** Start of inlined file: juce_Justification.cpp ***/
  66860. BEGIN_JUCE_NAMESPACE
  66861. Justification::Justification (const Justification& other) throw()
  66862. : flags (other.flags)
  66863. {
  66864. }
  66865. Justification& Justification::operator= (const Justification& other) throw()
  66866. {
  66867. flags = other.flags;
  66868. return *this;
  66869. }
  66870. int Justification::getOnlyVerticalFlags() const throw()
  66871. {
  66872. return flags & (top | bottom | verticallyCentred);
  66873. }
  66874. int Justification::getOnlyHorizontalFlags() const throw()
  66875. {
  66876. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66877. }
  66878. void Justification::applyToRectangle (int& x, int& y,
  66879. const int w, const int h,
  66880. const int spaceX, const int spaceY,
  66881. const int spaceW, const int spaceH) const throw()
  66882. {
  66883. if ((flags & horizontallyCentred) != 0)
  66884. x = spaceX + ((spaceW - w) >> 1);
  66885. else if ((flags & right) != 0)
  66886. x = spaceX + spaceW - w;
  66887. else
  66888. x = spaceX;
  66889. if ((flags & verticallyCentred) != 0)
  66890. y = spaceY + ((spaceH - h) >> 1);
  66891. else if ((flags & bottom) != 0)
  66892. y = spaceY + spaceH - h;
  66893. else
  66894. y = spaceY;
  66895. }
  66896. END_JUCE_NAMESPACE
  66897. /*** End of inlined file: juce_Justification.cpp ***/
  66898. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66899. BEGIN_JUCE_NAMESPACE
  66900. // this will throw an assertion if you try to draw something that's not
  66901. // possible in postscript
  66902. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66903. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66904. #define notPossibleInPostscriptAssert jassertfalse
  66905. #else
  66906. #define notPossibleInPostscriptAssert
  66907. #endif
  66908. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66909. const String& documentTitle,
  66910. const int totalWidth_,
  66911. const int totalHeight_)
  66912. : out (resultingPostScript),
  66913. totalWidth (totalWidth_),
  66914. totalHeight (totalHeight_),
  66915. needToClip (true)
  66916. {
  66917. stateStack.add (new SavedState());
  66918. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66919. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66920. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66921. "\n%%BoundingBox: 0 0 600 824"
  66922. "\n%%Pages: 0"
  66923. "\n%%Creator: Raw Material Software JUCE"
  66924. "\n%%Title: " << documentTitle <<
  66925. "\n%%CreationDate: none"
  66926. "\n%%LanguageLevel: 2"
  66927. "\n%%EndComments"
  66928. "\n%%BeginProlog"
  66929. "\n%%BeginResource: JRes"
  66930. "\n/bd {bind def} bind def"
  66931. "\n/c {setrgbcolor} bd"
  66932. "\n/m {moveto} bd"
  66933. "\n/l {lineto} bd"
  66934. "\n/rl {rlineto} bd"
  66935. "\n/ct {curveto} bd"
  66936. "\n/cp {closepath} bd"
  66937. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66938. "\n/doclip {initclip newpath} bd"
  66939. "\n/endclip {clip newpath} bd"
  66940. "\n%%EndResource"
  66941. "\n%%EndProlog"
  66942. "\n%%BeginSetup"
  66943. "\n%%EndSetup"
  66944. "\n%%Page: 1 1"
  66945. "\n%%BeginPageSetup"
  66946. "\n%%EndPageSetup\n\n"
  66947. << "40 800 translate\n"
  66948. << scale << ' ' << scale << " scale\n\n";
  66949. }
  66950. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66951. {
  66952. }
  66953. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66954. {
  66955. return true;
  66956. }
  66957. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66958. {
  66959. if (x != 0 || y != 0)
  66960. {
  66961. stateStack.getLast()->xOffset += x;
  66962. stateStack.getLast()->yOffset += y;
  66963. needToClip = true;
  66964. }
  66965. }
  66966. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66967. {
  66968. needToClip = true;
  66969. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66970. }
  66971. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66972. {
  66973. needToClip = true;
  66974. return stateStack.getLast()->clip.clipTo (clipRegion);
  66975. }
  66976. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66977. {
  66978. needToClip = true;
  66979. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66980. }
  66981. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66982. {
  66983. writeClip();
  66984. Path p (path);
  66985. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66986. writePath (p);
  66987. out << "clip\n";
  66988. }
  66989. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66990. {
  66991. needToClip = true;
  66992. jassertfalse; // xxx
  66993. }
  66994. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66995. {
  66996. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66997. }
  66998. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66999. {
  67000. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67001. -stateStack.getLast()->yOffset);
  67002. }
  67003. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67004. {
  67005. return stateStack.getLast()->clip.isEmpty();
  67006. }
  67007. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67008. : xOffset (0),
  67009. yOffset (0)
  67010. {
  67011. }
  67012. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67013. {
  67014. }
  67015. void LowLevelGraphicsPostScriptRenderer::saveState()
  67016. {
  67017. stateStack.add (new SavedState (*stateStack.getLast()));
  67018. }
  67019. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67020. {
  67021. jassert (stateStack.size() > 0);
  67022. if (stateStack.size() > 0)
  67023. stateStack.removeLast();
  67024. }
  67025. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67026. {
  67027. if (needToClip)
  67028. {
  67029. needToClip = false;
  67030. out << "doclip ";
  67031. int itemsOnLine = 0;
  67032. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67033. {
  67034. if (++itemsOnLine == 6)
  67035. {
  67036. itemsOnLine = 0;
  67037. out << '\n';
  67038. }
  67039. const Rectangle<int>& r = *i.getRectangle();
  67040. out << r.getX() << ' ' << -r.getY() << ' '
  67041. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67042. }
  67043. out << "endclip\n";
  67044. }
  67045. }
  67046. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67047. {
  67048. Colour c (Colours::white.overlaidWith (colour));
  67049. if (lastColour != c)
  67050. {
  67051. lastColour = c;
  67052. out << String (c.getFloatRed(), 3) << ' '
  67053. << String (c.getFloatGreen(), 3) << ' '
  67054. << String (c.getFloatBlue(), 3) << " c\n";
  67055. }
  67056. }
  67057. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67058. {
  67059. out << String (x, 2) << ' '
  67060. << String (-y, 2) << ' ';
  67061. }
  67062. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67063. {
  67064. out << "newpath ";
  67065. float lastX = 0.0f;
  67066. float lastY = 0.0f;
  67067. int itemsOnLine = 0;
  67068. Path::Iterator i (path);
  67069. while (i.next())
  67070. {
  67071. if (++itemsOnLine == 4)
  67072. {
  67073. itemsOnLine = 0;
  67074. out << '\n';
  67075. }
  67076. switch (i.elementType)
  67077. {
  67078. case Path::Iterator::startNewSubPath:
  67079. writeXY (i.x1, i.y1);
  67080. lastX = i.x1;
  67081. lastY = i.y1;
  67082. out << "m ";
  67083. break;
  67084. case Path::Iterator::lineTo:
  67085. writeXY (i.x1, i.y1);
  67086. lastX = i.x1;
  67087. lastY = i.y1;
  67088. out << "l ";
  67089. break;
  67090. case Path::Iterator::quadraticTo:
  67091. {
  67092. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67093. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67094. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67095. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67096. writeXY (cp1x, cp1y);
  67097. writeXY (cp2x, cp2y);
  67098. writeXY (i.x2, i.y2);
  67099. out << "ct ";
  67100. lastX = i.x2;
  67101. lastY = i.y2;
  67102. }
  67103. break;
  67104. case Path::Iterator::cubicTo:
  67105. writeXY (i.x1, i.y1);
  67106. writeXY (i.x2, i.y2);
  67107. writeXY (i.x3, i.y3);
  67108. out << "ct ";
  67109. lastX = i.x3;
  67110. lastY = i.y3;
  67111. break;
  67112. case Path::Iterator::closePath:
  67113. out << "cp ";
  67114. break;
  67115. default:
  67116. jassertfalse;
  67117. break;
  67118. }
  67119. }
  67120. out << '\n';
  67121. }
  67122. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67123. {
  67124. out << "[ "
  67125. << trans.mat00 << ' '
  67126. << trans.mat10 << ' '
  67127. << trans.mat01 << ' '
  67128. << trans.mat11 << ' '
  67129. << trans.mat02 << ' '
  67130. << trans.mat12 << " ] concat ";
  67131. }
  67132. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67133. {
  67134. stateStack.getLast()->fillType = fillType;
  67135. }
  67136. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67137. {
  67138. }
  67139. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67140. {
  67141. }
  67142. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67143. {
  67144. if (stateStack.getLast()->fillType.isColour())
  67145. {
  67146. writeClip();
  67147. writeColour (stateStack.getLast()->fillType.colour);
  67148. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67149. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67150. }
  67151. else
  67152. {
  67153. Path p;
  67154. p.addRectangle (r);
  67155. fillPath (p, AffineTransform::identity);
  67156. }
  67157. }
  67158. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67159. {
  67160. if (stateStack.getLast()->fillType.isColour())
  67161. {
  67162. writeClip();
  67163. Path p (path);
  67164. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67165. (float) stateStack.getLast()->yOffset));
  67166. writePath (p);
  67167. writeColour (stateStack.getLast()->fillType.colour);
  67168. out << "fill\n";
  67169. }
  67170. else if (stateStack.getLast()->fillType.isGradient())
  67171. {
  67172. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67173. // postscript can't do semi-transparent ones.
  67174. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67175. writeClip();
  67176. out << "gsave ";
  67177. {
  67178. Path p (path);
  67179. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67180. writePath (p);
  67181. out << "clip\n";
  67182. }
  67183. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67184. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67185. // time-being, this just fills it with the average colour..
  67186. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67187. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67188. out << "grestore\n";
  67189. }
  67190. }
  67191. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67192. const int sx, const int sy,
  67193. const int maxW, const int maxH) const
  67194. {
  67195. out << "{<\n";
  67196. const int w = jmin (maxW, im.getWidth());
  67197. const int h = jmin (maxH, im.getHeight());
  67198. int charsOnLine = 0;
  67199. const Image::BitmapData srcData (im, 0, 0, w, h);
  67200. Colour pixel;
  67201. for (int y = h; --y >= 0;)
  67202. {
  67203. for (int x = 0; x < w; ++x)
  67204. {
  67205. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67206. if (x >= sx && y >= sy)
  67207. {
  67208. if (im.isARGB())
  67209. {
  67210. PixelARGB p (*(const PixelARGB*) pixelData);
  67211. p.unpremultiply();
  67212. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67213. }
  67214. else if (im.isRGB())
  67215. {
  67216. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67217. }
  67218. else
  67219. {
  67220. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67221. }
  67222. }
  67223. else
  67224. {
  67225. pixel = Colours::transparentWhite;
  67226. }
  67227. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67228. out << String::toHexString (pixelValues, 3, 0);
  67229. charsOnLine += 3;
  67230. if (charsOnLine > 100)
  67231. {
  67232. out << '\n';
  67233. charsOnLine = 0;
  67234. }
  67235. }
  67236. }
  67237. out << "\n>}\n";
  67238. }
  67239. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67240. {
  67241. const int w = sourceImage.getWidth();
  67242. const int h = sourceImage.getHeight();
  67243. writeClip();
  67244. out << "gsave ";
  67245. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67246. .scaled (1.0f, -1.0f));
  67247. RectangleList imageClip;
  67248. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67249. out << "newpath ";
  67250. int itemsOnLine = 0;
  67251. for (RectangleList::Iterator i (imageClip); i.next();)
  67252. {
  67253. if (++itemsOnLine == 6)
  67254. {
  67255. out << '\n';
  67256. itemsOnLine = 0;
  67257. }
  67258. const Rectangle<int>& r = *i.getRectangle();
  67259. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67260. }
  67261. out << " clip newpath\n";
  67262. out << w << ' ' << h << " scale\n";
  67263. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67264. writeImage (sourceImage, 0, 0, w, h);
  67265. out << "false 3 colorimage grestore\n";
  67266. needToClip = true;
  67267. }
  67268. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67269. {
  67270. Path p;
  67271. p.addLineSegment (line, 1.0f);
  67272. fillPath (p, AffineTransform::identity);
  67273. }
  67274. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67275. {
  67276. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67277. }
  67278. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67279. {
  67280. drawLine (Line<float> (left, (float) y, right, (float) y));
  67281. }
  67282. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67283. {
  67284. stateStack.getLast()->font = newFont;
  67285. }
  67286. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67287. {
  67288. return stateStack.getLast()->font;
  67289. }
  67290. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67291. {
  67292. Path p;
  67293. Font& font = stateStack.getLast()->font;
  67294. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67295. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67296. }
  67297. END_JUCE_NAMESPACE
  67298. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67299. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67300. BEGIN_JUCE_NAMESPACE
  67301. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67302. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67303. #endif
  67304. #if JUCE_MSVC
  67305. #pragma warning (push)
  67306. #pragma warning (disable: 4127) // "expression is constant" warning
  67307. #if JUCE_DEBUG
  67308. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67309. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67310. #endif
  67311. #endif
  67312. namespace SoftwareRendererClasses
  67313. {
  67314. template <class PixelType, bool replaceExisting = false>
  67315. class SolidColourEdgeTableRenderer
  67316. {
  67317. public:
  67318. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67319. : data (data_),
  67320. sourceColour (colour)
  67321. {
  67322. if (sizeof (PixelType) == 3)
  67323. {
  67324. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67325. && sourceColour.getGreen() == sourceColour.getBlue();
  67326. filler[0].set (sourceColour);
  67327. filler[1].set (sourceColour);
  67328. filler[2].set (sourceColour);
  67329. filler[3].set (sourceColour);
  67330. }
  67331. }
  67332. forcedinline void setEdgeTableYPos (const int y) throw()
  67333. {
  67334. linePixels = (PixelType*) data.getLinePointer (y);
  67335. }
  67336. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67337. {
  67338. if (replaceExisting)
  67339. linePixels[x].set (sourceColour);
  67340. else
  67341. linePixels[x].blend (sourceColour, alphaLevel);
  67342. }
  67343. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67344. {
  67345. if (replaceExisting)
  67346. linePixels[x].set (sourceColour);
  67347. else
  67348. linePixels[x].blend (sourceColour);
  67349. }
  67350. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67351. {
  67352. PixelARGB p (sourceColour);
  67353. p.multiplyAlpha (alphaLevel);
  67354. PixelType* dest = linePixels + x;
  67355. if (replaceExisting || p.getAlpha() >= 0xff)
  67356. replaceLine (dest, p, width);
  67357. else
  67358. blendLine (dest, p, width);
  67359. }
  67360. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67361. {
  67362. PixelType* dest = linePixels + x;
  67363. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67364. replaceLine (dest, sourceColour, width);
  67365. else
  67366. blendLine (dest, sourceColour, width);
  67367. }
  67368. private:
  67369. const Image::BitmapData& data;
  67370. PixelType* linePixels;
  67371. PixelARGB sourceColour;
  67372. PixelRGB filler [4];
  67373. bool areRGBComponentsEqual;
  67374. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67375. {
  67376. do
  67377. {
  67378. dest->blend (colour);
  67379. ++dest;
  67380. } while (--width > 0);
  67381. }
  67382. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67383. {
  67384. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67385. {
  67386. memset (dest, colour.getRed(), width * 3);
  67387. }
  67388. else
  67389. {
  67390. if (width >> 5)
  67391. {
  67392. const int* const intFiller = (const int*) filler;
  67393. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67394. {
  67395. dest->set (colour);
  67396. ++dest;
  67397. --width;
  67398. }
  67399. while (width > 4)
  67400. {
  67401. ((int*) dest) [0] = intFiller[0];
  67402. ((int*) dest) [1] = intFiller[1];
  67403. ((int*) dest) [2] = intFiller[2];
  67404. dest = (PixelRGB*) (((uint8*) dest) + 12);
  67405. width -= 4;
  67406. }
  67407. }
  67408. while (--width >= 0)
  67409. {
  67410. dest->set (colour);
  67411. ++dest;
  67412. }
  67413. }
  67414. }
  67415. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67416. {
  67417. memset (dest, colour.getAlpha(), width);
  67418. }
  67419. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67420. {
  67421. do
  67422. {
  67423. dest->set (colour);
  67424. ++dest;
  67425. } while (--width > 0);
  67426. }
  67427. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67428. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67429. };
  67430. class LinearGradientPixelGenerator
  67431. {
  67432. public:
  67433. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67434. : lookupTable (lookupTable_), numEntries (numEntries_)
  67435. {
  67436. jassert (numEntries_ >= 0);
  67437. Point<float> p1 (gradient.point1);
  67438. Point<float> p2 (gradient.point2);
  67439. if (! transform.isIdentity())
  67440. {
  67441. const Line<float> l (p2, p1);
  67442. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67443. p1.applyTransform (transform);
  67444. p2.applyTransform (transform);
  67445. p3.applyTransform (transform);
  67446. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67447. }
  67448. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67449. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67450. if (vertical)
  67451. {
  67452. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67453. start = roundToInt (p1.getY() * scale);
  67454. }
  67455. else if (horizontal)
  67456. {
  67457. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67458. start = roundToInt (p1.getX() * scale);
  67459. }
  67460. else
  67461. {
  67462. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67463. yTerm = p1.getY() - p1.getX() / grad;
  67464. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67465. grad *= scale;
  67466. }
  67467. }
  67468. forcedinline void setY (const int y) throw()
  67469. {
  67470. if (vertical)
  67471. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67472. else if (! horizontal)
  67473. start = roundToInt ((y - yTerm) * grad);
  67474. }
  67475. inline const PixelARGB getPixel (const int x) const throw()
  67476. {
  67477. return vertical ? linePix
  67478. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67479. }
  67480. private:
  67481. const PixelARGB* const lookupTable;
  67482. const int numEntries;
  67483. PixelARGB linePix;
  67484. int start, scale;
  67485. double grad, yTerm;
  67486. bool vertical, horizontal;
  67487. enum { numScaleBits = 12 };
  67488. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67489. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67490. };
  67491. class RadialGradientPixelGenerator
  67492. {
  67493. public:
  67494. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67495. const PixelARGB* const lookupTable_, const int numEntries_)
  67496. : lookupTable (lookupTable_),
  67497. numEntries (numEntries_),
  67498. gx1 (gradient.point1.getX()),
  67499. gy1 (gradient.point1.getY())
  67500. {
  67501. jassert (numEntries_ >= 0);
  67502. const Point<float> diff (gradient.point1 - gradient.point2);
  67503. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67504. invScale = numEntries / std::sqrt (maxDist);
  67505. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67506. }
  67507. forcedinline void setY (const int y) throw()
  67508. {
  67509. dy = y - gy1;
  67510. dy *= dy;
  67511. }
  67512. inline const PixelARGB getPixel (const int px) const throw()
  67513. {
  67514. double x = px - gx1;
  67515. x *= x;
  67516. x += dy;
  67517. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67518. }
  67519. protected:
  67520. const PixelARGB* const lookupTable;
  67521. const int numEntries;
  67522. const double gx1, gy1;
  67523. double maxDist, invScale, dy;
  67524. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67525. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67526. };
  67527. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67528. {
  67529. public:
  67530. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67531. const PixelARGB* const lookupTable_, const int numEntries_)
  67532. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67533. inverseTransform (transform.inverted())
  67534. {
  67535. tM10 = inverseTransform.mat10;
  67536. tM00 = inverseTransform.mat00;
  67537. }
  67538. forcedinline void setY (const int y) throw()
  67539. {
  67540. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67541. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67542. }
  67543. inline const PixelARGB getPixel (const int px) const throw()
  67544. {
  67545. double x = px;
  67546. const double y = tM10 * x + lineYM11;
  67547. x = tM00 * x + lineYM01;
  67548. x *= x;
  67549. x += y * y;
  67550. if (x >= maxDist)
  67551. return lookupTable [numEntries];
  67552. else
  67553. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67554. }
  67555. private:
  67556. double tM10, tM00, lineYM01, lineYM11;
  67557. const AffineTransform inverseTransform;
  67558. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67559. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67560. };
  67561. template <class PixelType, class GradientType>
  67562. class GradientEdgeTableRenderer : public GradientType
  67563. {
  67564. public:
  67565. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67566. const PixelARGB* const lookupTable_, const int numEntries_)
  67567. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67568. destData (destData_)
  67569. {
  67570. }
  67571. forcedinline void setEdgeTableYPos (const int y) throw()
  67572. {
  67573. linePixels = (PixelType*) destData.getLinePointer (y);
  67574. GradientType::setY (y);
  67575. }
  67576. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67577. {
  67578. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67579. }
  67580. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67581. {
  67582. linePixels[x].blend (GradientType::getPixel (x));
  67583. }
  67584. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67585. {
  67586. PixelType* dest = linePixels + x;
  67587. if (alphaLevel < 0xff)
  67588. {
  67589. do
  67590. {
  67591. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67592. } while (--width > 0);
  67593. }
  67594. else
  67595. {
  67596. do
  67597. {
  67598. (dest++)->blend (GradientType::getPixel (x++));
  67599. } while (--width > 0);
  67600. }
  67601. }
  67602. void handleEdgeTableLineFull (int x, int width) const throw()
  67603. {
  67604. PixelType* dest = linePixels + x;
  67605. do
  67606. {
  67607. (dest++)->blend (GradientType::getPixel (x++));
  67608. } while (--width > 0);
  67609. }
  67610. private:
  67611. const Image::BitmapData& destData;
  67612. PixelType* linePixels;
  67613. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67614. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67615. };
  67616. static forcedinline int safeModulo (int n, const int divisor) throw()
  67617. {
  67618. jassert (divisor > 0);
  67619. n %= divisor;
  67620. return (n < 0) ? (n + divisor) : n;
  67621. }
  67622. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67623. class ImageFillEdgeTableRenderer
  67624. {
  67625. public:
  67626. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67627. const Image::BitmapData& srcData_,
  67628. const int extraAlpha_,
  67629. const int x, const int y)
  67630. : destData (destData_),
  67631. srcData (srcData_),
  67632. extraAlpha (extraAlpha_ + 1),
  67633. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67634. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67635. {
  67636. }
  67637. forcedinline void setEdgeTableYPos (int y) throw()
  67638. {
  67639. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67640. y -= yOffset;
  67641. if (repeatPattern)
  67642. {
  67643. jassert (y >= 0);
  67644. y %= srcData.height;
  67645. }
  67646. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67647. }
  67648. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67649. {
  67650. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67651. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67652. }
  67653. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67654. {
  67655. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67656. }
  67657. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67658. {
  67659. DestPixelType* dest = linePixels + x;
  67660. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67661. x -= xOffset;
  67662. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67663. if (alphaLevel < 0xfe)
  67664. {
  67665. do
  67666. {
  67667. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67668. } while (--width > 0);
  67669. }
  67670. else
  67671. {
  67672. if (repeatPattern)
  67673. {
  67674. do
  67675. {
  67676. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67677. } while (--width > 0);
  67678. }
  67679. else
  67680. {
  67681. copyRow (dest, sourceLineStart + x, width);
  67682. }
  67683. }
  67684. }
  67685. void handleEdgeTableLineFull (int x, int width) const throw()
  67686. {
  67687. DestPixelType* dest = linePixels + x;
  67688. x -= xOffset;
  67689. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67690. if (extraAlpha < 0xfe)
  67691. {
  67692. do
  67693. {
  67694. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67695. } while (--width > 0);
  67696. }
  67697. else
  67698. {
  67699. if (repeatPattern)
  67700. {
  67701. do
  67702. {
  67703. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67704. } while (--width > 0);
  67705. }
  67706. else
  67707. {
  67708. copyRow (dest, sourceLineStart + x, width);
  67709. }
  67710. }
  67711. }
  67712. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67713. {
  67714. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67715. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67716. uint8* mask = (uint8*) (s + x - xOffset);
  67717. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67718. mask += PixelARGB::indexA;
  67719. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67720. }
  67721. private:
  67722. const Image::BitmapData& destData;
  67723. const Image::BitmapData& srcData;
  67724. const int extraAlpha, xOffset, yOffset;
  67725. DestPixelType* linePixels;
  67726. SrcPixelType* sourceLineStart;
  67727. template <class PixelType1, class PixelType2>
  67728. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67729. {
  67730. do
  67731. {
  67732. dest++ ->blend (*src++);
  67733. } while (--width > 0);
  67734. }
  67735. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67736. {
  67737. memcpy (dest, src, width * sizeof (PixelRGB));
  67738. }
  67739. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67740. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67741. };
  67742. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67743. class TransformedImageFillEdgeTableRenderer
  67744. {
  67745. public:
  67746. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67747. const Image::BitmapData& srcData_,
  67748. const AffineTransform& transform,
  67749. const int extraAlpha_,
  67750. const bool betterQuality_)
  67751. : interpolator (transform),
  67752. destData (destData_),
  67753. srcData (srcData_),
  67754. extraAlpha (extraAlpha_ + 1),
  67755. betterQuality (betterQuality_),
  67756. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67757. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67758. maxX (srcData_.width - 1),
  67759. maxY (srcData_.height - 1),
  67760. scratchSize (2048)
  67761. {
  67762. scratchBuffer.malloc (scratchSize);
  67763. }
  67764. ~TransformedImageFillEdgeTableRenderer()
  67765. {
  67766. }
  67767. forcedinline void setEdgeTableYPos (const int newY) throw()
  67768. {
  67769. y = newY;
  67770. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67771. }
  67772. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67773. {
  67774. alphaLevel *= extraAlpha;
  67775. alphaLevel >>= 8;
  67776. SrcPixelType p;
  67777. generate (&p, x, 1);
  67778. linePixels[x].blend (p, alphaLevel);
  67779. }
  67780. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67781. {
  67782. SrcPixelType p;
  67783. generate (&p, x, 1);
  67784. linePixels[x].blend (p, extraAlpha);
  67785. }
  67786. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67787. {
  67788. if (width > scratchSize)
  67789. {
  67790. scratchSize = width;
  67791. scratchBuffer.malloc (scratchSize);
  67792. }
  67793. SrcPixelType* span = scratchBuffer;
  67794. generate (span, x, width);
  67795. DestPixelType* dest = linePixels + x;
  67796. alphaLevel *= extraAlpha;
  67797. alphaLevel >>= 8;
  67798. if (alphaLevel < 0xfe)
  67799. {
  67800. do
  67801. {
  67802. dest++ ->blend (*span++, alphaLevel);
  67803. } while (--width > 0);
  67804. }
  67805. else
  67806. {
  67807. do
  67808. {
  67809. dest++ ->blend (*span++);
  67810. } while (--width > 0);
  67811. }
  67812. }
  67813. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67814. {
  67815. handleEdgeTableLine (x, width, 255);
  67816. }
  67817. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67818. {
  67819. if (width > scratchSize)
  67820. {
  67821. scratchSize = width;
  67822. scratchBuffer.malloc (scratchSize);
  67823. }
  67824. y = y_;
  67825. generate (scratchBuffer, x, width);
  67826. et.clipLineToMask (x, y_,
  67827. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67828. sizeof (SrcPixelType), width);
  67829. }
  67830. private:
  67831. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67832. {
  67833. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67834. do
  67835. {
  67836. int hiResX, hiResY;
  67837. this->interpolator.next (hiResX, hiResY);
  67838. hiResX += pixelOffsetInt;
  67839. hiResY += pixelOffsetInt;
  67840. int loResX = hiResX >> 8;
  67841. int loResY = hiResY >> 8;
  67842. if (repeatPattern)
  67843. {
  67844. loResX = safeModulo (loResX, srcData.width);
  67845. loResY = safeModulo (loResY, srcData.height);
  67846. }
  67847. if (betterQuality
  67848. && ((unsigned int) loResX) < (unsigned int) maxX
  67849. && ((unsigned int) loResY) < (unsigned int) maxY)
  67850. {
  67851. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67852. hiResX &= 255;
  67853. hiResY &= 255;
  67854. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67855. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67856. c[0] += weight * src[0];
  67857. c[1] += weight * src[1];
  67858. c[2] += weight * src[2];
  67859. c[3] += weight * src[3];
  67860. weight = hiResX * (256 - hiResY);
  67861. c[0] += weight * src[4];
  67862. c[1] += weight * src[5];
  67863. c[2] += weight * src[6];
  67864. c[3] += weight * src[7];
  67865. src += this->srcData.lineStride;
  67866. weight = (256 - hiResX) * hiResY;
  67867. c[0] += weight * src[0];
  67868. c[1] += weight * src[1];
  67869. c[2] += weight * src[2];
  67870. c[3] += weight * src[3];
  67871. weight = hiResX * hiResY;
  67872. c[0] += weight * src[4];
  67873. c[1] += weight * src[5];
  67874. c[2] += weight * src[6];
  67875. c[3] += weight * src[7];
  67876. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67877. (uint8) (c[PixelARGB::indexR] >> 16),
  67878. (uint8) (c[PixelARGB::indexG] >> 16),
  67879. (uint8) (c[PixelARGB::indexB] >> 16));
  67880. }
  67881. else
  67882. {
  67883. if (! repeatPattern)
  67884. {
  67885. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67886. if (loResX < 0) loResX = 0;
  67887. if (loResY < 0) loResY = 0;
  67888. if (loResX > maxX) loResX = maxX;
  67889. if (loResY > maxY) loResY = maxY;
  67890. }
  67891. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67892. }
  67893. ++dest;
  67894. } while (--numPixels > 0);
  67895. }
  67896. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67897. {
  67898. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67899. do
  67900. {
  67901. int hiResX, hiResY;
  67902. this->interpolator.next (hiResX, hiResY);
  67903. hiResX += pixelOffsetInt;
  67904. hiResY += pixelOffsetInt;
  67905. int loResX = hiResX >> 8;
  67906. int loResY = hiResY >> 8;
  67907. if (repeatPattern)
  67908. {
  67909. loResX = safeModulo (loResX, srcData.width);
  67910. loResY = safeModulo (loResY, srcData.height);
  67911. }
  67912. if (betterQuality
  67913. && ((unsigned int) loResX) < (unsigned int) maxX
  67914. && ((unsigned int) loResY) < (unsigned int) maxY)
  67915. {
  67916. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67917. hiResX &= 255;
  67918. hiResY &= 255;
  67919. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67920. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  67921. c[0] += weight * src[0];
  67922. c[1] += weight * src[1];
  67923. c[2] += weight * src[2];
  67924. weight = hiResX * (256 - hiResY);
  67925. c[0] += weight * src[3];
  67926. c[1] += weight * src[4];
  67927. c[2] += weight * src[5];
  67928. src += this->srcData.lineStride;
  67929. weight = (256 - hiResX) * hiResY;
  67930. c[0] += weight * src[0];
  67931. c[1] += weight * src[1];
  67932. c[2] += weight * src[2];
  67933. weight = hiResX * hiResY;
  67934. c[0] += weight * src[3];
  67935. c[1] += weight * src[4];
  67936. c[2] += weight * src[5];
  67937. dest->setARGB ((uint8) 255,
  67938. (uint8) (c[PixelRGB::indexR] >> 16),
  67939. (uint8) (c[PixelRGB::indexG] >> 16),
  67940. (uint8) (c[PixelRGB::indexB] >> 16));
  67941. }
  67942. else
  67943. {
  67944. if (! repeatPattern)
  67945. {
  67946. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67947. if (loResX < 0) loResX = 0;
  67948. if (loResY < 0) loResY = 0;
  67949. if (loResX > maxX) loResX = maxX;
  67950. if (loResY > maxY) loResY = maxY;
  67951. }
  67952. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  67953. }
  67954. ++dest;
  67955. } while (--numPixels > 0);
  67956. }
  67957. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  67958. {
  67959. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67960. do
  67961. {
  67962. int hiResX, hiResY;
  67963. this->interpolator.next (hiResX, hiResY);
  67964. hiResX += pixelOffsetInt;
  67965. hiResY += pixelOffsetInt;
  67966. int loResX = hiResX >> 8;
  67967. int loResY = hiResY >> 8;
  67968. if (repeatPattern)
  67969. {
  67970. loResX = safeModulo (loResX, srcData.width);
  67971. loResY = safeModulo (loResY, srcData.height);
  67972. }
  67973. if (betterQuality
  67974. && ((unsigned int) loResX) < (unsigned int) maxX
  67975. && ((unsigned int) loResY) < (unsigned int) maxY)
  67976. {
  67977. hiResX &= 255;
  67978. hiResY &= 255;
  67979. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67980. uint32 c = 256 * 128;
  67981. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  67982. c += src[1] * (hiResX * (256 - hiResY));
  67983. src += this->srcData.lineStride;
  67984. c += src[0] * ((256 - hiResX) * hiResY);
  67985. c += src[1] * (hiResX * hiResY);
  67986. *((uint8*) dest) = (uint8) c;
  67987. }
  67988. else
  67989. {
  67990. if (! repeatPattern)
  67991. {
  67992. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67993. if (loResX < 0) loResX = 0;
  67994. if (loResY < 0) loResY = 0;
  67995. if (loResX > maxX) loResX = maxX;
  67996. if (loResY > maxY) loResY = maxY;
  67997. }
  67998. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  67999. }
  68000. ++dest;
  68001. } while (--numPixels > 0);
  68002. }
  68003. class TransformedImageSpanInterpolator
  68004. {
  68005. public:
  68006. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68007. : inverseTransform (transform.inverted())
  68008. {}
  68009. void setStartOfLine (float x, float y, const int numPixels) throw()
  68010. {
  68011. float x1 = x, y1 = y;
  68012. x += numPixels;
  68013. inverseTransform.transformPoints (x1, y1, x, y);
  68014. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68015. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68016. }
  68017. void next (int& x, int& y) throw()
  68018. {
  68019. x = xBresenham.n;
  68020. xBresenham.stepToNext();
  68021. y = yBresenham.n;
  68022. yBresenham.stepToNext();
  68023. }
  68024. private:
  68025. class BresenhamInterpolator
  68026. {
  68027. public:
  68028. BresenhamInterpolator() throw() {}
  68029. void set (const int n1, const int n2, const int numSteps_) throw()
  68030. {
  68031. numSteps = jmax (1, numSteps_);
  68032. step = (n2 - n1) / numSteps;
  68033. remainder = modulo = (n2 - n1) % numSteps;
  68034. n = n1;
  68035. if (modulo <= 0)
  68036. {
  68037. modulo += numSteps;
  68038. remainder += numSteps;
  68039. --step;
  68040. }
  68041. modulo -= numSteps;
  68042. }
  68043. forcedinline void stepToNext() throw()
  68044. {
  68045. modulo += remainder;
  68046. n += step;
  68047. if (modulo > 0)
  68048. {
  68049. modulo -= numSteps;
  68050. ++n;
  68051. }
  68052. }
  68053. int n;
  68054. private:
  68055. int numSteps, step, modulo, remainder;
  68056. };
  68057. const AffineTransform inverseTransform;
  68058. BresenhamInterpolator xBresenham, yBresenham;
  68059. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68060. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68061. };
  68062. TransformedImageSpanInterpolator interpolator;
  68063. const Image::BitmapData& destData;
  68064. const Image::BitmapData& srcData;
  68065. const int extraAlpha;
  68066. const bool betterQuality;
  68067. const float pixelOffset;
  68068. const int pixelOffsetInt, maxX, maxY;
  68069. int y;
  68070. DestPixelType* linePixels;
  68071. HeapBlock <SrcPixelType> scratchBuffer;
  68072. int scratchSize;
  68073. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68074. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68075. };
  68076. class ClipRegionBase : public ReferenceCountedObject
  68077. {
  68078. public:
  68079. ClipRegionBase() {}
  68080. virtual ~ClipRegionBase() {}
  68081. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68082. virtual const Ptr clone() const = 0;
  68083. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68084. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68085. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68086. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68087. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68088. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68089. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68090. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68091. virtual const Rectangle<int> getClipBounds() const = 0;
  68092. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68093. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68094. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68095. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68096. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68097. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68098. protected:
  68099. template <class Iterator>
  68100. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68101. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68102. {
  68103. switch (destData.pixelFormat)
  68104. {
  68105. case Image::ARGB:
  68106. switch (srcData.pixelFormat)
  68107. {
  68108. case Image::ARGB:
  68109. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68110. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68111. break;
  68112. case Image::RGB:
  68113. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68114. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68115. break;
  68116. default:
  68117. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68118. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68119. break;
  68120. }
  68121. break;
  68122. case Image::RGB:
  68123. switch (srcData.pixelFormat)
  68124. {
  68125. case Image::ARGB:
  68126. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68127. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68128. break;
  68129. case Image::RGB:
  68130. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68131. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68132. break;
  68133. default:
  68134. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68135. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68136. break;
  68137. }
  68138. break;
  68139. default:
  68140. switch (srcData.pixelFormat)
  68141. {
  68142. case Image::ARGB:
  68143. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68144. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68145. break;
  68146. case Image::RGB:
  68147. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68148. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68149. break;
  68150. default:
  68151. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68152. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68153. break;
  68154. }
  68155. break;
  68156. }
  68157. }
  68158. template <class Iterator>
  68159. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68160. {
  68161. switch (destData.pixelFormat)
  68162. {
  68163. case Image::ARGB:
  68164. switch (srcData.pixelFormat)
  68165. {
  68166. case Image::ARGB:
  68167. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68168. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68169. break;
  68170. case Image::RGB:
  68171. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68172. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68173. break;
  68174. default:
  68175. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68176. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68177. break;
  68178. }
  68179. break;
  68180. case Image::RGB:
  68181. switch (srcData.pixelFormat)
  68182. {
  68183. case Image::ARGB:
  68184. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68185. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68186. break;
  68187. case Image::RGB:
  68188. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68189. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68190. break;
  68191. default:
  68192. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68193. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68194. break;
  68195. }
  68196. break;
  68197. default:
  68198. switch (srcData.pixelFormat)
  68199. {
  68200. case Image::ARGB:
  68201. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68202. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68203. break;
  68204. case Image::RGB:
  68205. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68206. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68207. break;
  68208. default:
  68209. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68210. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68211. break;
  68212. }
  68213. break;
  68214. }
  68215. }
  68216. template <class Iterator, class DestPixelType>
  68217. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68218. {
  68219. jassert (destData.pixelStride == sizeof (DestPixelType));
  68220. if (replaceContents)
  68221. {
  68222. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68223. iter.iterate (r);
  68224. }
  68225. else
  68226. {
  68227. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68228. iter.iterate (r);
  68229. }
  68230. }
  68231. template <class Iterator, class DestPixelType>
  68232. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68233. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68234. {
  68235. jassert (destData.pixelStride == sizeof (DestPixelType));
  68236. if (g.isRadial)
  68237. {
  68238. if (isIdentity)
  68239. {
  68240. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68241. iter.iterate (renderer);
  68242. }
  68243. else
  68244. {
  68245. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68246. iter.iterate (renderer);
  68247. }
  68248. }
  68249. else
  68250. {
  68251. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68252. iter.iterate (renderer);
  68253. }
  68254. }
  68255. };
  68256. class ClipRegion_EdgeTable : public ClipRegionBase
  68257. {
  68258. public:
  68259. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68260. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68261. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68262. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68263. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68264. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68265. ~ClipRegion_EdgeTable() {}
  68266. const Ptr clone() const
  68267. {
  68268. return new ClipRegion_EdgeTable (*this);
  68269. }
  68270. const Ptr applyClipTo (const Ptr& target) const
  68271. {
  68272. return target->clipToEdgeTable (edgeTable);
  68273. }
  68274. const Ptr clipToRectangle (const Rectangle<int>& r)
  68275. {
  68276. edgeTable.clipToRectangle (r);
  68277. return edgeTable.isEmpty() ? 0 : this;
  68278. }
  68279. const Ptr clipToRectangleList (const RectangleList& r)
  68280. {
  68281. RectangleList inverse (edgeTable.getMaximumBounds());
  68282. if (inverse.subtract (r))
  68283. for (RectangleList::Iterator iter (inverse); iter.next();)
  68284. edgeTable.excludeRectangle (*iter.getRectangle());
  68285. return edgeTable.isEmpty() ? 0 : this;
  68286. }
  68287. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68288. {
  68289. edgeTable.excludeRectangle (r);
  68290. return edgeTable.isEmpty() ? 0 : this;
  68291. }
  68292. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68293. {
  68294. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68295. edgeTable.clipToEdgeTable (et);
  68296. return edgeTable.isEmpty() ? 0 : this;
  68297. }
  68298. const Ptr clipToEdgeTable (const EdgeTable& et)
  68299. {
  68300. edgeTable.clipToEdgeTable (et);
  68301. return edgeTable.isEmpty() ? 0 : this;
  68302. }
  68303. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68304. {
  68305. const Image::BitmapData srcData (image, false);
  68306. if (transform.isOnlyTranslation())
  68307. {
  68308. // If our translation doesn't involve any distortion, just use a simple blit..
  68309. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68310. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68311. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68312. {
  68313. const int imageX = ((tx + 128) >> 8);
  68314. const int imageY = ((ty + 128) >> 8);
  68315. if (image.getFormat() == Image::ARGB)
  68316. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68317. else
  68318. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68319. return edgeTable.isEmpty() ? 0 : this;
  68320. }
  68321. }
  68322. if (transform.isSingularity())
  68323. return 0;
  68324. {
  68325. Path p;
  68326. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68327. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68328. edgeTable.clipToEdgeTable (et2);
  68329. }
  68330. if (! edgeTable.isEmpty())
  68331. {
  68332. if (image.getFormat() == Image::ARGB)
  68333. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68334. else
  68335. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68336. }
  68337. return edgeTable.isEmpty() ? 0 : this;
  68338. }
  68339. bool clipRegionIntersects (const Rectangle<int>& r) const
  68340. {
  68341. return edgeTable.getMaximumBounds().intersects (r);
  68342. }
  68343. const Rectangle<int> getClipBounds() const
  68344. {
  68345. return edgeTable.getMaximumBounds();
  68346. }
  68347. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68348. {
  68349. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68350. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68351. if (! clipped.isEmpty())
  68352. {
  68353. ClipRegion_EdgeTable et (clipped);
  68354. et.edgeTable.clipToEdgeTable (edgeTable);
  68355. et.fillAllWithColour (destData, colour, replaceContents);
  68356. }
  68357. }
  68358. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68359. {
  68360. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68361. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68362. if (! clipped.isEmpty())
  68363. {
  68364. ClipRegion_EdgeTable et (clipped);
  68365. et.edgeTable.clipToEdgeTable (edgeTable);
  68366. et.fillAllWithColour (destData, colour, false);
  68367. }
  68368. }
  68369. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68370. {
  68371. switch (destData.pixelFormat)
  68372. {
  68373. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68374. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68375. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68376. }
  68377. }
  68378. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68379. {
  68380. HeapBlock <PixelARGB> lookupTable;
  68381. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68382. jassert (numLookupEntries > 0);
  68383. switch (destData.pixelFormat)
  68384. {
  68385. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68386. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68387. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68388. }
  68389. }
  68390. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68391. {
  68392. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68393. }
  68394. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68395. {
  68396. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68397. }
  68398. EdgeTable edgeTable;
  68399. private:
  68400. template <class SrcPixelType>
  68401. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68402. {
  68403. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68404. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68405. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68406. edgeTable.getMaximumBounds().getWidth());
  68407. }
  68408. template <class SrcPixelType>
  68409. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68410. {
  68411. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68412. edgeTable.clipToRectangle (r);
  68413. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68414. for (int y = 0; y < r.getHeight(); ++y)
  68415. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68416. }
  68417. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68418. };
  68419. class ClipRegion_RectangleList : public ClipRegionBase
  68420. {
  68421. public:
  68422. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68423. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68424. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68425. ~ClipRegion_RectangleList() {}
  68426. const Ptr clone() const
  68427. {
  68428. return new ClipRegion_RectangleList (*this);
  68429. }
  68430. const Ptr applyClipTo (const Ptr& target) const
  68431. {
  68432. return target->clipToRectangleList (clip);
  68433. }
  68434. const Ptr clipToRectangle (const Rectangle<int>& r)
  68435. {
  68436. clip.clipTo (r);
  68437. return clip.isEmpty() ? 0 : this;
  68438. }
  68439. const Ptr clipToRectangleList (const RectangleList& r)
  68440. {
  68441. clip.clipTo (r);
  68442. return clip.isEmpty() ? 0 : this;
  68443. }
  68444. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68445. {
  68446. clip.subtract (r);
  68447. return clip.isEmpty() ? 0 : this;
  68448. }
  68449. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68450. {
  68451. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68452. }
  68453. const Ptr clipToEdgeTable (const EdgeTable& et)
  68454. {
  68455. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68456. }
  68457. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68458. {
  68459. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68460. }
  68461. bool clipRegionIntersects (const Rectangle<int>& r) const
  68462. {
  68463. return clip.intersects (r);
  68464. }
  68465. const Rectangle<int> getClipBounds() const
  68466. {
  68467. return clip.getBounds();
  68468. }
  68469. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68470. {
  68471. SubRectangleIterator iter (clip, area);
  68472. switch (destData.pixelFormat)
  68473. {
  68474. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68475. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68476. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68477. }
  68478. }
  68479. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68480. {
  68481. SubRectangleIteratorFloat iter (clip, area);
  68482. switch (destData.pixelFormat)
  68483. {
  68484. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68485. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68486. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68487. }
  68488. }
  68489. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68490. {
  68491. switch (destData.pixelFormat)
  68492. {
  68493. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68494. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68495. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68496. }
  68497. }
  68498. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68499. {
  68500. HeapBlock <PixelARGB> lookupTable;
  68501. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68502. jassert (numLookupEntries > 0);
  68503. switch (destData.pixelFormat)
  68504. {
  68505. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68506. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68507. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68508. }
  68509. }
  68510. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68511. {
  68512. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68513. }
  68514. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68515. {
  68516. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68517. }
  68518. RectangleList clip;
  68519. template <class Renderer>
  68520. void iterate (Renderer& r) const throw()
  68521. {
  68522. RectangleList::Iterator iter (clip);
  68523. while (iter.next())
  68524. {
  68525. const Rectangle<int> rect (*iter.getRectangle());
  68526. const int x = rect.getX();
  68527. const int w = rect.getWidth();
  68528. jassert (w > 0);
  68529. const int bottom = rect.getBottom();
  68530. for (int y = rect.getY(); y < bottom; ++y)
  68531. {
  68532. r.setEdgeTableYPos (y);
  68533. r.handleEdgeTableLineFull (x, w);
  68534. }
  68535. }
  68536. }
  68537. private:
  68538. class SubRectangleIterator
  68539. {
  68540. public:
  68541. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68542. : clip (clip_), area (area_)
  68543. {
  68544. }
  68545. template <class Renderer>
  68546. void iterate (Renderer& r) const throw()
  68547. {
  68548. RectangleList::Iterator iter (clip);
  68549. while (iter.next())
  68550. {
  68551. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68552. if (! rect.isEmpty())
  68553. {
  68554. const int x = rect.getX();
  68555. const int w = rect.getWidth();
  68556. const int bottom = rect.getBottom();
  68557. for (int y = rect.getY(); y < bottom; ++y)
  68558. {
  68559. r.setEdgeTableYPos (y);
  68560. r.handleEdgeTableLineFull (x, w);
  68561. }
  68562. }
  68563. }
  68564. }
  68565. private:
  68566. const RectangleList& clip;
  68567. const Rectangle<int> area;
  68568. SubRectangleIterator (const SubRectangleIterator&);
  68569. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68570. };
  68571. class SubRectangleIteratorFloat
  68572. {
  68573. public:
  68574. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68575. : clip (clip_), area (area_)
  68576. {
  68577. }
  68578. template <class Renderer>
  68579. void iterate (Renderer& r) const throw()
  68580. {
  68581. int left = roundToInt (area.getX() * 256.0f);
  68582. int top = roundToInt (area.getY() * 256.0f);
  68583. int right = roundToInt (area.getRight() * 256.0f);
  68584. int bottom = roundToInt (area.getBottom() * 256.0f);
  68585. int totalTop, totalLeft, totalBottom, totalRight;
  68586. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68587. if ((top >> 8) == (bottom >> 8))
  68588. {
  68589. topAlpha = bottom - top;
  68590. bottomAlpha = 0;
  68591. totalTop = top >> 8;
  68592. totalBottom = bottom = top = totalTop + 1;
  68593. }
  68594. else
  68595. {
  68596. if ((top & 255) == 0)
  68597. {
  68598. topAlpha = 0;
  68599. top = totalTop = (top >> 8);
  68600. }
  68601. else
  68602. {
  68603. topAlpha = 255 - (top & 255);
  68604. totalTop = (top >> 8);
  68605. top = totalTop + 1;
  68606. }
  68607. bottomAlpha = bottom & 255;
  68608. bottom >>= 8;
  68609. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68610. }
  68611. if ((left >> 8) == (right >> 8))
  68612. {
  68613. leftAlpha = right - left;
  68614. rightAlpha = 0;
  68615. totalLeft = (left >> 8);
  68616. totalRight = right = left = totalLeft + 1;
  68617. }
  68618. else
  68619. {
  68620. if ((left & 255) == 0)
  68621. {
  68622. leftAlpha = 0;
  68623. left = totalLeft = (left >> 8);
  68624. }
  68625. else
  68626. {
  68627. leftAlpha = 255 - (left & 255);
  68628. totalLeft = (left >> 8);
  68629. left = totalLeft + 1;
  68630. }
  68631. rightAlpha = right & 255;
  68632. right >>= 8;
  68633. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68634. }
  68635. RectangleList::Iterator iter (clip);
  68636. while (iter.next())
  68637. {
  68638. const int clipLeft = iter.getRectangle()->getX();
  68639. const int clipRight = iter.getRectangle()->getRight();
  68640. const int clipTop = iter.getRectangle()->getY();
  68641. const int clipBottom = iter.getRectangle()->getBottom();
  68642. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68643. {
  68644. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68645. {
  68646. if (topAlpha != 0 && totalTop >= clipTop)
  68647. {
  68648. r.setEdgeTableYPos (totalTop);
  68649. r.handleEdgeTablePixel (left, topAlpha);
  68650. }
  68651. const int endY = jmin (bottom, clipBottom);
  68652. for (int y = jmax (clipTop, top); y < endY; ++y)
  68653. {
  68654. r.setEdgeTableYPos (y);
  68655. r.handleEdgeTablePixelFull (left);
  68656. }
  68657. if (bottomAlpha != 0 && bottom < clipBottom)
  68658. {
  68659. r.setEdgeTableYPos (bottom);
  68660. r.handleEdgeTablePixel (left, bottomAlpha);
  68661. }
  68662. }
  68663. else
  68664. {
  68665. const int clippedLeft = jmax (left, clipLeft);
  68666. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68667. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68668. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68669. if (topAlpha != 0 && totalTop >= clipTop)
  68670. {
  68671. r.setEdgeTableYPos (totalTop);
  68672. if (doLeftAlpha)
  68673. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68674. if (clippedWidth > 0)
  68675. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68676. if (doRightAlpha)
  68677. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68678. }
  68679. const int endY = jmin (bottom, clipBottom);
  68680. for (int y = jmax (clipTop, top); y < endY; ++y)
  68681. {
  68682. r.setEdgeTableYPos (y);
  68683. if (doLeftAlpha)
  68684. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68685. if (clippedWidth > 0)
  68686. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68687. if (doRightAlpha)
  68688. r.handleEdgeTablePixel (right, rightAlpha);
  68689. }
  68690. if (bottomAlpha != 0 && bottom < clipBottom)
  68691. {
  68692. r.setEdgeTableYPos (bottom);
  68693. if (doLeftAlpha)
  68694. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68695. if (clippedWidth > 0)
  68696. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68697. if (doRightAlpha)
  68698. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68699. }
  68700. }
  68701. }
  68702. }
  68703. }
  68704. private:
  68705. const RectangleList& clip;
  68706. const Rectangle<float>& area;
  68707. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68708. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68709. };
  68710. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68711. };
  68712. }
  68713. class LowLevelGraphicsSoftwareRenderer::SavedState
  68714. {
  68715. public:
  68716. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68717. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68718. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68719. {
  68720. }
  68721. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68722. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68723. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68724. {
  68725. }
  68726. SavedState (const SavedState& other)
  68727. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68728. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68729. {
  68730. }
  68731. ~SavedState()
  68732. {
  68733. }
  68734. void setOrigin (const int x, const int y) throw()
  68735. {
  68736. xOffset += x;
  68737. yOffset += y;
  68738. }
  68739. bool clipToRectangle (const Rectangle<int>& r)
  68740. {
  68741. if (clip != 0)
  68742. {
  68743. cloneClipIfMultiplyReferenced();
  68744. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68745. }
  68746. return clip != 0;
  68747. }
  68748. bool clipToRectangleList (const RectangleList& r)
  68749. {
  68750. if (clip != 0)
  68751. {
  68752. cloneClipIfMultiplyReferenced();
  68753. RectangleList offsetList (r);
  68754. offsetList.offsetAll (xOffset, yOffset);
  68755. clip = clip->clipToRectangleList (offsetList);
  68756. }
  68757. return clip != 0;
  68758. }
  68759. bool excludeClipRectangle (const Rectangle<int>& r)
  68760. {
  68761. if (clip != 0)
  68762. {
  68763. cloneClipIfMultiplyReferenced();
  68764. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68765. }
  68766. return clip != 0;
  68767. }
  68768. void clipToPath (const Path& p, const AffineTransform& transform)
  68769. {
  68770. if (clip != 0)
  68771. {
  68772. cloneClipIfMultiplyReferenced();
  68773. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68774. }
  68775. }
  68776. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68777. {
  68778. if (clip != 0)
  68779. {
  68780. if (image.hasAlphaChannel())
  68781. {
  68782. cloneClipIfMultiplyReferenced();
  68783. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68784. interpolationQuality != Graphics::lowResamplingQuality);
  68785. }
  68786. else
  68787. {
  68788. Path p;
  68789. p.addRectangle (image.getBounds());
  68790. clipToPath (p, t);
  68791. }
  68792. }
  68793. }
  68794. bool clipRegionIntersects (const Rectangle<int>& r) const
  68795. {
  68796. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68797. }
  68798. const Rectangle<int> getClipBounds() const
  68799. {
  68800. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68801. }
  68802. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68803. {
  68804. if (clip != 0)
  68805. {
  68806. if (fillType.isColour())
  68807. {
  68808. Image::BitmapData destData (image, true);
  68809. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68810. }
  68811. else
  68812. {
  68813. const Rectangle<int> totalClip (clip->getClipBounds());
  68814. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68815. if (! clipped.isEmpty())
  68816. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68817. }
  68818. }
  68819. }
  68820. void fillRect (Image& image, const Rectangle<float>& r)
  68821. {
  68822. if (clip != 0)
  68823. {
  68824. if (fillType.isColour())
  68825. {
  68826. Image::BitmapData destData (image, true);
  68827. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68828. }
  68829. else
  68830. {
  68831. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68832. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68833. if (! clipped.isEmpty())
  68834. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68835. }
  68836. }
  68837. }
  68838. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68839. {
  68840. if (clip != 0)
  68841. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68842. }
  68843. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68844. {
  68845. if (clip != 0)
  68846. {
  68847. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68848. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68849. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68850. fillShape (image, shapeToFill, false);
  68851. }
  68852. }
  68853. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68854. {
  68855. jassert (clip != 0);
  68856. shapeToFill = clip->applyClipTo (shapeToFill);
  68857. if (shapeToFill != 0)
  68858. {
  68859. Image::BitmapData destData (image, true);
  68860. if (fillType.isGradient())
  68861. {
  68862. jassert (! replaceContents); // that option is just for solid colours
  68863. ColourGradient g2 (*(fillType.gradient));
  68864. g2.multiplyOpacity (fillType.getOpacity());
  68865. g2.point1.addXY (-0.5f, -0.5f);
  68866. g2.point2.addXY (-0.5f, -0.5f);
  68867. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68868. const bool isIdentity = transform.isOnlyTranslation();
  68869. if (isIdentity)
  68870. {
  68871. // If our translation doesn't involve any distortion, we can speed it up..
  68872. g2.point1.applyTransform (transform);
  68873. g2.point2.applyTransform (transform);
  68874. transform = AffineTransform::identity;
  68875. }
  68876. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68877. }
  68878. else if (fillType.isTiledImage())
  68879. {
  68880. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68881. }
  68882. else
  68883. {
  68884. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68885. }
  68886. }
  68887. }
  68888. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68889. {
  68890. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68891. const Image::BitmapData destData (destImage, true);
  68892. const Image::BitmapData srcData (sourceImage, false);
  68893. const int alpha = fillType.colour.getAlpha();
  68894. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68895. if (transform.isOnlyTranslation())
  68896. {
  68897. // If our translation doesn't involve any distortion, just use a simple blit..
  68898. int tx = (int) (transform.getTranslationX() * 256.0f);
  68899. int ty = (int) (transform.getTranslationY() * 256.0f);
  68900. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68901. {
  68902. tx = ((tx + 128) >> 8);
  68903. ty = ((ty + 128) >> 8);
  68904. if (tiledFillClipRegion != 0)
  68905. {
  68906. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68907. }
  68908. else
  68909. {
  68910. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68911. c = clip->applyClipTo (c);
  68912. if (c != 0)
  68913. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68914. }
  68915. return;
  68916. }
  68917. }
  68918. if (transform.isSingularity())
  68919. return;
  68920. if (tiledFillClipRegion != 0)
  68921. {
  68922. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68923. }
  68924. else
  68925. {
  68926. Path p;
  68927. p.addRectangle (sourceImage.getBounds());
  68928. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68929. c = c->clipToPath (p, transform);
  68930. if (c != 0)
  68931. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68932. }
  68933. }
  68934. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68935. int xOffset, yOffset;
  68936. Font font;
  68937. FillType fillType;
  68938. Graphics::ResamplingQuality interpolationQuality;
  68939. private:
  68940. void cloneClipIfMultiplyReferenced()
  68941. {
  68942. if (clip->getReferenceCount() > 1)
  68943. clip = clip->clone();
  68944. }
  68945. SavedState& operator= (const SavedState&);
  68946. };
  68947. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68948. : image (image_)
  68949. {
  68950. currentState = new SavedState (image_.getBounds(), 0, 0);
  68951. }
  68952. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68953. const RectangleList& initialClip)
  68954. : image (image_)
  68955. {
  68956. currentState = new SavedState (initialClip, xOffset, yOffset);
  68957. }
  68958. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68959. {
  68960. }
  68961. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68962. {
  68963. return false;
  68964. }
  68965. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68966. {
  68967. currentState->setOrigin (x, y);
  68968. }
  68969. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68970. {
  68971. return currentState->clipToRectangle (r);
  68972. }
  68973. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68974. {
  68975. return currentState->clipToRectangleList (clipRegion);
  68976. }
  68977. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68978. {
  68979. currentState->excludeClipRectangle (r);
  68980. }
  68981. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68982. {
  68983. currentState->clipToPath (path, transform);
  68984. }
  68985. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68986. {
  68987. currentState->clipToImageAlpha (sourceImage, transform);
  68988. }
  68989. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68990. {
  68991. return currentState->clipRegionIntersects (r);
  68992. }
  68993. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68994. {
  68995. return currentState->getClipBounds();
  68996. }
  68997. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68998. {
  68999. return currentState->clip == 0;
  69000. }
  69001. void LowLevelGraphicsSoftwareRenderer::saveState()
  69002. {
  69003. stateStack.add (new SavedState (*currentState));
  69004. }
  69005. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69006. {
  69007. SavedState* const top = stateStack.getLast();
  69008. if (top != 0)
  69009. {
  69010. currentState = top;
  69011. stateStack.removeLast (1, false);
  69012. }
  69013. else
  69014. {
  69015. jassertfalse; // trying to pop with an empty stack!
  69016. }
  69017. }
  69018. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69019. {
  69020. currentState->fillType = fillType;
  69021. }
  69022. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69023. {
  69024. currentState->fillType.setOpacity (newOpacity);
  69025. }
  69026. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69027. {
  69028. currentState->interpolationQuality = quality;
  69029. }
  69030. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69031. {
  69032. currentState->fillRect (image, r, replaceExistingContents);
  69033. }
  69034. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69035. {
  69036. currentState->fillPath (image, path, transform);
  69037. }
  69038. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69039. {
  69040. currentState->renderImage (image, sourceImage, transform,
  69041. fillEntireClipAsTiles ? currentState->clip : 0);
  69042. }
  69043. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69044. {
  69045. Path p;
  69046. p.addLineSegment (line, 1.0f);
  69047. fillPath (p, AffineTransform::identity);
  69048. }
  69049. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69050. {
  69051. if (bottom > top)
  69052. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69053. }
  69054. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69055. {
  69056. if (right > left)
  69057. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69058. }
  69059. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69060. {
  69061. public:
  69062. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69063. ~CachedGlyph() {}
  69064. void draw (SavedState& state, Image& image, const float x, const float y) const
  69065. {
  69066. if (edgeTable != 0)
  69067. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69068. }
  69069. void generate (const Font& newFont, const int glyphNumber)
  69070. {
  69071. font = newFont;
  69072. glyph = glyphNumber;
  69073. edgeTable = 0;
  69074. Path glyphPath;
  69075. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69076. if (! glyphPath.isEmpty())
  69077. {
  69078. const float fontHeight = font.getHeight();
  69079. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69080. #if JUCE_MAC || JUCE_IOS
  69081. .translated (0.0f, -0.5f)
  69082. #endif
  69083. );
  69084. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69085. glyphPath, transform);
  69086. }
  69087. }
  69088. int glyph, lastAccessCount;
  69089. Font font;
  69090. juce_UseDebuggingNewOperator
  69091. private:
  69092. ScopedPointer <EdgeTable> edgeTable;
  69093. CachedGlyph (const CachedGlyph&);
  69094. CachedGlyph& operator= (const CachedGlyph&);
  69095. };
  69096. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69097. {
  69098. public:
  69099. GlyphCache()
  69100. : accessCounter (0), hits (0), misses (0)
  69101. {
  69102. for (int i = 120; --i >= 0;)
  69103. glyphs.add (new CachedGlyph());
  69104. }
  69105. ~GlyphCache()
  69106. {
  69107. clearSingletonInstance();
  69108. }
  69109. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69110. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69111. {
  69112. ++accessCounter;
  69113. int oldestCounter = std::numeric_limits<int>::max();
  69114. CachedGlyph* oldest = 0;
  69115. for (int i = glyphs.size(); --i >= 0;)
  69116. {
  69117. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69118. if (glyph->glyph == glyphNumber && glyph->font == font)
  69119. {
  69120. ++hits;
  69121. glyph->lastAccessCount = accessCounter;
  69122. glyph->draw (state, image, x, y);
  69123. return;
  69124. }
  69125. if (glyph->lastAccessCount <= oldestCounter)
  69126. {
  69127. oldestCounter = glyph->lastAccessCount;
  69128. oldest = glyph;
  69129. }
  69130. }
  69131. if (hits + ++misses > (glyphs.size() << 4))
  69132. {
  69133. if (misses * 2 > hits)
  69134. {
  69135. for (int i = 32; --i >= 0;)
  69136. glyphs.add (new CachedGlyph());
  69137. }
  69138. hits = misses = 0;
  69139. oldest = glyphs.getLast();
  69140. }
  69141. jassert (oldest != 0);
  69142. oldest->lastAccessCount = accessCounter;
  69143. oldest->generate (font, glyphNumber);
  69144. oldest->draw (state, image, x, y);
  69145. }
  69146. juce_UseDebuggingNewOperator
  69147. private:
  69148. friend class OwnedArray <CachedGlyph>;
  69149. OwnedArray <CachedGlyph> glyphs;
  69150. int accessCounter, hits, misses;
  69151. GlyphCache (const GlyphCache&);
  69152. GlyphCache& operator= (const GlyphCache&);
  69153. };
  69154. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69155. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69156. {
  69157. currentState->font = newFont;
  69158. }
  69159. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69160. {
  69161. return currentState->font;
  69162. }
  69163. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69164. {
  69165. Font& f = currentState->font;
  69166. if (transform.isOnlyTranslation())
  69167. {
  69168. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69169. transform.getTranslationX(),
  69170. transform.getTranslationY());
  69171. }
  69172. else
  69173. {
  69174. Path p;
  69175. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69176. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69177. }
  69178. }
  69179. #if JUCE_MSVC
  69180. #pragma warning (pop)
  69181. #if JUCE_DEBUG
  69182. #pragma optimize ("", on) // resets optimisations to the project defaults
  69183. #endif
  69184. #endif
  69185. END_JUCE_NAMESPACE
  69186. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69187. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69188. BEGIN_JUCE_NAMESPACE
  69189. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69190. : flags (other.flags)
  69191. {
  69192. }
  69193. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69194. {
  69195. flags = other.flags;
  69196. return *this;
  69197. }
  69198. void RectanglePlacement::applyTo (double& x, double& y,
  69199. double& w, double& h,
  69200. const double dx, const double dy,
  69201. const double dw, const double dh) const throw()
  69202. {
  69203. if (w == 0 || h == 0)
  69204. return;
  69205. if ((flags & stretchToFit) != 0)
  69206. {
  69207. x = dx;
  69208. y = dy;
  69209. w = dw;
  69210. h = dh;
  69211. }
  69212. else
  69213. {
  69214. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69215. : jmin (dw / w, dh / h);
  69216. if ((flags & onlyReduceInSize) != 0)
  69217. scale = jmin (scale, 1.0);
  69218. if ((flags & onlyIncreaseInSize) != 0)
  69219. scale = jmax (scale, 1.0);
  69220. w *= scale;
  69221. h *= scale;
  69222. if ((flags & xLeft) != 0)
  69223. x = dx;
  69224. else if ((flags & xRight) != 0)
  69225. x = dx + dw - w;
  69226. else
  69227. x = dx + (dw - w) * 0.5;
  69228. if ((flags & yTop) != 0)
  69229. y = dy;
  69230. else if ((flags & yBottom) != 0)
  69231. y = dy + dh - h;
  69232. else
  69233. y = dy + (dh - h) * 0.5;
  69234. }
  69235. }
  69236. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69237. float w, float h,
  69238. const float dx, const float dy,
  69239. const float dw, const float dh) const throw()
  69240. {
  69241. if (w == 0 || h == 0)
  69242. return AffineTransform::identity;
  69243. const float scaleX = dw / w;
  69244. const float scaleY = dh / h;
  69245. if ((flags & stretchToFit) != 0)
  69246. return AffineTransform::translation (-x, -y)
  69247. .scaled (scaleX, scaleY)
  69248. .translated (dx, dy);
  69249. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69250. : jmin (scaleX, scaleY);
  69251. if ((flags & onlyReduceInSize) != 0)
  69252. scale = jmin (scale, 1.0f);
  69253. if ((flags & onlyIncreaseInSize) != 0)
  69254. scale = jmax (scale, 1.0f);
  69255. w *= scale;
  69256. h *= scale;
  69257. float newX = dx;
  69258. if ((flags & xRight) != 0)
  69259. newX += dw - w; // right
  69260. else if ((flags & xLeft) == 0)
  69261. newX += (dw - w) / 2.0f; // centre
  69262. float newY = dy;
  69263. if ((flags & yBottom) != 0)
  69264. newY += dh - h; // bottom
  69265. else if ((flags & yTop) == 0)
  69266. newY += (dh - h) / 2.0f; // centre
  69267. return AffineTransform::translation (-x, -y)
  69268. .scaled (scale, scale)
  69269. .translated (newX, newY);
  69270. }
  69271. END_JUCE_NAMESPACE
  69272. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69273. /*** Start of inlined file: juce_Drawable.cpp ***/
  69274. BEGIN_JUCE_NAMESPACE
  69275. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69276. const AffineTransform& transform_,
  69277. const float opacity_) throw()
  69278. : g (g_),
  69279. transform (transform_),
  69280. opacity (opacity_)
  69281. {
  69282. }
  69283. Drawable::Drawable()
  69284. : parent (0)
  69285. {
  69286. }
  69287. Drawable::~Drawable()
  69288. {
  69289. }
  69290. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69291. {
  69292. render (RenderingContext (g, transform, opacity));
  69293. }
  69294. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69295. {
  69296. draw (g, opacity, AffineTransform::translation (x, y));
  69297. }
  69298. void Drawable::drawWithin (Graphics& g,
  69299. const int destX,
  69300. const int destY,
  69301. const int destW,
  69302. const int destH,
  69303. const RectanglePlacement& placement,
  69304. const float opacity) const
  69305. {
  69306. if (destW > 0 && destH > 0)
  69307. {
  69308. Rectangle<float> bounds (getBounds());
  69309. draw (g, opacity,
  69310. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69311. (float) destX, (float) destY,
  69312. (float) destW, (float) destH));
  69313. }
  69314. }
  69315. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69316. {
  69317. Drawable* result = 0;
  69318. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69319. if (image.isValid())
  69320. {
  69321. DrawableImage* const di = new DrawableImage();
  69322. di->setImage (image);
  69323. result = di;
  69324. }
  69325. else
  69326. {
  69327. const String asString (String::createStringFromData (data, (int) numBytes));
  69328. XmlDocument doc (asString);
  69329. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69330. if (outer != 0 && outer->hasTagName ("svg"))
  69331. {
  69332. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69333. if (svg != 0)
  69334. result = Drawable::createFromSVG (*svg);
  69335. }
  69336. }
  69337. return result;
  69338. }
  69339. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69340. {
  69341. MemoryOutputStream mo;
  69342. mo.writeFromInputStream (dataSource, -1);
  69343. return createFromImageData (mo.getData(), mo.getDataSize());
  69344. }
  69345. Drawable* Drawable::createFromImageFile (const File& file)
  69346. {
  69347. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69348. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69349. }
  69350. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69351. {
  69352. return createChildFromValueTree (0, tree, imageProvider);
  69353. }
  69354. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69355. {
  69356. const Identifier type (tree.getType());
  69357. Drawable* d = 0;
  69358. if (type == DrawablePath::valueTreeType)
  69359. d = new DrawablePath();
  69360. else if (type == DrawableComposite::valueTreeType)
  69361. d = new DrawableComposite();
  69362. else if (type == DrawableImage::valueTreeType)
  69363. d = new DrawableImage();
  69364. else if (type == DrawableText::valueTreeType)
  69365. d = new DrawableText();
  69366. if (d != 0)
  69367. {
  69368. d->parent = parent;
  69369. d->refreshFromValueTree (tree, imageProvider);
  69370. }
  69371. return d;
  69372. }
  69373. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69374. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69375. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69376. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69377. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69378. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69379. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69380. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69381. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69382. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69383. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69384. : state (state_)
  69385. {
  69386. }
  69387. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69388. {
  69389. }
  69390. const String Drawable::ValueTreeWrapperBase::getID() const
  69391. {
  69392. return state [idProperty];
  69393. }
  69394. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69395. {
  69396. if (newID.isEmpty())
  69397. state.removeProperty (idProperty, undoManager);
  69398. else
  69399. state.setProperty (idProperty, newID, undoManager);
  69400. }
  69401. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69402. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69403. {
  69404. const String newType (v[type].toString());
  69405. if (newType == "solid")
  69406. {
  69407. const String colourString (v [colour].toString());
  69408. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69409. : (uint32) colourString.getHexValue32()));
  69410. }
  69411. else if (newType == "gradient")
  69412. {
  69413. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69414. ColourGradient g;
  69415. if (gp1 != 0) *gp1 = p1;
  69416. if (gp2 != 0) *gp2 = p2;
  69417. if (gp3 != 0) *gp3 = p3;
  69418. g.point1 = p1.resolve (nameFinder);
  69419. g.point2 = p2.resolve (nameFinder);
  69420. g.isRadial = v[radial];
  69421. StringArray colourSteps;
  69422. colourSteps.addTokens (v[colours].toString(), false);
  69423. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69424. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69425. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69426. FillType fillType (g);
  69427. if (g.isRadial)
  69428. {
  69429. const Point<float> point3 (p3.resolve (nameFinder));
  69430. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69431. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69432. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69433. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69434. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69435. }
  69436. return fillType;
  69437. }
  69438. else if (newType == "image")
  69439. {
  69440. Image im;
  69441. if (imageProvider != 0)
  69442. im = imageProvider->getImageForIdentifier (v[imageId]);
  69443. FillType f (im, AffineTransform::identity);
  69444. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69445. return f;
  69446. }
  69447. jassertfalse;
  69448. return FillType();
  69449. }
  69450. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69451. {
  69452. const ColourGradient& g = *fillType.gradient;
  69453. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69454. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69455. return point3Source.transformedBy (fillType.transform);
  69456. }
  69457. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69458. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69459. ImageProvider* imageProvider, UndoManager* const undoManager)
  69460. {
  69461. if (fillType.isColour())
  69462. {
  69463. v.setProperty (type, "solid", undoManager);
  69464. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69465. }
  69466. else if (fillType.isGradient())
  69467. {
  69468. v.setProperty (type, "gradient", undoManager);
  69469. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69470. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69471. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69472. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69473. String s;
  69474. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69475. s << ' ' << fillType.gradient->getColourPosition (i)
  69476. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69477. v.setProperty (colours, s.trimStart(), undoManager);
  69478. }
  69479. else if (fillType.isTiledImage())
  69480. {
  69481. v.setProperty (type, "image", undoManager);
  69482. if (imageProvider != 0)
  69483. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69484. if (fillType.getOpacity() < 1.0f)
  69485. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69486. else
  69487. v.removeProperty (imageOpacity, undoManager);
  69488. }
  69489. else
  69490. {
  69491. jassertfalse;
  69492. }
  69493. }
  69494. END_JUCE_NAMESPACE
  69495. /*** End of inlined file: juce_Drawable.cpp ***/
  69496. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69497. BEGIN_JUCE_NAMESPACE
  69498. DrawableComposite::DrawableComposite()
  69499. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69500. {
  69501. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69502. RelativeCoordinate (100.0),
  69503. RelativeCoordinate (0.0),
  69504. RelativeCoordinate (100.0)));
  69505. }
  69506. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69507. {
  69508. bounds = other.bounds;
  69509. for (int i = 0; i < other.drawables.size(); ++i)
  69510. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69511. markersX.addCopiesOf (other.markersX);
  69512. markersY.addCopiesOf (other.markersY);
  69513. }
  69514. DrawableComposite::~DrawableComposite()
  69515. {
  69516. }
  69517. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69518. {
  69519. if (drawable != 0)
  69520. {
  69521. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69522. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69523. drawables.insert (index, drawable);
  69524. drawable->parent = this;
  69525. }
  69526. }
  69527. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69528. {
  69529. insertDrawable (drawable.createCopy(), index);
  69530. }
  69531. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69532. {
  69533. drawables.remove (index, deleteDrawable);
  69534. }
  69535. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69536. {
  69537. for (int i = drawables.size(); --i >= 0;)
  69538. if (drawables.getUnchecked(i)->getName() == name)
  69539. return drawables.getUnchecked(i);
  69540. return 0;
  69541. }
  69542. void DrawableComposite::bringToFront (const int index)
  69543. {
  69544. if (index >= 0 && index < drawables.size() - 1)
  69545. drawables.move (index, -1);
  69546. }
  69547. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69548. {
  69549. bounds = newBoundingBox;
  69550. }
  69551. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69552. : name (other.name), position (other.position)
  69553. {
  69554. }
  69555. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69556. : name (name_), position (position_)
  69557. {
  69558. }
  69559. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69560. {
  69561. return name != other.name || position != other.position;
  69562. }
  69563. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69564. const char* const DrawableComposite::contentRightMarkerName ("right");
  69565. const char* const DrawableComposite::contentTopMarkerName ("top");
  69566. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69567. const RelativeRectangle DrawableComposite::getContentArea() const
  69568. {
  69569. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69570. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69571. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69572. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69573. }
  69574. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69575. {
  69576. setMarker (contentLeftMarkerName, true, newArea.left);
  69577. setMarker (contentRightMarkerName, true, newArea.right);
  69578. setMarker (contentTopMarkerName, false, newArea.top);
  69579. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69580. }
  69581. void DrawableComposite::resetBoundingBoxToContentArea()
  69582. {
  69583. const RelativeRectangle content (getContentArea());
  69584. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69585. RelativePoint (content.right, content.top),
  69586. RelativePoint (content.left, content.bottom)));
  69587. }
  69588. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69589. {
  69590. const Rectangle<float> bounds (getUntransformedBounds (false));
  69591. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69592. RelativeCoordinate (bounds.getRight()),
  69593. RelativeCoordinate (bounds.getY()),
  69594. RelativeCoordinate (bounds.getBottom())));
  69595. resetBoundingBoxToContentArea();
  69596. }
  69597. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69598. {
  69599. return (xAxis ? markersX : markersY).size();
  69600. }
  69601. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69602. {
  69603. return (xAxis ? markersX : markersY) [index];
  69604. }
  69605. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69606. {
  69607. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69608. for (int i = 0; i < markers.size(); ++i)
  69609. {
  69610. Marker* const m = markers.getUnchecked(i);
  69611. if (m->name == name)
  69612. {
  69613. if (m->position != position)
  69614. {
  69615. m->position = position;
  69616. invalidatePoints();
  69617. }
  69618. return;
  69619. }
  69620. }
  69621. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69622. invalidatePoints();
  69623. }
  69624. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69625. {
  69626. jassert (index >= 2);
  69627. if (index >= 2)
  69628. (xAxis ? markersX : markersY).remove (index);
  69629. }
  69630. const AffineTransform DrawableComposite::calculateTransform() const
  69631. {
  69632. Point<float> resolved[3];
  69633. bounds.resolveThreePoints (resolved, parent);
  69634. const Rectangle<float> content (getContentArea().resolve (parent));
  69635. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69636. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69637. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69638. }
  69639. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69640. {
  69641. if (drawables.size() > 0 && context.opacity > 0)
  69642. {
  69643. if (context.opacity >= 1.0f || drawables.size() == 1)
  69644. {
  69645. Drawable::RenderingContext contextCopy (context);
  69646. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69647. for (int i = 0; i < drawables.size(); ++i)
  69648. drawables.getUnchecked(i)->render (contextCopy);
  69649. }
  69650. else
  69651. {
  69652. // To correctly render a whole composite layer with an overall transparency,
  69653. // we need to render everything opaquely into a temp buffer, then blend that
  69654. // with the target opacity...
  69655. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69656. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69657. {
  69658. Graphics tempG (tempImage);
  69659. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69660. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69661. render (tempContext);
  69662. }
  69663. context.g.setOpacity (context.opacity);
  69664. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69665. }
  69666. }
  69667. }
  69668. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69669. {
  69670. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69671. int i;
  69672. for (i = 0; i < markersX.size(); ++i)
  69673. {
  69674. Marker* const m = markersX.getUnchecked(i);
  69675. if (m->name == symbol)
  69676. return m->position.getExpression();
  69677. }
  69678. for (i = 0; i < markersY.size(); ++i)
  69679. {
  69680. Marker* const m = markersY.getUnchecked(i);
  69681. if (m->name == symbol)
  69682. return m->position.getExpression();
  69683. }
  69684. return Expression::EvaluationContext::getSymbolValue (symbol, member);
  69685. }
  69686. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69687. {
  69688. Rectangle<float> bounds;
  69689. int i;
  69690. for (i = 0; i < drawables.size(); ++i)
  69691. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69692. if (includeMarkers)
  69693. {
  69694. if (markersX.size() > 0)
  69695. {
  69696. float minX = std::numeric_limits<float>::max();
  69697. float maxX = std::numeric_limits<float>::min();
  69698. for (i = markersX.size(); --i >= 0;)
  69699. {
  69700. const Marker* m = markersX.getUnchecked(i);
  69701. const float pos = (float) m->position.resolve (this);
  69702. minX = jmin (minX, pos);
  69703. maxX = jmax (maxX, pos);
  69704. }
  69705. if (minX <= maxX)
  69706. {
  69707. if (bounds.getHeight() > 0)
  69708. {
  69709. minX = jmin (minX, bounds.getX());
  69710. maxX = jmax (maxX, bounds.getRight());
  69711. }
  69712. bounds.setLeft (minX);
  69713. bounds.setWidth (maxX - minX);
  69714. }
  69715. }
  69716. if (markersY.size() > 0)
  69717. {
  69718. float minY = std::numeric_limits<float>::max();
  69719. float maxY = std::numeric_limits<float>::min();
  69720. for (i = markersY.size(); --i >= 0;)
  69721. {
  69722. const Marker* m = markersY.getUnchecked(i);
  69723. const float pos = (float) m->position.resolve (this);
  69724. minY = jmin (minY, pos);
  69725. maxY = jmax (maxY, pos);
  69726. }
  69727. if (minY <= maxY)
  69728. {
  69729. if (bounds.getHeight() > 0)
  69730. {
  69731. minY = jmin (minY, bounds.getY());
  69732. maxY = jmax (maxY, bounds.getBottom());
  69733. }
  69734. bounds.setTop (minY);
  69735. bounds.setHeight (maxY - minY);
  69736. }
  69737. }
  69738. }
  69739. return bounds;
  69740. }
  69741. const Rectangle<float> DrawableComposite::getBounds() const
  69742. {
  69743. return getUntransformedBounds (true).transformed (calculateTransform());
  69744. }
  69745. bool DrawableComposite::hitTest (float x, float y) const
  69746. {
  69747. calculateTransform().inverted().transformPoint (x, y);
  69748. for (int i = 0; i < drawables.size(); ++i)
  69749. if (drawables.getUnchecked(i)->hitTest (x, y))
  69750. return true;
  69751. return false;
  69752. }
  69753. Drawable* DrawableComposite::createCopy() const
  69754. {
  69755. return new DrawableComposite (*this);
  69756. }
  69757. void DrawableComposite::invalidatePoints()
  69758. {
  69759. for (int i = 0; i < drawables.size(); ++i)
  69760. drawables.getUnchecked(i)->invalidatePoints();
  69761. }
  69762. const Identifier DrawableComposite::valueTreeType ("Group");
  69763. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69764. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69765. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69766. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69767. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69768. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69769. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69770. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69771. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69772. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69773. : ValueTreeWrapperBase (state_)
  69774. {
  69775. jassert (state.hasType (valueTreeType));
  69776. }
  69777. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69778. {
  69779. return state.getChildWithName (childGroupTag);
  69780. }
  69781. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69782. {
  69783. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69784. }
  69785. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69786. {
  69787. return getChildList().getNumChildren();
  69788. }
  69789. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69790. {
  69791. return getChildList().getChild (index);
  69792. }
  69793. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69794. {
  69795. if (getID() == objectId)
  69796. return state;
  69797. if (! recursive)
  69798. {
  69799. return getChildList().getChildWithProperty (idProperty, objectId);
  69800. }
  69801. else
  69802. {
  69803. const ValueTree childList (getChildList());
  69804. for (int i = getNumDrawables(); --i >= 0;)
  69805. {
  69806. const ValueTree& child = childList.getChild (i);
  69807. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69808. return child;
  69809. if (child.hasType (DrawableComposite::valueTreeType))
  69810. {
  69811. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69812. if (v.isValid())
  69813. return v;
  69814. }
  69815. }
  69816. return ValueTree::invalid;
  69817. }
  69818. }
  69819. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69820. {
  69821. return getChildList().indexOf (item);
  69822. }
  69823. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69824. {
  69825. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69826. }
  69827. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69828. {
  69829. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69830. }
  69831. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69832. {
  69833. getChildList().removeChild (child, undoManager);
  69834. }
  69835. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69836. {
  69837. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69838. state.getProperty (topRight, "100, 0"),
  69839. state.getProperty (bottomLeft, "0, 100"));
  69840. }
  69841. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69842. {
  69843. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69844. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69845. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69846. }
  69847. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69848. {
  69849. const RelativeRectangle content (getContentArea());
  69850. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69851. RelativePoint (content.right, content.top),
  69852. RelativePoint (content.left, content.bottom)), undoManager);
  69853. }
  69854. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69855. {
  69856. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69857. getMarker (true, getMarkerState (true, 1)).position,
  69858. getMarker (false, getMarkerState (false, 0)).position,
  69859. getMarker (false, getMarkerState (false, 1)).position);
  69860. }
  69861. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69862. {
  69863. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69864. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69865. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69866. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69867. }
  69868. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69869. {
  69870. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69871. }
  69872. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69873. {
  69874. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69875. }
  69876. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69877. {
  69878. return getMarkerList (xAxis).getNumChildren();
  69879. }
  69880. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69881. {
  69882. return getMarkerList (xAxis).getChild (index);
  69883. }
  69884. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69885. {
  69886. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69887. }
  69888. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69889. {
  69890. return state.isAChildOf (getMarkerList (xAxis));
  69891. }
  69892. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69893. {
  69894. jassert (containsMarker (xAxis, state));
  69895. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  69896. }
  69897. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69898. {
  69899. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69900. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69901. if (marker.isValid())
  69902. {
  69903. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69904. }
  69905. else
  69906. {
  69907. marker = ValueTree (markerTag);
  69908. marker.setProperty (nameProperty, m.name, 0);
  69909. marker.setProperty (posProperty, m.position.toString(), 0);
  69910. markerList.addChild (marker, -1, undoManager);
  69911. }
  69912. }
  69913. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  69914. {
  69915. if (state [nameProperty].toString() != contentLeftMarkerName
  69916. && state [nameProperty].toString() != contentRightMarkerName
  69917. && state [nameProperty].toString() != contentTopMarkerName
  69918. && state [nameProperty].toString() != contentBottomMarkerName)
  69919. return getMarkerList (xAxis).removeChild (state, undoManager);
  69920. }
  69921. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69922. {
  69923. const ValueTreeWrapper wrapper (tree);
  69924. setName (wrapper.getID());
  69925. Rectangle<float> damage;
  69926. bool redrawAll = false;
  69927. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  69928. if (bounds != newBounds)
  69929. {
  69930. redrawAll = true;
  69931. damage = getBounds();
  69932. bounds = newBounds;
  69933. }
  69934. const int numMarkersX = wrapper.getNumMarkers (true);
  69935. const int numMarkersY = wrapper.getNumMarkers (false);
  69936. // Remove deleted markers...
  69937. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  69938. {
  69939. if (! redrawAll)
  69940. {
  69941. redrawAll = true;
  69942. damage = getBounds();
  69943. }
  69944. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  69945. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  69946. }
  69947. // Update markers and add new ones..
  69948. int i;
  69949. for (i = 0; i < numMarkersX; ++i)
  69950. {
  69951. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  69952. Marker* m = markersX[i];
  69953. if (m == 0 || newMarker != *m)
  69954. {
  69955. if (! redrawAll)
  69956. {
  69957. redrawAll = true;
  69958. damage = getBounds();
  69959. }
  69960. if (m == 0)
  69961. markersX.add (new Marker (newMarker));
  69962. else
  69963. *m = newMarker;
  69964. }
  69965. }
  69966. for (i = 0; i < numMarkersY; ++i)
  69967. {
  69968. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  69969. Marker* m = markersY[i];
  69970. if (m == 0 || newMarker != *m)
  69971. {
  69972. if (! redrawAll)
  69973. {
  69974. redrawAll = true;
  69975. damage = getBounds();
  69976. }
  69977. if (m == 0)
  69978. markersY.add (new Marker (newMarker));
  69979. else
  69980. *m = newMarker;
  69981. }
  69982. }
  69983. // Remove deleted drawables..
  69984. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  69985. {
  69986. Drawable* const d = drawables.getUnchecked(i);
  69987. if (! redrawAll)
  69988. damage = damage.getUnion (d->getBounds());
  69989. d->parent = 0;
  69990. drawables.remove (i);
  69991. }
  69992. // Update drawables and add new ones..
  69993. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  69994. {
  69995. const ValueTree newDrawable (wrapper.getDrawableState (i));
  69996. Drawable* d = drawables[i];
  69997. if (d != 0)
  69998. {
  69999. if (newDrawable.hasType (d->getValueTreeType()))
  70000. {
  70001. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70002. if (! redrawAll)
  70003. damage = damage.getUnion (area);
  70004. }
  70005. else
  70006. {
  70007. if (! redrawAll)
  70008. damage = damage.getUnion (d->getBounds());
  70009. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70010. drawables.set (i, d);
  70011. if (! redrawAll)
  70012. damage = damage.getUnion (d->getBounds());
  70013. }
  70014. }
  70015. else
  70016. {
  70017. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70018. drawables.set (i, d);
  70019. if (! redrawAll)
  70020. damage = damage.getUnion (d->getBounds());
  70021. }
  70022. }
  70023. if (redrawAll)
  70024. damage = damage.getUnion (getBounds());
  70025. else if (! damage.isEmpty())
  70026. damage = damage.transformed (calculateTransform());
  70027. return damage;
  70028. }
  70029. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70030. {
  70031. ValueTree tree (valueTreeType);
  70032. ValueTreeWrapper v (tree);
  70033. v.setID (getName(), 0);
  70034. v.setBoundingBox (bounds, 0);
  70035. int i;
  70036. for (i = 0; i < drawables.size(); ++i)
  70037. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70038. for (i = 0; i < markersX.size(); ++i)
  70039. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70040. for (i = 0; i < markersY.size(); ++i)
  70041. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70042. return tree;
  70043. }
  70044. END_JUCE_NAMESPACE
  70045. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70046. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70047. BEGIN_JUCE_NAMESPACE
  70048. DrawableImage::DrawableImage()
  70049. : image (0),
  70050. opacity (1.0f),
  70051. overlayColour (0x00000000)
  70052. {
  70053. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70054. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70055. }
  70056. DrawableImage::DrawableImage (const DrawableImage& other)
  70057. : image (other.image),
  70058. opacity (other.opacity),
  70059. overlayColour (other.overlayColour),
  70060. bounds (other.bounds)
  70061. {
  70062. }
  70063. DrawableImage::~DrawableImage()
  70064. {
  70065. }
  70066. void DrawableImage::setImage (const Image& imageToUse)
  70067. {
  70068. image = imageToUse;
  70069. if (image.isValid())
  70070. {
  70071. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70072. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70073. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70074. }
  70075. }
  70076. void DrawableImage::setOpacity (const float newOpacity)
  70077. {
  70078. opacity = newOpacity;
  70079. }
  70080. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70081. {
  70082. overlayColour = newOverlayColour;
  70083. }
  70084. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70085. {
  70086. bounds = newBounds;
  70087. }
  70088. const AffineTransform DrawableImage::calculateTransform() const
  70089. {
  70090. if (image.isNull())
  70091. return AffineTransform::identity;
  70092. Point<float> resolved[3];
  70093. bounds.resolveThreePoints (resolved, parent);
  70094. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70095. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70096. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70097. tr.getX(), tr.getY(),
  70098. bl.getX(), bl.getY());
  70099. }
  70100. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70101. {
  70102. if (image.isValid())
  70103. {
  70104. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70105. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70106. {
  70107. context.g.setOpacity (context.opacity * opacity);
  70108. context.g.drawImageTransformed (image, t, false);
  70109. }
  70110. if (! overlayColour.isTransparent())
  70111. {
  70112. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70113. context.g.drawImageTransformed (image, t, true);
  70114. }
  70115. }
  70116. }
  70117. const Rectangle<float> DrawableImage::getBounds() const
  70118. {
  70119. if (image.isNull())
  70120. return Rectangle<float>();
  70121. return bounds.getBounds (parent);
  70122. }
  70123. bool DrawableImage::hitTest (float x, float y) const
  70124. {
  70125. if (image.isNull())
  70126. return false;
  70127. calculateTransform().inverted().transformPoint (x, y);
  70128. const int ix = roundToInt (x);
  70129. const int iy = roundToInt (y);
  70130. return ix >= 0
  70131. && iy >= 0
  70132. && ix < image.getWidth()
  70133. && iy < image.getHeight()
  70134. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70135. }
  70136. Drawable* DrawableImage::createCopy() const
  70137. {
  70138. return new DrawableImage (*this);
  70139. }
  70140. void DrawableImage::invalidatePoints()
  70141. {
  70142. }
  70143. const Identifier DrawableImage::valueTreeType ("Image");
  70144. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70145. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70146. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70147. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70148. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70149. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70150. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70151. : ValueTreeWrapperBase (state_)
  70152. {
  70153. jassert (state.hasType (valueTreeType));
  70154. }
  70155. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70156. {
  70157. return state [image];
  70158. }
  70159. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70160. {
  70161. return state.getPropertyAsValue (image, undoManager);
  70162. }
  70163. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70164. {
  70165. state.setProperty (image, newIdentifier, undoManager);
  70166. }
  70167. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70168. {
  70169. return (float) state.getProperty (opacity, 1.0);
  70170. }
  70171. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70172. {
  70173. if (! state.hasProperty (opacity))
  70174. state.setProperty (opacity, 1.0, undoManager);
  70175. return state.getPropertyAsValue (opacity, undoManager);
  70176. }
  70177. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70178. {
  70179. state.setProperty (opacity, newOpacity, undoManager);
  70180. }
  70181. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70182. {
  70183. return Colour (state [overlay].toString().getHexValue32());
  70184. }
  70185. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70186. {
  70187. if (newColour.isTransparent())
  70188. state.removeProperty (overlay, undoManager);
  70189. else
  70190. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70191. }
  70192. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70193. {
  70194. return state.getPropertyAsValue (overlay, undoManager);
  70195. }
  70196. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70197. {
  70198. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70199. state.getProperty (topRight, "100, 0"),
  70200. state.getProperty (bottomLeft, "0, 100"));
  70201. }
  70202. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70203. {
  70204. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70205. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70206. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70207. }
  70208. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70209. {
  70210. const ValueTreeWrapper controller (tree);
  70211. setName (controller.getID());
  70212. const float newOpacity = controller.getOpacity();
  70213. const Colour newOverlayColour (controller.getOverlayColour());
  70214. Image newImage;
  70215. const var imageIdentifier (controller.getImageIdentifier());
  70216. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70217. if (imageProvider != 0)
  70218. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70219. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70220. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70221. {
  70222. const Rectangle<float> damage (getBounds());
  70223. opacity = newOpacity;
  70224. overlayColour = newOverlayColour;
  70225. bounds = newBounds;
  70226. image = newImage;
  70227. return damage.getUnion (getBounds());
  70228. }
  70229. return Rectangle<float>();
  70230. }
  70231. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70232. {
  70233. ValueTree tree (valueTreeType);
  70234. ValueTreeWrapper v (tree);
  70235. v.setID (getName(), 0);
  70236. v.setOpacity (opacity, 0);
  70237. v.setOverlayColour (overlayColour, 0);
  70238. v.setBoundingBox (bounds, 0);
  70239. if (image.isValid())
  70240. {
  70241. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70242. if (imageProvider != 0)
  70243. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70244. }
  70245. return tree;
  70246. }
  70247. END_JUCE_NAMESPACE
  70248. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70249. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70250. BEGIN_JUCE_NAMESPACE
  70251. DrawablePath::DrawablePath()
  70252. : mainFill (Colours::black),
  70253. strokeFill (Colours::black),
  70254. strokeType (0.0f),
  70255. pathNeedsUpdating (true),
  70256. strokeNeedsUpdating (true)
  70257. {
  70258. }
  70259. DrawablePath::DrawablePath (const DrawablePath& other)
  70260. : mainFill (other.mainFill),
  70261. strokeFill (other.strokeFill),
  70262. strokeType (other.strokeType),
  70263. pathNeedsUpdating (true),
  70264. strokeNeedsUpdating (true)
  70265. {
  70266. if (other.relativePath != 0)
  70267. relativePath = new RelativePointPath (*other.relativePath);
  70268. else
  70269. path = other.path;
  70270. }
  70271. DrawablePath::~DrawablePath()
  70272. {
  70273. }
  70274. void DrawablePath::setPath (const Path& newPath)
  70275. {
  70276. path = newPath;
  70277. strokeNeedsUpdating = true;
  70278. }
  70279. void DrawablePath::setFill (const FillType& newFill)
  70280. {
  70281. mainFill = newFill;
  70282. }
  70283. void DrawablePath::setStrokeFill (const FillType& newFill)
  70284. {
  70285. strokeFill = newFill;
  70286. }
  70287. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70288. {
  70289. strokeType = newStrokeType;
  70290. strokeNeedsUpdating = true;
  70291. }
  70292. void DrawablePath::setStrokeThickness (const float newThickness)
  70293. {
  70294. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70295. }
  70296. void DrawablePath::updatePath() const
  70297. {
  70298. if (pathNeedsUpdating)
  70299. {
  70300. pathNeedsUpdating = false;
  70301. if (relativePath != 0)
  70302. {
  70303. path.clear();
  70304. relativePath->createPath (path, parent);
  70305. strokeNeedsUpdating = true;
  70306. }
  70307. }
  70308. }
  70309. void DrawablePath::updateStroke() const
  70310. {
  70311. if (strokeNeedsUpdating)
  70312. {
  70313. strokeNeedsUpdating = false;
  70314. updatePath();
  70315. stroke.clear();
  70316. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70317. }
  70318. }
  70319. const Path& DrawablePath::getPath() const
  70320. {
  70321. updatePath();
  70322. return path;
  70323. }
  70324. const Path& DrawablePath::getStrokePath() const
  70325. {
  70326. updateStroke();
  70327. return stroke;
  70328. }
  70329. bool DrawablePath::isStrokeVisible() const throw()
  70330. {
  70331. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70332. }
  70333. void DrawablePath::invalidatePoints()
  70334. {
  70335. pathNeedsUpdating = true;
  70336. strokeNeedsUpdating = true;
  70337. }
  70338. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70339. {
  70340. {
  70341. FillType f (mainFill);
  70342. if (f.isGradient())
  70343. f.gradient->multiplyOpacity (context.opacity);
  70344. else
  70345. f.setOpacity (f.getOpacity() * context.opacity);
  70346. f.transform = f.transform.followedBy (context.transform);
  70347. context.g.setFillType (f);
  70348. context.g.fillPath (getPath(), context.transform);
  70349. }
  70350. if (isStrokeVisible())
  70351. {
  70352. FillType f (strokeFill);
  70353. if (f.isGradient())
  70354. f.gradient->multiplyOpacity (context.opacity);
  70355. else
  70356. f.setOpacity (f.getOpacity() * context.opacity);
  70357. f.transform = f.transform.followedBy (context.transform);
  70358. context.g.setFillType (f);
  70359. context.g.fillPath (getStrokePath(), context.transform);
  70360. }
  70361. }
  70362. const Rectangle<float> DrawablePath::getBounds() const
  70363. {
  70364. if (isStrokeVisible())
  70365. return getStrokePath().getBounds();
  70366. else
  70367. return getPath().getBounds();
  70368. }
  70369. bool DrawablePath::hitTest (float x, float y) const
  70370. {
  70371. return getPath().contains (x, y)
  70372. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70373. }
  70374. Drawable* DrawablePath::createCopy() const
  70375. {
  70376. return new DrawablePath (*this);
  70377. }
  70378. const Identifier DrawablePath::valueTreeType ("Path");
  70379. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70380. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70381. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70382. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70383. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70384. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70385. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70386. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70387. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70388. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70389. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70390. : ValueTreeWrapperBase (state_)
  70391. {
  70392. jassert (state.hasType (valueTreeType));
  70393. }
  70394. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70395. {
  70396. return state.getOrCreateChildWithName (path, 0);
  70397. }
  70398. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70399. {
  70400. ValueTree v (state.getChildWithName (fill));
  70401. if (v.isValid())
  70402. return v;
  70403. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70404. return getMainFillState();
  70405. }
  70406. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70407. {
  70408. ValueTree v (state.getChildWithName (stroke));
  70409. if (v.isValid())
  70410. return v;
  70411. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70412. return getStrokeFillState();
  70413. }
  70414. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70415. ImageProvider* imageProvider) const
  70416. {
  70417. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70418. }
  70419. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70420. const RelativePoint* gp2, const RelativePoint* gp3,
  70421. ImageProvider* imageProvider, UndoManager* undoManager)
  70422. {
  70423. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70424. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70425. }
  70426. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70427. ImageProvider* imageProvider) const
  70428. {
  70429. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70430. }
  70431. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70432. const RelativePoint* gp2, const RelativePoint* gp3,
  70433. ImageProvider* imageProvider, UndoManager* undoManager)
  70434. {
  70435. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70436. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70437. }
  70438. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70439. {
  70440. const String jointStyleString (state [jointStyle].toString());
  70441. const String capStyleString (state [capStyle].toString());
  70442. return PathStrokeType (state [strokeWidth],
  70443. jointStyleString == "curved" ? PathStrokeType::curved
  70444. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70445. : PathStrokeType::mitered),
  70446. capStyleString == "square" ? PathStrokeType::square
  70447. : (capStyleString == "round" ? PathStrokeType::rounded
  70448. : PathStrokeType::butt));
  70449. }
  70450. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70451. {
  70452. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70453. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70454. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70455. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70456. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70457. }
  70458. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70459. {
  70460. return state [nonZeroWinding];
  70461. }
  70462. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70463. {
  70464. state.setProperty (nonZeroWinding, b, undoManager);
  70465. }
  70466. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70467. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70468. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70469. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70470. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70471. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70472. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70473. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70474. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70475. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70476. : state (state_)
  70477. {
  70478. }
  70479. DrawablePath::ValueTreeWrapper::Element::~Element()
  70480. {
  70481. }
  70482. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70483. {
  70484. return ValueTreeWrapper (state.getParent().getParent());
  70485. }
  70486. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70487. {
  70488. return Element (state.getSibling (-1));
  70489. }
  70490. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70491. {
  70492. const Identifier i (state.getType());
  70493. if (i == startSubPathElement || i == lineToElement) return 1;
  70494. if (i == quadraticToElement) return 2;
  70495. if (i == cubicToElement) return 3;
  70496. return 0;
  70497. }
  70498. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70499. {
  70500. jassert (index >= 0 && index < getNumControlPoints());
  70501. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70502. }
  70503. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70504. {
  70505. jassert (index >= 0 && index < getNumControlPoints());
  70506. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70507. }
  70508. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70509. {
  70510. jassert (index >= 0 && index < getNumControlPoints());
  70511. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70512. }
  70513. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70514. {
  70515. const Identifier i (state.getType());
  70516. if (i == startSubPathElement)
  70517. return getControlPoint (0);
  70518. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70519. return getPreviousElement().getEndPoint();
  70520. }
  70521. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70522. {
  70523. const Identifier i (state.getType());
  70524. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70525. if (i == quadraticToElement) return getControlPoint (1);
  70526. if (i == cubicToElement) return getControlPoint (2);
  70527. jassert (i == closeSubPathElement);
  70528. return RelativePoint();
  70529. }
  70530. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70531. {
  70532. const Identifier i (state.getType());
  70533. if (i == lineToElement || i == closeSubPathElement)
  70534. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70535. if (i == cubicToElement)
  70536. {
  70537. Path p;
  70538. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70539. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70540. return p.getLength();
  70541. }
  70542. if (i == quadraticToElement)
  70543. {
  70544. Path p;
  70545. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70546. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70547. return p.getLength();
  70548. }
  70549. jassert (i == startSubPathElement);
  70550. return 0;
  70551. }
  70552. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70553. {
  70554. return state [mode].toString();
  70555. }
  70556. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70557. {
  70558. if (state.hasType (cubicToElement))
  70559. state.setProperty (mode, newMode, undoManager);
  70560. }
  70561. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70562. {
  70563. const Identifier i (state.getType());
  70564. if (i == quadraticToElement || i == cubicToElement)
  70565. {
  70566. ValueTree newState (lineToElement);
  70567. Element e (newState);
  70568. e.setControlPoint (0, getEndPoint(), undoManager);
  70569. state = newState;
  70570. }
  70571. }
  70572. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70573. {
  70574. const Identifier i (state.getType());
  70575. if (i == lineToElement || i == quadraticToElement)
  70576. {
  70577. ValueTree newState (cubicToElement);
  70578. Element e (newState);
  70579. const RelativePoint start (getStartPoint());
  70580. const RelativePoint end (getEndPoint());
  70581. const Point<float> startResolved (start.resolve (nameFinder));
  70582. const Point<float> endResolved (end.resolve (nameFinder));
  70583. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70584. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70585. e.setControlPoint (2, end, undoManager);
  70586. state = newState;
  70587. }
  70588. }
  70589. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70590. {
  70591. const Identifier i (state.getType());
  70592. if (i != startSubPathElement)
  70593. {
  70594. ValueTree newState (startSubPathElement);
  70595. Element e (newState);
  70596. e.setControlPoint (0, getEndPoint(), undoManager);
  70597. state = newState;
  70598. }
  70599. }
  70600. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70601. {
  70602. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70603. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70604. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70605. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70606. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70607. return newCp1 + (newCp2 - newCp1) * proportion;
  70608. }
  70609. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70610. {
  70611. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70612. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70613. return mid1 + (mid2 - mid1) * proportion;
  70614. }
  70615. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70616. {
  70617. const Identifier i (state.getType());
  70618. float bestProp = 0;
  70619. if (i == cubicToElement)
  70620. {
  70621. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70622. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70623. float bestDistance = std::numeric_limits<float>::max();
  70624. for (int i = 110; --i >= 0;)
  70625. {
  70626. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70627. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70628. const float distance = centre.getDistanceFrom (targetPoint);
  70629. if (distance < bestDistance)
  70630. {
  70631. bestProp = prop;
  70632. bestDistance = distance;
  70633. }
  70634. }
  70635. }
  70636. else if (i == quadraticToElement)
  70637. {
  70638. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70639. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70640. float bestDistance = std::numeric_limits<float>::max();
  70641. for (int i = 110; --i >= 0;)
  70642. {
  70643. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70644. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70645. const float distance = centre.getDistanceFrom (targetPoint);
  70646. if (distance < bestDistance)
  70647. {
  70648. bestProp = prop;
  70649. bestDistance = distance;
  70650. }
  70651. }
  70652. }
  70653. else if (i == lineToElement)
  70654. {
  70655. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70656. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70657. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70658. }
  70659. return bestProp;
  70660. }
  70661. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70662. {
  70663. ValueTree newTree;
  70664. const Identifier i (state.getType());
  70665. if (i == cubicToElement)
  70666. {
  70667. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70668. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70669. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70670. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70671. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70672. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70673. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70674. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70675. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70676. setControlPoint (0, mid1, undoManager);
  70677. setControlPoint (1, newCp1, undoManager);
  70678. setControlPoint (2, newCentre, undoManager);
  70679. setModeOfEndPoint (roundedMode, undoManager);
  70680. Element newElement (newTree = ValueTree (cubicToElement));
  70681. newElement.setControlPoint (0, newCp2, 0);
  70682. newElement.setControlPoint (1, mid3, 0);
  70683. newElement.setControlPoint (2, rp4, 0);
  70684. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70685. }
  70686. else if (i == quadraticToElement)
  70687. {
  70688. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70689. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70690. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70691. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70692. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70693. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70694. setControlPoint (0, mid1, undoManager);
  70695. setControlPoint (1, newCentre, undoManager);
  70696. setModeOfEndPoint (roundedMode, undoManager);
  70697. Element newElement (newTree = ValueTree (quadraticToElement));
  70698. newElement.setControlPoint (0, mid2, 0);
  70699. newElement.setControlPoint (1, rp3, 0);
  70700. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70701. }
  70702. else if (i == lineToElement)
  70703. {
  70704. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70705. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70706. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70707. setControlPoint (0, newPoint, undoManager);
  70708. Element newElement (newTree = ValueTree (lineToElement));
  70709. newElement.setControlPoint (0, rp2, 0);
  70710. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70711. }
  70712. else if (i == closeSubPathElement)
  70713. {
  70714. }
  70715. return newTree;
  70716. }
  70717. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70718. {
  70719. state.getParent().removeChild (state, undoManager);
  70720. }
  70721. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70722. {
  70723. Rectangle<float> damageRect;
  70724. ValueTreeWrapper v (tree);
  70725. setName (v.getID());
  70726. bool needsRedraw = false;
  70727. const FillType newFill (v.getMainFill (parent, imageProvider));
  70728. if (mainFill != newFill)
  70729. {
  70730. needsRedraw = true;
  70731. mainFill = newFill;
  70732. }
  70733. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70734. if (strokeFill != newStrokeFill)
  70735. {
  70736. needsRedraw = true;
  70737. strokeFill = newStrokeFill;
  70738. }
  70739. const PathStrokeType newStroke (v.getStrokeType());
  70740. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70741. Path newPath;
  70742. newRelativePath->createPath (newPath, parent);
  70743. if (! newRelativePath->containsAnyDynamicPoints())
  70744. newRelativePath = 0;
  70745. if (strokeType != newStroke || path != newPath)
  70746. {
  70747. damageRect = getBounds();
  70748. path.swapWithPath (newPath);
  70749. strokeNeedsUpdating = true;
  70750. strokeType = newStroke;
  70751. needsRedraw = true;
  70752. }
  70753. relativePath = newRelativePath;
  70754. if (needsRedraw)
  70755. damageRect = damageRect.getUnion (getBounds());
  70756. return damageRect;
  70757. }
  70758. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70759. {
  70760. ValueTree tree (valueTreeType);
  70761. ValueTreeWrapper v (tree);
  70762. v.setID (getName(), 0);
  70763. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70764. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70765. v.setStrokeType (strokeType, 0);
  70766. if (relativePath != 0)
  70767. {
  70768. relativePath->writeTo (tree, 0);
  70769. }
  70770. else
  70771. {
  70772. RelativePointPath rp (path);
  70773. rp.writeTo (tree, 0);
  70774. }
  70775. return tree;
  70776. }
  70777. END_JUCE_NAMESPACE
  70778. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70779. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70780. BEGIN_JUCE_NAMESPACE
  70781. DrawableText::DrawableText()
  70782. : colour (Colours::black),
  70783. justification (Justification::centredLeft)
  70784. {
  70785. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70786. RelativePoint (50.0f, 0.0f),
  70787. RelativePoint (0.0f, 20.0f)));
  70788. setFont (Font (15.0f), true);
  70789. }
  70790. DrawableText::DrawableText (const DrawableText& other)
  70791. : text (other.text),
  70792. font (other.font),
  70793. colour (other.colour),
  70794. justification (other.justification),
  70795. bounds (other.bounds),
  70796. fontSizeControlPoint (other.fontSizeControlPoint)
  70797. {
  70798. }
  70799. DrawableText::~DrawableText()
  70800. {
  70801. }
  70802. void DrawableText::setText (const String& newText)
  70803. {
  70804. text = newText;
  70805. }
  70806. void DrawableText::setColour (const Colour& newColour)
  70807. {
  70808. colour = newColour;
  70809. }
  70810. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70811. {
  70812. font = newFont;
  70813. if (applySizeAndScale)
  70814. {
  70815. Point<float> corners[3];
  70816. bounds.resolveThreePoints (corners, parent);
  70817. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70818. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70819. }
  70820. }
  70821. void DrawableText::setJustification (const Justification& newJustification)
  70822. {
  70823. justification = newJustification;
  70824. }
  70825. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70826. {
  70827. bounds = newBounds;
  70828. }
  70829. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70830. {
  70831. fontSizeControlPoint = newPoint;
  70832. }
  70833. void DrawableText::render (const Drawable::RenderingContext& context) const
  70834. {
  70835. Point<float> points[3];
  70836. bounds.resolveThreePoints (points, parent);
  70837. const float w = Line<float> (points[0], points[1]).getLength();
  70838. const float h = Line<float> (points[0], points[2]).getLength();
  70839. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70840. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70841. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70842. Font f (font);
  70843. f.setHeight (fontHeight);
  70844. f.setHorizontalScale (fontWidth / fontHeight);
  70845. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70846. GlyphArrangement ga;
  70847. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70848. ga.draw (context.g,
  70849. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70850. w, 0, points[1].getX(), points[1].getY(),
  70851. 0, h, points[2].getX(), points[2].getY())
  70852. .followedBy (context.transform));
  70853. }
  70854. const Rectangle<float> DrawableText::getBounds() const
  70855. {
  70856. return bounds.getBounds (parent);
  70857. }
  70858. bool DrawableText::hitTest (float x, float y) const
  70859. {
  70860. Path p;
  70861. bounds.getPath (p, parent);
  70862. return p.contains (x, y);
  70863. }
  70864. Drawable* DrawableText::createCopy() const
  70865. {
  70866. return new DrawableText (*this);
  70867. }
  70868. void DrawableText::invalidatePoints()
  70869. {
  70870. }
  70871. const Identifier DrawableText::valueTreeType ("Text");
  70872. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70873. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70874. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70875. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70876. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70877. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70878. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70879. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70880. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70881. : ValueTreeWrapperBase (state_)
  70882. {
  70883. jassert (state.hasType (valueTreeType));
  70884. }
  70885. const String DrawableText::ValueTreeWrapper::getText() const
  70886. {
  70887. return state [text].toString();
  70888. }
  70889. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70890. {
  70891. state.setProperty (text, newText, undoManager);
  70892. }
  70893. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70894. {
  70895. return state.getPropertyAsValue (text, undoManager);
  70896. }
  70897. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70898. {
  70899. return Colour::fromString (state [colour].toString());
  70900. }
  70901. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70902. {
  70903. state.setProperty (colour, newColour.toString(), undoManager);
  70904. }
  70905. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70906. {
  70907. return Justification ((int) state [justification]);
  70908. }
  70909. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70910. {
  70911. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70912. }
  70913. const Font DrawableText::ValueTreeWrapper::getFont() const
  70914. {
  70915. return Font::fromString (state [font]);
  70916. }
  70917. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70918. {
  70919. state.setProperty (font, newFont.toString(), undoManager);
  70920. }
  70921. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70922. {
  70923. return state.getPropertyAsValue (font, undoManager);
  70924. }
  70925. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70926. {
  70927. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70928. }
  70929. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70930. {
  70931. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70932. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70933. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70934. }
  70935. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70936. {
  70937. return state [fontSizeAnchor].toString();
  70938. }
  70939. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70940. {
  70941. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70942. }
  70943. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70944. {
  70945. ValueTreeWrapper v (tree);
  70946. setName (v.getID());
  70947. const RelativeParallelogram newBounds (v.getBoundingBox());
  70948. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70949. const Colour newColour (v.getColour());
  70950. const Justification newJustification (v.getJustification());
  70951. const String newText (v.getText());
  70952. const Font newFont (v.getFont());
  70953. if (text != newText || font != newFont || justification != newJustification
  70954. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70955. {
  70956. const Rectangle<float> damage (getBounds());
  70957. setBoundingBox (newBounds);
  70958. setFontSizeControlPoint (newFontPoint);
  70959. setColour (newColour);
  70960. setFont (newFont, false);
  70961. setJustification (newJustification);
  70962. setText (newText);
  70963. return damage.getUnion (getBounds());
  70964. }
  70965. return Rectangle<float>();
  70966. }
  70967. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70968. {
  70969. ValueTree tree (valueTreeType);
  70970. ValueTreeWrapper v (tree);
  70971. v.setID (getName(), 0);
  70972. v.setText (text, 0);
  70973. v.setFont (font, 0);
  70974. v.setJustification (justification, 0);
  70975. v.setColour (colour, 0);
  70976. v.setBoundingBox (bounds, 0);
  70977. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  70978. return tree;
  70979. }
  70980. END_JUCE_NAMESPACE
  70981. /*** End of inlined file: juce_DrawableText.cpp ***/
  70982. /*** Start of inlined file: juce_SVGParser.cpp ***/
  70983. BEGIN_JUCE_NAMESPACE
  70984. class SVGState
  70985. {
  70986. public:
  70987. SVGState (const XmlElement* const topLevel)
  70988. : topLevelXml (topLevel),
  70989. elementX (0), elementY (0),
  70990. width (512), height (512),
  70991. viewBoxW (0), viewBoxH (0)
  70992. {
  70993. }
  70994. ~SVGState()
  70995. {
  70996. }
  70997. Drawable* parseSVGElement (const XmlElement& xml)
  70998. {
  70999. if (! xml.hasTagName ("svg"))
  71000. return 0;
  71001. DrawableComposite* const drawable = new DrawableComposite();
  71002. drawable->setName (xml.getStringAttribute ("id"));
  71003. SVGState newState (*this);
  71004. if (xml.hasAttribute ("transform"))
  71005. newState.addTransform (xml);
  71006. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71007. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71008. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71009. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71010. if (xml.hasAttribute ("viewBox"))
  71011. {
  71012. const String viewParams (xml.getStringAttribute ("viewBox"));
  71013. int i = 0;
  71014. float vx, vy, vw, vh;
  71015. if (parseCoords (viewParams, vx, vy, i, true)
  71016. && parseCoords (viewParams, vw, vh, i, true)
  71017. && vw > 0
  71018. && vh > 0)
  71019. {
  71020. newState.viewBoxW = vw;
  71021. newState.viewBoxH = vh;
  71022. int placementFlags = 0;
  71023. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71024. if (aspect.containsIgnoreCase ("none"))
  71025. {
  71026. placementFlags = RectanglePlacement::stretchToFit;
  71027. }
  71028. else
  71029. {
  71030. if (aspect.containsIgnoreCase ("slice"))
  71031. placementFlags |= RectanglePlacement::fillDestination;
  71032. if (aspect.containsIgnoreCase ("xMin"))
  71033. placementFlags |= RectanglePlacement::xLeft;
  71034. else if (aspect.containsIgnoreCase ("xMax"))
  71035. placementFlags |= RectanglePlacement::xRight;
  71036. else
  71037. placementFlags |= RectanglePlacement::xMid;
  71038. if (aspect.containsIgnoreCase ("yMin"))
  71039. placementFlags |= RectanglePlacement::yTop;
  71040. else if (aspect.containsIgnoreCase ("yMax"))
  71041. placementFlags |= RectanglePlacement::yBottom;
  71042. else
  71043. placementFlags |= RectanglePlacement::yMid;
  71044. }
  71045. const RectanglePlacement placement (placementFlags);
  71046. newState.transform
  71047. = placement.getTransformToFit (vx, vy, vw, vh,
  71048. 0.0f, 0.0f, newState.width, newState.height)
  71049. .followedBy (newState.transform);
  71050. }
  71051. }
  71052. else
  71053. {
  71054. if (viewBoxW == 0)
  71055. newState.viewBoxW = newState.width;
  71056. if (viewBoxH == 0)
  71057. newState.viewBoxH = newState.height;
  71058. }
  71059. newState.parseSubElements (xml, drawable);
  71060. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71061. return drawable;
  71062. }
  71063. private:
  71064. const XmlElement* const topLevelXml;
  71065. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71066. AffineTransform transform;
  71067. String cssStyleText;
  71068. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71069. {
  71070. forEachXmlChildElement (xml, e)
  71071. {
  71072. Drawable* d = 0;
  71073. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71074. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71075. else if (e->hasTagName ("path")) d = parsePath (*e);
  71076. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71077. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71078. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71079. else if (e->hasTagName ("line")) d = parseLine (*e);
  71080. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71081. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71082. else if (e->hasTagName ("text")) d = parseText (*e);
  71083. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71084. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71085. parentDrawable->insertDrawable (d);
  71086. }
  71087. }
  71088. DrawableComposite* parseSwitch (const XmlElement& xml)
  71089. {
  71090. const XmlElement* const group = xml.getChildByName ("g");
  71091. if (group != 0)
  71092. return parseGroupElement (*group);
  71093. return 0;
  71094. }
  71095. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71096. {
  71097. DrawableComposite* const drawable = new DrawableComposite();
  71098. drawable->setName (xml.getStringAttribute ("id"));
  71099. if (xml.hasAttribute ("transform"))
  71100. {
  71101. SVGState newState (*this);
  71102. newState.addTransform (xml);
  71103. newState.parseSubElements (xml, drawable);
  71104. }
  71105. else
  71106. {
  71107. parseSubElements (xml, drawable);
  71108. }
  71109. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71110. return drawable;
  71111. }
  71112. Drawable* parsePath (const XmlElement& xml) const
  71113. {
  71114. const String d (xml.getStringAttribute ("d").trimStart());
  71115. Path path;
  71116. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71117. path.setUsingNonZeroWinding (false);
  71118. int index = 0;
  71119. float lastX = 0, lastY = 0;
  71120. float lastX2 = 0, lastY2 = 0;
  71121. juce_wchar lastCommandChar = 0;
  71122. bool isRelative = true;
  71123. bool carryOn = true;
  71124. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71125. while (d[index] != 0)
  71126. {
  71127. float x, y, x2, y2, x3, y3;
  71128. if (validCommandChars.containsChar (d[index]))
  71129. {
  71130. lastCommandChar = d [index++];
  71131. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71132. }
  71133. switch (lastCommandChar)
  71134. {
  71135. case 'M':
  71136. case 'm':
  71137. case 'L':
  71138. case 'l':
  71139. if (parseCoords (d, x, y, index, false))
  71140. {
  71141. if (isRelative)
  71142. {
  71143. x += lastX;
  71144. y += lastY;
  71145. }
  71146. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71147. {
  71148. path.startNewSubPath (x, y);
  71149. lastCommandChar = 'l';
  71150. }
  71151. else
  71152. path.lineTo (x, y);
  71153. lastX2 = lastX;
  71154. lastY2 = lastY;
  71155. lastX = x;
  71156. lastY = y;
  71157. }
  71158. else
  71159. {
  71160. ++index;
  71161. }
  71162. break;
  71163. case 'H':
  71164. case 'h':
  71165. if (parseCoord (d, x, index, false, true))
  71166. {
  71167. if (isRelative)
  71168. x += lastX;
  71169. path.lineTo (x, lastY);
  71170. lastX2 = lastX;
  71171. lastX = x;
  71172. }
  71173. else
  71174. {
  71175. ++index;
  71176. }
  71177. break;
  71178. case 'V':
  71179. case 'v':
  71180. if (parseCoord (d, y, index, false, false))
  71181. {
  71182. if (isRelative)
  71183. y += lastY;
  71184. path.lineTo (lastX, y);
  71185. lastY2 = lastY;
  71186. lastY = y;
  71187. }
  71188. else
  71189. {
  71190. ++index;
  71191. }
  71192. break;
  71193. case 'C':
  71194. case 'c':
  71195. if (parseCoords (d, x, y, index, false)
  71196. && parseCoords (d, x2, y2, index, false)
  71197. && parseCoords (d, x3, y3, index, false))
  71198. {
  71199. if (isRelative)
  71200. {
  71201. x += lastX;
  71202. y += lastY;
  71203. x2 += lastX;
  71204. y2 += lastY;
  71205. x3 += lastX;
  71206. y3 += lastY;
  71207. }
  71208. path.cubicTo (x, y, x2, y2, x3, y3);
  71209. lastX2 = x2;
  71210. lastY2 = y2;
  71211. lastX = x3;
  71212. lastY = y3;
  71213. }
  71214. else
  71215. {
  71216. ++index;
  71217. }
  71218. break;
  71219. case 'S':
  71220. case 's':
  71221. if (parseCoords (d, x, y, index, false)
  71222. && parseCoords (d, x3, y3, index, false))
  71223. {
  71224. if (isRelative)
  71225. {
  71226. x += lastX;
  71227. y += lastY;
  71228. x3 += lastX;
  71229. y3 += lastY;
  71230. }
  71231. x2 = lastX + (lastX - lastX2);
  71232. y2 = lastY + (lastY - lastY2);
  71233. path.cubicTo (x2, y2, x, y, x3, y3);
  71234. lastX2 = x;
  71235. lastY2 = y;
  71236. lastX = x3;
  71237. lastY = y3;
  71238. }
  71239. else
  71240. {
  71241. ++index;
  71242. }
  71243. break;
  71244. case 'Q':
  71245. case 'q':
  71246. if (parseCoords (d, x, y, index, false)
  71247. && parseCoords (d, x2, y2, index, false))
  71248. {
  71249. if (isRelative)
  71250. {
  71251. x += lastX;
  71252. y += lastY;
  71253. x2 += lastX;
  71254. y2 += lastY;
  71255. }
  71256. path.quadraticTo (x, y, x2, y2);
  71257. lastX2 = x;
  71258. lastY2 = y;
  71259. lastX = x2;
  71260. lastY = y2;
  71261. }
  71262. else
  71263. {
  71264. ++index;
  71265. }
  71266. break;
  71267. case 'T':
  71268. case 't':
  71269. if (parseCoords (d, x, y, index, false))
  71270. {
  71271. if (isRelative)
  71272. {
  71273. x += lastX;
  71274. y += lastY;
  71275. }
  71276. x2 = lastX + (lastX - lastX2);
  71277. y2 = lastY + (lastY - lastY2);
  71278. path.quadraticTo (x2, y2, x, y);
  71279. lastX2 = x2;
  71280. lastY2 = y2;
  71281. lastX = x;
  71282. lastY = y;
  71283. }
  71284. else
  71285. {
  71286. ++index;
  71287. }
  71288. break;
  71289. case 'A':
  71290. case 'a':
  71291. if (parseCoords (d, x, y, index, false))
  71292. {
  71293. String num;
  71294. if (parseNextNumber (d, num, index, false))
  71295. {
  71296. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71297. if (parseNextNumber (d, num, index, false))
  71298. {
  71299. const bool largeArc = num.getIntValue() != 0;
  71300. if (parseNextNumber (d, num, index, false))
  71301. {
  71302. const bool sweep = num.getIntValue() != 0;
  71303. if (parseCoords (d, x2, y2, index, false))
  71304. {
  71305. if (isRelative)
  71306. {
  71307. x2 += lastX;
  71308. y2 += lastY;
  71309. }
  71310. if (lastX != x2 || lastY != y2)
  71311. {
  71312. double centreX, centreY, startAngle, deltaAngle;
  71313. double rx = x, ry = y;
  71314. endpointToCentreParameters (lastX, lastY, x2, y2,
  71315. angle, largeArc, sweep,
  71316. rx, ry, centreX, centreY,
  71317. startAngle, deltaAngle);
  71318. path.addCentredArc ((float) centreX, (float) centreY,
  71319. (float) rx, (float) ry,
  71320. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71321. false);
  71322. path.lineTo (x2, y2);
  71323. }
  71324. lastX2 = lastX;
  71325. lastY2 = lastY;
  71326. lastX = x2;
  71327. lastY = y2;
  71328. }
  71329. }
  71330. }
  71331. }
  71332. }
  71333. else
  71334. {
  71335. ++index;
  71336. }
  71337. break;
  71338. case 'Z':
  71339. case 'z':
  71340. path.closeSubPath();
  71341. while (CharacterFunctions::isWhitespace (d [index]))
  71342. ++index;
  71343. break;
  71344. default:
  71345. carryOn = false;
  71346. break;
  71347. }
  71348. if (! carryOn)
  71349. break;
  71350. }
  71351. return parseShape (xml, path);
  71352. }
  71353. Drawable* parseRect (const XmlElement& xml) const
  71354. {
  71355. Path rect;
  71356. const bool hasRX = xml.hasAttribute ("rx");
  71357. const bool hasRY = xml.hasAttribute ("ry");
  71358. if (hasRX || hasRY)
  71359. {
  71360. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71361. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71362. if (! hasRX)
  71363. rx = ry;
  71364. else if (! hasRY)
  71365. ry = rx;
  71366. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71367. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71368. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71369. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71370. rx, ry);
  71371. }
  71372. else
  71373. {
  71374. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71375. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71376. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71377. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71378. }
  71379. return parseShape (xml, rect);
  71380. }
  71381. Drawable* parseCircle (const XmlElement& xml) const
  71382. {
  71383. Path circle;
  71384. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71385. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71386. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71387. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71388. return parseShape (xml, circle);
  71389. }
  71390. Drawable* parseEllipse (const XmlElement& xml) const
  71391. {
  71392. Path ellipse;
  71393. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71394. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71395. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71396. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71397. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71398. return parseShape (xml, ellipse);
  71399. }
  71400. Drawable* parseLine (const XmlElement& xml) const
  71401. {
  71402. Path line;
  71403. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71404. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71405. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71406. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71407. line.startNewSubPath (x1, y1);
  71408. line.lineTo (x2, y2);
  71409. return parseShape (xml, line);
  71410. }
  71411. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71412. {
  71413. const String points (xml.getStringAttribute ("points"));
  71414. Path path;
  71415. int index = 0;
  71416. float x, y;
  71417. if (parseCoords (points, x, y, index, true))
  71418. {
  71419. float firstX = x;
  71420. float firstY = y;
  71421. float lastX = 0, lastY = 0;
  71422. path.startNewSubPath (x, y);
  71423. while (parseCoords (points, x, y, index, true))
  71424. {
  71425. lastX = x;
  71426. lastY = y;
  71427. path.lineTo (x, y);
  71428. }
  71429. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71430. path.closeSubPath();
  71431. }
  71432. return parseShape (xml, path);
  71433. }
  71434. Drawable* parseShape (const XmlElement& xml, Path& path,
  71435. const bool shouldParseTransform = true) const
  71436. {
  71437. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71438. {
  71439. SVGState newState (*this);
  71440. newState.addTransform (xml);
  71441. return newState.parseShape (xml, path, false);
  71442. }
  71443. DrawablePath* dp = new DrawablePath();
  71444. dp->setName (xml.getStringAttribute ("id"));
  71445. dp->setFill (Colours::transparentBlack);
  71446. path.applyTransform (transform);
  71447. dp->setPath (path);
  71448. Path::Iterator iter (path);
  71449. bool containsClosedSubPath = false;
  71450. while (iter.next())
  71451. {
  71452. if (iter.elementType == Path::Iterator::closePath)
  71453. {
  71454. containsClosedSubPath = true;
  71455. break;
  71456. }
  71457. }
  71458. dp->setFill (getPathFillType (path,
  71459. getStyleAttribute (&xml, "fill"),
  71460. getStyleAttribute (&xml, "fill-opacity"),
  71461. getStyleAttribute (&xml, "opacity"),
  71462. containsClosedSubPath ? Colours::black
  71463. : Colours::transparentBlack));
  71464. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71465. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71466. {
  71467. dp->setStrokeFill (getPathFillType (path, strokeType,
  71468. getStyleAttribute (&xml, "stroke-opacity"),
  71469. getStyleAttribute (&xml, "opacity"),
  71470. Colours::transparentBlack));
  71471. dp->setStrokeType (getStrokeFor (&xml));
  71472. }
  71473. return dp;
  71474. }
  71475. const XmlElement* findLinkedElement (const XmlElement* e) const
  71476. {
  71477. const String id (e->getStringAttribute ("xlink:href"));
  71478. if (! id.startsWithChar ('#'))
  71479. return 0;
  71480. return findElementForId (topLevelXml, id.substring (1));
  71481. }
  71482. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71483. {
  71484. if (fillXml == 0)
  71485. return;
  71486. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71487. {
  71488. int index = 0;
  71489. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71490. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71491. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71492. double offset = e->getDoubleAttribute ("offset");
  71493. if (e->getStringAttribute ("offset").containsChar ('%'))
  71494. offset *= 0.01;
  71495. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71496. }
  71497. }
  71498. const FillType getPathFillType (const Path& path,
  71499. const String& fill,
  71500. const String& fillOpacity,
  71501. const String& overallOpacity,
  71502. const Colour& defaultColour) const
  71503. {
  71504. float opacity = 1.0f;
  71505. if (overallOpacity.isNotEmpty())
  71506. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71507. if (fillOpacity.isNotEmpty())
  71508. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71509. if (fill.startsWithIgnoreCase ("url"))
  71510. {
  71511. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71512. .upToLastOccurrenceOf (")", false, false).trim());
  71513. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71514. if (fillXml != 0
  71515. && (fillXml->hasTagName ("linearGradient")
  71516. || fillXml->hasTagName ("radialGradient")))
  71517. {
  71518. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71519. ColourGradient gradient;
  71520. addGradientStopsIn (gradient, inheritedFrom);
  71521. addGradientStopsIn (gradient, fillXml);
  71522. if (gradient.getNumColours() > 0)
  71523. {
  71524. gradient.addColour (0.0, gradient.getColour (0));
  71525. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71526. }
  71527. else
  71528. {
  71529. gradient.addColour (0.0, Colours::black);
  71530. gradient.addColour (1.0, Colours::black);
  71531. }
  71532. if (overallOpacity.isNotEmpty())
  71533. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71534. jassert (gradient.getNumColours() > 0);
  71535. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71536. float gradientWidth = viewBoxW;
  71537. float gradientHeight = viewBoxH;
  71538. float dx = 0.0f;
  71539. float dy = 0.0f;
  71540. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71541. if (! userSpace)
  71542. {
  71543. const Rectangle<float> bounds (path.getBounds());
  71544. dx = bounds.getX();
  71545. dy = bounds.getY();
  71546. gradientWidth = bounds.getWidth();
  71547. gradientHeight = bounds.getHeight();
  71548. }
  71549. if (gradient.isRadial)
  71550. {
  71551. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71552. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71553. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71554. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71555. //xxx (the fx, fy focal point isn't handled properly here..)
  71556. }
  71557. else
  71558. {
  71559. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71560. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71561. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71562. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71563. if (gradient.point1 == gradient.point2)
  71564. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71565. }
  71566. FillType type (gradient);
  71567. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71568. .followedBy (transform);
  71569. return type;
  71570. }
  71571. }
  71572. if (fill.equalsIgnoreCase ("none"))
  71573. return Colours::transparentBlack;
  71574. int i = 0;
  71575. const Colour colour (parseColour (fill, i, defaultColour));
  71576. return colour.withMultipliedAlpha (opacity);
  71577. }
  71578. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71579. {
  71580. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71581. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71582. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71583. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71584. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71585. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71586. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71587. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71588. if (join.equalsIgnoreCase ("round"))
  71589. joinStyle = PathStrokeType::curved;
  71590. else if (join.equalsIgnoreCase ("bevel"))
  71591. joinStyle = PathStrokeType::beveled;
  71592. if (cap.equalsIgnoreCase ("round"))
  71593. capStyle = PathStrokeType::rounded;
  71594. else if (cap.equalsIgnoreCase ("square"))
  71595. capStyle = PathStrokeType::square;
  71596. float ox = 0.0f, oy = 0.0f;
  71597. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71598. transform.transformPoints (ox, oy, x, y);
  71599. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71600. joinStyle, capStyle);
  71601. }
  71602. Drawable* parseText (const XmlElement& xml)
  71603. {
  71604. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71605. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71606. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71607. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71608. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71609. //xxx not done text yet!
  71610. forEachXmlChildElement (xml, e)
  71611. {
  71612. if (e->isTextElement())
  71613. {
  71614. const String text (e->getText());
  71615. Path path;
  71616. Drawable* s = parseShape (*e, path);
  71617. delete s; // xxx not finished!
  71618. }
  71619. else if (e->hasTagName ("tspan"))
  71620. {
  71621. Drawable* s = parseText (*e);
  71622. delete s; // xxx not finished!
  71623. }
  71624. }
  71625. return 0;
  71626. }
  71627. void addTransform (const XmlElement& xml)
  71628. {
  71629. transform = parseTransform (xml.getStringAttribute ("transform"))
  71630. .followedBy (transform);
  71631. }
  71632. bool parseCoord (const String& s, float& value, int& index,
  71633. const bool allowUnits, const bool isX) const
  71634. {
  71635. String number;
  71636. if (! parseNextNumber (s, number, index, allowUnits))
  71637. {
  71638. value = 0;
  71639. return false;
  71640. }
  71641. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71642. return true;
  71643. }
  71644. bool parseCoords (const String& s, float& x, float& y,
  71645. int& index, const bool allowUnits) const
  71646. {
  71647. return parseCoord (s, x, index, allowUnits, true)
  71648. && parseCoord (s, y, index, allowUnits, false);
  71649. }
  71650. float getCoordLength (const String& s, const float sizeForProportions) const
  71651. {
  71652. float n = s.getFloatValue();
  71653. const int len = s.length();
  71654. if (len > 2)
  71655. {
  71656. const float dpi = 96.0f;
  71657. const juce_wchar n1 = s [len - 2];
  71658. const juce_wchar n2 = s [len - 1];
  71659. if (n1 == 'i' && n2 == 'n')
  71660. n *= dpi;
  71661. else if (n1 == 'm' && n2 == 'm')
  71662. n *= dpi / 25.4f;
  71663. else if (n1 == 'c' && n2 == 'm')
  71664. n *= dpi / 2.54f;
  71665. else if (n1 == 'p' && n2 == 'c')
  71666. n *= 15.0f;
  71667. else if (n2 == '%')
  71668. n *= 0.01f * sizeForProportions;
  71669. }
  71670. return n;
  71671. }
  71672. void getCoordList (Array <float>& coords, const String& list,
  71673. const bool allowUnits, const bool isX) const
  71674. {
  71675. int index = 0;
  71676. float value;
  71677. while (parseCoord (list, value, index, allowUnits, isX))
  71678. coords.add (value);
  71679. }
  71680. void parseCSSStyle (const XmlElement& xml)
  71681. {
  71682. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71683. }
  71684. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71685. const String& defaultValue = String::empty) const
  71686. {
  71687. if (xml->hasAttribute (attributeName))
  71688. return xml->getStringAttribute (attributeName, defaultValue);
  71689. const String styleAtt (xml->getStringAttribute ("style"));
  71690. if (styleAtt.isNotEmpty())
  71691. {
  71692. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71693. if (value.isNotEmpty())
  71694. return value;
  71695. }
  71696. else if (xml->hasAttribute ("class"))
  71697. {
  71698. const String className ("." + xml->getStringAttribute ("class"));
  71699. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71700. if (index < 0)
  71701. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71702. if (index >= 0)
  71703. {
  71704. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71705. if (openBracket > index)
  71706. {
  71707. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71708. if (closeBracket > openBracket)
  71709. {
  71710. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71711. if (value.isNotEmpty())
  71712. return value;
  71713. }
  71714. }
  71715. }
  71716. }
  71717. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71718. if (xml != 0)
  71719. return getStyleAttribute (xml, attributeName, defaultValue);
  71720. return defaultValue;
  71721. }
  71722. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71723. {
  71724. if (xml->hasAttribute (attributeName))
  71725. return xml->getStringAttribute (attributeName);
  71726. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71727. if (xml != 0)
  71728. return getInheritedAttribute (xml, attributeName);
  71729. return String::empty;
  71730. }
  71731. static bool isIdentifierChar (const juce_wchar c)
  71732. {
  71733. return CharacterFunctions::isLetter (c) || c == '-';
  71734. }
  71735. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71736. {
  71737. int i = 0;
  71738. for (;;)
  71739. {
  71740. i = list.indexOf (i, attributeName);
  71741. if (i < 0)
  71742. break;
  71743. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71744. && ! isIdentifierChar (list [i + attributeName.length()]))
  71745. {
  71746. i = list.indexOfChar (i, ':');
  71747. if (i < 0)
  71748. break;
  71749. int end = list.indexOfChar (i, ';');
  71750. if (end < 0)
  71751. end = 0x7ffff;
  71752. return list.substring (i + 1, end).trim();
  71753. }
  71754. ++i;
  71755. }
  71756. return defaultValue;
  71757. }
  71758. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71759. {
  71760. const juce_wchar* const s = source;
  71761. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71762. ++index;
  71763. int start = index;
  71764. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71765. ++index;
  71766. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71767. ++index;
  71768. if ((s[index] == 'e' || s[index] == 'E')
  71769. && (CharacterFunctions::isDigit (s[index + 1])
  71770. || s[index + 1] == '-'
  71771. || s[index + 1] == '+'))
  71772. {
  71773. index += 2;
  71774. while (CharacterFunctions::isDigit (s[index]))
  71775. ++index;
  71776. }
  71777. if (allowUnits)
  71778. {
  71779. while (CharacterFunctions::isLetter (s[index]))
  71780. ++index;
  71781. }
  71782. if (index == start)
  71783. return false;
  71784. value = String (s + start, index - start);
  71785. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71786. ++index;
  71787. return true;
  71788. }
  71789. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71790. {
  71791. if (s [index] == '#')
  71792. {
  71793. uint32 hex [6];
  71794. zeromem (hex, sizeof (hex));
  71795. int numChars = 0;
  71796. for (int i = 6; --i >= 0;)
  71797. {
  71798. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71799. if (hexValue >= 0)
  71800. hex [numChars++] = hexValue;
  71801. else
  71802. break;
  71803. }
  71804. if (numChars <= 3)
  71805. return Colour ((uint8) (hex [0] * 0x11),
  71806. (uint8) (hex [1] * 0x11),
  71807. (uint8) (hex [2] * 0x11));
  71808. else
  71809. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71810. (uint8) ((hex [2] << 4) + hex [3]),
  71811. (uint8) ((hex [4] << 4) + hex [5]));
  71812. }
  71813. else if (s [index] == 'r'
  71814. && s [index + 1] == 'g'
  71815. && s [index + 2] == 'b')
  71816. {
  71817. const int openBracket = s.indexOfChar (index, '(');
  71818. const int closeBracket = s.indexOfChar (openBracket, ')');
  71819. if (openBracket >= 3 && closeBracket > openBracket)
  71820. {
  71821. index = closeBracket;
  71822. StringArray tokens;
  71823. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71824. tokens.trim();
  71825. tokens.removeEmptyStrings();
  71826. if (tokens[0].containsChar ('%'))
  71827. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71828. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71829. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71830. else
  71831. return Colour ((uint8) tokens[0].getIntValue(),
  71832. (uint8) tokens[1].getIntValue(),
  71833. (uint8) tokens[2].getIntValue());
  71834. }
  71835. }
  71836. return Colours::findColourForName (s, defaultColour);
  71837. }
  71838. static const AffineTransform parseTransform (String t)
  71839. {
  71840. AffineTransform result;
  71841. while (t.isNotEmpty())
  71842. {
  71843. StringArray tokens;
  71844. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71845. .upToFirstOccurrenceOf (")", false, false),
  71846. ", ", String::empty);
  71847. tokens.removeEmptyStrings (true);
  71848. float numbers [6];
  71849. for (int i = 0; i < 6; ++i)
  71850. numbers[i] = tokens[i].getFloatValue();
  71851. AffineTransform trans;
  71852. if (t.startsWithIgnoreCase ("matrix"))
  71853. {
  71854. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71855. numbers[1], numbers[3], numbers[5]);
  71856. }
  71857. else if (t.startsWithIgnoreCase ("translate"))
  71858. {
  71859. jassert (tokens.size() == 2);
  71860. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71861. }
  71862. else if (t.startsWithIgnoreCase ("scale"))
  71863. {
  71864. if (tokens.size() == 1)
  71865. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71866. else
  71867. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71868. }
  71869. else if (t.startsWithIgnoreCase ("rotate"))
  71870. {
  71871. if (tokens.size() != 3)
  71872. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71873. else
  71874. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71875. numbers[1], numbers[2]);
  71876. }
  71877. else if (t.startsWithIgnoreCase ("skewX"))
  71878. {
  71879. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71880. 0.0f, 1.0f, 0.0f);
  71881. }
  71882. else if (t.startsWithIgnoreCase ("skewY"))
  71883. {
  71884. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71885. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71886. }
  71887. result = trans.followedBy (result);
  71888. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71889. }
  71890. return result;
  71891. }
  71892. static void endpointToCentreParameters (const double x1, const double y1,
  71893. const double x2, const double y2,
  71894. const double angle,
  71895. const bool largeArc, const bool sweep,
  71896. double& rx, double& ry,
  71897. double& centreX, double& centreY,
  71898. double& startAngle, double& deltaAngle)
  71899. {
  71900. const double midX = (x1 - x2) * 0.5;
  71901. const double midY = (y1 - y2) * 0.5;
  71902. const double cosAngle = cos (angle);
  71903. const double sinAngle = sin (angle);
  71904. const double xp = cosAngle * midX + sinAngle * midY;
  71905. const double yp = cosAngle * midY - sinAngle * midX;
  71906. const double xp2 = xp * xp;
  71907. const double yp2 = yp * yp;
  71908. double rx2 = rx * rx;
  71909. double ry2 = ry * ry;
  71910. const double s = (xp2 / rx2) + (yp2 / ry2);
  71911. double c;
  71912. if (s <= 1.0)
  71913. {
  71914. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71915. / (( rx2 * yp2) + (ry2 * xp2))));
  71916. if (largeArc == sweep)
  71917. c = -c;
  71918. }
  71919. else
  71920. {
  71921. const double s2 = std::sqrt (s);
  71922. rx *= s2;
  71923. ry *= s2;
  71924. rx2 = rx * rx;
  71925. ry2 = ry * ry;
  71926. c = 0;
  71927. }
  71928. const double cpx = ((rx * yp) / ry) * c;
  71929. const double cpy = ((-ry * xp) / rx) * c;
  71930. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71931. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71932. const double ux = (xp - cpx) / rx;
  71933. const double uy = (yp - cpy) / ry;
  71934. const double vx = (-xp - cpx) / rx;
  71935. const double vy = (-yp - cpy) / ry;
  71936. const double length = juce_hypot (ux, uy);
  71937. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71938. if (uy < 0)
  71939. startAngle = -startAngle;
  71940. startAngle += double_Pi * 0.5;
  71941. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71942. / (length * juce_hypot (vx, vy))));
  71943. if ((ux * vy) - (uy * vx) < 0)
  71944. deltaAngle = -deltaAngle;
  71945. if (sweep)
  71946. {
  71947. if (deltaAngle < 0)
  71948. deltaAngle += double_Pi * 2.0;
  71949. }
  71950. else
  71951. {
  71952. if (deltaAngle > 0)
  71953. deltaAngle -= double_Pi * 2.0;
  71954. }
  71955. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71956. }
  71957. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71958. {
  71959. forEachXmlChildElement (*parent, e)
  71960. {
  71961. if (e->compareAttribute ("id", id))
  71962. return e;
  71963. const XmlElement* const found = findElementForId (e, id);
  71964. if (found != 0)
  71965. return found;
  71966. }
  71967. return 0;
  71968. }
  71969. SVGState& operator= (const SVGState&);
  71970. };
  71971. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  71972. {
  71973. SVGState state (&svgDocument);
  71974. return state.parseSVGElement (svgDocument);
  71975. }
  71976. END_JUCE_NAMESPACE
  71977. /*** End of inlined file: juce_SVGParser.cpp ***/
  71978. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  71979. BEGIN_JUCE_NAMESPACE
  71980. #if JUCE_MSVC && JUCE_DEBUG
  71981. #pragma optimize ("t", on)
  71982. #endif
  71983. DropShadowEffect::DropShadowEffect()
  71984. : offsetX (0),
  71985. offsetY (0),
  71986. radius (4),
  71987. opacity (0.6f)
  71988. {
  71989. }
  71990. DropShadowEffect::~DropShadowEffect()
  71991. {
  71992. }
  71993. void DropShadowEffect::setShadowProperties (const float newRadius,
  71994. const float newOpacity,
  71995. const int newShadowOffsetX,
  71996. const int newShadowOffsetY)
  71997. {
  71998. radius = jmax (1.1f, newRadius);
  71999. offsetX = newShadowOffsetX;
  72000. offsetY = newShadowOffsetY;
  72001. opacity = newOpacity;
  72002. }
  72003. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72004. {
  72005. const int w = image.getWidth();
  72006. const int h = image.getHeight();
  72007. Image shadowImage (Image::SingleChannel, w, h, false);
  72008. const Image::BitmapData srcData (image, false);
  72009. const Image::BitmapData destData (shadowImage, true);
  72010. const int filter = roundToInt (63.0f / radius);
  72011. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72012. for (int x = w; --x >= 0;)
  72013. {
  72014. int shadowAlpha = 0;
  72015. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72016. uint8* shadowPix = destData.data + x;
  72017. for (int y = h; --y >= 0;)
  72018. {
  72019. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72020. *shadowPix = (uint8) shadowAlpha;
  72021. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72022. shadowPix += destData.lineStride;
  72023. }
  72024. }
  72025. for (int y = h; --y >= 0;)
  72026. {
  72027. int shadowAlpha = 0;
  72028. uint8* shadowPix = destData.getLinePointer (y);
  72029. for (int x = w; --x >= 0;)
  72030. {
  72031. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72032. *shadowPix++ = (uint8) shadowAlpha;
  72033. }
  72034. }
  72035. g.setColour (Colours::black.withAlpha (opacity));
  72036. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72037. g.setOpacity (1.0f);
  72038. g.drawImageAt (image, 0, 0);
  72039. }
  72040. #if JUCE_MSVC && JUCE_DEBUG
  72041. #pragma optimize ("", on) // resets optimisations to the project defaults
  72042. #endif
  72043. END_JUCE_NAMESPACE
  72044. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72045. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72046. BEGIN_JUCE_NAMESPACE
  72047. GlowEffect::GlowEffect()
  72048. : radius (2.0f),
  72049. colour (Colours::white)
  72050. {
  72051. }
  72052. GlowEffect::~GlowEffect()
  72053. {
  72054. }
  72055. void GlowEffect::setGlowProperties (const float newRadius,
  72056. const Colour& newColour)
  72057. {
  72058. radius = newRadius;
  72059. colour = newColour;
  72060. }
  72061. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72062. {
  72063. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72064. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72065. blurKernel.createGaussianBlur (radius);
  72066. blurKernel.rescaleAllValues (radius);
  72067. blurKernel.applyToImage (temp, image, image.getBounds());
  72068. g.setColour (colour);
  72069. g.drawImageAt (temp, 0, 0, true);
  72070. g.setOpacity (1.0f);
  72071. g.drawImageAt (image, 0, 0, false);
  72072. }
  72073. END_JUCE_NAMESPACE
  72074. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72075. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72076. BEGIN_JUCE_NAMESPACE
  72077. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72078. : opacity (opacity_)
  72079. {
  72080. }
  72081. ReduceOpacityEffect::~ReduceOpacityEffect()
  72082. {
  72083. }
  72084. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72085. {
  72086. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72087. }
  72088. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72089. {
  72090. g.setOpacity (opacity);
  72091. g.drawImageAt (image, 0, 0);
  72092. }
  72093. END_JUCE_NAMESPACE
  72094. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72095. /*** Start of inlined file: juce_Font.cpp ***/
  72096. BEGIN_JUCE_NAMESPACE
  72097. namespace FontValues
  72098. {
  72099. static float limitFontHeight (const float height) throw()
  72100. {
  72101. return jlimit (0.1f, 10000.0f, height);
  72102. }
  72103. static const float defaultFontHeight = 14.0f;
  72104. static String fallbackFont;
  72105. }
  72106. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72107. const float kerning_, const float ascent_, const int styleFlags_,
  72108. Typeface* const typeface_) throw()
  72109. : typefaceName (typefaceName_),
  72110. height (height_),
  72111. horizontalScale (horizontalScale_),
  72112. kerning (kerning_),
  72113. ascent (ascent_),
  72114. styleFlags (styleFlags_),
  72115. typeface (typeface_)
  72116. {
  72117. }
  72118. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72119. : typefaceName (other.typefaceName),
  72120. height (other.height),
  72121. horizontalScale (other.horizontalScale),
  72122. kerning (other.kerning),
  72123. ascent (other.ascent),
  72124. styleFlags (other.styleFlags),
  72125. typeface (other.typeface)
  72126. {
  72127. }
  72128. Font::Font() throw()
  72129. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72130. 1.0f, 0, 0, Font::plain, 0))
  72131. {
  72132. }
  72133. Font::Font (const float fontHeight, const int styleFlags_) throw()
  72134. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72135. 1.0f, 0, 0, styleFlags_, 0))
  72136. {
  72137. }
  72138. Font::Font (const String& typefaceName_,
  72139. const float fontHeight,
  72140. const int styleFlags_) throw()
  72141. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72142. 1.0f, 0, 0, styleFlags_, 0))
  72143. {
  72144. }
  72145. Font::Font (const Font& other) throw()
  72146. : font (other.font)
  72147. {
  72148. }
  72149. Font& Font::operator= (const Font& other) throw()
  72150. {
  72151. font = other.font;
  72152. return *this;
  72153. }
  72154. Font::~Font() throw()
  72155. {
  72156. }
  72157. Font::Font (const Typeface::Ptr& typeface) throw()
  72158. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72159. 1.0f, 0, 0, Font::plain, typeface))
  72160. {
  72161. }
  72162. bool Font::operator== (const Font& other) const throw()
  72163. {
  72164. return font == other.font
  72165. || (font->height == other.font->height
  72166. && font->styleFlags == other.font->styleFlags
  72167. && font->horizontalScale == other.font->horizontalScale
  72168. && font->kerning == other.font->kerning
  72169. && font->typefaceName == other.font->typefaceName);
  72170. }
  72171. bool Font::operator!= (const Font& other) const throw()
  72172. {
  72173. return ! operator== (other);
  72174. }
  72175. void Font::dupeInternalIfShared() throw()
  72176. {
  72177. if (font->getReferenceCount() > 1)
  72178. font = new SharedFontInternal (*font);
  72179. }
  72180. const String Font::getDefaultSansSerifFontName() throw()
  72181. {
  72182. static const String name ("<Sans-Serif>");
  72183. return name;
  72184. }
  72185. const String Font::getDefaultSerifFontName() throw()
  72186. {
  72187. static const String name ("<Serif>");
  72188. return name;
  72189. }
  72190. const String Font::getDefaultMonospacedFontName() throw()
  72191. {
  72192. static const String name ("<Monospaced>");
  72193. return name;
  72194. }
  72195. void Font::setTypefaceName (const String& faceName) throw()
  72196. {
  72197. if (faceName != font->typefaceName)
  72198. {
  72199. dupeInternalIfShared();
  72200. font->typefaceName = faceName;
  72201. font->typeface = 0;
  72202. font->ascent = 0;
  72203. }
  72204. }
  72205. const String Font::getFallbackFontName() throw()
  72206. {
  72207. return FontValues::fallbackFont;
  72208. }
  72209. void Font::setFallbackFontName (const String& name) throw()
  72210. {
  72211. FontValues::fallbackFont = name;
  72212. }
  72213. void Font::setHeight (float newHeight) throw()
  72214. {
  72215. newHeight = FontValues::limitFontHeight (newHeight);
  72216. if (font->height != newHeight)
  72217. {
  72218. dupeInternalIfShared();
  72219. font->height = newHeight;
  72220. }
  72221. }
  72222. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  72223. {
  72224. newHeight = FontValues::limitFontHeight (newHeight);
  72225. if (font->height != newHeight)
  72226. {
  72227. dupeInternalIfShared();
  72228. font->horizontalScale *= (font->height / newHeight);
  72229. font->height = newHeight;
  72230. }
  72231. }
  72232. void Font::setStyleFlags (const int newFlags) throw()
  72233. {
  72234. if (font->styleFlags != newFlags)
  72235. {
  72236. dupeInternalIfShared();
  72237. font->styleFlags = newFlags;
  72238. font->typeface = 0;
  72239. font->ascent = 0;
  72240. }
  72241. }
  72242. void Font::setSizeAndStyle (float newHeight,
  72243. const int newStyleFlags,
  72244. const float newHorizontalScale,
  72245. const float newKerningAmount) throw()
  72246. {
  72247. newHeight = FontValues::limitFontHeight (newHeight);
  72248. if (font->height != newHeight
  72249. || font->horizontalScale != newHorizontalScale
  72250. || font->kerning != newKerningAmount)
  72251. {
  72252. dupeInternalIfShared();
  72253. font->height = newHeight;
  72254. font->horizontalScale = newHorizontalScale;
  72255. font->kerning = newKerningAmount;
  72256. }
  72257. setStyleFlags (newStyleFlags);
  72258. }
  72259. void Font::setHorizontalScale (const float scaleFactor) throw()
  72260. {
  72261. dupeInternalIfShared();
  72262. font->horizontalScale = scaleFactor;
  72263. }
  72264. void Font::setExtraKerningFactor (const float extraKerning) throw()
  72265. {
  72266. dupeInternalIfShared();
  72267. font->kerning = extraKerning;
  72268. }
  72269. void Font::setBold (const bool shouldBeBold) throw()
  72270. {
  72271. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72272. : (font->styleFlags & ~bold));
  72273. }
  72274. bool Font::isBold() const throw()
  72275. {
  72276. return (font->styleFlags & bold) != 0;
  72277. }
  72278. void Font::setItalic (const bool shouldBeItalic) throw()
  72279. {
  72280. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72281. : (font->styleFlags & ~italic));
  72282. }
  72283. bool Font::isItalic() const throw()
  72284. {
  72285. return (font->styleFlags & italic) != 0;
  72286. }
  72287. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  72288. {
  72289. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72290. : (font->styleFlags & ~underlined));
  72291. }
  72292. bool Font::isUnderlined() const throw()
  72293. {
  72294. return (font->styleFlags & underlined) != 0;
  72295. }
  72296. float Font::getAscent() const throw()
  72297. {
  72298. if (font->ascent == 0)
  72299. font->ascent = getTypeface()->getAscent();
  72300. return font->height * font->ascent;
  72301. }
  72302. float Font::getDescent() const throw()
  72303. {
  72304. return font->height - getAscent();
  72305. }
  72306. int Font::getStringWidth (const String& text) const throw()
  72307. {
  72308. return roundToInt (getStringWidthFloat (text));
  72309. }
  72310. float Font::getStringWidthFloat (const String& text) const throw()
  72311. {
  72312. float w = getTypeface()->getStringWidth (text);
  72313. if (font->kerning != 0)
  72314. w += font->kerning * text.length();
  72315. return w * font->height * font->horizontalScale;
  72316. }
  72317. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  72318. {
  72319. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72320. const float scale = font->height * font->horizontalScale;
  72321. const int num = xOffsets.size();
  72322. if (num > 0)
  72323. {
  72324. float* const x = &(xOffsets.getReference(0));
  72325. if (font->kerning != 0)
  72326. {
  72327. for (int i = 0; i < num; ++i)
  72328. x[i] = (x[i] + i * font->kerning) * scale;
  72329. }
  72330. else
  72331. {
  72332. for (int i = 0; i < num; ++i)
  72333. x[i] *= scale;
  72334. }
  72335. }
  72336. }
  72337. void Font::findFonts (Array<Font>& destArray) throw()
  72338. {
  72339. const StringArray names (findAllTypefaceNames());
  72340. for (int i = 0; i < names.size(); ++i)
  72341. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72342. }
  72343. const String Font::toString() const
  72344. {
  72345. String s (getTypefaceName());
  72346. if (s == getDefaultSansSerifFontName())
  72347. s = String::empty;
  72348. else
  72349. s += "; ";
  72350. s += String (getHeight(), 1);
  72351. if (isBold())
  72352. s += " bold";
  72353. if (isItalic())
  72354. s += " italic";
  72355. return s;
  72356. }
  72357. const Font Font::fromString (const String& fontDescription)
  72358. {
  72359. String name;
  72360. const int separator = fontDescription.indexOfChar (';');
  72361. if (separator > 0)
  72362. name = fontDescription.substring (0, separator).trim();
  72363. if (name.isEmpty())
  72364. name = getDefaultSansSerifFontName();
  72365. String sizeAndStyle (fontDescription.substring (separator + 1));
  72366. float height = sizeAndStyle.getFloatValue();
  72367. if (height <= 0)
  72368. height = 10.0f;
  72369. int flags = Font::plain;
  72370. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72371. flags |= Font::bold;
  72372. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72373. flags |= Font::italic;
  72374. return Font (name, height, flags);
  72375. }
  72376. class TypefaceCache : public DeletedAtShutdown
  72377. {
  72378. public:
  72379. TypefaceCache (int numToCache = 10) throw()
  72380. : counter (1)
  72381. {
  72382. while (--numToCache >= 0)
  72383. faces.add (new CachedFace());
  72384. }
  72385. ~TypefaceCache()
  72386. {
  72387. clearSingletonInstance();
  72388. }
  72389. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72390. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  72391. {
  72392. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72393. const String faceName (font.getTypefaceName());
  72394. int i;
  72395. for (i = faces.size(); --i >= 0;)
  72396. {
  72397. CachedFace* const face = faces.getUnchecked(i);
  72398. if (face->flags == flags
  72399. && face->typefaceName == faceName)
  72400. {
  72401. face->lastUsageCount = ++counter;
  72402. return face->typeFace;
  72403. }
  72404. }
  72405. int replaceIndex = 0;
  72406. int bestLastUsageCount = std::numeric_limits<int>::max();
  72407. for (i = faces.size(); --i >= 0;)
  72408. {
  72409. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72410. if (bestLastUsageCount > lu)
  72411. {
  72412. bestLastUsageCount = lu;
  72413. replaceIndex = i;
  72414. }
  72415. }
  72416. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72417. face->typefaceName = faceName;
  72418. face->flags = flags;
  72419. face->lastUsageCount = ++counter;
  72420. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72421. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72422. return face->typeFace;
  72423. }
  72424. juce_UseDebuggingNewOperator
  72425. private:
  72426. struct CachedFace
  72427. {
  72428. CachedFace() throw()
  72429. : lastUsageCount (0), flags (-1)
  72430. {
  72431. }
  72432. String typefaceName;
  72433. int lastUsageCount;
  72434. int flags;
  72435. Typeface::Ptr typeFace;
  72436. };
  72437. int counter;
  72438. OwnedArray <CachedFace> faces;
  72439. TypefaceCache (const TypefaceCache&);
  72440. TypefaceCache& operator= (const TypefaceCache&);
  72441. };
  72442. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72443. Typeface* Font::getTypeface() const throw()
  72444. {
  72445. if (font->typeface == 0)
  72446. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72447. return font->typeface;
  72448. }
  72449. END_JUCE_NAMESPACE
  72450. /*** End of inlined file: juce_Font.cpp ***/
  72451. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72452. BEGIN_JUCE_NAMESPACE
  72453. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72454. const juce_wchar character_, const int glyph_)
  72455. : x (x_),
  72456. y (y_),
  72457. w (w_),
  72458. font (font_),
  72459. character (character_),
  72460. glyph (glyph_)
  72461. {
  72462. }
  72463. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72464. : x (other.x),
  72465. y (other.y),
  72466. w (other.w),
  72467. font (other.font),
  72468. character (other.character),
  72469. glyph (other.glyph)
  72470. {
  72471. }
  72472. void PositionedGlyph::draw (const Graphics& g) const
  72473. {
  72474. if (! isWhitespace())
  72475. {
  72476. g.getInternalContext()->setFont (font);
  72477. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72478. }
  72479. }
  72480. void PositionedGlyph::draw (const Graphics& g,
  72481. const AffineTransform& transform) const
  72482. {
  72483. if (! isWhitespace())
  72484. {
  72485. g.getInternalContext()->setFont (font);
  72486. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72487. .followedBy (transform));
  72488. }
  72489. }
  72490. void PositionedGlyph::createPath (Path& path) const
  72491. {
  72492. if (! isWhitespace())
  72493. {
  72494. Typeface* const t = font.getTypeface();
  72495. if (t != 0)
  72496. {
  72497. Path p;
  72498. t->getOutlineForGlyph (glyph, p);
  72499. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72500. .translated (x, y));
  72501. }
  72502. }
  72503. }
  72504. bool PositionedGlyph::hitTest (float px, float py) const
  72505. {
  72506. if (getBounds().contains (px, py) && ! isWhitespace())
  72507. {
  72508. Typeface* const t = font.getTypeface();
  72509. if (t != 0)
  72510. {
  72511. Path p;
  72512. t->getOutlineForGlyph (glyph, p);
  72513. AffineTransform::translation (-x, -y)
  72514. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72515. .transformPoint (px, py);
  72516. return p.contains (px, py);
  72517. }
  72518. }
  72519. return false;
  72520. }
  72521. void PositionedGlyph::moveBy (const float deltaX,
  72522. const float deltaY)
  72523. {
  72524. x += deltaX;
  72525. y += deltaY;
  72526. }
  72527. GlyphArrangement::GlyphArrangement()
  72528. {
  72529. glyphs.ensureStorageAllocated (128);
  72530. }
  72531. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72532. {
  72533. addGlyphArrangement (other);
  72534. }
  72535. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72536. {
  72537. if (this != &other)
  72538. {
  72539. clear();
  72540. addGlyphArrangement (other);
  72541. }
  72542. return *this;
  72543. }
  72544. GlyphArrangement::~GlyphArrangement()
  72545. {
  72546. }
  72547. void GlyphArrangement::clear()
  72548. {
  72549. glyphs.clear();
  72550. }
  72551. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72552. {
  72553. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72554. return *glyphs [index];
  72555. }
  72556. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72557. {
  72558. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72559. glyphs.addCopiesOf (other.glyphs);
  72560. }
  72561. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72562. {
  72563. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72564. }
  72565. void GlyphArrangement::addLineOfText (const Font& font,
  72566. const String& text,
  72567. const float xOffset,
  72568. const float yOffset)
  72569. {
  72570. addCurtailedLineOfText (font, text,
  72571. xOffset, yOffset,
  72572. 1.0e10f, false);
  72573. }
  72574. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72575. const String& text,
  72576. float xOffset,
  72577. const float yOffset,
  72578. const float maxWidthPixels,
  72579. const bool useEllipsis)
  72580. {
  72581. if (text.isNotEmpty())
  72582. {
  72583. Array <int> newGlyphs;
  72584. Array <float> xOffsets;
  72585. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72586. const int textLen = newGlyphs.size();
  72587. const juce_wchar* const unicodeText = text;
  72588. for (int i = 0; i < textLen; ++i)
  72589. {
  72590. const float thisX = xOffsets.getUnchecked (i);
  72591. const float nextX = xOffsets.getUnchecked (i + 1);
  72592. if (nextX > maxWidthPixels + 1.0f)
  72593. {
  72594. // curtail the string if it's too wide..
  72595. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72596. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72597. break;
  72598. }
  72599. else
  72600. {
  72601. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72602. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72603. }
  72604. }
  72605. }
  72606. }
  72607. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72608. const int startIndex, int endIndex)
  72609. {
  72610. int numDeleted = 0;
  72611. if (glyphs.size() > 0)
  72612. {
  72613. Array<int> dotGlyphs;
  72614. Array<float> dotXs;
  72615. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72616. const float dx = dotXs[1];
  72617. float xOffset = 0.0f, yOffset = 0.0f;
  72618. while (endIndex > startIndex)
  72619. {
  72620. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72621. xOffset = pg->x;
  72622. yOffset = pg->y;
  72623. glyphs.remove (endIndex);
  72624. ++numDeleted;
  72625. if (xOffset + dx * 3 <= maxXPos)
  72626. break;
  72627. }
  72628. for (int i = 3; --i >= 0;)
  72629. {
  72630. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72631. font, '.', dotGlyphs.getFirst()));
  72632. --numDeleted;
  72633. xOffset += dx;
  72634. if (xOffset > maxXPos)
  72635. break;
  72636. }
  72637. }
  72638. return numDeleted;
  72639. }
  72640. void GlyphArrangement::addJustifiedText (const Font& font,
  72641. const String& text,
  72642. float x, float y,
  72643. const float maxLineWidth,
  72644. const Justification& horizontalLayout)
  72645. {
  72646. int lineStartIndex = glyphs.size();
  72647. addLineOfText (font, text, x, y);
  72648. const float originalY = y;
  72649. while (lineStartIndex < glyphs.size())
  72650. {
  72651. int i = lineStartIndex;
  72652. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72653. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72654. ++i;
  72655. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72656. int lastWordBreakIndex = -1;
  72657. while (i < glyphs.size())
  72658. {
  72659. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72660. const juce_wchar c = pg->getCharacter();
  72661. if (c == '\r' || c == '\n')
  72662. {
  72663. ++i;
  72664. if (c == '\r' && i < glyphs.size()
  72665. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72666. ++i;
  72667. break;
  72668. }
  72669. else if (pg->isWhitespace())
  72670. {
  72671. lastWordBreakIndex = i + 1;
  72672. }
  72673. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72674. {
  72675. if (lastWordBreakIndex >= 0)
  72676. i = lastWordBreakIndex;
  72677. break;
  72678. }
  72679. ++i;
  72680. }
  72681. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72682. float currentLineEndX = currentLineStartX;
  72683. for (int j = i; --j >= lineStartIndex;)
  72684. {
  72685. if (! glyphs.getUnchecked (j)->isWhitespace())
  72686. {
  72687. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72688. break;
  72689. }
  72690. }
  72691. float deltaX = 0.0f;
  72692. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72693. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72694. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72695. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72696. else if (horizontalLayout.testFlags (Justification::right))
  72697. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72698. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72699. x + deltaX - currentLineStartX, y - originalY);
  72700. lineStartIndex = i;
  72701. y += font.getHeight();
  72702. }
  72703. }
  72704. void GlyphArrangement::addFittedText (const Font& f,
  72705. const String& text,
  72706. const float x, const float y,
  72707. const float width, const float height,
  72708. const Justification& layout,
  72709. int maximumLines,
  72710. const float minimumHorizontalScale)
  72711. {
  72712. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72713. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72714. if (text.containsAnyOf ("\r\n"))
  72715. {
  72716. GlyphArrangement ga;
  72717. ga.addJustifiedText (f, text, x, y, width, layout);
  72718. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72719. float dy = y - bb.getY();
  72720. if (layout.testFlags (Justification::verticallyCentred))
  72721. dy += (height - bb.getHeight()) * 0.5f;
  72722. else if (layout.testFlags (Justification::bottom))
  72723. dy += height - bb.getHeight();
  72724. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72725. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72726. for (int i = 0; i < ga.glyphs.size(); ++i)
  72727. glyphs.add (ga.glyphs.getUnchecked (i));
  72728. ga.glyphs.clear (false);
  72729. return;
  72730. }
  72731. int startIndex = glyphs.size();
  72732. addLineOfText (f, text.trim(), x, y);
  72733. if (glyphs.size() > startIndex)
  72734. {
  72735. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72736. - glyphs.getUnchecked (startIndex)->getLeft();
  72737. if (lineWidth <= 0)
  72738. return;
  72739. if (lineWidth * minimumHorizontalScale < width)
  72740. {
  72741. if (lineWidth > width)
  72742. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72743. width / lineWidth);
  72744. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72745. x, y, width, height, layout);
  72746. }
  72747. else if (maximumLines <= 1)
  72748. {
  72749. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72750. x, y, width, height, f, layout, minimumHorizontalScale);
  72751. }
  72752. else
  72753. {
  72754. Font font (f);
  72755. String txt (text.trim());
  72756. const int length = txt.length();
  72757. const int originalStartIndex = startIndex;
  72758. int numLines = 1;
  72759. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72760. maximumLines = 1;
  72761. maximumLines = jmin (maximumLines, length);
  72762. while (numLines < maximumLines)
  72763. {
  72764. ++numLines;
  72765. const float newFontHeight = height / (float) numLines;
  72766. if (newFontHeight < font.getHeight())
  72767. {
  72768. font.setHeight (jmax (8.0f, newFontHeight));
  72769. removeRangeOfGlyphs (startIndex, -1);
  72770. addLineOfText (font, txt, x, y);
  72771. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72772. - glyphs.getUnchecked (startIndex)->getLeft();
  72773. }
  72774. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72775. break;
  72776. }
  72777. if (numLines < 1)
  72778. numLines = 1;
  72779. float lineY = y;
  72780. float widthPerLine = lineWidth / numLines;
  72781. int lastLineStartIndex = 0;
  72782. for (int line = 0; line < numLines; ++line)
  72783. {
  72784. int i = startIndex;
  72785. lastLineStartIndex = i;
  72786. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72787. if (line == numLines - 1)
  72788. {
  72789. widthPerLine = width;
  72790. i = glyphs.size();
  72791. }
  72792. else
  72793. {
  72794. while (i < glyphs.size())
  72795. {
  72796. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72797. if (lineWidth > widthPerLine)
  72798. {
  72799. // got to a point where the line's too long, so skip forward to find a
  72800. // good place to break it..
  72801. const int searchStartIndex = i;
  72802. while (i < glyphs.size())
  72803. {
  72804. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72805. {
  72806. if (glyphs.getUnchecked (i)->isWhitespace()
  72807. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72808. {
  72809. ++i;
  72810. break;
  72811. }
  72812. }
  72813. else
  72814. {
  72815. // can't find a suitable break, so try looking backwards..
  72816. i = searchStartIndex;
  72817. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72818. {
  72819. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72820. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72821. {
  72822. i -= back - 1;
  72823. break;
  72824. }
  72825. }
  72826. break;
  72827. }
  72828. ++i;
  72829. }
  72830. break;
  72831. }
  72832. ++i;
  72833. }
  72834. int wsStart = i;
  72835. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72836. --wsStart;
  72837. int wsEnd = i;
  72838. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72839. ++wsEnd;
  72840. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72841. i = jmax (wsStart, startIndex + 1);
  72842. }
  72843. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72844. x, lineY, width, font.getHeight(), font,
  72845. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72846. minimumHorizontalScale);
  72847. startIndex = i;
  72848. lineY += font.getHeight();
  72849. if (startIndex >= glyphs.size())
  72850. break;
  72851. }
  72852. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72853. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72854. }
  72855. }
  72856. }
  72857. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72858. const float dx, const float dy)
  72859. {
  72860. jassert (startIndex >= 0);
  72861. if (dx != 0.0f || dy != 0.0f)
  72862. {
  72863. if (num < 0 || startIndex + num > glyphs.size())
  72864. num = glyphs.size() - startIndex;
  72865. while (--num >= 0)
  72866. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72867. }
  72868. }
  72869. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72870. const Justification& justification, float minimumHorizontalScale)
  72871. {
  72872. int numDeleted = 0;
  72873. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72874. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72875. if (lineWidth > w)
  72876. {
  72877. if (minimumHorizontalScale < 1.0f)
  72878. {
  72879. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72880. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72881. }
  72882. if (lineWidth > w)
  72883. {
  72884. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72885. numGlyphs -= numDeleted;
  72886. }
  72887. }
  72888. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72889. return numDeleted;
  72890. }
  72891. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72892. const float horizontalScaleFactor)
  72893. {
  72894. jassert (startIndex >= 0);
  72895. if (num < 0 || startIndex + num > glyphs.size())
  72896. num = glyphs.size() - startIndex;
  72897. if (num > 0)
  72898. {
  72899. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72900. while (--num >= 0)
  72901. {
  72902. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72903. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72904. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72905. pg->w *= horizontalScaleFactor;
  72906. }
  72907. }
  72908. }
  72909. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72910. {
  72911. jassert (startIndex >= 0);
  72912. if (num < 0 || startIndex + num > glyphs.size())
  72913. num = glyphs.size() - startIndex;
  72914. Rectangle<float> result;
  72915. while (--num >= 0)
  72916. {
  72917. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72918. if (includeWhitespace || ! pg->isWhitespace())
  72919. result = result.getUnion (pg->getBounds());
  72920. }
  72921. return result;
  72922. }
  72923. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72924. const float x, const float y, const float width, const float height,
  72925. const Justification& justification)
  72926. {
  72927. jassert (num >= 0 && startIndex >= 0);
  72928. if (glyphs.size() > 0 && num > 0)
  72929. {
  72930. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72931. | Justification::horizontallyCentred)));
  72932. float deltaX = 0.0f;
  72933. if (justification.testFlags (Justification::horizontallyJustified))
  72934. deltaX = x - bb.getX();
  72935. else if (justification.testFlags (Justification::horizontallyCentred))
  72936. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72937. else if (justification.testFlags (Justification::right))
  72938. deltaX = (x + width) - bb.getRight();
  72939. else
  72940. deltaX = x - bb.getX();
  72941. float deltaY = 0.0f;
  72942. if (justification.testFlags (Justification::top))
  72943. deltaY = y - bb.getY();
  72944. else if (justification.testFlags (Justification::bottom))
  72945. deltaY = (y + height) - bb.getBottom();
  72946. else
  72947. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72948. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72949. if (justification.testFlags (Justification::horizontallyJustified))
  72950. {
  72951. int lineStart = 0;
  72952. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72953. int i;
  72954. for (i = 0; i < num; ++i)
  72955. {
  72956. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72957. if (glyphY != baseY)
  72958. {
  72959. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72960. lineStart = i;
  72961. baseY = glyphY;
  72962. }
  72963. }
  72964. if (i > lineStart)
  72965. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72966. }
  72967. }
  72968. }
  72969. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72970. {
  72971. if (start + num < glyphs.size()
  72972. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  72973. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  72974. {
  72975. int numSpaces = 0;
  72976. int spacesAtEnd = 0;
  72977. for (int i = 0; i < num; ++i)
  72978. {
  72979. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72980. {
  72981. ++spacesAtEnd;
  72982. ++numSpaces;
  72983. }
  72984. else
  72985. {
  72986. spacesAtEnd = 0;
  72987. }
  72988. }
  72989. numSpaces -= spacesAtEnd;
  72990. if (numSpaces > 0)
  72991. {
  72992. const float startX = glyphs.getUnchecked (start)->getLeft();
  72993. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  72994. const float extraPaddingBetweenWords
  72995. = (targetWidth - (endX - startX)) / (float) numSpaces;
  72996. float deltaX = 0.0f;
  72997. for (int i = 0; i < num; ++i)
  72998. {
  72999. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73000. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73001. deltaX += extraPaddingBetweenWords;
  73002. }
  73003. }
  73004. }
  73005. }
  73006. void GlyphArrangement::draw (const Graphics& g) const
  73007. {
  73008. for (int i = 0; i < glyphs.size(); ++i)
  73009. {
  73010. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73011. if (pg->font.isUnderlined())
  73012. {
  73013. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73014. float nextX = pg->x + pg->w;
  73015. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73016. nextX = glyphs.getUnchecked (i + 1)->x;
  73017. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73018. nextX - pg->x, lineThickness);
  73019. }
  73020. pg->draw (g);
  73021. }
  73022. }
  73023. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73024. {
  73025. for (int i = 0; i < glyphs.size(); ++i)
  73026. {
  73027. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73028. if (pg->font.isUnderlined())
  73029. {
  73030. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73031. float nextX = pg->x + pg->w;
  73032. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73033. nextX = glyphs.getUnchecked (i + 1)->x;
  73034. Path p;
  73035. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73036. nextX, pg->y + lineThickness * 2.0f),
  73037. lineThickness);
  73038. g.fillPath (p, transform);
  73039. }
  73040. pg->draw (g, transform);
  73041. }
  73042. }
  73043. void GlyphArrangement::createPath (Path& path) const
  73044. {
  73045. for (int i = 0; i < glyphs.size(); ++i)
  73046. glyphs.getUnchecked (i)->createPath (path);
  73047. }
  73048. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73049. {
  73050. for (int i = 0; i < glyphs.size(); ++i)
  73051. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73052. return i;
  73053. return -1;
  73054. }
  73055. END_JUCE_NAMESPACE
  73056. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73057. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73058. BEGIN_JUCE_NAMESPACE
  73059. class TextLayout::Token
  73060. {
  73061. public:
  73062. String text;
  73063. Font font;
  73064. int x, y, w, h;
  73065. int line, lineHeight;
  73066. bool isWhitespace, isNewLine;
  73067. Token (const String& t,
  73068. const Font& f,
  73069. const bool isWhitespace_)
  73070. : text (t),
  73071. font (f),
  73072. x(0),
  73073. y(0),
  73074. isWhitespace (isWhitespace_)
  73075. {
  73076. w = font.getStringWidth (t);
  73077. h = roundToInt (f.getHeight());
  73078. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73079. }
  73080. Token (const Token& other)
  73081. : text (other.text),
  73082. font (other.font),
  73083. x (other.x),
  73084. y (other.y),
  73085. w (other.w),
  73086. h (other.h),
  73087. line (other.line),
  73088. lineHeight (other.lineHeight),
  73089. isWhitespace (other.isWhitespace),
  73090. isNewLine (other.isNewLine)
  73091. {
  73092. }
  73093. ~Token()
  73094. {
  73095. }
  73096. void draw (Graphics& g,
  73097. const int xOffset,
  73098. const int yOffset)
  73099. {
  73100. if (! isWhitespace)
  73101. {
  73102. g.setFont (font);
  73103. g.drawSingleLineText (text.trimEnd(),
  73104. xOffset + x,
  73105. yOffset + y + (lineHeight - h)
  73106. + roundToInt (font.getAscent()));
  73107. }
  73108. }
  73109. juce_UseDebuggingNewOperator
  73110. };
  73111. TextLayout::TextLayout()
  73112. : totalLines (0)
  73113. {
  73114. tokens.ensureStorageAllocated (64);
  73115. }
  73116. TextLayout::TextLayout (const String& text, const Font& font)
  73117. : totalLines (0)
  73118. {
  73119. tokens.ensureStorageAllocated (64);
  73120. appendText (text, font);
  73121. }
  73122. TextLayout::TextLayout (const TextLayout& other)
  73123. : totalLines (0)
  73124. {
  73125. *this = other;
  73126. }
  73127. TextLayout& TextLayout::operator= (const TextLayout& other)
  73128. {
  73129. if (this != &other)
  73130. {
  73131. clear();
  73132. totalLines = other.totalLines;
  73133. tokens.addCopiesOf (other.tokens);
  73134. }
  73135. return *this;
  73136. }
  73137. TextLayout::~TextLayout()
  73138. {
  73139. clear();
  73140. }
  73141. void TextLayout::clear()
  73142. {
  73143. tokens.clear();
  73144. totalLines = 0;
  73145. }
  73146. void TextLayout::appendText (const String& text, const Font& font)
  73147. {
  73148. const juce_wchar* t = text;
  73149. String currentString;
  73150. int lastCharType = 0;
  73151. for (;;)
  73152. {
  73153. const juce_wchar c = *t++;
  73154. if (c == 0)
  73155. break;
  73156. int charType;
  73157. if (c == '\r' || c == '\n')
  73158. {
  73159. charType = 0;
  73160. }
  73161. else if (CharacterFunctions::isWhitespace (c))
  73162. {
  73163. charType = 2;
  73164. }
  73165. else
  73166. {
  73167. charType = 1;
  73168. }
  73169. if (charType == 0 || charType != lastCharType)
  73170. {
  73171. if (currentString.isNotEmpty())
  73172. {
  73173. tokens.add (new Token (currentString, font,
  73174. lastCharType == 2 || lastCharType == 0));
  73175. }
  73176. currentString = String::charToString (c);
  73177. if (c == '\r' && *t == '\n')
  73178. currentString += *t++;
  73179. }
  73180. else
  73181. {
  73182. currentString += c;
  73183. }
  73184. lastCharType = charType;
  73185. }
  73186. if (currentString.isNotEmpty())
  73187. tokens.add (new Token (currentString, font, lastCharType == 2));
  73188. }
  73189. void TextLayout::setText (const String& text, const Font& font)
  73190. {
  73191. clear();
  73192. appendText (text, font);
  73193. }
  73194. void TextLayout::layout (int maxWidth,
  73195. const Justification& justification,
  73196. const bool attemptToBalanceLineLengths)
  73197. {
  73198. if (attemptToBalanceLineLengths)
  73199. {
  73200. const int originalW = maxWidth;
  73201. int bestWidth = maxWidth;
  73202. float bestLineProportion = 0.0f;
  73203. while (maxWidth > originalW / 2)
  73204. {
  73205. layout (maxWidth, justification, false);
  73206. if (getNumLines() <= 1)
  73207. return;
  73208. const int lastLineW = getLineWidth (getNumLines() - 1);
  73209. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73210. const float prop = lastLineW / (float) lastButOneLineW;
  73211. if (prop > 0.9f)
  73212. return;
  73213. if (prop > bestLineProportion)
  73214. {
  73215. bestLineProportion = prop;
  73216. bestWidth = maxWidth;
  73217. }
  73218. maxWidth -= 10;
  73219. }
  73220. layout (bestWidth, justification, false);
  73221. }
  73222. else
  73223. {
  73224. int x = 0;
  73225. int y = 0;
  73226. int h = 0;
  73227. totalLines = 0;
  73228. int i;
  73229. for (i = 0; i < tokens.size(); ++i)
  73230. {
  73231. Token* const t = tokens.getUnchecked(i);
  73232. t->x = x;
  73233. t->y = y;
  73234. t->line = totalLines;
  73235. x += t->w;
  73236. h = jmax (h, t->h);
  73237. const Token* nextTok = tokens [i + 1];
  73238. if (nextTok == 0)
  73239. break;
  73240. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73241. {
  73242. // finished a line, so go back and update the heights of the things on it
  73243. for (int j = i; j >= 0; --j)
  73244. {
  73245. Token* const tok = tokens.getUnchecked(j);
  73246. if (tok->line == totalLines)
  73247. tok->lineHeight = h;
  73248. else
  73249. break;
  73250. }
  73251. x = 0;
  73252. y += h;
  73253. h = 0;
  73254. ++totalLines;
  73255. }
  73256. }
  73257. // finished a line, so go back and update the heights of the things on it
  73258. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73259. {
  73260. Token* const t = tokens.getUnchecked(j);
  73261. if (t->line == totalLines)
  73262. t->lineHeight = h;
  73263. else
  73264. break;
  73265. }
  73266. ++totalLines;
  73267. if (! justification.testFlags (Justification::left))
  73268. {
  73269. int totalW = getWidth();
  73270. for (i = totalLines; --i >= 0;)
  73271. {
  73272. const int lineW = getLineWidth (i);
  73273. int dx = 0;
  73274. if (justification.testFlags (Justification::horizontallyCentred))
  73275. dx = (totalW - lineW) / 2;
  73276. else if (justification.testFlags (Justification::right))
  73277. dx = totalW - lineW;
  73278. for (int j = tokens.size(); --j >= 0;)
  73279. {
  73280. Token* const t = tokens.getUnchecked(j);
  73281. if (t->line == i)
  73282. t->x += dx;
  73283. }
  73284. }
  73285. }
  73286. }
  73287. }
  73288. int TextLayout::getLineWidth (const int lineNumber) const
  73289. {
  73290. int maxW = 0;
  73291. for (int i = tokens.size(); --i >= 0;)
  73292. {
  73293. const Token* const t = tokens.getUnchecked(i);
  73294. if (t->line == lineNumber && ! t->isWhitespace)
  73295. maxW = jmax (maxW, t->x + t->w);
  73296. }
  73297. return maxW;
  73298. }
  73299. int TextLayout::getWidth() const
  73300. {
  73301. int maxW = 0;
  73302. for (int i = tokens.size(); --i >= 0;)
  73303. {
  73304. const Token* const t = tokens.getUnchecked(i);
  73305. if (! t->isWhitespace)
  73306. maxW = jmax (maxW, t->x + t->w);
  73307. }
  73308. return maxW;
  73309. }
  73310. int TextLayout::getHeight() const
  73311. {
  73312. int maxH = 0;
  73313. for (int i = tokens.size(); --i >= 0;)
  73314. {
  73315. const Token* const t = tokens.getUnchecked(i);
  73316. if (! t->isWhitespace)
  73317. maxH = jmax (maxH, t->y + t->h);
  73318. }
  73319. return maxH;
  73320. }
  73321. void TextLayout::draw (Graphics& g,
  73322. const int xOffset,
  73323. const int yOffset) const
  73324. {
  73325. for (int i = tokens.size(); --i >= 0;)
  73326. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73327. }
  73328. void TextLayout::drawWithin (Graphics& g,
  73329. int x, int y, int w, int h,
  73330. const Justification& justification) const
  73331. {
  73332. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73333. x, y, w, h);
  73334. draw (g, x, y);
  73335. }
  73336. END_JUCE_NAMESPACE
  73337. /*** End of inlined file: juce_TextLayout.cpp ***/
  73338. /*** Start of inlined file: juce_Typeface.cpp ***/
  73339. BEGIN_JUCE_NAMESPACE
  73340. Typeface::Typeface (const String& name_) throw()
  73341. : name (name_)
  73342. {
  73343. }
  73344. Typeface::~Typeface()
  73345. {
  73346. }
  73347. class CustomTypeface::GlyphInfo
  73348. {
  73349. public:
  73350. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73351. : character (character_), path (path_), width (width_)
  73352. {
  73353. }
  73354. ~GlyphInfo() throw()
  73355. {
  73356. }
  73357. struct KerningPair
  73358. {
  73359. juce_wchar character2;
  73360. float kerningAmount;
  73361. };
  73362. void addKerningPair (const juce_wchar subsequentCharacter,
  73363. const float extraKerningAmount) throw()
  73364. {
  73365. KerningPair kp;
  73366. kp.character2 = subsequentCharacter;
  73367. kp.kerningAmount = extraKerningAmount;
  73368. kerningPairs.add (kp);
  73369. }
  73370. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73371. {
  73372. if (subsequentCharacter != 0)
  73373. {
  73374. for (int i = kerningPairs.size(); --i >= 0;)
  73375. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73376. return width + kerningPairs.getReference(i).kerningAmount;
  73377. }
  73378. return width;
  73379. }
  73380. const juce_wchar character;
  73381. const Path path;
  73382. float width;
  73383. Array <KerningPair> kerningPairs;
  73384. juce_UseDebuggingNewOperator
  73385. private:
  73386. GlyphInfo (const GlyphInfo&);
  73387. GlyphInfo& operator= (const GlyphInfo&);
  73388. };
  73389. CustomTypeface::CustomTypeface()
  73390. : Typeface (String::empty)
  73391. {
  73392. clear();
  73393. }
  73394. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73395. : Typeface (String::empty)
  73396. {
  73397. clear();
  73398. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73399. BufferedInputStream in (&gzin, 32768, false);
  73400. name = in.readString();
  73401. isBold = in.readBool();
  73402. isItalic = in.readBool();
  73403. ascent = in.readFloat();
  73404. defaultCharacter = (juce_wchar) in.readShort();
  73405. int i, numChars = in.readInt();
  73406. for (i = 0; i < numChars; ++i)
  73407. {
  73408. const juce_wchar c = (juce_wchar) in.readShort();
  73409. const float width = in.readFloat();
  73410. Path p;
  73411. p.loadPathFromStream (in);
  73412. addGlyph (c, p, width);
  73413. }
  73414. const int numKerningPairs = in.readInt();
  73415. for (i = 0; i < numKerningPairs; ++i)
  73416. {
  73417. const juce_wchar char1 = (juce_wchar) in.readShort();
  73418. const juce_wchar char2 = (juce_wchar) in.readShort();
  73419. addKerningPair (char1, char2, in.readFloat());
  73420. }
  73421. }
  73422. CustomTypeface::~CustomTypeface()
  73423. {
  73424. }
  73425. void CustomTypeface::clear()
  73426. {
  73427. defaultCharacter = 0;
  73428. ascent = 1.0f;
  73429. isBold = isItalic = false;
  73430. zeromem (lookupTable, sizeof (lookupTable));
  73431. glyphs.clear();
  73432. }
  73433. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73434. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73435. {
  73436. name = name_;
  73437. defaultCharacter = defaultCharacter_;
  73438. ascent = ascent_;
  73439. isBold = isBold_;
  73440. isItalic = isItalic_;
  73441. }
  73442. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73443. {
  73444. // Check that you're not trying to add the same character twice..
  73445. jassert (findGlyph (character, false) == 0);
  73446. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73447. lookupTable [character] = (short) glyphs.size();
  73448. glyphs.add (new GlyphInfo (character, path, width));
  73449. }
  73450. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73451. {
  73452. if (extraAmount != 0)
  73453. {
  73454. GlyphInfo* const g = findGlyph (char1, true);
  73455. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73456. if (g != 0)
  73457. g->addKerningPair (char2, extraAmount);
  73458. }
  73459. }
  73460. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73461. {
  73462. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73463. return glyphs [(int) lookupTable [(int) character]];
  73464. for (int i = 0; i < glyphs.size(); ++i)
  73465. {
  73466. GlyphInfo* const g = glyphs.getUnchecked(i);
  73467. if (g->character == character)
  73468. return g;
  73469. }
  73470. if (loadIfNeeded && loadGlyphIfPossible (character))
  73471. return findGlyph (character, false);
  73472. return 0;
  73473. }
  73474. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73475. {
  73476. GlyphInfo* glyph = findGlyph (character, true);
  73477. if (glyph == 0)
  73478. {
  73479. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73480. glyph = findGlyph (L' ', true);
  73481. if (glyph == 0)
  73482. {
  73483. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73484. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73485. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73486. {
  73487. //xxx
  73488. }
  73489. if (glyph == 0)
  73490. glyph = findGlyph (defaultCharacter, true);
  73491. }
  73492. }
  73493. return glyph;
  73494. }
  73495. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73496. {
  73497. return false;
  73498. }
  73499. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73500. {
  73501. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73502. for (int i = 0; i < numCharacters; ++i)
  73503. {
  73504. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73505. Array <int> glyphIndexes;
  73506. Array <float> offsets;
  73507. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73508. const int glyphIndex = glyphIndexes.getFirst();
  73509. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73510. {
  73511. const float glyphWidth = offsets[1];
  73512. Path p;
  73513. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73514. addGlyph (c, p, glyphWidth);
  73515. for (int j = glyphs.size() - 1; --j >= 0;)
  73516. {
  73517. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73518. glyphIndexes.clearQuick();
  73519. offsets.clearQuick();
  73520. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73521. if (offsets.size() > 1)
  73522. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73523. }
  73524. }
  73525. }
  73526. }
  73527. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73528. {
  73529. GZIPCompressorOutputStream out (&outputStream);
  73530. out.writeString (name);
  73531. out.writeBool (isBold);
  73532. out.writeBool (isItalic);
  73533. out.writeFloat (ascent);
  73534. out.writeShort ((short) (unsigned short) defaultCharacter);
  73535. out.writeInt (glyphs.size());
  73536. int i, numKerningPairs = 0;
  73537. for (i = 0; i < glyphs.size(); ++i)
  73538. {
  73539. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73540. out.writeShort ((short) (unsigned short) g->character);
  73541. out.writeFloat (g->width);
  73542. g->path.writePathToStream (out);
  73543. numKerningPairs += g->kerningPairs.size();
  73544. }
  73545. out.writeInt (numKerningPairs);
  73546. for (i = 0; i < glyphs.size(); ++i)
  73547. {
  73548. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73549. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73550. {
  73551. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73552. out.writeShort ((short) (unsigned short) g->character);
  73553. out.writeShort ((short) (unsigned short) p.character2);
  73554. out.writeFloat (p.kerningAmount);
  73555. }
  73556. }
  73557. return true;
  73558. }
  73559. float CustomTypeface::getAscent() const
  73560. {
  73561. return ascent;
  73562. }
  73563. float CustomTypeface::getDescent() const
  73564. {
  73565. return 1.0f - ascent;
  73566. }
  73567. float CustomTypeface::getStringWidth (const String& text)
  73568. {
  73569. float x = 0;
  73570. const juce_wchar* t = text;
  73571. while (*t != 0)
  73572. {
  73573. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73574. if (glyph != 0)
  73575. x += glyph->getHorizontalSpacing (*t);
  73576. }
  73577. return x;
  73578. }
  73579. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73580. {
  73581. xOffsets.add (0);
  73582. float x = 0;
  73583. const juce_wchar* t = text;
  73584. while (*t != 0)
  73585. {
  73586. const juce_wchar c = *t++;
  73587. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73588. if (glyph != 0)
  73589. {
  73590. x += glyph->getHorizontalSpacing (*t);
  73591. resultGlyphs.add ((int) glyph->character);
  73592. xOffsets.add (x);
  73593. }
  73594. }
  73595. }
  73596. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73597. {
  73598. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73599. if (glyph != 0)
  73600. {
  73601. path = glyph->path;
  73602. return true;
  73603. }
  73604. return false;
  73605. }
  73606. END_JUCE_NAMESPACE
  73607. /*** End of inlined file: juce_Typeface.cpp ***/
  73608. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73609. BEGIN_JUCE_NAMESPACE
  73610. AffineTransform::AffineTransform() throw()
  73611. : mat00 (1.0f),
  73612. mat01 (0),
  73613. mat02 (0),
  73614. mat10 (0),
  73615. mat11 (1.0f),
  73616. mat12 (0)
  73617. {
  73618. }
  73619. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73620. : mat00 (other.mat00),
  73621. mat01 (other.mat01),
  73622. mat02 (other.mat02),
  73623. mat10 (other.mat10),
  73624. mat11 (other.mat11),
  73625. mat12 (other.mat12)
  73626. {
  73627. }
  73628. AffineTransform::AffineTransform (const float mat00_,
  73629. const float mat01_,
  73630. const float mat02_,
  73631. const float mat10_,
  73632. const float mat11_,
  73633. const float mat12_) throw()
  73634. : mat00 (mat00_),
  73635. mat01 (mat01_),
  73636. mat02 (mat02_),
  73637. mat10 (mat10_),
  73638. mat11 (mat11_),
  73639. mat12 (mat12_)
  73640. {
  73641. }
  73642. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73643. {
  73644. mat00 = other.mat00;
  73645. mat01 = other.mat01;
  73646. mat02 = other.mat02;
  73647. mat10 = other.mat10;
  73648. mat11 = other.mat11;
  73649. mat12 = other.mat12;
  73650. return *this;
  73651. }
  73652. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73653. {
  73654. return mat00 == other.mat00
  73655. && mat01 == other.mat01
  73656. && mat02 == other.mat02
  73657. && mat10 == other.mat10
  73658. && mat11 == other.mat11
  73659. && mat12 == other.mat12;
  73660. }
  73661. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73662. {
  73663. return ! operator== (other);
  73664. }
  73665. bool AffineTransform::isIdentity() const throw()
  73666. {
  73667. return (mat01 == 0)
  73668. && (mat02 == 0)
  73669. && (mat10 == 0)
  73670. && (mat12 == 0)
  73671. && (mat00 == 1.0f)
  73672. && (mat11 == 1.0f);
  73673. }
  73674. const AffineTransform AffineTransform::identity;
  73675. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73676. {
  73677. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73678. other.mat00 * mat01 + other.mat01 * mat11,
  73679. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73680. other.mat10 * mat00 + other.mat11 * mat10,
  73681. other.mat10 * mat01 + other.mat11 * mat11,
  73682. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73683. }
  73684. const AffineTransform AffineTransform::followedBy (const float omat00,
  73685. const float omat01,
  73686. const float omat02,
  73687. const float omat10,
  73688. const float omat11,
  73689. const float omat12) const throw()
  73690. {
  73691. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73692. omat00 * mat01 + omat01 * mat11,
  73693. omat00 * mat02 + omat01 * mat12 + omat02,
  73694. omat10 * mat00 + omat11 * mat10,
  73695. omat10 * mat01 + omat11 * mat11,
  73696. omat10 * mat02 + omat11 * mat12 + omat12);
  73697. }
  73698. const AffineTransform AffineTransform::translated (const float dx,
  73699. const float dy) const throw()
  73700. {
  73701. return AffineTransform (mat00, mat01, mat02 + dx,
  73702. mat10, mat11, mat12 + dy);
  73703. }
  73704. const AffineTransform AffineTransform::translation (const float dx,
  73705. const float dy) throw()
  73706. {
  73707. return AffineTransform (1.0f, 0, dx,
  73708. 0, 1.0f, dy);
  73709. }
  73710. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73711. {
  73712. const float cosRad = std::cos (rad);
  73713. const float sinRad = std::sin (rad);
  73714. return followedBy (cosRad, -sinRad, 0,
  73715. sinRad, cosRad, 0);
  73716. }
  73717. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73718. {
  73719. const float cosRad = std::cos (rad);
  73720. const float sinRad = std::sin (rad);
  73721. return AffineTransform (cosRad, -sinRad, 0,
  73722. sinRad, cosRad, 0);
  73723. }
  73724. const AffineTransform AffineTransform::rotated (const float angle,
  73725. const float pivotX,
  73726. const float pivotY) const throw()
  73727. {
  73728. return translated (-pivotX, -pivotY)
  73729. .rotated (angle)
  73730. .translated (pivotX, pivotY);
  73731. }
  73732. const AffineTransform AffineTransform::rotation (const float angle,
  73733. const float pivotX,
  73734. const float pivotY) throw()
  73735. {
  73736. return translation (-pivotX, -pivotY)
  73737. .rotated (angle)
  73738. .translated (pivotX, pivotY);
  73739. }
  73740. const AffineTransform AffineTransform::scaled (const float factorX,
  73741. const float factorY) const throw()
  73742. {
  73743. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73744. factorY * mat10, factorY * mat11, factorY * mat12);
  73745. }
  73746. const AffineTransform AffineTransform::scale (const float factorX,
  73747. const float factorY) throw()
  73748. {
  73749. return AffineTransform (factorX, 0, 0,
  73750. 0, factorY, 0);
  73751. }
  73752. const AffineTransform AffineTransform::sheared (const float shearX,
  73753. const float shearY) const throw()
  73754. {
  73755. return followedBy (1.0f, shearX, 0,
  73756. shearY, 1.0f, 0);
  73757. }
  73758. const AffineTransform AffineTransform::inverted() const throw()
  73759. {
  73760. double determinant = (mat00 * mat11 - mat10 * mat01);
  73761. if (determinant != 0.0)
  73762. {
  73763. determinant = 1.0 / determinant;
  73764. const float dst00 = (float) (mat11 * determinant);
  73765. const float dst10 = (float) (-mat10 * determinant);
  73766. const float dst01 = (float) (-mat01 * determinant);
  73767. const float dst11 = (float) (mat00 * determinant);
  73768. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73769. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73770. }
  73771. else
  73772. {
  73773. // singularity..
  73774. return *this;
  73775. }
  73776. }
  73777. bool AffineTransform::isSingularity() const throw()
  73778. {
  73779. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73780. }
  73781. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73782. const float x10, const float y10,
  73783. const float x01, const float y01) throw()
  73784. {
  73785. return AffineTransform (x10 - x00, x01 - x00, x00,
  73786. y10 - y00, y01 - y00, y00);
  73787. }
  73788. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73789. const float sx2, const float sy2, const float tx2, const float ty2,
  73790. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73791. {
  73792. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73793. .inverted()
  73794. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73795. }
  73796. bool AffineTransform::isOnlyTranslation() const throw()
  73797. {
  73798. return (mat01 == 0)
  73799. && (mat10 == 0)
  73800. && (mat00 == 1.0f)
  73801. && (mat11 == 1.0f);
  73802. }
  73803. END_JUCE_NAMESPACE
  73804. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73805. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73806. BEGIN_JUCE_NAMESPACE
  73807. BorderSize::BorderSize() throw()
  73808. : top (0),
  73809. left (0),
  73810. bottom (0),
  73811. right (0)
  73812. {
  73813. }
  73814. BorderSize::BorderSize (const BorderSize& other) throw()
  73815. : top (other.top),
  73816. left (other.left),
  73817. bottom (other.bottom),
  73818. right (other.right)
  73819. {
  73820. }
  73821. BorderSize::BorderSize (const int topGap,
  73822. const int leftGap,
  73823. const int bottomGap,
  73824. const int rightGap) throw()
  73825. : top (topGap),
  73826. left (leftGap),
  73827. bottom (bottomGap),
  73828. right (rightGap)
  73829. {
  73830. }
  73831. BorderSize::BorderSize (const int allGaps) throw()
  73832. : top (allGaps),
  73833. left (allGaps),
  73834. bottom (allGaps),
  73835. right (allGaps)
  73836. {
  73837. }
  73838. BorderSize::~BorderSize() throw()
  73839. {
  73840. }
  73841. void BorderSize::setTop (const int newTopGap) throw()
  73842. {
  73843. top = newTopGap;
  73844. }
  73845. void BorderSize::setLeft (const int newLeftGap) throw()
  73846. {
  73847. left = newLeftGap;
  73848. }
  73849. void BorderSize::setBottom (const int newBottomGap) throw()
  73850. {
  73851. bottom = newBottomGap;
  73852. }
  73853. void BorderSize::setRight (const int newRightGap) throw()
  73854. {
  73855. right = newRightGap;
  73856. }
  73857. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73858. {
  73859. return Rectangle<int> (r.getX() + left,
  73860. r.getY() + top,
  73861. r.getWidth() - (left + right),
  73862. r.getHeight() - (top + bottom));
  73863. }
  73864. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73865. {
  73866. r.setBounds (r.getX() + left,
  73867. r.getY() + top,
  73868. r.getWidth() - (left + right),
  73869. r.getHeight() - (top + bottom));
  73870. }
  73871. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73872. {
  73873. return Rectangle<int> (r.getX() - left,
  73874. r.getY() - top,
  73875. r.getWidth() + (left + right),
  73876. r.getHeight() + (top + bottom));
  73877. }
  73878. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73879. {
  73880. r.setBounds (r.getX() - left,
  73881. r.getY() - top,
  73882. r.getWidth() + (left + right),
  73883. r.getHeight() + (top + bottom));
  73884. }
  73885. bool BorderSize::operator== (const BorderSize& other) const throw()
  73886. {
  73887. return top == other.top
  73888. && left == other.left
  73889. && bottom == other.bottom
  73890. && right == other.right;
  73891. }
  73892. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73893. {
  73894. return ! operator== (other);
  73895. }
  73896. END_JUCE_NAMESPACE
  73897. /*** End of inlined file: juce_BorderSize.cpp ***/
  73898. /*** Start of inlined file: juce_Path.cpp ***/
  73899. BEGIN_JUCE_NAMESPACE
  73900. // tests that some co-ords aren't NaNs
  73901. #define CHECK_COORDS_ARE_VALID(x, y) \
  73902. jassert (x == x && y == y);
  73903. namespace PathHelpers
  73904. {
  73905. static const float ellipseAngularIncrement = 0.05f;
  73906. static const String nextToken (const juce_wchar*& t)
  73907. {
  73908. while (CharacterFunctions::isWhitespace (*t))
  73909. ++t;
  73910. const juce_wchar* const start = t;
  73911. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73912. ++t;
  73913. return String (start, (int) (t - start));
  73914. }
  73915. }
  73916. const float Path::lineMarker = 100001.0f;
  73917. const float Path::moveMarker = 100002.0f;
  73918. const float Path::quadMarker = 100003.0f;
  73919. const float Path::cubicMarker = 100004.0f;
  73920. const float Path::closeSubPathMarker = 100005.0f;
  73921. Path::Path()
  73922. : numElements (0),
  73923. pathXMin (0),
  73924. pathXMax (0),
  73925. pathYMin (0),
  73926. pathYMax (0),
  73927. useNonZeroWinding (true)
  73928. {
  73929. }
  73930. Path::~Path()
  73931. {
  73932. }
  73933. Path::Path (const Path& other)
  73934. : numElements (other.numElements),
  73935. pathXMin (other.pathXMin),
  73936. pathXMax (other.pathXMax),
  73937. pathYMin (other.pathYMin),
  73938. pathYMax (other.pathYMax),
  73939. useNonZeroWinding (other.useNonZeroWinding)
  73940. {
  73941. if (numElements > 0)
  73942. {
  73943. data.setAllocatedSize ((int) numElements);
  73944. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73945. }
  73946. }
  73947. Path& Path::operator= (const Path& other)
  73948. {
  73949. if (this != &other)
  73950. {
  73951. data.ensureAllocatedSize ((int) other.numElements);
  73952. numElements = other.numElements;
  73953. pathXMin = other.pathXMin;
  73954. pathXMax = other.pathXMax;
  73955. pathYMin = other.pathYMin;
  73956. pathYMax = other.pathYMax;
  73957. useNonZeroWinding = other.useNonZeroWinding;
  73958. if (numElements > 0)
  73959. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73960. }
  73961. return *this;
  73962. }
  73963. bool Path::operator== (const Path& other) const throw()
  73964. {
  73965. return ! operator!= (other);
  73966. }
  73967. bool Path::operator!= (const Path& other) const throw()
  73968. {
  73969. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  73970. return true;
  73971. for (size_t i = 0; i < numElements; ++i)
  73972. if (data.elements[i] != other.data.elements[i])
  73973. return true;
  73974. return false;
  73975. }
  73976. void Path::clear() throw()
  73977. {
  73978. numElements = 0;
  73979. pathXMin = 0;
  73980. pathYMin = 0;
  73981. pathYMax = 0;
  73982. pathXMax = 0;
  73983. }
  73984. void Path::swapWithPath (Path& other) throw()
  73985. {
  73986. data.swapWith (other.data);
  73987. swapVariables <size_t> (numElements, other.numElements);
  73988. swapVariables <float> (pathXMin, other.pathXMin);
  73989. swapVariables <float> (pathXMax, other.pathXMax);
  73990. swapVariables <float> (pathYMin, other.pathYMin);
  73991. swapVariables <float> (pathYMax, other.pathYMax);
  73992. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  73993. }
  73994. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  73995. {
  73996. useNonZeroWinding = isNonZero;
  73997. }
  73998. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  73999. const bool preserveProportions) throw()
  74000. {
  74001. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74002. }
  74003. bool Path::isEmpty() const throw()
  74004. {
  74005. size_t i = 0;
  74006. while (i < numElements)
  74007. {
  74008. const float type = data.elements [i++];
  74009. if (type == moveMarker)
  74010. {
  74011. i += 2;
  74012. }
  74013. else if (type == lineMarker
  74014. || type == quadMarker
  74015. || type == cubicMarker)
  74016. {
  74017. return false;
  74018. }
  74019. }
  74020. return true;
  74021. }
  74022. const Rectangle<float> Path::getBounds() const throw()
  74023. {
  74024. return Rectangle<float> (pathXMin, pathYMin,
  74025. pathXMax - pathXMin,
  74026. pathYMax - pathYMin);
  74027. }
  74028. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74029. {
  74030. return getBounds().transformed (transform);
  74031. }
  74032. void Path::startNewSubPath (const float x, const float y)
  74033. {
  74034. CHECK_COORDS_ARE_VALID (x, y);
  74035. if (numElements == 0)
  74036. {
  74037. pathXMin = pathXMax = x;
  74038. pathYMin = pathYMax = y;
  74039. }
  74040. else
  74041. {
  74042. pathXMin = jmin (pathXMin, x);
  74043. pathXMax = jmax (pathXMax, x);
  74044. pathYMin = jmin (pathYMin, y);
  74045. pathYMax = jmax (pathYMax, y);
  74046. }
  74047. data.ensureAllocatedSize ((int) numElements + 3);
  74048. data.elements [numElements++] = moveMarker;
  74049. data.elements [numElements++] = x;
  74050. data.elements [numElements++] = y;
  74051. }
  74052. void Path::startNewSubPath (const Point<float>& start)
  74053. {
  74054. startNewSubPath (start.getX(), start.getY());
  74055. }
  74056. void Path::lineTo (const float x, const float y)
  74057. {
  74058. CHECK_COORDS_ARE_VALID (x, y);
  74059. if (numElements == 0)
  74060. startNewSubPath (0, 0);
  74061. data.ensureAllocatedSize ((int) numElements + 3);
  74062. data.elements [numElements++] = lineMarker;
  74063. data.elements [numElements++] = x;
  74064. data.elements [numElements++] = y;
  74065. pathXMin = jmin (pathXMin, x);
  74066. pathXMax = jmax (pathXMax, x);
  74067. pathYMin = jmin (pathYMin, y);
  74068. pathYMax = jmax (pathYMax, y);
  74069. }
  74070. void Path::lineTo (const Point<float>& end)
  74071. {
  74072. lineTo (end.getX(), end.getY());
  74073. }
  74074. void Path::quadraticTo (const float x1, const float y1,
  74075. const float x2, const float y2)
  74076. {
  74077. CHECK_COORDS_ARE_VALID (x1, y1);
  74078. CHECK_COORDS_ARE_VALID (x2, y2);
  74079. if (numElements == 0)
  74080. startNewSubPath (0, 0);
  74081. data.ensureAllocatedSize ((int) numElements + 5);
  74082. data.elements [numElements++] = quadMarker;
  74083. data.elements [numElements++] = x1;
  74084. data.elements [numElements++] = y1;
  74085. data.elements [numElements++] = x2;
  74086. data.elements [numElements++] = y2;
  74087. pathXMin = jmin (pathXMin, x1, x2);
  74088. pathXMax = jmax (pathXMax, x1, x2);
  74089. pathYMin = jmin (pathYMin, y1, y2);
  74090. pathYMax = jmax (pathYMax, y1, y2);
  74091. }
  74092. void Path::quadraticTo (const Point<float>& controlPoint,
  74093. const Point<float>& endPoint)
  74094. {
  74095. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74096. endPoint.getX(), endPoint.getY());
  74097. }
  74098. void Path::cubicTo (const float x1, const float y1,
  74099. const float x2, const float y2,
  74100. const float x3, const float y3)
  74101. {
  74102. CHECK_COORDS_ARE_VALID (x1, y1);
  74103. CHECK_COORDS_ARE_VALID (x2, y2);
  74104. CHECK_COORDS_ARE_VALID (x3, y3);
  74105. if (numElements == 0)
  74106. startNewSubPath (0, 0);
  74107. data.ensureAllocatedSize ((int) numElements + 7);
  74108. data.elements [numElements++] = cubicMarker;
  74109. data.elements [numElements++] = x1;
  74110. data.elements [numElements++] = y1;
  74111. data.elements [numElements++] = x2;
  74112. data.elements [numElements++] = y2;
  74113. data.elements [numElements++] = x3;
  74114. data.elements [numElements++] = y3;
  74115. pathXMin = jmin (pathXMin, x1, x2, x3);
  74116. pathXMax = jmax (pathXMax, x1, x2, x3);
  74117. pathYMin = jmin (pathYMin, y1, y2, y3);
  74118. pathYMax = jmax (pathYMax, y1, y2, y3);
  74119. }
  74120. void Path::cubicTo (const Point<float>& controlPoint1,
  74121. const Point<float>& controlPoint2,
  74122. const Point<float>& endPoint)
  74123. {
  74124. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74125. controlPoint2.getX(), controlPoint2.getY(),
  74126. endPoint.getX(), endPoint.getY());
  74127. }
  74128. void Path::closeSubPath()
  74129. {
  74130. if (numElements > 0
  74131. && data.elements [numElements - 1] != closeSubPathMarker)
  74132. {
  74133. data.ensureAllocatedSize ((int) numElements + 1);
  74134. data.elements [numElements++] = closeSubPathMarker;
  74135. }
  74136. }
  74137. const Point<float> Path::getCurrentPosition() const
  74138. {
  74139. size_t i = numElements - 1;
  74140. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74141. {
  74142. while (i >= 0)
  74143. {
  74144. if (data.elements[i] == moveMarker)
  74145. {
  74146. i += 2;
  74147. break;
  74148. }
  74149. --i;
  74150. }
  74151. }
  74152. if (i > 0)
  74153. return Point<float> (data.elements [i - 1], data.elements [i]);
  74154. return Point<float>();
  74155. }
  74156. void Path::addRectangle (const float x, const float y,
  74157. const float w, const float h)
  74158. {
  74159. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74160. if (w < 0)
  74161. swapVariables (x1, x2);
  74162. if (h < 0)
  74163. swapVariables (y1, y2);
  74164. data.ensureAllocatedSize ((int) numElements + 13);
  74165. if (numElements == 0)
  74166. {
  74167. pathXMin = x1;
  74168. pathXMax = x2;
  74169. pathYMin = y1;
  74170. pathYMax = y2;
  74171. }
  74172. else
  74173. {
  74174. pathXMin = jmin (pathXMin, x1);
  74175. pathXMax = jmax (pathXMax, x2);
  74176. pathYMin = jmin (pathYMin, y1);
  74177. pathYMax = jmax (pathYMax, y2);
  74178. }
  74179. data.elements [numElements++] = moveMarker;
  74180. data.elements [numElements++] = x1;
  74181. data.elements [numElements++] = y2;
  74182. data.elements [numElements++] = lineMarker;
  74183. data.elements [numElements++] = x1;
  74184. data.elements [numElements++] = y1;
  74185. data.elements [numElements++] = lineMarker;
  74186. data.elements [numElements++] = x2;
  74187. data.elements [numElements++] = y1;
  74188. data.elements [numElements++] = lineMarker;
  74189. data.elements [numElements++] = x2;
  74190. data.elements [numElements++] = y2;
  74191. data.elements [numElements++] = closeSubPathMarker;
  74192. }
  74193. void Path::addRectangle (const Rectangle<int>& rectangle)
  74194. {
  74195. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  74196. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  74197. }
  74198. void Path::addRoundedRectangle (const float x, const float y,
  74199. const float w, const float h,
  74200. float csx,
  74201. float csy)
  74202. {
  74203. csx = jmin (csx, w * 0.5f);
  74204. csy = jmin (csy, h * 0.5f);
  74205. const float cs45x = csx * 0.45f;
  74206. const float cs45y = csy * 0.45f;
  74207. const float x2 = x + w;
  74208. const float y2 = y + h;
  74209. startNewSubPath (x + csx, y);
  74210. lineTo (x2 - csx, y);
  74211. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74212. lineTo (x2, y2 - csy);
  74213. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74214. lineTo (x + csx, y2);
  74215. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74216. lineTo (x, y + csy);
  74217. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74218. closeSubPath();
  74219. }
  74220. void Path::addRoundedRectangle (const float x, const float y,
  74221. const float w, const float h,
  74222. float cs)
  74223. {
  74224. addRoundedRectangle (x, y, w, h, cs, cs);
  74225. }
  74226. void Path::addTriangle (const float x1, const float y1,
  74227. const float x2, const float y2,
  74228. const float x3, const float y3)
  74229. {
  74230. startNewSubPath (x1, y1);
  74231. lineTo (x2, y2);
  74232. lineTo (x3, y3);
  74233. closeSubPath();
  74234. }
  74235. void Path::addQuadrilateral (const float x1, const float y1,
  74236. const float x2, const float y2,
  74237. const float x3, const float y3,
  74238. const float x4, const float y4)
  74239. {
  74240. startNewSubPath (x1, y1);
  74241. lineTo (x2, y2);
  74242. lineTo (x3, y3);
  74243. lineTo (x4, y4);
  74244. closeSubPath();
  74245. }
  74246. void Path::addEllipse (const float x, const float y,
  74247. const float w, const float h)
  74248. {
  74249. const float hw = w * 0.5f;
  74250. const float hw55 = hw * 0.55f;
  74251. const float hh = h * 0.5f;
  74252. const float hh45 = hh * 0.55f;
  74253. const float cx = x + hw;
  74254. const float cy = y + hh;
  74255. startNewSubPath (cx, cy - hh);
  74256. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74257. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74258. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74259. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74260. closeSubPath();
  74261. }
  74262. void Path::addArc (const float x, const float y,
  74263. const float w, const float h,
  74264. const float fromRadians,
  74265. const float toRadians,
  74266. const bool startAsNewSubPath)
  74267. {
  74268. const float radiusX = w / 2.0f;
  74269. const float radiusY = h / 2.0f;
  74270. addCentredArc (x + radiusX,
  74271. y + radiusY,
  74272. radiusX, radiusY,
  74273. 0.0f,
  74274. fromRadians, toRadians,
  74275. startAsNewSubPath);
  74276. }
  74277. void Path::addCentredArc (const float centreX, const float centreY,
  74278. const float radiusX, const float radiusY,
  74279. const float rotationOfEllipse,
  74280. const float fromRadians,
  74281. const float toRadians,
  74282. const bool startAsNewSubPath)
  74283. {
  74284. if (radiusX > 0.0f && radiusY > 0.0f)
  74285. {
  74286. const Point<float> centre (centreX, centreY);
  74287. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74288. float angle = fromRadians;
  74289. if (startAsNewSubPath)
  74290. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74291. if (fromRadians < toRadians)
  74292. {
  74293. if (startAsNewSubPath)
  74294. angle += PathHelpers::ellipseAngularIncrement;
  74295. while (angle < toRadians)
  74296. {
  74297. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74298. angle += PathHelpers::ellipseAngularIncrement;
  74299. }
  74300. }
  74301. else
  74302. {
  74303. if (startAsNewSubPath)
  74304. angle -= PathHelpers::ellipseAngularIncrement;
  74305. while (angle > toRadians)
  74306. {
  74307. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74308. angle -= PathHelpers::ellipseAngularIncrement;
  74309. }
  74310. }
  74311. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74312. }
  74313. }
  74314. void Path::addPieSegment (const float x, const float y,
  74315. const float width, const float height,
  74316. const float fromRadians,
  74317. const float toRadians,
  74318. const float innerCircleProportionalSize)
  74319. {
  74320. float radiusX = width * 0.5f;
  74321. float radiusY = height * 0.5f;
  74322. const Point<float> centre (x + radiusX, y + radiusY);
  74323. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74324. addArc (x, y, width, height, fromRadians, toRadians);
  74325. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74326. {
  74327. closeSubPath();
  74328. if (innerCircleProportionalSize > 0)
  74329. {
  74330. radiusX *= innerCircleProportionalSize;
  74331. radiusY *= innerCircleProportionalSize;
  74332. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74333. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74334. }
  74335. }
  74336. else
  74337. {
  74338. if (innerCircleProportionalSize > 0)
  74339. {
  74340. radiusX *= innerCircleProportionalSize;
  74341. radiusY *= innerCircleProportionalSize;
  74342. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74343. }
  74344. else
  74345. {
  74346. lineTo (centre);
  74347. }
  74348. }
  74349. closeSubPath();
  74350. }
  74351. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74352. {
  74353. const Line<float> reversed (line.reversed());
  74354. lineThickness *= 0.5f;
  74355. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74356. lineTo (line.getPointAlongLine (0, -lineThickness));
  74357. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74358. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74359. closeSubPath();
  74360. }
  74361. void Path::addArrow (const Line<float>& line, float lineThickness,
  74362. float arrowheadWidth, float arrowheadLength)
  74363. {
  74364. const Line<float> reversed (line.reversed());
  74365. lineThickness *= 0.5f;
  74366. arrowheadWidth *= 0.5f;
  74367. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74368. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74369. lineTo (line.getPointAlongLine (0, -lineThickness));
  74370. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74371. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74372. lineTo (line.getEnd());
  74373. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74374. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74375. closeSubPath();
  74376. }
  74377. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74378. const float radius, const float startAngle)
  74379. {
  74380. jassert (numberOfSides > 1); // this would be silly.
  74381. if (numberOfSides > 1)
  74382. {
  74383. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74384. for (int i = 0; i < numberOfSides; ++i)
  74385. {
  74386. const float angle = startAngle + i * angleBetweenPoints;
  74387. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74388. if (i == 0)
  74389. startNewSubPath (p);
  74390. else
  74391. lineTo (p);
  74392. }
  74393. closeSubPath();
  74394. }
  74395. }
  74396. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74397. const float innerRadius, const float outerRadius, const float startAngle)
  74398. {
  74399. jassert (numberOfPoints > 1); // this would be silly.
  74400. if (numberOfPoints > 1)
  74401. {
  74402. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74403. for (int i = 0; i < numberOfPoints; ++i)
  74404. {
  74405. const float angle = startAngle + i * angleBetweenPoints;
  74406. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74407. if (i == 0)
  74408. startNewSubPath (p);
  74409. else
  74410. lineTo (p);
  74411. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74412. }
  74413. closeSubPath();
  74414. }
  74415. }
  74416. void Path::addBubble (float x, float y,
  74417. float w, float h,
  74418. float cs,
  74419. float tipX,
  74420. float tipY,
  74421. int whichSide,
  74422. float arrowPos,
  74423. float arrowWidth)
  74424. {
  74425. if (w > 1.0f && h > 1.0f)
  74426. {
  74427. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74428. const float cs2 = 2.0f * cs;
  74429. startNewSubPath (x + cs, y);
  74430. if (whichSide == 0)
  74431. {
  74432. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74433. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74434. lineTo (arrowX1, y);
  74435. lineTo (tipX, tipY);
  74436. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74437. }
  74438. lineTo (x + w - cs, y);
  74439. if (cs > 0.0f)
  74440. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74441. if (whichSide == 3)
  74442. {
  74443. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74444. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74445. lineTo (x + w, arrowY1);
  74446. lineTo (tipX, tipY);
  74447. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74448. }
  74449. lineTo (x + w, y + h - cs);
  74450. if (cs > 0.0f)
  74451. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74452. if (whichSide == 2)
  74453. {
  74454. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74455. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74456. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74457. lineTo (tipX, tipY);
  74458. lineTo (arrowX1, y + h);
  74459. }
  74460. lineTo (x + cs, y + h);
  74461. if (cs > 0.0f)
  74462. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74463. if (whichSide == 1)
  74464. {
  74465. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74466. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74467. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74468. lineTo (tipX, tipY);
  74469. lineTo (x, arrowY1);
  74470. }
  74471. lineTo (x, y + cs);
  74472. if (cs > 0.0f)
  74473. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74474. closeSubPath();
  74475. }
  74476. }
  74477. void Path::addPath (const Path& other)
  74478. {
  74479. size_t i = 0;
  74480. while (i < other.numElements)
  74481. {
  74482. const float type = other.data.elements [i++];
  74483. if (type == moveMarker)
  74484. {
  74485. startNewSubPath (other.data.elements [i],
  74486. other.data.elements [i + 1]);
  74487. i += 2;
  74488. }
  74489. else if (type == lineMarker)
  74490. {
  74491. lineTo (other.data.elements [i],
  74492. other.data.elements [i + 1]);
  74493. i += 2;
  74494. }
  74495. else if (type == quadMarker)
  74496. {
  74497. quadraticTo (other.data.elements [i],
  74498. other.data.elements [i + 1],
  74499. other.data.elements [i + 2],
  74500. other.data.elements [i + 3]);
  74501. i += 4;
  74502. }
  74503. else if (type == cubicMarker)
  74504. {
  74505. cubicTo (other.data.elements [i],
  74506. other.data.elements [i + 1],
  74507. other.data.elements [i + 2],
  74508. other.data.elements [i + 3],
  74509. other.data.elements [i + 4],
  74510. other.data.elements [i + 5]);
  74511. i += 6;
  74512. }
  74513. else if (type == closeSubPathMarker)
  74514. {
  74515. closeSubPath();
  74516. }
  74517. else
  74518. {
  74519. // something's gone wrong with the element list!
  74520. jassertfalse;
  74521. }
  74522. }
  74523. }
  74524. void Path::addPath (const Path& other,
  74525. const AffineTransform& transformToApply)
  74526. {
  74527. size_t i = 0;
  74528. while (i < other.numElements)
  74529. {
  74530. const float type = other.data.elements [i++];
  74531. if (type == closeSubPathMarker)
  74532. {
  74533. closeSubPath();
  74534. }
  74535. else
  74536. {
  74537. float x = other.data.elements [i++];
  74538. float y = other.data.elements [i++];
  74539. transformToApply.transformPoint (x, y);
  74540. if (type == moveMarker)
  74541. {
  74542. startNewSubPath (x, y);
  74543. }
  74544. else if (type == lineMarker)
  74545. {
  74546. lineTo (x, y);
  74547. }
  74548. else if (type == quadMarker)
  74549. {
  74550. float x2 = other.data.elements [i++];
  74551. float y2 = other.data.elements [i++];
  74552. transformToApply.transformPoint (x2, y2);
  74553. quadraticTo (x, y, x2, y2);
  74554. }
  74555. else if (type == cubicMarker)
  74556. {
  74557. float x2 = other.data.elements [i++];
  74558. float y2 = other.data.elements [i++];
  74559. float x3 = other.data.elements [i++];
  74560. float y3 = other.data.elements [i++];
  74561. transformToApply.transformPoints (x2, y2, x3, y3);
  74562. cubicTo (x, y, x2, y2, x3, y3);
  74563. }
  74564. else
  74565. {
  74566. // something's gone wrong with the element list!
  74567. jassertfalse;
  74568. }
  74569. }
  74570. }
  74571. }
  74572. void Path::applyTransform (const AffineTransform& transform) throw()
  74573. {
  74574. size_t i = 0;
  74575. pathYMin = pathXMin = 0;
  74576. pathYMax = pathXMax = 0;
  74577. bool setMaxMin = false;
  74578. while (i < numElements)
  74579. {
  74580. const float type = data.elements [i++];
  74581. if (type == moveMarker)
  74582. {
  74583. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74584. if (setMaxMin)
  74585. {
  74586. pathXMin = jmin (pathXMin, data.elements [i]);
  74587. pathXMax = jmax (pathXMax, data.elements [i]);
  74588. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74589. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74590. }
  74591. else
  74592. {
  74593. pathXMin = pathXMax = data.elements [i];
  74594. pathYMin = pathYMax = data.elements [i + 1];
  74595. setMaxMin = true;
  74596. }
  74597. i += 2;
  74598. }
  74599. else if (type == lineMarker)
  74600. {
  74601. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74602. pathXMin = jmin (pathXMin, data.elements [i]);
  74603. pathXMax = jmax (pathXMax, data.elements [i]);
  74604. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74605. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74606. i += 2;
  74607. }
  74608. else if (type == quadMarker)
  74609. {
  74610. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74611. data.elements [i + 2], data.elements [i + 3]);
  74612. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74613. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74614. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74615. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74616. i += 4;
  74617. }
  74618. else if (type == cubicMarker)
  74619. {
  74620. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74621. data.elements [i + 2], data.elements [i + 3],
  74622. data.elements [i + 4], data.elements [i + 5]);
  74623. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74624. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74625. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74626. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74627. i += 6;
  74628. }
  74629. }
  74630. }
  74631. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74632. const float w, const float h,
  74633. const bool preserveProportions,
  74634. const Justification& justification) const
  74635. {
  74636. Rectangle<float> bounds (getBounds());
  74637. if (preserveProportions)
  74638. {
  74639. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74640. return AffineTransform::identity;
  74641. float newW, newH;
  74642. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74643. if (srcRatio > h / w)
  74644. {
  74645. newW = h / srcRatio;
  74646. newH = h;
  74647. }
  74648. else
  74649. {
  74650. newW = w;
  74651. newH = w * srcRatio;
  74652. }
  74653. float newXCentre = x;
  74654. float newYCentre = y;
  74655. if (justification.testFlags (Justification::left))
  74656. newXCentre += newW * 0.5f;
  74657. else if (justification.testFlags (Justification::right))
  74658. newXCentre += w - newW * 0.5f;
  74659. else
  74660. newXCentre += w * 0.5f;
  74661. if (justification.testFlags (Justification::top))
  74662. newYCentre += newH * 0.5f;
  74663. else if (justification.testFlags (Justification::bottom))
  74664. newYCentre += h - newH * 0.5f;
  74665. else
  74666. newYCentre += h * 0.5f;
  74667. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74668. bounds.getHeight() * -0.5f - bounds.getY())
  74669. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74670. .translated (newXCentre, newYCentre);
  74671. }
  74672. else
  74673. {
  74674. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74675. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74676. .translated (x, y);
  74677. }
  74678. }
  74679. bool Path::contains (const float x, const float y, const float tolerence) const
  74680. {
  74681. if (x <= pathXMin || x >= pathXMax
  74682. || y <= pathYMin || y >= pathYMax)
  74683. return false;
  74684. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74685. int positiveCrossings = 0;
  74686. int negativeCrossings = 0;
  74687. while (i.next())
  74688. {
  74689. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74690. {
  74691. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74692. if (intersectX <= x)
  74693. {
  74694. if (i.y1 < i.y2)
  74695. ++positiveCrossings;
  74696. else
  74697. ++negativeCrossings;
  74698. }
  74699. }
  74700. }
  74701. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74702. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74703. }
  74704. bool Path::contains (const Point<float>& point, const float tolerence) const
  74705. {
  74706. return contains (point.getX(), point.getY(), tolerence);
  74707. }
  74708. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74709. {
  74710. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74711. Point<float> intersection;
  74712. while (i.next())
  74713. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74714. return true;
  74715. return false;
  74716. }
  74717. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74718. {
  74719. Line<float> result (line);
  74720. const bool startInside = contains (line.getStart());
  74721. const bool endInside = contains (line.getEnd());
  74722. if (startInside == endInside)
  74723. {
  74724. if (keepSectionOutsidePath == startInside)
  74725. result = Line<float>();
  74726. }
  74727. else
  74728. {
  74729. PathFlatteningIterator i (*this, AffineTransform::identity);
  74730. Point<float> intersection;
  74731. while (i.next())
  74732. {
  74733. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74734. {
  74735. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74736. result.setStart (intersection);
  74737. else
  74738. result.setEnd (intersection);
  74739. }
  74740. }
  74741. }
  74742. return result;
  74743. }
  74744. float Path::getLength (const AffineTransform& transform) const
  74745. {
  74746. float length = 0;
  74747. PathFlatteningIterator i (*this, transform);
  74748. while (i.next())
  74749. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74750. return length;
  74751. }
  74752. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74753. {
  74754. PathFlatteningIterator i (*this, transform);
  74755. while (i.next())
  74756. {
  74757. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74758. const float lineLength = line.getLength();
  74759. if (distanceFromStart <= lineLength)
  74760. return line.getPointAlongLine (distanceFromStart);
  74761. distanceFromStart -= lineLength;
  74762. }
  74763. return Point<float> (i.x2, i.y2);
  74764. }
  74765. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74766. const AffineTransform& transform) const
  74767. {
  74768. PathFlatteningIterator i (*this, transform);
  74769. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74770. float length = 0;
  74771. Point<float> pointOnLine;
  74772. while (i.next())
  74773. {
  74774. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74775. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74776. if (distance < bestDistance)
  74777. {
  74778. bestDistance = distance;
  74779. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74780. pointOnPath = pointOnLine;
  74781. }
  74782. length += line.getLength();
  74783. }
  74784. return bestPosition;
  74785. }
  74786. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74787. {
  74788. if (cornerRadius <= 0.01f)
  74789. return *this;
  74790. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74791. size_t n = 0;
  74792. bool lastWasLine = false, firstWasLine = false;
  74793. Path p;
  74794. while (n < numElements)
  74795. {
  74796. const float type = data.elements [n++];
  74797. if (type == moveMarker)
  74798. {
  74799. indexOfPathStart = p.numElements;
  74800. indexOfPathStartThis = n - 1;
  74801. const float x = data.elements [n++];
  74802. const float y = data.elements [n++];
  74803. p.startNewSubPath (x, y);
  74804. lastWasLine = false;
  74805. firstWasLine = (data.elements [n] == lineMarker);
  74806. }
  74807. else if (type == lineMarker || type == closeSubPathMarker)
  74808. {
  74809. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74810. if (type == lineMarker)
  74811. {
  74812. endX = data.elements [n++];
  74813. endY = data.elements [n++];
  74814. if (n > 8)
  74815. {
  74816. startX = data.elements [n - 8];
  74817. startY = data.elements [n - 7];
  74818. joinX = data.elements [n - 5];
  74819. joinY = data.elements [n - 4];
  74820. }
  74821. }
  74822. else
  74823. {
  74824. endX = data.elements [indexOfPathStartThis + 1];
  74825. endY = data.elements [indexOfPathStartThis + 2];
  74826. if (n > 6)
  74827. {
  74828. startX = data.elements [n - 6];
  74829. startY = data.elements [n - 5];
  74830. joinX = data.elements [n - 3];
  74831. joinY = data.elements [n - 2];
  74832. }
  74833. }
  74834. if (lastWasLine)
  74835. {
  74836. const double len1 = juce_hypot (startX - joinX,
  74837. startY - joinY);
  74838. if (len1 > 0)
  74839. {
  74840. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74841. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74842. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74843. }
  74844. const double len2 = juce_hypot (endX - joinX,
  74845. endY - joinY);
  74846. if (len2 > 0)
  74847. {
  74848. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74849. p.quadraticTo (joinX, joinY,
  74850. (float) (joinX + (endX - joinX) * propNeeded),
  74851. (float) (joinY + (endY - joinY) * propNeeded));
  74852. }
  74853. p.lineTo (endX, endY);
  74854. }
  74855. else if (type == lineMarker)
  74856. {
  74857. p.lineTo (endX, endY);
  74858. lastWasLine = true;
  74859. }
  74860. if (type == closeSubPathMarker)
  74861. {
  74862. if (firstWasLine)
  74863. {
  74864. startX = data.elements [n - 3];
  74865. startY = data.elements [n - 2];
  74866. joinX = endX;
  74867. joinY = endY;
  74868. endX = data.elements [indexOfPathStartThis + 4];
  74869. endY = data.elements [indexOfPathStartThis + 5];
  74870. const double len1 = juce_hypot (startX - joinX,
  74871. startY - joinY);
  74872. if (len1 > 0)
  74873. {
  74874. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74875. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74876. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74877. }
  74878. const double len2 = juce_hypot (endX - joinX,
  74879. endY - joinY);
  74880. if (len2 > 0)
  74881. {
  74882. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74883. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74884. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74885. p.quadraticTo (joinX, joinY, endX, endY);
  74886. p.data.elements [indexOfPathStart + 1] = endX;
  74887. p.data.elements [indexOfPathStart + 2] = endY;
  74888. }
  74889. }
  74890. p.closeSubPath();
  74891. }
  74892. }
  74893. else if (type == quadMarker)
  74894. {
  74895. lastWasLine = false;
  74896. const float x1 = data.elements [n++];
  74897. const float y1 = data.elements [n++];
  74898. const float x2 = data.elements [n++];
  74899. const float y2 = data.elements [n++];
  74900. p.quadraticTo (x1, y1, x2, y2);
  74901. }
  74902. else if (type == cubicMarker)
  74903. {
  74904. lastWasLine = false;
  74905. const float x1 = data.elements [n++];
  74906. const float y1 = data.elements [n++];
  74907. const float x2 = data.elements [n++];
  74908. const float y2 = data.elements [n++];
  74909. const float x3 = data.elements [n++];
  74910. const float y3 = data.elements [n++];
  74911. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74912. }
  74913. }
  74914. return p;
  74915. }
  74916. void Path::loadPathFromStream (InputStream& source)
  74917. {
  74918. while (! source.isExhausted())
  74919. {
  74920. switch (source.readByte())
  74921. {
  74922. case 'm':
  74923. {
  74924. const float x = source.readFloat();
  74925. const float y = source.readFloat();
  74926. startNewSubPath (x, y);
  74927. break;
  74928. }
  74929. case 'l':
  74930. {
  74931. const float x = source.readFloat();
  74932. const float y = source.readFloat();
  74933. lineTo (x, y);
  74934. break;
  74935. }
  74936. case 'q':
  74937. {
  74938. const float x1 = source.readFloat();
  74939. const float y1 = source.readFloat();
  74940. const float x2 = source.readFloat();
  74941. const float y2 = source.readFloat();
  74942. quadraticTo (x1, y1, x2, y2);
  74943. break;
  74944. }
  74945. case 'b':
  74946. {
  74947. const float x1 = source.readFloat();
  74948. const float y1 = source.readFloat();
  74949. const float x2 = source.readFloat();
  74950. const float y2 = source.readFloat();
  74951. const float x3 = source.readFloat();
  74952. const float y3 = source.readFloat();
  74953. cubicTo (x1, y1, x2, y2, x3, y3);
  74954. break;
  74955. }
  74956. case 'c':
  74957. closeSubPath();
  74958. break;
  74959. case 'n':
  74960. useNonZeroWinding = true;
  74961. break;
  74962. case 'z':
  74963. useNonZeroWinding = false;
  74964. break;
  74965. case 'e':
  74966. return; // end of path marker
  74967. default:
  74968. jassertfalse; // illegal char in the stream
  74969. break;
  74970. }
  74971. }
  74972. }
  74973. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  74974. {
  74975. MemoryInputStream in (pathData, numberOfBytes, false);
  74976. loadPathFromStream (in);
  74977. }
  74978. void Path::writePathToStream (OutputStream& dest) const
  74979. {
  74980. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  74981. size_t i = 0;
  74982. while (i < numElements)
  74983. {
  74984. const float type = data.elements [i++];
  74985. if (type == moveMarker)
  74986. {
  74987. dest.writeByte ('m');
  74988. dest.writeFloat (data.elements [i++]);
  74989. dest.writeFloat (data.elements [i++]);
  74990. }
  74991. else if (type == lineMarker)
  74992. {
  74993. dest.writeByte ('l');
  74994. dest.writeFloat (data.elements [i++]);
  74995. dest.writeFloat (data.elements [i++]);
  74996. }
  74997. else if (type == quadMarker)
  74998. {
  74999. dest.writeByte ('q');
  75000. dest.writeFloat (data.elements [i++]);
  75001. dest.writeFloat (data.elements [i++]);
  75002. dest.writeFloat (data.elements [i++]);
  75003. dest.writeFloat (data.elements [i++]);
  75004. }
  75005. else if (type == cubicMarker)
  75006. {
  75007. dest.writeByte ('b');
  75008. dest.writeFloat (data.elements [i++]);
  75009. dest.writeFloat (data.elements [i++]);
  75010. dest.writeFloat (data.elements [i++]);
  75011. dest.writeFloat (data.elements [i++]);
  75012. dest.writeFloat (data.elements [i++]);
  75013. dest.writeFloat (data.elements [i++]);
  75014. }
  75015. else if (type == closeSubPathMarker)
  75016. {
  75017. dest.writeByte ('c');
  75018. }
  75019. }
  75020. dest.writeByte ('e'); // marks the end-of-path
  75021. }
  75022. const String Path::toString() const
  75023. {
  75024. MemoryOutputStream s (2048);
  75025. if (! useNonZeroWinding)
  75026. s << 'a';
  75027. size_t i = 0;
  75028. float lastMarker = 0.0f;
  75029. while (i < numElements)
  75030. {
  75031. const float marker = data.elements [i++];
  75032. char markerChar = 0;
  75033. int numCoords = 0;
  75034. if (marker == moveMarker)
  75035. {
  75036. markerChar = 'm';
  75037. numCoords = 2;
  75038. }
  75039. else if (marker == lineMarker)
  75040. {
  75041. markerChar = 'l';
  75042. numCoords = 2;
  75043. }
  75044. else if (marker == quadMarker)
  75045. {
  75046. markerChar = 'q';
  75047. numCoords = 4;
  75048. }
  75049. else if (marker == cubicMarker)
  75050. {
  75051. markerChar = 'c';
  75052. numCoords = 6;
  75053. }
  75054. else
  75055. {
  75056. jassert (marker == closeSubPathMarker);
  75057. markerChar = 'z';
  75058. }
  75059. if (marker != lastMarker)
  75060. {
  75061. if (s.getDataSize() != 0)
  75062. s << ' ';
  75063. s << markerChar;
  75064. lastMarker = marker;
  75065. }
  75066. while (--numCoords >= 0 && i < numElements)
  75067. {
  75068. String coord (data.elements [i++], 3);
  75069. while (coord.endsWithChar ('0') && coord != "0")
  75070. coord = coord.dropLastCharacters (1);
  75071. if (coord.endsWithChar ('.'))
  75072. coord = coord.dropLastCharacters (1);
  75073. if (s.getDataSize() != 0)
  75074. s << ' ';
  75075. s << coord;
  75076. }
  75077. }
  75078. return s.toUTF8();
  75079. }
  75080. void Path::restoreFromString (const String& stringVersion)
  75081. {
  75082. clear();
  75083. setUsingNonZeroWinding (true);
  75084. const juce_wchar* t = stringVersion;
  75085. juce_wchar marker = 'm';
  75086. int numValues = 2;
  75087. float values [6];
  75088. for (;;)
  75089. {
  75090. const String token (PathHelpers::nextToken (t));
  75091. const juce_wchar firstChar = token[0];
  75092. int startNum = 0;
  75093. if (firstChar == 0)
  75094. break;
  75095. if (firstChar == 'm' || firstChar == 'l')
  75096. {
  75097. marker = firstChar;
  75098. numValues = 2;
  75099. }
  75100. else if (firstChar == 'q')
  75101. {
  75102. marker = firstChar;
  75103. numValues = 4;
  75104. }
  75105. else if (firstChar == 'c')
  75106. {
  75107. marker = firstChar;
  75108. numValues = 6;
  75109. }
  75110. else if (firstChar == 'z')
  75111. {
  75112. marker = firstChar;
  75113. numValues = 0;
  75114. }
  75115. else if (firstChar == 'a')
  75116. {
  75117. setUsingNonZeroWinding (false);
  75118. continue;
  75119. }
  75120. else
  75121. {
  75122. ++startNum;
  75123. values [0] = token.getFloatValue();
  75124. }
  75125. for (int i = startNum; i < numValues; ++i)
  75126. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75127. switch (marker)
  75128. {
  75129. case 'm':
  75130. startNewSubPath (values[0], values[1]);
  75131. break;
  75132. case 'l':
  75133. lineTo (values[0], values[1]);
  75134. break;
  75135. case 'q':
  75136. quadraticTo (values[0], values[1],
  75137. values[2], values[3]);
  75138. break;
  75139. case 'c':
  75140. cubicTo (values[0], values[1],
  75141. values[2], values[3],
  75142. values[4], values[5]);
  75143. break;
  75144. case 'z':
  75145. closeSubPath();
  75146. break;
  75147. default:
  75148. jassertfalse; // illegal string format?
  75149. break;
  75150. }
  75151. }
  75152. }
  75153. Path::Iterator::Iterator (const Path& path_)
  75154. : path (path_),
  75155. index (0)
  75156. {
  75157. }
  75158. Path::Iterator::~Iterator()
  75159. {
  75160. }
  75161. bool Path::Iterator::next()
  75162. {
  75163. const float* const elements = path.data.elements;
  75164. if (index < path.numElements)
  75165. {
  75166. const float type = elements [index++];
  75167. if (type == moveMarker)
  75168. {
  75169. elementType = startNewSubPath;
  75170. x1 = elements [index++];
  75171. y1 = elements [index++];
  75172. }
  75173. else if (type == lineMarker)
  75174. {
  75175. elementType = lineTo;
  75176. x1 = elements [index++];
  75177. y1 = elements [index++];
  75178. }
  75179. else if (type == quadMarker)
  75180. {
  75181. elementType = quadraticTo;
  75182. x1 = elements [index++];
  75183. y1 = elements [index++];
  75184. x2 = elements [index++];
  75185. y2 = elements [index++];
  75186. }
  75187. else if (type == cubicMarker)
  75188. {
  75189. elementType = cubicTo;
  75190. x1 = elements [index++];
  75191. y1 = elements [index++];
  75192. x2 = elements [index++];
  75193. y2 = elements [index++];
  75194. x3 = elements [index++];
  75195. y3 = elements [index++];
  75196. }
  75197. else if (type == closeSubPathMarker)
  75198. {
  75199. elementType = closePath;
  75200. }
  75201. return true;
  75202. }
  75203. return false;
  75204. }
  75205. END_JUCE_NAMESPACE
  75206. /*** End of inlined file: juce_Path.cpp ***/
  75207. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75208. BEGIN_JUCE_NAMESPACE
  75209. #if JUCE_MSVC && JUCE_DEBUG
  75210. #pragma optimize ("t", on)
  75211. #endif
  75212. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75213. const AffineTransform& transform_,
  75214. float tolerence_)
  75215. : x2 (0),
  75216. y2 (0),
  75217. closesSubPath (false),
  75218. subPathIndex (-1),
  75219. path (path_),
  75220. transform (transform_),
  75221. points (path_.data.elements),
  75222. tolerence (tolerence_ * tolerence_),
  75223. subPathCloseX (0),
  75224. subPathCloseY (0),
  75225. isIdentityTransform (transform_.isIdentity()),
  75226. stackBase (32),
  75227. index (0),
  75228. stackSize (32)
  75229. {
  75230. stackPos = stackBase;
  75231. }
  75232. PathFlatteningIterator::~PathFlatteningIterator()
  75233. {
  75234. }
  75235. bool PathFlatteningIterator::next()
  75236. {
  75237. x1 = x2;
  75238. y1 = y2;
  75239. float x3 = 0;
  75240. float y3 = 0;
  75241. float x4 = 0;
  75242. float y4 = 0;
  75243. float type;
  75244. for (;;)
  75245. {
  75246. if (stackPos == stackBase)
  75247. {
  75248. if (index >= path.numElements)
  75249. {
  75250. return false;
  75251. }
  75252. else
  75253. {
  75254. type = points [index++];
  75255. if (type != Path::closeSubPathMarker)
  75256. {
  75257. x2 = points [index++];
  75258. y2 = points [index++];
  75259. if (type == Path::quadMarker)
  75260. {
  75261. x3 = points [index++];
  75262. y3 = points [index++];
  75263. if (! isIdentityTransform)
  75264. transform.transformPoints (x2, y2, x3, y3);
  75265. }
  75266. else if (type == Path::cubicMarker)
  75267. {
  75268. x3 = points [index++];
  75269. y3 = points [index++];
  75270. x4 = points [index++];
  75271. y4 = points [index++];
  75272. if (! isIdentityTransform)
  75273. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75274. }
  75275. else
  75276. {
  75277. if (! isIdentityTransform)
  75278. transform.transformPoint (x2, y2);
  75279. }
  75280. }
  75281. }
  75282. }
  75283. else
  75284. {
  75285. type = *--stackPos;
  75286. if (type != Path::closeSubPathMarker)
  75287. {
  75288. x2 = *--stackPos;
  75289. y2 = *--stackPos;
  75290. if (type == Path::quadMarker)
  75291. {
  75292. x3 = *--stackPos;
  75293. y3 = *--stackPos;
  75294. }
  75295. else if (type == Path::cubicMarker)
  75296. {
  75297. x3 = *--stackPos;
  75298. y3 = *--stackPos;
  75299. x4 = *--stackPos;
  75300. y4 = *--stackPos;
  75301. }
  75302. }
  75303. }
  75304. if (type == Path::lineMarker)
  75305. {
  75306. ++subPathIndex;
  75307. closesSubPath = (stackPos == stackBase)
  75308. && (index < path.numElements)
  75309. && (points [index] == Path::closeSubPathMarker)
  75310. && x2 == subPathCloseX
  75311. && y2 == subPathCloseY;
  75312. return true;
  75313. }
  75314. else if (type == Path::quadMarker)
  75315. {
  75316. const size_t offset = (size_t) (stackPos - stackBase);
  75317. if (offset >= stackSize - 10)
  75318. {
  75319. stackSize <<= 1;
  75320. stackBase.realloc (stackSize);
  75321. stackPos = stackBase + offset;
  75322. }
  75323. const float dx1 = x1 - x2;
  75324. const float dy1 = y1 - y2;
  75325. const float dx2 = x2 - x3;
  75326. const float dy2 = y2 - y3;
  75327. const float m1x = (x1 + x2) * 0.5f;
  75328. const float m1y = (y1 + y2) * 0.5f;
  75329. const float m2x = (x2 + x3) * 0.5f;
  75330. const float m2y = (y2 + y3) * 0.5f;
  75331. const float m3x = (m1x + m2x) * 0.5f;
  75332. const float m3y = (m1y + m2y) * 0.5f;
  75333. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75334. {
  75335. *stackPos++ = y3;
  75336. *stackPos++ = x3;
  75337. *stackPos++ = m2y;
  75338. *stackPos++ = m2x;
  75339. *stackPos++ = Path::quadMarker;
  75340. *stackPos++ = m3y;
  75341. *stackPos++ = m3x;
  75342. *stackPos++ = m1y;
  75343. *stackPos++ = m1x;
  75344. *stackPos++ = Path::quadMarker;
  75345. }
  75346. else
  75347. {
  75348. *stackPos++ = y3;
  75349. *stackPos++ = x3;
  75350. *stackPos++ = Path::lineMarker;
  75351. *stackPos++ = m3y;
  75352. *stackPos++ = m3x;
  75353. *stackPos++ = Path::lineMarker;
  75354. }
  75355. jassert (stackPos < stackBase + stackSize);
  75356. }
  75357. else if (type == Path::cubicMarker)
  75358. {
  75359. const size_t offset = (size_t) (stackPos - stackBase);
  75360. if (offset >= stackSize - 16)
  75361. {
  75362. stackSize <<= 1;
  75363. stackBase.realloc (stackSize);
  75364. stackPos = stackBase + offset;
  75365. }
  75366. const float dx1 = x1 - x2;
  75367. const float dy1 = y1 - y2;
  75368. const float dx2 = x2 - x3;
  75369. const float dy2 = y2 - y3;
  75370. const float dx3 = x3 - x4;
  75371. const float dy3 = y3 - y4;
  75372. const float m1x = (x1 + x2) * 0.5f;
  75373. const float m1y = (y1 + y2) * 0.5f;
  75374. const float m2x = (x3 + x2) * 0.5f;
  75375. const float m2y = (y3 + y2) * 0.5f;
  75376. const float m3x = (x3 + x4) * 0.5f;
  75377. const float m3y = (y3 + y4) * 0.5f;
  75378. const float m4x = (m1x + m2x) * 0.5f;
  75379. const float m4y = (m1y + m2y) * 0.5f;
  75380. const float m5x = (m3x + m2x) * 0.5f;
  75381. const float m5y = (m3y + m2y) * 0.5f;
  75382. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75383. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75384. {
  75385. *stackPos++ = y4;
  75386. *stackPos++ = x4;
  75387. *stackPos++ = m3y;
  75388. *stackPos++ = m3x;
  75389. *stackPos++ = m5y;
  75390. *stackPos++ = m5x;
  75391. *stackPos++ = Path::cubicMarker;
  75392. *stackPos++ = (m4y + m5y) * 0.5f;
  75393. *stackPos++ = (m4x + m5x) * 0.5f;
  75394. *stackPos++ = m4y;
  75395. *stackPos++ = m4x;
  75396. *stackPos++ = m1y;
  75397. *stackPos++ = m1x;
  75398. *stackPos++ = Path::cubicMarker;
  75399. }
  75400. else
  75401. {
  75402. *stackPos++ = y4;
  75403. *stackPos++ = x4;
  75404. *stackPos++ = Path::lineMarker;
  75405. *stackPos++ = m5y;
  75406. *stackPos++ = m5x;
  75407. *stackPos++ = Path::lineMarker;
  75408. *stackPos++ = m4y;
  75409. *stackPos++ = m4x;
  75410. *stackPos++ = Path::lineMarker;
  75411. }
  75412. }
  75413. else if (type == Path::closeSubPathMarker)
  75414. {
  75415. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75416. {
  75417. x1 = x2;
  75418. y1 = y2;
  75419. x2 = subPathCloseX;
  75420. y2 = subPathCloseY;
  75421. closesSubPath = true;
  75422. return true;
  75423. }
  75424. }
  75425. else
  75426. {
  75427. jassert (type == Path::moveMarker);
  75428. subPathIndex = -1;
  75429. subPathCloseX = x1 = x2;
  75430. subPathCloseY = y1 = y2;
  75431. }
  75432. }
  75433. }
  75434. #if JUCE_MSVC && JUCE_DEBUG
  75435. #pragma optimize ("", on) // resets optimisations to the project defaults
  75436. #endif
  75437. END_JUCE_NAMESPACE
  75438. /*** End of inlined file: juce_PathIterator.cpp ***/
  75439. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75440. BEGIN_JUCE_NAMESPACE
  75441. PathStrokeType::PathStrokeType (const float strokeThickness,
  75442. const JointStyle jointStyle_,
  75443. const EndCapStyle endStyle_) throw()
  75444. : thickness (strokeThickness),
  75445. jointStyle (jointStyle_),
  75446. endStyle (endStyle_)
  75447. {
  75448. }
  75449. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75450. : thickness (other.thickness),
  75451. jointStyle (other.jointStyle),
  75452. endStyle (other.endStyle)
  75453. {
  75454. }
  75455. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75456. {
  75457. thickness = other.thickness;
  75458. jointStyle = other.jointStyle;
  75459. endStyle = other.endStyle;
  75460. return *this;
  75461. }
  75462. PathStrokeType::~PathStrokeType() throw()
  75463. {
  75464. }
  75465. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75466. {
  75467. return thickness == other.thickness
  75468. && jointStyle == other.jointStyle
  75469. && endStyle == other.endStyle;
  75470. }
  75471. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75472. {
  75473. return ! operator== (other);
  75474. }
  75475. namespace PathStrokeHelpers
  75476. {
  75477. static bool lineIntersection (const float x1, const float y1,
  75478. const float x2, const float y2,
  75479. const float x3, const float y3,
  75480. const float x4, const float y4,
  75481. float& intersectionX,
  75482. float& intersectionY,
  75483. float& distanceBeyondLine1EndSquared) throw()
  75484. {
  75485. if (x2 != x3 || y2 != y3)
  75486. {
  75487. const float dx1 = x2 - x1;
  75488. const float dy1 = y2 - y1;
  75489. const float dx2 = x4 - x3;
  75490. const float dy2 = y4 - y3;
  75491. const float divisor = dx1 * dy2 - dx2 * dy1;
  75492. if (divisor == 0)
  75493. {
  75494. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75495. {
  75496. if (dy1 == 0 && dy2 != 0)
  75497. {
  75498. const float along = (y1 - y3) / dy2;
  75499. intersectionX = x3 + along * dx2;
  75500. intersectionY = y1;
  75501. distanceBeyondLine1EndSquared = intersectionX - x2;
  75502. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75503. if ((x2 > x1) == (intersectionX < x2))
  75504. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75505. return along >= 0 && along <= 1.0f;
  75506. }
  75507. else if (dy2 == 0 && dy1 != 0)
  75508. {
  75509. const float along = (y3 - y1) / dy1;
  75510. intersectionX = x1 + along * dx1;
  75511. intersectionY = y3;
  75512. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75513. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75514. if (along < 1.0f)
  75515. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75516. return along >= 0 && along <= 1.0f;
  75517. }
  75518. else if (dx1 == 0 && dx2 != 0)
  75519. {
  75520. const float along = (x1 - x3) / dx2;
  75521. intersectionX = x1;
  75522. intersectionY = y3 + along * dy2;
  75523. distanceBeyondLine1EndSquared = intersectionY - y2;
  75524. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75525. if ((y2 > y1) == (intersectionY < y2))
  75526. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75527. return along >= 0 && along <= 1.0f;
  75528. }
  75529. else if (dx2 == 0 && dx1 != 0)
  75530. {
  75531. const float along = (x3 - x1) / dx1;
  75532. intersectionX = x3;
  75533. intersectionY = y1 + along * dy1;
  75534. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75535. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75536. if (along < 1.0f)
  75537. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75538. return along >= 0 && along <= 1.0f;
  75539. }
  75540. }
  75541. intersectionX = 0.5f * (x2 + x3);
  75542. intersectionY = 0.5f * (y2 + y3);
  75543. distanceBeyondLine1EndSquared = 0.0f;
  75544. return false;
  75545. }
  75546. else
  75547. {
  75548. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75549. intersectionX = x1 + along1 * dx1;
  75550. intersectionY = y1 + along1 * dy1;
  75551. if (along1 >= 0 && along1 <= 1.0f)
  75552. {
  75553. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75554. if (along2 >= 0 && along2 <= divisor)
  75555. {
  75556. distanceBeyondLine1EndSquared = 0.0f;
  75557. return true;
  75558. }
  75559. }
  75560. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75561. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75562. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75563. if (along1 < 1.0f)
  75564. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75565. return false;
  75566. }
  75567. }
  75568. intersectionX = x2;
  75569. intersectionY = y2;
  75570. distanceBeyondLine1EndSquared = 0.0f;
  75571. return true;
  75572. }
  75573. static void addEdgeAndJoint (Path& destPath,
  75574. const PathStrokeType::JointStyle style,
  75575. const float maxMiterExtensionSquared, const float width,
  75576. const float x1, const float y1,
  75577. const float x2, const float y2,
  75578. const float x3, const float y3,
  75579. const float x4, const float y4,
  75580. const float midX, const float midY)
  75581. {
  75582. if (style == PathStrokeType::beveled
  75583. || (x3 == x4 && y3 == y4)
  75584. || (x1 == x2 && y1 == y2))
  75585. {
  75586. destPath.lineTo (x2, y2);
  75587. destPath.lineTo (x3, y3);
  75588. }
  75589. else
  75590. {
  75591. float jx, jy, distanceBeyondLine1EndSquared;
  75592. // if they intersect, use this point..
  75593. if (lineIntersection (x1, y1, x2, y2,
  75594. x3, y3, x4, y4,
  75595. jx, jy, distanceBeyondLine1EndSquared))
  75596. {
  75597. destPath.lineTo (jx, jy);
  75598. }
  75599. else
  75600. {
  75601. if (style == PathStrokeType::mitered)
  75602. {
  75603. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75604. && distanceBeyondLine1EndSquared > 0.0f)
  75605. {
  75606. destPath.lineTo (jx, jy);
  75607. }
  75608. else
  75609. {
  75610. // the end sticks out too far, so just use a blunt joint
  75611. destPath.lineTo (x2, y2);
  75612. destPath.lineTo (x3, y3);
  75613. }
  75614. }
  75615. else
  75616. {
  75617. // curved joints
  75618. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75619. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75620. const float angleIncrement = 0.1f;
  75621. destPath.lineTo (x2, y2);
  75622. if (std::abs (angle1 - angle2) > angleIncrement)
  75623. {
  75624. if (angle2 > angle1 + float_Pi
  75625. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75626. {
  75627. if (angle2 > angle1)
  75628. angle2 -= float_Pi * 2.0f;
  75629. jassert (angle1 <= angle2 + float_Pi);
  75630. angle1 -= angleIncrement;
  75631. while (angle1 > angle2)
  75632. {
  75633. destPath.lineTo (midX + width * std::sin (angle1),
  75634. midY + width * std::cos (angle1));
  75635. angle1 -= angleIncrement;
  75636. }
  75637. }
  75638. else
  75639. {
  75640. if (angle1 > angle2)
  75641. angle1 -= float_Pi * 2.0f;
  75642. jassert (angle1 >= angle2 - float_Pi);
  75643. angle1 += angleIncrement;
  75644. while (angle1 < angle2)
  75645. {
  75646. destPath.lineTo (midX + width * std::sin (angle1),
  75647. midY + width * std::cos (angle1));
  75648. angle1 += angleIncrement;
  75649. }
  75650. }
  75651. }
  75652. destPath.lineTo (x3, y3);
  75653. }
  75654. }
  75655. }
  75656. }
  75657. static void addLineEnd (Path& destPath,
  75658. const PathStrokeType::EndCapStyle style,
  75659. const float x1, const float y1,
  75660. const float x2, const float y2,
  75661. const float width)
  75662. {
  75663. if (style == PathStrokeType::butt)
  75664. {
  75665. destPath.lineTo (x2, y2);
  75666. }
  75667. else
  75668. {
  75669. float offx1, offy1, offx2, offy2;
  75670. float dx = x2 - x1;
  75671. float dy = y2 - y1;
  75672. const float len = juce_hypotf (dx, dy);
  75673. if (len == 0)
  75674. {
  75675. offx1 = offx2 = x1;
  75676. offy1 = offy2 = y1;
  75677. }
  75678. else
  75679. {
  75680. const float offset = width / len;
  75681. dx *= offset;
  75682. dy *= offset;
  75683. offx1 = x1 + dy;
  75684. offy1 = y1 - dx;
  75685. offx2 = x2 + dy;
  75686. offy2 = y2 - dx;
  75687. }
  75688. if (style == PathStrokeType::square)
  75689. {
  75690. // sqaure ends
  75691. destPath.lineTo (offx1, offy1);
  75692. destPath.lineTo (offx2, offy2);
  75693. destPath.lineTo (x2, y2);
  75694. }
  75695. else
  75696. {
  75697. // rounded ends
  75698. const float midx = (offx1 + offx2) * 0.5f;
  75699. const float midy = (offy1 + offy2) * 0.5f;
  75700. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75701. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75702. midx, midy);
  75703. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75704. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75705. x2, y2);
  75706. }
  75707. }
  75708. }
  75709. struct Arrowhead
  75710. {
  75711. float startWidth, startLength;
  75712. float endWidth, endLength;
  75713. };
  75714. static void addArrowhead (Path& destPath,
  75715. const float x1, const float y1,
  75716. const float x2, const float y2,
  75717. const float tipX, const float tipY,
  75718. const float width,
  75719. const float arrowheadWidth)
  75720. {
  75721. Line<float> line (x1, y1, x2, y2);
  75722. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75723. destPath.lineTo (tipX, tipY);
  75724. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75725. destPath.lineTo (x2, y2);
  75726. }
  75727. struct LineSection
  75728. {
  75729. float x1, y1, x2, y2; // original line
  75730. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75731. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75732. };
  75733. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75734. {
  75735. while (amountAtEnd > 0 && subPath.size() > 0)
  75736. {
  75737. LineSection& l = subPath.getReference (subPath.size() - 1);
  75738. float dx = l.rx2 - l.rx1;
  75739. float dy = l.ry2 - l.ry1;
  75740. const float len = juce_hypotf (dx, dy);
  75741. if (len <= amountAtEnd && subPath.size() > 1)
  75742. {
  75743. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75744. prev.x2 = l.x2;
  75745. prev.y2 = l.y2;
  75746. subPath.removeLast();
  75747. amountAtEnd -= len;
  75748. }
  75749. else
  75750. {
  75751. const float prop = jmin (0.9999f, amountAtEnd / len);
  75752. dx *= prop;
  75753. dy *= prop;
  75754. l.rx1 += dx;
  75755. l.ry1 += dy;
  75756. l.lx2 += dx;
  75757. l.ly2 += dy;
  75758. break;
  75759. }
  75760. }
  75761. while (amountAtStart > 0 && subPath.size() > 0)
  75762. {
  75763. LineSection& l = subPath.getReference (0);
  75764. float dx = l.rx2 - l.rx1;
  75765. float dy = l.ry2 - l.ry1;
  75766. const float len = juce_hypotf (dx, dy);
  75767. if (len <= amountAtStart && subPath.size() > 1)
  75768. {
  75769. LineSection& next = subPath.getReference (1);
  75770. next.x1 = l.x1;
  75771. next.y1 = l.y1;
  75772. subPath.remove (0);
  75773. amountAtStart -= len;
  75774. }
  75775. else
  75776. {
  75777. const float prop = jmin (0.9999f, amountAtStart / len);
  75778. dx *= prop;
  75779. dy *= prop;
  75780. l.rx2 -= dx;
  75781. l.ry2 -= dy;
  75782. l.lx1 -= dx;
  75783. l.ly1 -= dy;
  75784. break;
  75785. }
  75786. }
  75787. }
  75788. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75789. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75790. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75791. const Arrowhead* const arrowhead)
  75792. {
  75793. jassert (subPath.size() > 0);
  75794. if (arrowhead != 0)
  75795. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75796. const LineSection& firstLine = subPath.getReference (0);
  75797. float lastX1 = firstLine.lx1;
  75798. float lastY1 = firstLine.ly1;
  75799. float lastX2 = firstLine.lx2;
  75800. float lastY2 = firstLine.ly2;
  75801. if (isClosed)
  75802. {
  75803. destPath.startNewSubPath (lastX1, lastY1);
  75804. }
  75805. else
  75806. {
  75807. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75808. if (arrowhead != 0)
  75809. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75810. width, arrowhead->startWidth);
  75811. else
  75812. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75813. }
  75814. int i;
  75815. for (i = 1; i < subPath.size(); ++i)
  75816. {
  75817. const LineSection& l = subPath.getReference (i);
  75818. addEdgeAndJoint (destPath, jointStyle,
  75819. maxMiterExtensionSquared, width,
  75820. lastX1, lastY1, lastX2, lastY2,
  75821. l.lx1, l.ly1, l.lx2, l.ly2,
  75822. l.x1, l.y1);
  75823. lastX1 = l.lx1;
  75824. lastY1 = l.ly1;
  75825. lastX2 = l.lx2;
  75826. lastY2 = l.ly2;
  75827. }
  75828. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75829. if (isClosed)
  75830. {
  75831. const LineSection& l = subPath.getReference (0);
  75832. addEdgeAndJoint (destPath, jointStyle,
  75833. maxMiterExtensionSquared, width,
  75834. lastX1, lastY1, lastX2, lastY2,
  75835. l.lx1, l.ly1, l.lx2, l.ly2,
  75836. l.x1, l.y1);
  75837. destPath.closeSubPath();
  75838. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75839. }
  75840. else
  75841. {
  75842. destPath.lineTo (lastX2, lastY2);
  75843. if (arrowhead != 0)
  75844. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75845. width, arrowhead->endWidth);
  75846. else
  75847. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75848. }
  75849. lastX1 = lastLine.rx1;
  75850. lastY1 = lastLine.ry1;
  75851. lastX2 = lastLine.rx2;
  75852. lastY2 = lastLine.ry2;
  75853. for (i = subPath.size() - 1; --i >= 0;)
  75854. {
  75855. const LineSection& l = subPath.getReference (i);
  75856. addEdgeAndJoint (destPath, jointStyle,
  75857. maxMiterExtensionSquared, width,
  75858. lastX1, lastY1, lastX2, lastY2,
  75859. l.rx1, l.ry1, l.rx2, l.ry2,
  75860. l.x2, l.y2);
  75861. lastX1 = l.rx1;
  75862. lastY1 = l.ry1;
  75863. lastX2 = l.rx2;
  75864. lastY2 = l.ry2;
  75865. }
  75866. if (isClosed)
  75867. {
  75868. addEdgeAndJoint (destPath, jointStyle,
  75869. maxMiterExtensionSquared, width,
  75870. lastX1, lastY1, lastX2, lastY2,
  75871. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75872. lastLine.x2, lastLine.y2);
  75873. }
  75874. else
  75875. {
  75876. // do the last line
  75877. destPath.lineTo (lastX2, lastY2);
  75878. }
  75879. destPath.closeSubPath();
  75880. }
  75881. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75882. const PathStrokeType::EndCapStyle endStyle,
  75883. Path& destPath, const Path& source,
  75884. const AffineTransform& transform,
  75885. const float extraAccuracy, const Arrowhead* const arrowhead)
  75886. {
  75887. if (thickness <= 0)
  75888. {
  75889. destPath.clear();
  75890. return;
  75891. }
  75892. const Path* sourcePath = &source;
  75893. Path temp;
  75894. if (sourcePath == &destPath)
  75895. {
  75896. destPath.swapWithPath (temp);
  75897. sourcePath = &temp;
  75898. }
  75899. else
  75900. {
  75901. destPath.clear();
  75902. }
  75903. destPath.setUsingNonZeroWinding (true);
  75904. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75905. const float width = 0.5f * thickness;
  75906. // Iterate the path, creating a list of the
  75907. // left/right-hand lines along either side of it...
  75908. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75909. Array <LineSection> subPath;
  75910. subPath.ensureStorageAllocated (512);
  75911. LineSection l;
  75912. l.x1 = 0;
  75913. l.y1 = 0;
  75914. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75915. while (it.next())
  75916. {
  75917. if (it.subPathIndex == 0)
  75918. {
  75919. if (subPath.size() > 0)
  75920. {
  75921. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75922. subPath.clearQuick();
  75923. }
  75924. l.x1 = it.x1;
  75925. l.y1 = it.y1;
  75926. }
  75927. l.x2 = it.x2;
  75928. l.y2 = it.y2;
  75929. float dx = l.x2 - l.x1;
  75930. float dy = l.y2 - l.y1;
  75931. const float hypotSquared = dx*dx + dy*dy;
  75932. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75933. {
  75934. const float len = std::sqrt (hypotSquared);
  75935. if (len == 0)
  75936. {
  75937. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75938. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75939. }
  75940. else
  75941. {
  75942. const float offset = width / len;
  75943. dx *= offset;
  75944. dy *= offset;
  75945. l.rx2 = l.x1 - dy;
  75946. l.ry2 = l.y1 + dx;
  75947. l.lx1 = l.x1 + dy;
  75948. l.ly1 = l.y1 - dx;
  75949. l.lx2 = l.x2 + dy;
  75950. l.ly2 = l.y2 - dx;
  75951. l.rx1 = l.x2 - dy;
  75952. l.ry1 = l.y2 + dx;
  75953. }
  75954. subPath.add (l);
  75955. if (it.closesSubPath)
  75956. {
  75957. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75958. subPath.clearQuick();
  75959. }
  75960. else
  75961. {
  75962. l.x1 = it.x2;
  75963. l.y1 = it.y2;
  75964. }
  75965. }
  75966. }
  75967. if (subPath.size() > 0)
  75968. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75969. }
  75970. }
  75971. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  75972. const AffineTransform& transform, const float extraAccuracy) const
  75973. {
  75974. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  75975. transform, extraAccuracy, 0);
  75976. }
  75977. void PathStrokeType::createDashedStroke (Path& destPath,
  75978. const Path& sourcePath,
  75979. const float* dashLengths,
  75980. int numDashLengths,
  75981. const AffineTransform& transform,
  75982. const float extraAccuracy) const
  75983. {
  75984. if (thickness <= 0)
  75985. return;
  75986. // this should really be an even number..
  75987. jassert ((numDashLengths & 1) == 0);
  75988. Path newDestPath;
  75989. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  75990. bool first = true;
  75991. int dashNum = 0;
  75992. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  75993. float dx = 0.0f, dy = 0.0f;
  75994. for (;;)
  75995. {
  75996. const bool isSolid = ((dashNum & 1) == 0);
  75997. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  75998. jassert (dashLen > 0); // must be a positive increment!
  75999. if (dashLen <= 0)
  76000. break;
  76001. pos += dashLen;
  76002. while (pos > lineEndPos)
  76003. {
  76004. if (! it.next())
  76005. {
  76006. if (isSolid && ! first)
  76007. newDestPath.lineTo (it.x2, it.y2);
  76008. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76009. return;
  76010. }
  76011. if (isSolid && ! first)
  76012. newDestPath.lineTo (it.x1, it.y1);
  76013. else
  76014. newDestPath.startNewSubPath (it.x1, it.y1);
  76015. dx = it.x2 - it.x1;
  76016. dy = it.y2 - it.y1;
  76017. lineLen = juce_hypotf (dx, dy);
  76018. lineEndPos += lineLen;
  76019. first = it.closesSubPath;
  76020. }
  76021. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76022. if (isSolid)
  76023. newDestPath.lineTo (it.x1 + dx * alpha,
  76024. it.y1 + dy * alpha);
  76025. else
  76026. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76027. it.y1 + dy * alpha);
  76028. }
  76029. }
  76030. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76031. const Path& sourcePath,
  76032. const float arrowheadStartWidth, const float arrowheadStartLength,
  76033. const float arrowheadEndWidth, const float arrowheadEndLength,
  76034. const AffineTransform& transform,
  76035. const float extraAccuracy) const
  76036. {
  76037. PathStrokeHelpers::Arrowhead head;
  76038. head.startWidth = arrowheadStartWidth;
  76039. head.startLength = arrowheadStartLength;
  76040. head.endWidth = arrowheadEndWidth;
  76041. head.endLength = arrowheadEndLength;
  76042. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76043. destPath, sourcePath, transform, extraAccuracy, &head);
  76044. }
  76045. END_JUCE_NAMESPACE
  76046. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76047. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76048. BEGIN_JUCE_NAMESPACE
  76049. PositionedRectangle::PositionedRectangle() throw()
  76050. : x (0.0),
  76051. y (0.0),
  76052. w (0.0),
  76053. h (0.0),
  76054. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76055. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76056. wMode (absoluteSize),
  76057. hMode (absoluteSize)
  76058. {
  76059. }
  76060. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76061. : x (other.x),
  76062. y (other.y),
  76063. w (other.w),
  76064. h (other.h),
  76065. xMode (other.xMode),
  76066. yMode (other.yMode),
  76067. wMode (other.wMode),
  76068. hMode (other.hMode)
  76069. {
  76070. }
  76071. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76072. {
  76073. x = other.x;
  76074. y = other.y;
  76075. w = other.w;
  76076. h = other.h;
  76077. xMode = other.xMode;
  76078. yMode = other.yMode;
  76079. wMode = other.wMode;
  76080. hMode = other.hMode;
  76081. return *this;
  76082. }
  76083. PositionedRectangle::~PositionedRectangle() throw()
  76084. {
  76085. }
  76086. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76087. {
  76088. return x == other.x
  76089. && y == other.y
  76090. && w == other.w
  76091. && h == other.h
  76092. && xMode == other.xMode
  76093. && yMode == other.yMode
  76094. && wMode == other.wMode
  76095. && hMode == other.hMode;
  76096. }
  76097. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76098. {
  76099. return ! operator== (other);
  76100. }
  76101. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76102. {
  76103. StringArray tokens;
  76104. tokens.addTokens (stringVersion, false);
  76105. decodePosString (tokens [0], xMode, x);
  76106. decodePosString (tokens [1], yMode, y);
  76107. decodeSizeString (tokens [2], wMode, w);
  76108. decodeSizeString (tokens [3], hMode, h);
  76109. }
  76110. const String PositionedRectangle::toString() const throw()
  76111. {
  76112. String s;
  76113. s.preallocateStorage (12);
  76114. addPosDescription (s, xMode, x);
  76115. s << ' ';
  76116. addPosDescription (s, yMode, y);
  76117. s << ' ';
  76118. addSizeDescription (s, wMode, w);
  76119. s << ' ';
  76120. addSizeDescription (s, hMode, h);
  76121. return s;
  76122. }
  76123. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76124. {
  76125. jassert (! target.isEmpty());
  76126. double x_, y_, w_, h_;
  76127. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76128. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76129. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76130. roundToInt (w_), roundToInt (h_));
  76131. }
  76132. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76133. double& x_, double& y_,
  76134. double& w_, double& h_) const throw()
  76135. {
  76136. jassert (! target.isEmpty());
  76137. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76138. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76139. }
  76140. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76141. {
  76142. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76143. }
  76144. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76145. const Rectangle<int>& target) throw()
  76146. {
  76147. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76148. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76149. }
  76150. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76151. const double newW, const double newH,
  76152. const Rectangle<int>& target) throw()
  76153. {
  76154. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76155. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76156. }
  76157. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76158. {
  76159. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76160. updateFrom (comp.getBounds(), Rectangle<int>());
  76161. else
  76162. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76163. }
  76164. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76165. {
  76166. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76167. }
  76168. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76169. {
  76170. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76171. | absoluteFromParentBottomRight
  76172. | absoluteFromParentCentre
  76173. | proportionOfParentSize));
  76174. }
  76175. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76176. {
  76177. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76178. }
  76179. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76180. {
  76181. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76182. | absoluteFromParentBottomRight
  76183. | absoluteFromParentCentre
  76184. | proportionOfParentSize));
  76185. }
  76186. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76187. {
  76188. return (SizeMode) wMode;
  76189. }
  76190. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76191. {
  76192. return (SizeMode) hMode;
  76193. }
  76194. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76195. const PositionMode xMode_,
  76196. const AnchorPoint yAnchor,
  76197. const PositionMode yMode_,
  76198. const SizeMode widthMode,
  76199. const SizeMode heightMode,
  76200. const Rectangle<int>& target) throw()
  76201. {
  76202. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76203. {
  76204. double tx, tw;
  76205. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76206. xMode = (uint8) (xAnchor | xMode_);
  76207. wMode = (uint8) widthMode;
  76208. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76209. }
  76210. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76211. {
  76212. double ty, th;
  76213. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76214. yMode = (uint8) (yAnchor | yMode_);
  76215. hMode = (uint8) heightMode;
  76216. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76217. }
  76218. }
  76219. bool PositionedRectangle::isPositionAbsolute() const throw()
  76220. {
  76221. return xMode == absoluteFromParentTopLeft
  76222. && yMode == absoluteFromParentTopLeft
  76223. && wMode == absoluteSize
  76224. && hMode == absoluteSize;
  76225. }
  76226. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76227. {
  76228. if ((mode & proportionOfParentSize) != 0)
  76229. {
  76230. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76231. }
  76232. else
  76233. {
  76234. s << (roundToInt (value * 100.0) / 100.0);
  76235. if ((mode & absoluteFromParentBottomRight) != 0)
  76236. s << 'R';
  76237. else if ((mode & absoluteFromParentCentre) != 0)
  76238. s << 'C';
  76239. }
  76240. if ((mode & anchorAtRightOrBottom) != 0)
  76241. s << 'r';
  76242. else if ((mode & anchorAtCentre) != 0)
  76243. s << 'c';
  76244. }
  76245. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76246. {
  76247. if (mode == proportionalSize)
  76248. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76249. else if (mode == parentSizeMinusAbsolute)
  76250. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76251. else
  76252. s << (roundToInt (value * 100.0) / 100.0);
  76253. }
  76254. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76255. {
  76256. if (s.containsChar ('r'))
  76257. mode = anchorAtRightOrBottom;
  76258. else if (s.containsChar ('c'))
  76259. mode = anchorAtCentre;
  76260. else
  76261. mode = anchorAtLeftOrTop;
  76262. if (s.containsChar ('%'))
  76263. {
  76264. mode |= proportionOfParentSize;
  76265. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76266. }
  76267. else
  76268. {
  76269. if (s.containsChar ('R'))
  76270. mode |= absoluteFromParentBottomRight;
  76271. else if (s.containsChar ('C'))
  76272. mode |= absoluteFromParentCentre;
  76273. else
  76274. mode |= absoluteFromParentTopLeft;
  76275. value = s.removeCharacters ("rcRC").getDoubleValue();
  76276. }
  76277. }
  76278. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76279. {
  76280. if (s.containsChar ('%'))
  76281. {
  76282. mode = proportionalSize;
  76283. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76284. }
  76285. else if (s.containsChar ('M'))
  76286. {
  76287. mode = parentSizeMinusAbsolute;
  76288. value = s.getDoubleValue();
  76289. }
  76290. else
  76291. {
  76292. mode = absoluteSize;
  76293. value = s.getDoubleValue();
  76294. }
  76295. }
  76296. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76297. const double x_, const double w_,
  76298. const uint8 xMode_, const uint8 wMode_,
  76299. const int parentPos,
  76300. const int parentSize) const throw()
  76301. {
  76302. if (wMode_ == proportionalSize)
  76303. wOut = roundToInt (w_ * parentSize);
  76304. else if (wMode_ == parentSizeMinusAbsolute)
  76305. wOut = jmax (0, parentSize - roundToInt (w_));
  76306. else
  76307. wOut = roundToInt (w_);
  76308. if ((xMode_ & proportionOfParentSize) != 0)
  76309. xOut = parentPos + x_ * parentSize;
  76310. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76311. xOut = (parentPos + parentSize) - x_;
  76312. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76313. xOut = x_ + (parentPos + parentSize / 2);
  76314. else
  76315. xOut = x_ + parentPos;
  76316. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76317. xOut -= wOut;
  76318. else if ((xMode_ & anchorAtCentre) != 0)
  76319. xOut -= wOut / 2;
  76320. }
  76321. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76322. double x_, const double w_,
  76323. const uint8 xMode_, const uint8 wMode_,
  76324. const int parentPos,
  76325. const int parentSize) const throw()
  76326. {
  76327. if (wMode_ == proportionalSize)
  76328. {
  76329. if (parentSize > 0)
  76330. wOut = w_ / parentSize;
  76331. }
  76332. else if (wMode_ == parentSizeMinusAbsolute)
  76333. wOut = parentSize - w_;
  76334. else
  76335. wOut = w_;
  76336. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76337. x_ += w_;
  76338. else if ((xMode_ & anchorAtCentre) != 0)
  76339. x_ += w_ / 2;
  76340. if ((xMode_ & proportionOfParentSize) != 0)
  76341. {
  76342. if (parentSize > 0)
  76343. xOut = (x_ - parentPos) / parentSize;
  76344. }
  76345. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76346. xOut = (parentPos + parentSize) - x_;
  76347. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76348. xOut = x_ - (parentPos + parentSize / 2);
  76349. else
  76350. xOut = x_ - parentPos;
  76351. }
  76352. END_JUCE_NAMESPACE
  76353. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76354. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76355. BEGIN_JUCE_NAMESPACE
  76356. RectangleList::RectangleList() throw()
  76357. {
  76358. }
  76359. RectangleList::RectangleList (const Rectangle<int>& rect)
  76360. {
  76361. if (! rect.isEmpty())
  76362. rects.add (rect);
  76363. }
  76364. RectangleList::RectangleList (const RectangleList& other)
  76365. : rects (other.rects)
  76366. {
  76367. }
  76368. RectangleList& RectangleList::operator= (const RectangleList& other)
  76369. {
  76370. rects = other.rects;
  76371. return *this;
  76372. }
  76373. RectangleList::~RectangleList()
  76374. {
  76375. }
  76376. void RectangleList::clear()
  76377. {
  76378. rects.clearQuick();
  76379. }
  76380. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76381. {
  76382. if (((unsigned int) index) < (unsigned int) rects.size())
  76383. return rects.getReference (index);
  76384. return Rectangle<int>();
  76385. }
  76386. bool RectangleList::isEmpty() const throw()
  76387. {
  76388. return rects.size() == 0;
  76389. }
  76390. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76391. : current (0),
  76392. owner (list),
  76393. index (list.rects.size())
  76394. {
  76395. }
  76396. RectangleList::Iterator::~Iterator()
  76397. {
  76398. }
  76399. bool RectangleList::Iterator::next() throw()
  76400. {
  76401. if (--index >= 0)
  76402. {
  76403. current = & (owner.rects.getReference (index));
  76404. return true;
  76405. }
  76406. return false;
  76407. }
  76408. void RectangleList::add (const Rectangle<int>& rect)
  76409. {
  76410. if (! rect.isEmpty())
  76411. {
  76412. if (rects.size() == 0)
  76413. {
  76414. rects.add (rect);
  76415. }
  76416. else
  76417. {
  76418. bool anyOverlaps = false;
  76419. int i;
  76420. for (i = rects.size(); --i >= 0;)
  76421. {
  76422. Rectangle<int>& ourRect = rects.getReference (i);
  76423. if (rect.intersects (ourRect))
  76424. {
  76425. if (rect.contains (ourRect))
  76426. rects.remove (i);
  76427. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76428. anyOverlaps = true;
  76429. }
  76430. }
  76431. if (anyOverlaps && rects.size() > 0)
  76432. {
  76433. RectangleList r (rect);
  76434. for (i = rects.size(); --i >= 0;)
  76435. {
  76436. const Rectangle<int>& ourRect = rects.getReference (i);
  76437. if (rect.intersects (ourRect))
  76438. {
  76439. r.subtract (ourRect);
  76440. if (r.rects.size() == 0)
  76441. return;
  76442. }
  76443. }
  76444. for (i = r.getNumRectangles(); --i >= 0;)
  76445. rects.add (r.rects.getReference (i));
  76446. }
  76447. else
  76448. {
  76449. rects.add (rect);
  76450. }
  76451. }
  76452. }
  76453. }
  76454. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76455. {
  76456. if (! rect.isEmpty())
  76457. rects.add (rect);
  76458. }
  76459. void RectangleList::add (const int x, const int y, const int w, const int h)
  76460. {
  76461. if (rects.size() == 0)
  76462. {
  76463. if (w > 0 && h > 0)
  76464. rects.add (Rectangle<int> (x, y, w, h));
  76465. }
  76466. else
  76467. {
  76468. add (Rectangle<int> (x, y, w, h));
  76469. }
  76470. }
  76471. void RectangleList::add (const RectangleList& other)
  76472. {
  76473. for (int i = 0; i < other.rects.size(); ++i)
  76474. add (other.rects.getReference (i));
  76475. }
  76476. void RectangleList::subtract (const Rectangle<int>& rect)
  76477. {
  76478. const int originalNumRects = rects.size();
  76479. if (originalNumRects > 0)
  76480. {
  76481. const int x1 = rect.x;
  76482. const int y1 = rect.y;
  76483. const int x2 = x1 + rect.w;
  76484. const int y2 = y1 + rect.h;
  76485. for (int i = getNumRectangles(); --i >= 0;)
  76486. {
  76487. Rectangle<int>& r = rects.getReference (i);
  76488. const int rx1 = r.x;
  76489. const int ry1 = r.y;
  76490. const int rx2 = rx1 + r.w;
  76491. const int ry2 = ry1 + r.h;
  76492. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76493. {
  76494. if (x1 > rx1 && x1 < rx2)
  76495. {
  76496. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76497. {
  76498. r.w = x1 - rx1;
  76499. }
  76500. else
  76501. {
  76502. r.x = x1;
  76503. r.w = rx2 - x1;
  76504. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76505. i += 2;
  76506. }
  76507. }
  76508. else if (x2 > rx1 && x2 < rx2)
  76509. {
  76510. r.x = x2;
  76511. r.w = rx2 - x2;
  76512. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76513. {
  76514. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76515. i += 2;
  76516. }
  76517. }
  76518. else if (y1 > ry1 && y1 < ry2)
  76519. {
  76520. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76521. {
  76522. r.h = y1 - ry1;
  76523. }
  76524. else
  76525. {
  76526. r.y = y1;
  76527. r.h = ry2 - y1;
  76528. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76529. i += 2;
  76530. }
  76531. }
  76532. else if (y2 > ry1 && y2 < ry2)
  76533. {
  76534. r.y = y2;
  76535. r.h = ry2 - y2;
  76536. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76537. {
  76538. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76539. i += 2;
  76540. }
  76541. }
  76542. else
  76543. {
  76544. rects.remove (i);
  76545. }
  76546. }
  76547. }
  76548. }
  76549. }
  76550. bool RectangleList::subtract (const RectangleList& otherList)
  76551. {
  76552. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76553. subtract (otherList.rects.getReference (i));
  76554. return rects.size() > 0;
  76555. }
  76556. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76557. {
  76558. bool notEmpty = false;
  76559. if (rect.isEmpty())
  76560. {
  76561. clear();
  76562. }
  76563. else
  76564. {
  76565. for (int i = rects.size(); --i >= 0;)
  76566. {
  76567. Rectangle<int>& r = rects.getReference (i);
  76568. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76569. rects.remove (i);
  76570. else
  76571. notEmpty = true;
  76572. }
  76573. }
  76574. return notEmpty;
  76575. }
  76576. bool RectangleList::clipTo (const RectangleList& other)
  76577. {
  76578. if (rects.size() == 0)
  76579. return false;
  76580. RectangleList result;
  76581. for (int j = 0; j < rects.size(); ++j)
  76582. {
  76583. const Rectangle<int>& rect = rects.getReference (j);
  76584. for (int i = other.rects.size(); --i >= 0;)
  76585. {
  76586. Rectangle<int> r (other.rects.getReference (i));
  76587. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76588. result.rects.add (r);
  76589. }
  76590. }
  76591. swapWith (result);
  76592. return ! isEmpty();
  76593. }
  76594. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76595. {
  76596. destRegion.clear();
  76597. if (! rect.isEmpty())
  76598. {
  76599. for (int i = rects.size(); --i >= 0;)
  76600. {
  76601. Rectangle<int> r (rects.getReference (i));
  76602. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76603. destRegion.rects.add (r);
  76604. }
  76605. }
  76606. return destRegion.rects.size() > 0;
  76607. }
  76608. void RectangleList::swapWith (RectangleList& otherList) throw()
  76609. {
  76610. rects.swapWithArray (otherList.rects);
  76611. }
  76612. void RectangleList::consolidate()
  76613. {
  76614. int i;
  76615. for (i = 0; i < getNumRectangles() - 1; ++i)
  76616. {
  76617. Rectangle<int>& r = rects.getReference (i);
  76618. const int rx1 = r.x;
  76619. const int ry1 = r.y;
  76620. const int rx2 = rx1 + r.w;
  76621. const int ry2 = ry1 + r.h;
  76622. for (int j = rects.size(); --j > i;)
  76623. {
  76624. Rectangle<int>& r2 = rects.getReference (j);
  76625. const int jrx1 = r2.x;
  76626. const int jry1 = r2.y;
  76627. const int jrx2 = jrx1 + r2.w;
  76628. const int jry2 = jry1 + r2.h;
  76629. // if the vertical edges of any blocks are touching and their horizontals don't
  76630. // line up, split them horizontally..
  76631. if (jrx1 == rx2 || jrx2 == rx1)
  76632. {
  76633. if (jry1 > ry1 && jry1 < ry2)
  76634. {
  76635. r.h = jry1 - ry1;
  76636. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76637. i = -1;
  76638. break;
  76639. }
  76640. if (jry2 > ry1 && jry2 < ry2)
  76641. {
  76642. r.h = jry2 - ry1;
  76643. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76644. i = -1;
  76645. break;
  76646. }
  76647. else if (ry1 > jry1 && ry1 < jry2)
  76648. {
  76649. r2.h = ry1 - jry1;
  76650. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76651. i = -1;
  76652. break;
  76653. }
  76654. else if (ry2 > jry1 && ry2 < jry2)
  76655. {
  76656. r2.h = ry2 - jry1;
  76657. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76658. i = -1;
  76659. break;
  76660. }
  76661. }
  76662. }
  76663. }
  76664. for (i = 0; i < rects.size() - 1; ++i)
  76665. {
  76666. Rectangle<int>& r = rects.getReference (i);
  76667. for (int j = rects.size(); --j > i;)
  76668. {
  76669. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76670. {
  76671. rects.remove (j);
  76672. i = -1;
  76673. break;
  76674. }
  76675. }
  76676. }
  76677. }
  76678. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76679. {
  76680. for (int i = getNumRectangles(); --i >= 0;)
  76681. if (rects.getReference (i).contains (x, y))
  76682. return true;
  76683. return false;
  76684. }
  76685. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76686. {
  76687. if (rects.size() > 1)
  76688. {
  76689. RectangleList r (rectangleToCheck);
  76690. for (int i = rects.size(); --i >= 0;)
  76691. {
  76692. r.subtract (rects.getReference (i));
  76693. if (r.rects.size() == 0)
  76694. return true;
  76695. }
  76696. }
  76697. else if (rects.size() > 0)
  76698. {
  76699. return rects.getReference (0).contains (rectangleToCheck);
  76700. }
  76701. return false;
  76702. }
  76703. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76704. {
  76705. for (int i = rects.size(); --i >= 0;)
  76706. if (rects.getReference (i).intersects (rectangleToCheck))
  76707. return true;
  76708. return false;
  76709. }
  76710. bool RectangleList::intersects (const RectangleList& other) const throw()
  76711. {
  76712. for (int i = rects.size(); --i >= 0;)
  76713. if (other.intersectsRectangle (rects.getReference (i)))
  76714. return true;
  76715. return false;
  76716. }
  76717. const Rectangle<int> RectangleList::getBounds() const throw()
  76718. {
  76719. if (rects.size() <= 1)
  76720. {
  76721. if (rects.size() == 0)
  76722. return Rectangle<int>();
  76723. else
  76724. return rects.getReference (0);
  76725. }
  76726. else
  76727. {
  76728. const Rectangle<int>& r = rects.getReference (0);
  76729. int minX = r.x;
  76730. int minY = r.y;
  76731. int maxX = minX + r.w;
  76732. int maxY = minY + r.h;
  76733. for (int i = rects.size(); --i > 0;)
  76734. {
  76735. const Rectangle<int>& r2 = rects.getReference (i);
  76736. minX = jmin (minX, r2.x);
  76737. minY = jmin (minY, r2.y);
  76738. maxX = jmax (maxX, r2.getRight());
  76739. maxY = jmax (maxY, r2.getBottom());
  76740. }
  76741. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76742. }
  76743. }
  76744. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76745. {
  76746. for (int i = rects.size(); --i >= 0;)
  76747. {
  76748. Rectangle<int>& r = rects.getReference (i);
  76749. r.x += dx;
  76750. r.y += dy;
  76751. }
  76752. }
  76753. const Path RectangleList::toPath() const
  76754. {
  76755. Path p;
  76756. for (int i = rects.size(); --i >= 0;)
  76757. {
  76758. const Rectangle<int>& r = rects.getReference (i);
  76759. p.addRectangle ((float) r.x,
  76760. (float) r.y,
  76761. (float) r.w,
  76762. (float) r.h);
  76763. }
  76764. return p;
  76765. }
  76766. END_JUCE_NAMESPACE
  76767. /*** End of inlined file: juce_RectangleList.cpp ***/
  76768. /*** Start of inlined file: juce_Image.cpp ***/
  76769. BEGIN_JUCE_NAMESPACE
  76770. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76771. : format (format_), width (width_), height (height_)
  76772. {
  76773. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76774. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76775. }
  76776. Image::SharedImage::~SharedImage()
  76777. {
  76778. }
  76779. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76780. {
  76781. return imageData + lineStride * y + pixelStride * x;
  76782. }
  76783. class SoftwareSharedImage : public Image::SharedImage
  76784. {
  76785. public:
  76786. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76787. : Image::SharedImage (format_, width_, height_)
  76788. {
  76789. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76790. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76791. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76792. imageData = imageDataAllocated;
  76793. }
  76794. ~SoftwareSharedImage()
  76795. {
  76796. }
  76797. Image::ImageType getType() const
  76798. {
  76799. return Image::SoftwareImage;
  76800. }
  76801. LowLevelGraphicsContext* createLowLevelContext()
  76802. {
  76803. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76804. }
  76805. SharedImage* clone()
  76806. {
  76807. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76808. memcpy (s->imageData, imageData, lineStride * height);
  76809. return s;
  76810. }
  76811. private:
  76812. HeapBlock<uint8> imageDataAllocated;
  76813. };
  76814. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76815. {
  76816. return new SoftwareSharedImage (format, width, height, clearImage);
  76817. }
  76818. class SubsectionSharedImage : public Image::SharedImage
  76819. {
  76820. public:
  76821. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76822. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76823. image (image_), area (area_)
  76824. {
  76825. pixelStride = image_->getPixelStride();
  76826. lineStride = image_->getLineStride();
  76827. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76828. }
  76829. ~SubsectionSharedImage() {}
  76830. Image::ImageType getType() const
  76831. {
  76832. return Image::SoftwareImage;
  76833. }
  76834. LowLevelGraphicsContext* createLowLevelContext()
  76835. {
  76836. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76837. g->clipToRectangle (area);
  76838. g->setOrigin (area.getX(), area.getY());
  76839. return g;
  76840. }
  76841. SharedImage* clone()
  76842. {
  76843. return new SubsectionSharedImage (image->clone(), area);
  76844. }
  76845. private:
  76846. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76847. const Rectangle<int> area;
  76848. SubsectionSharedImage (const SubsectionSharedImage&);
  76849. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76850. };
  76851. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76852. {
  76853. if (area.contains (getBounds()))
  76854. return *this;
  76855. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76856. if (validArea.isEmpty())
  76857. return Image::null;
  76858. return Image (new SubsectionSharedImage (image, validArea));
  76859. }
  76860. Image::Image()
  76861. {
  76862. }
  76863. Image::Image (SharedImage* const instance)
  76864. : image (instance)
  76865. {
  76866. }
  76867. Image::Image (const PixelFormat format,
  76868. const int width, const int height,
  76869. const bool clearImage, const ImageType type)
  76870. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76871. : new SoftwareSharedImage (format, width, height, clearImage))
  76872. {
  76873. }
  76874. Image::Image (const Image& other)
  76875. : image (other.image)
  76876. {
  76877. }
  76878. Image& Image::operator= (const Image& other)
  76879. {
  76880. image = other.image;
  76881. return *this;
  76882. }
  76883. Image::~Image()
  76884. {
  76885. }
  76886. const Image Image::null;
  76887. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76888. {
  76889. return image == 0 ? 0 : image->createLowLevelContext();
  76890. }
  76891. void Image::duplicateIfShared()
  76892. {
  76893. if (image != 0 && image->getReferenceCount() > 1)
  76894. image = image->clone();
  76895. }
  76896. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76897. {
  76898. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76899. return *this;
  76900. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76901. Graphics g (newImage);
  76902. g.setImageResamplingQuality (quality);
  76903. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76904. return newImage;
  76905. }
  76906. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76907. {
  76908. if (image == 0 || newFormat == image->format)
  76909. return *this;
  76910. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76911. if (newFormat == SingleChannel)
  76912. {
  76913. if (! hasAlphaChannel())
  76914. {
  76915. newImage.clear (getBounds(), Colours::black);
  76916. }
  76917. else
  76918. {
  76919. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76920. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76921. for (int y = 0; y < image->height; ++y)
  76922. {
  76923. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76924. uint8* dst = destData.getLinePointer (y);
  76925. for (int x = image->width; --x >= 0;)
  76926. {
  76927. *dst++ = src->getAlpha();
  76928. ++src;
  76929. }
  76930. }
  76931. }
  76932. }
  76933. else
  76934. {
  76935. if (hasAlphaChannel())
  76936. newImage.clear (getBounds());
  76937. Graphics g (newImage);
  76938. g.drawImageAt (*this, 0, 0);
  76939. }
  76940. return newImage;
  76941. }
  76942. const var Image::getTag() const
  76943. {
  76944. return image == 0 ? var::null : image->userTag;
  76945. }
  76946. void Image::setTag (const var& newTag)
  76947. {
  76948. if (image != 0)
  76949. image->userTag = newTag;
  76950. }
  76951. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76952. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76953. pixelFormat (image.getFormat()),
  76954. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76955. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76956. width (w),
  76957. height (h)
  76958. {
  76959. jassert (data != 0);
  76960. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76961. }
  76962. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76963. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76964. pixelFormat (image.getFormat()),
  76965. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76966. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76967. width (w),
  76968. height (h)
  76969. {
  76970. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76971. }
  76972. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76973. : data (image.image == 0 ? 0 : image.image->imageData),
  76974. pixelFormat (image.getFormat()),
  76975. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76976. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76977. width (image.getWidth()),
  76978. height (image.getHeight())
  76979. {
  76980. }
  76981. Image::BitmapData::~BitmapData()
  76982. {
  76983. }
  76984. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76985. {
  76986. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76987. const uint8* const pixel = getPixelPointer (x, y);
  76988. switch (pixelFormat)
  76989. {
  76990. case Image::ARGB:
  76991. {
  76992. PixelARGB p (*(const PixelARGB*) pixel);
  76993. p.unpremultiply();
  76994. return Colour (p.getARGB());
  76995. }
  76996. case Image::RGB:
  76997. return Colour (((const PixelRGB*) pixel)->getARGB());
  76998. case Image::SingleChannel:
  76999. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77000. default:
  77001. jassertfalse;
  77002. break;
  77003. }
  77004. return Colour();
  77005. }
  77006. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77007. {
  77008. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77009. uint8* const pixel = getPixelPointer (x, y);
  77010. const PixelARGB col (colour.getPixelARGB());
  77011. switch (pixelFormat)
  77012. {
  77013. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77014. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77015. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77016. default: jassertfalse; break;
  77017. }
  77018. }
  77019. void Image::setPixelData (int x, int y, int w, int h,
  77020. const uint8* const sourcePixelData, const int sourceLineStride)
  77021. {
  77022. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77023. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77024. {
  77025. const BitmapData dest (*this, x, y, w, h, true);
  77026. for (int i = 0; i < h; ++i)
  77027. {
  77028. memcpy (dest.getLinePointer(i),
  77029. sourcePixelData + sourceLineStride * i,
  77030. w * dest.pixelStride);
  77031. }
  77032. }
  77033. }
  77034. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77035. {
  77036. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77037. if (! clipped.isEmpty())
  77038. {
  77039. const PixelARGB col (colourToClearTo.getPixelARGB());
  77040. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77041. uint8* dest = destData.data;
  77042. int dh = clipped.getHeight();
  77043. while (--dh >= 0)
  77044. {
  77045. uint8* line = dest;
  77046. dest += destData.lineStride;
  77047. if (isARGB())
  77048. {
  77049. for (int x = clipped.getWidth(); --x >= 0;)
  77050. {
  77051. ((PixelARGB*) line)->set (col);
  77052. line += destData.pixelStride;
  77053. }
  77054. }
  77055. else if (isRGB())
  77056. {
  77057. for (int x = clipped.getWidth(); --x >= 0;)
  77058. {
  77059. ((PixelRGB*) line)->set (col);
  77060. line += destData.pixelStride;
  77061. }
  77062. }
  77063. else
  77064. {
  77065. for (int x = clipped.getWidth(); --x >= 0;)
  77066. {
  77067. *line = col.getAlpha();
  77068. line += destData.pixelStride;
  77069. }
  77070. }
  77071. }
  77072. }
  77073. }
  77074. const Colour Image::getPixelAt (const int x, const int y) const
  77075. {
  77076. if (((unsigned int) x) < (unsigned int) getWidth()
  77077. && ((unsigned int) y) < (unsigned int) getHeight())
  77078. {
  77079. const BitmapData srcData (*this, x, y, 1, 1);
  77080. return srcData.getPixelColour (0, 0);
  77081. }
  77082. return Colour();
  77083. }
  77084. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77085. {
  77086. if (((unsigned int) x) < (unsigned int) getWidth()
  77087. && ((unsigned int) y) < (unsigned int) getHeight())
  77088. {
  77089. const BitmapData destData (*this, x, y, 1, 1, true);
  77090. destData.setPixelColour (0, 0, colour);
  77091. }
  77092. }
  77093. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77094. {
  77095. if (((unsigned int) x) < (unsigned int) getWidth()
  77096. && ((unsigned int) y) < (unsigned int) getHeight()
  77097. && hasAlphaChannel())
  77098. {
  77099. const BitmapData destData (*this, x, y, 1, 1, true);
  77100. if (isARGB())
  77101. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77102. else
  77103. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77104. }
  77105. }
  77106. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77107. {
  77108. if (hasAlphaChannel())
  77109. {
  77110. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77111. if (isARGB())
  77112. {
  77113. for (int y = 0; y < destData.height; ++y)
  77114. {
  77115. uint8* p = destData.getLinePointer (y);
  77116. for (int x = 0; x < destData.width; ++x)
  77117. {
  77118. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77119. p += destData.pixelStride;
  77120. }
  77121. }
  77122. }
  77123. else
  77124. {
  77125. for (int y = 0; y < destData.height; ++y)
  77126. {
  77127. uint8* p = destData.getLinePointer (y);
  77128. for (int x = 0; x < destData.width; ++x)
  77129. {
  77130. *p = (uint8) (*p * amountToMultiplyBy);
  77131. p += destData.pixelStride;
  77132. }
  77133. }
  77134. }
  77135. }
  77136. else
  77137. {
  77138. jassertfalse; // can't do this without an alpha-channel!
  77139. }
  77140. }
  77141. void Image::desaturate()
  77142. {
  77143. if (isARGB() || isRGB())
  77144. {
  77145. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77146. if (isARGB())
  77147. {
  77148. for (int y = 0; y < destData.height; ++y)
  77149. {
  77150. uint8* p = destData.getLinePointer (y);
  77151. for (int x = 0; x < destData.width; ++x)
  77152. {
  77153. ((PixelARGB*) p)->desaturate();
  77154. p += destData.pixelStride;
  77155. }
  77156. }
  77157. }
  77158. else
  77159. {
  77160. for (int y = 0; y < destData.height; ++y)
  77161. {
  77162. uint8* p = destData.getLinePointer (y);
  77163. for (int x = 0; x < destData.width; ++x)
  77164. {
  77165. ((PixelRGB*) p)->desaturate();
  77166. p += destData.pixelStride;
  77167. }
  77168. }
  77169. }
  77170. }
  77171. }
  77172. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77173. {
  77174. if (hasAlphaChannel())
  77175. {
  77176. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77177. SparseSet<int> pixelsOnRow;
  77178. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77179. for (int y = 0; y < srcData.height; ++y)
  77180. {
  77181. pixelsOnRow.clear();
  77182. const uint8* lineData = srcData.getLinePointer (y);
  77183. if (isARGB())
  77184. {
  77185. for (int x = 0; x < srcData.width; ++x)
  77186. {
  77187. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77188. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77189. lineData += srcData.pixelStride;
  77190. }
  77191. }
  77192. else
  77193. {
  77194. for (int x = 0; x < srcData.width; ++x)
  77195. {
  77196. if (*lineData >= threshold)
  77197. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77198. lineData += srcData.pixelStride;
  77199. }
  77200. }
  77201. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77202. {
  77203. const Range<int> range (pixelsOnRow.getRange (i));
  77204. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77205. }
  77206. result.consolidate();
  77207. }
  77208. }
  77209. else
  77210. {
  77211. result.add (0, 0, getWidth(), getHeight());
  77212. }
  77213. }
  77214. void Image::moveImageSection (int dx, int dy,
  77215. int sx, int sy,
  77216. int w, int h)
  77217. {
  77218. if (dx < 0)
  77219. {
  77220. w += dx;
  77221. sx -= dx;
  77222. dx = 0;
  77223. }
  77224. if (dy < 0)
  77225. {
  77226. h += dy;
  77227. sy -= dy;
  77228. dy = 0;
  77229. }
  77230. if (sx < 0)
  77231. {
  77232. w += sx;
  77233. dx -= sx;
  77234. sx = 0;
  77235. }
  77236. if (sy < 0)
  77237. {
  77238. h += sy;
  77239. dy -= sy;
  77240. sy = 0;
  77241. }
  77242. const int minX = jmin (dx, sx);
  77243. const int minY = jmin (dy, sy);
  77244. w = jmin (w, getWidth() - jmax (sx, dx));
  77245. h = jmin (h, getHeight() - jmax (sy, dy));
  77246. if (w > 0 && h > 0)
  77247. {
  77248. const int maxX = jmax (dx, sx) + w;
  77249. const int maxY = jmax (dy, sy) + h;
  77250. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77251. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77252. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77253. const int lineSize = destData.pixelStride * w;
  77254. if (dy > sy)
  77255. {
  77256. while (--h >= 0)
  77257. {
  77258. const int offset = h * destData.lineStride;
  77259. memmove (dst + offset, src + offset, lineSize);
  77260. }
  77261. }
  77262. else if (dst != src)
  77263. {
  77264. while (--h >= 0)
  77265. {
  77266. memmove (dst, src, lineSize);
  77267. dst += destData.lineStride;
  77268. src += destData.lineStride;
  77269. }
  77270. }
  77271. }
  77272. }
  77273. END_JUCE_NAMESPACE
  77274. /*** End of inlined file: juce_Image.cpp ***/
  77275. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77276. BEGIN_JUCE_NAMESPACE
  77277. class ImageCache::Pimpl : public Timer,
  77278. public DeletedAtShutdown
  77279. {
  77280. public:
  77281. Pimpl()
  77282. : cacheTimeout (5000)
  77283. {
  77284. }
  77285. ~Pimpl()
  77286. {
  77287. clearSingletonInstance();
  77288. }
  77289. const Image getFromHashCode (const int64 hashCode)
  77290. {
  77291. const ScopedLock sl (lock);
  77292. for (int i = images.size(); --i >= 0;)
  77293. {
  77294. Item* const item = images.getUnchecked(i);
  77295. if (item->hashCode == hashCode)
  77296. return item->image;
  77297. }
  77298. return Image::null;
  77299. }
  77300. void addImageToCache (const Image& image, const int64 hashCode)
  77301. {
  77302. if (image.isValid())
  77303. {
  77304. if (! isTimerRunning())
  77305. startTimer (2000);
  77306. Item* const item = new Item();
  77307. item->hashCode = hashCode;
  77308. item->image = image;
  77309. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77310. const ScopedLock sl (lock);
  77311. images.add (item);
  77312. }
  77313. }
  77314. void timerCallback()
  77315. {
  77316. const uint32 now = Time::getApproximateMillisecondCounter();
  77317. const ScopedLock sl (lock);
  77318. for (int i = images.size(); --i >= 0;)
  77319. {
  77320. Item* const item = images.getUnchecked(i);
  77321. if (item->image.getReferenceCount() <= 1)
  77322. {
  77323. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77324. images.remove (i);
  77325. }
  77326. else
  77327. {
  77328. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77329. }
  77330. }
  77331. if (images.size() == 0)
  77332. stopTimer();
  77333. }
  77334. struct Item
  77335. {
  77336. Image image;
  77337. int64 hashCode;
  77338. uint32 lastUseTime;
  77339. };
  77340. int cacheTimeout;
  77341. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77342. private:
  77343. OwnedArray<Item> images;
  77344. CriticalSection lock;
  77345. Pimpl (const Pimpl&);
  77346. Pimpl& operator= (const Pimpl&);
  77347. };
  77348. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77349. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77350. {
  77351. if (Pimpl::getInstanceWithoutCreating() != 0)
  77352. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77353. return Image::null;
  77354. }
  77355. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77356. {
  77357. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77358. }
  77359. const Image ImageCache::getFromFile (const File& file)
  77360. {
  77361. const int64 hashCode = file.hashCode64();
  77362. Image image (getFromHashCode (hashCode));
  77363. if (image.isNull())
  77364. {
  77365. image = ImageFileFormat::loadFrom (file);
  77366. addImageToCache (image, hashCode);
  77367. }
  77368. return image;
  77369. }
  77370. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77371. {
  77372. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77373. Image image (getFromHashCode (hashCode));
  77374. if (image.isNull())
  77375. {
  77376. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77377. addImageToCache (image, hashCode);
  77378. }
  77379. return image;
  77380. }
  77381. void ImageCache::setCacheTimeout (const int millisecs)
  77382. {
  77383. Pimpl::getInstance()->cacheTimeout = millisecs;
  77384. }
  77385. END_JUCE_NAMESPACE
  77386. /*** End of inlined file: juce_ImageCache.cpp ***/
  77387. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77388. BEGIN_JUCE_NAMESPACE
  77389. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77390. : values (size_ * size_),
  77391. size (size_)
  77392. {
  77393. clear();
  77394. }
  77395. ImageConvolutionKernel::~ImageConvolutionKernel()
  77396. {
  77397. }
  77398. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77399. {
  77400. if (((unsigned int) x) < (unsigned int) size
  77401. && ((unsigned int) y) < (unsigned int) size)
  77402. {
  77403. return values [x + y * size];
  77404. }
  77405. else
  77406. {
  77407. jassertfalse;
  77408. return 0;
  77409. }
  77410. }
  77411. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77412. {
  77413. if (((unsigned int) x) < (unsigned int) size
  77414. && ((unsigned int) y) < (unsigned int) size)
  77415. {
  77416. values [x + y * size] = value;
  77417. }
  77418. else
  77419. {
  77420. jassertfalse;
  77421. }
  77422. }
  77423. void ImageConvolutionKernel::clear()
  77424. {
  77425. for (int i = size * size; --i >= 0;)
  77426. values[i] = 0;
  77427. }
  77428. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77429. {
  77430. double currentTotal = 0.0;
  77431. for (int i = size * size; --i >= 0;)
  77432. currentTotal += values[i];
  77433. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77434. }
  77435. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77436. {
  77437. for (int i = size * size; --i >= 0;)
  77438. values[i] *= multiplier;
  77439. }
  77440. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77441. {
  77442. const double radiusFactor = -1.0 / (radius * radius * 2);
  77443. const int centre = size >> 1;
  77444. for (int y = size; --y >= 0;)
  77445. {
  77446. for (int x = size; --x >= 0;)
  77447. {
  77448. const int cx = x - centre;
  77449. const int cy = y - centre;
  77450. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77451. }
  77452. }
  77453. setOverallSum (1.0f);
  77454. }
  77455. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77456. const Image& sourceImage,
  77457. const Rectangle<int>& destinationArea) const
  77458. {
  77459. if (sourceImage == destImage)
  77460. {
  77461. destImage.duplicateIfShared();
  77462. }
  77463. else
  77464. {
  77465. if (sourceImage.getWidth() != destImage.getWidth()
  77466. || sourceImage.getHeight() != destImage.getHeight()
  77467. || sourceImage.getFormat() != destImage.getFormat())
  77468. {
  77469. jassertfalse;
  77470. return;
  77471. }
  77472. }
  77473. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77474. if (area.isEmpty())
  77475. return;
  77476. const int right = area.getRight();
  77477. const int bottom = area.getBottom();
  77478. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77479. uint8* line = destData.data;
  77480. const Image::BitmapData srcData (sourceImage, false);
  77481. if (destData.pixelStride == 4)
  77482. {
  77483. for (int y = area.getY(); y < bottom; ++y)
  77484. {
  77485. uint8* dest = line;
  77486. line += destData.lineStride;
  77487. for (int x = area.getX(); x < right; ++x)
  77488. {
  77489. float c1 = 0;
  77490. float c2 = 0;
  77491. float c3 = 0;
  77492. float c4 = 0;
  77493. for (int yy = 0; yy < size; ++yy)
  77494. {
  77495. const int sy = y + yy - (size >> 1);
  77496. if (sy >= srcData.height)
  77497. break;
  77498. if (sy >= 0)
  77499. {
  77500. int sx = x - (size >> 1);
  77501. const uint8* src = srcData.getPixelPointer (sx, sy);
  77502. for (int xx = 0; xx < size; ++xx)
  77503. {
  77504. if (sx >= srcData.width)
  77505. break;
  77506. if (sx >= 0)
  77507. {
  77508. const float kernelMult = values [xx + yy * size];
  77509. c1 += kernelMult * *src++;
  77510. c2 += kernelMult * *src++;
  77511. c3 += kernelMult * *src++;
  77512. c4 += kernelMult * *src++;
  77513. }
  77514. else
  77515. {
  77516. src += 4;
  77517. }
  77518. ++sx;
  77519. }
  77520. }
  77521. }
  77522. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77523. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77524. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77525. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77526. }
  77527. }
  77528. }
  77529. else if (destData.pixelStride == 3)
  77530. {
  77531. for (int y = area.getY(); y < bottom; ++y)
  77532. {
  77533. uint8* dest = line;
  77534. line += destData.lineStride;
  77535. for (int x = area.getX(); x < right; ++x)
  77536. {
  77537. float c1 = 0;
  77538. float c2 = 0;
  77539. float c3 = 0;
  77540. for (int yy = 0; yy < size; ++yy)
  77541. {
  77542. const int sy = y + yy - (size >> 1);
  77543. if (sy >= srcData.height)
  77544. break;
  77545. if (sy >= 0)
  77546. {
  77547. int sx = x - (size >> 1);
  77548. const uint8* src = srcData.getPixelPointer (sx, sy);
  77549. for (int xx = 0; xx < size; ++xx)
  77550. {
  77551. if (sx >= srcData.width)
  77552. break;
  77553. if (sx >= 0)
  77554. {
  77555. const float kernelMult = values [xx + yy * size];
  77556. c1 += kernelMult * *src++;
  77557. c2 += kernelMult * *src++;
  77558. c3 += kernelMult * *src++;
  77559. }
  77560. else
  77561. {
  77562. src += 3;
  77563. }
  77564. ++sx;
  77565. }
  77566. }
  77567. }
  77568. *dest++ = (uint8) roundToInt (c1);
  77569. *dest++ = (uint8) roundToInt (c2);
  77570. *dest++ = (uint8) roundToInt (c3);
  77571. }
  77572. }
  77573. }
  77574. }
  77575. END_JUCE_NAMESPACE
  77576. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77577. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77578. BEGIN_JUCE_NAMESPACE
  77579. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77580. {
  77581. static PNGImageFormat png;
  77582. static JPEGImageFormat jpg;
  77583. static GIFImageFormat gif;
  77584. ImageFileFormat* formats[4];
  77585. int numFormats = 0;
  77586. formats [numFormats++] = &png;
  77587. formats [numFormats++] = &jpg;
  77588. formats [numFormats++] = &gif;
  77589. const int64 streamPos = input.getPosition();
  77590. for (int i = 0; i < numFormats; ++i)
  77591. {
  77592. const bool found = formats[i]->canUnderstand (input);
  77593. input.setPosition (streamPos);
  77594. if (found)
  77595. return formats[i];
  77596. }
  77597. return 0;
  77598. }
  77599. const Image ImageFileFormat::loadFrom (InputStream& input)
  77600. {
  77601. ImageFileFormat* const format = findImageFormatForStream (input);
  77602. if (format != 0)
  77603. return format->decodeImage (input);
  77604. return Image::null;
  77605. }
  77606. const Image ImageFileFormat::loadFrom (const File& file)
  77607. {
  77608. InputStream* const in = file.createInputStream();
  77609. if (in != 0)
  77610. {
  77611. BufferedInputStream b (in, 8192, true);
  77612. return loadFrom (b);
  77613. }
  77614. return Image::null;
  77615. }
  77616. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77617. {
  77618. if (rawData != 0 && numBytes > 4)
  77619. {
  77620. MemoryInputStream stream (rawData, numBytes, false);
  77621. return loadFrom (stream);
  77622. }
  77623. return Image::null;
  77624. }
  77625. END_JUCE_NAMESPACE
  77626. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77627. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77628. BEGIN_JUCE_NAMESPACE
  77629. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77630. const Image juce_loadWithCoreImage (InputStream& input);
  77631. #else
  77632. class GIFLoader
  77633. {
  77634. public:
  77635. GIFLoader (InputStream& in)
  77636. : input (in),
  77637. dataBlockIsZero (false),
  77638. fresh (false),
  77639. finished (false)
  77640. {
  77641. currentBit = lastBit = lastByteIndex = 0;
  77642. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77643. firstcode = oldcode = 0;
  77644. clearCode = end_code = 0;
  77645. int imageWidth, imageHeight;
  77646. int transparent = -1;
  77647. if (! getSizeFromHeader (imageWidth, imageHeight))
  77648. return;
  77649. if ((imageWidth <= 0) || (imageHeight <= 0))
  77650. return;
  77651. unsigned char buf [16];
  77652. if (in.read (buf, 3) != 3)
  77653. return;
  77654. int numColours = 2 << (buf[0] & 7);
  77655. if ((buf[0] & 0x80) != 0)
  77656. readPalette (numColours);
  77657. for (;;)
  77658. {
  77659. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77660. break;
  77661. if (buf[0] == '!')
  77662. {
  77663. if (input.read (buf, 1) != 1)
  77664. break;
  77665. if (processExtension (buf[0], transparent) < 0)
  77666. break;
  77667. continue;
  77668. }
  77669. if (buf[0] != ',')
  77670. continue;
  77671. if (input.read (buf, 9) != 9)
  77672. break;
  77673. imageWidth = makeWord (buf[4], buf[5]);
  77674. imageHeight = makeWord (buf[6], buf[7]);
  77675. numColours = 2 << (buf[8] & 7);
  77676. if ((buf[8] & 0x80) != 0)
  77677. if (! readPalette (numColours))
  77678. break;
  77679. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77680. imageWidth, imageHeight, (transparent >= 0));
  77681. readImage ((buf[8] & 0x40) != 0, transparent);
  77682. break;
  77683. }
  77684. }
  77685. ~GIFLoader() {}
  77686. Image image;
  77687. private:
  77688. InputStream& input;
  77689. uint8 buffer [300];
  77690. uint8 palette [256][4];
  77691. bool dataBlockIsZero, fresh, finished;
  77692. int currentBit, lastBit, lastByteIndex;
  77693. int codeSize, setCodeSize;
  77694. int maxCode, maxCodeSize;
  77695. int firstcode, oldcode;
  77696. int clearCode, end_code;
  77697. enum { maxGifCode = 1 << 12 };
  77698. int table [2] [maxGifCode];
  77699. int stack [2 * maxGifCode];
  77700. int *sp;
  77701. bool getSizeFromHeader (int& w, int& h)
  77702. {
  77703. char b[8];
  77704. if (input.read (b, 6) == 6)
  77705. {
  77706. if ((strncmp ("GIF87a", b, 6) == 0)
  77707. || (strncmp ("GIF89a", b, 6) == 0))
  77708. {
  77709. if (input.read (b, 4) == 4)
  77710. {
  77711. w = makeWord (b[0], b[1]);
  77712. h = makeWord (b[2], b[3]);
  77713. return true;
  77714. }
  77715. }
  77716. }
  77717. return false;
  77718. }
  77719. bool readPalette (const int numCols)
  77720. {
  77721. unsigned char rgb[4];
  77722. for (int i = 0; i < numCols; ++i)
  77723. {
  77724. input.read (rgb, 3);
  77725. palette [i][0] = rgb[0];
  77726. palette [i][1] = rgb[1];
  77727. palette [i][2] = rgb[2];
  77728. palette [i][3] = 0xff;
  77729. }
  77730. return true;
  77731. }
  77732. int readDataBlock (unsigned char* dest)
  77733. {
  77734. unsigned char n;
  77735. if (input.read (&n, 1) == 1)
  77736. {
  77737. dataBlockIsZero = (n == 0);
  77738. if (dataBlockIsZero || (input.read (dest, n) == n))
  77739. return n;
  77740. }
  77741. return -1;
  77742. }
  77743. int processExtension (const int type, int& transparent)
  77744. {
  77745. unsigned char b [300];
  77746. int n = 0;
  77747. if (type == 0xf9)
  77748. {
  77749. n = readDataBlock (b);
  77750. if (n < 0)
  77751. return 1;
  77752. if ((b[0] & 0x1) != 0)
  77753. transparent = b[3];
  77754. }
  77755. do
  77756. {
  77757. n = readDataBlock (b);
  77758. }
  77759. while (n > 0);
  77760. return n;
  77761. }
  77762. int readLZWByte (const bool initialise, const int inputCodeSize)
  77763. {
  77764. int code, incode, i;
  77765. if (initialise)
  77766. {
  77767. setCodeSize = inputCodeSize;
  77768. codeSize = setCodeSize + 1;
  77769. clearCode = 1 << setCodeSize;
  77770. end_code = clearCode + 1;
  77771. maxCodeSize = 2 * clearCode;
  77772. maxCode = clearCode + 2;
  77773. getCode (0, true);
  77774. fresh = true;
  77775. for (i = 0; i < clearCode; ++i)
  77776. {
  77777. table[0][i] = 0;
  77778. table[1][i] = i;
  77779. }
  77780. for (; i < maxGifCode; ++i)
  77781. {
  77782. table[0][i] = 0;
  77783. table[1][i] = 0;
  77784. }
  77785. sp = stack;
  77786. return 0;
  77787. }
  77788. else if (fresh)
  77789. {
  77790. fresh = false;
  77791. do
  77792. {
  77793. firstcode = oldcode
  77794. = getCode (codeSize, false);
  77795. }
  77796. while (firstcode == clearCode);
  77797. return firstcode;
  77798. }
  77799. if (sp > stack)
  77800. return *--sp;
  77801. while ((code = getCode (codeSize, false)) >= 0)
  77802. {
  77803. if (code == clearCode)
  77804. {
  77805. for (i = 0; i < clearCode; ++i)
  77806. {
  77807. table[0][i] = 0;
  77808. table[1][i] = i;
  77809. }
  77810. for (; i < maxGifCode; ++i)
  77811. {
  77812. table[0][i] = 0;
  77813. table[1][i] = 0;
  77814. }
  77815. codeSize = setCodeSize + 1;
  77816. maxCodeSize = 2 * clearCode;
  77817. maxCode = clearCode + 2;
  77818. sp = stack;
  77819. firstcode = oldcode = getCode (codeSize, false);
  77820. return firstcode;
  77821. }
  77822. else if (code == end_code)
  77823. {
  77824. if (dataBlockIsZero)
  77825. return -2;
  77826. unsigned char buf [260];
  77827. int n;
  77828. while ((n = readDataBlock (buf)) > 0)
  77829. {}
  77830. if (n != 0)
  77831. return -2;
  77832. }
  77833. incode = code;
  77834. if (code >= maxCode)
  77835. {
  77836. *sp++ = firstcode;
  77837. code = oldcode;
  77838. }
  77839. while (code >= clearCode)
  77840. {
  77841. *sp++ = table[1][code];
  77842. if (code == table[0][code])
  77843. return -2;
  77844. code = table[0][code];
  77845. }
  77846. *sp++ = firstcode = table[1][code];
  77847. if ((code = maxCode) < maxGifCode)
  77848. {
  77849. table[0][code] = oldcode;
  77850. table[1][code] = firstcode;
  77851. ++maxCode;
  77852. if ((maxCode >= maxCodeSize)
  77853. && (maxCodeSize < maxGifCode))
  77854. {
  77855. maxCodeSize <<= 1;
  77856. ++codeSize;
  77857. }
  77858. }
  77859. oldcode = incode;
  77860. if (sp > stack)
  77861. return *--sp;
  77862. }
  77863. return code;
  77864. }
  77865. int getCode (const int codeSize_, const bool initialise)
  77866. {
  77867. if (initialise)
  77868. {
  77869. currentBit = 0;
  77870. lastBit = 0;
  77871. finished = false;
  77872. return 0;
  77873. }
  77874. if ((currentBit + codeSize_) >= lastBit)
  77875. {
  77876. if (finished)
  77877. return -1;
  77878. buffer[0] = buffer [lastByteIndex - 2];
  77879. buffer[1] = buffer [lastByteIndex - 1];
  77880. const int n = readDataBlock (&buffer[2]);
  77881. if (n == 0)
  77882. finished = true;
  77883. lastByteIndex = 2 + n;
  77884. currentBit = (currentBit - lastBit) + 16;
  77885. lastBit = (2 + n) * 8 ;
  77886. }
  77887. int result = 0;
  77888. int i = currentBit;
  77889. for (int j = 0; j < codeSize_; ++j)
  77890. {
  77891. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77892. ++i;
  77893. }
  77894. currentBit += codeSize_;
  77895. return result;
  77896. }
  77897. bool readImage (const int interlace, const int transparent)
  77898. {
  77899. unsigned char c;
  77900. if (input.read (&c, 1) != 1
  77901. || readLZWByte (true, c) < 0)
  77902. return false;
  77903. if (transparent >= 0)
  77904. {
  77905. palette [transparent][0] = 0;
  77906. palette [transparent][1] = 0;
  77907. palette [transparent][2] = 0;
  77908. palette [transparent][3] = 0;
  77909. }
  77910. int index;
  77911. int xpos = 0, ypos = 0, pass = 0;
  77912. const Image::BitmapData destData (image, true);
  77913. uint8* p = destData.data;
  77914. const bool hasAlpha = image.hasAlphaChannel();
  77915. while ((index = readLZWByte (false, c)) >= 0)
  77916. {
  77917. const uint8* const paletteEntry = palette [index];
  77918. if (hasAlpha)
  77919. {
  77920. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77921. paletteEntry[0],
  77922. paletteEntry[1],
  77923. paletteEntry[2]);
  77924. ((PixelARGB*) p)->premultiply();
  77925. }
  77926. else
  77927. {
  77928. ((PixelRGB*) p)->setARGB (0,
  77929. paletteEntry[0],
  77930. paletteEntry[1],
  77931. paletteEntry[2]);
  77932. }
  77933. p += destData.pixelStride;
  77934. ++xpos;
  77935. if (xpos == destData.width)
  77936. {
  77937. xpos = 0;
  77938. if (interlace)
  77939. {
  77940. switch (pass)
  77941. {
  77942. case 0:
  77943. case 1: ypos += 8; break;
  77944. case 2: ypos += 4; break;
  77945. case 3: ypos += 2; break;
  77946. }
  77947. while (ypos >= destData.height)
  77948. {
  77949. ++pass;
  77950. switch (pass)
  77951. {
  77952. case 1: ypos = 4; break;
  77953. case 2: ypos = 2; break;
  77954. case 3: ypos = 1; break;
  77955. default: return true;
  77956. }
  77957. }
  77958. }
  77959. else
  77960. {
  77961. ++ypos;
  77962. }
  77963. p = destData.getPixelPointer (xpos, ypos);
  77964. }
  77965. if (ypos >= destData.height)
  77966. break;
  77967. }
  77968. return true;
  77969. }
  77970. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77971. GIFLoader (const GIFLoader&);
  77972. GIFLoader& operator= (const GIFLoader&);
  77973. };
  77974. #endif
  77975. GIFImageFormat::GIFImageFormat() {}
  77976. GIFImageFormat::~GIFImageFormat() {}
  77977. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77978. bool GIFImageFormat::canUnderstand (InputStream& in)
  77979. {
  77980. char header [4];
  77981. return (in.read (header, sizeof (header)) == sizeof (header))
  77982. && header[0] == 'G'
  77983. && header[1] == 'I'
  77984. && header[2] == 'F';
  77985. }
  77986. const Image GIFImageFormat::decodeImage (InputStream& in)
  77987. {
  77988. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77989. return juce_loadWithCoreImage (in);
  77990. #else
  77991. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77992. return loader->image;
  77993. #endif
  77994. }
  77995. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77996. {
  77997. jassertfalse; // writing isn't implemented for GIFs!
  77998. return false;
  77999. }
  78000. END_JUCE_NAMESPACE
  78001. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78002. #endif
  78003. //==============================================================================
  78004. // some files include lots of library code, so leave them to the end to avoid cluttering
  78005. // up the build for the clean files.
  78006. #if JUCE_BUILD_CORE
  78007. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78008. namespace zlibNamespace
  78009. {
  78010. #if JUCE_INCLUDE_ZLIB_CODE
  78011. #undef OS_CODE
  78012. #undef fdopen
  78013. /*** Start of inlined file: zlib.h ***/
  78014. #ifndef ZLIB_H
  78015. #define ZLIB_H
  78016. /*** Start of inlined file: zconf.h ***/
  78017. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78018. #ifndef ZCONF_H
  78019. #define ZCONF_H
  78020. // *** Just a few hacks here to make it compile nicely with Juce..
  78021. #define Z_PREFIX 1
  78022. #undef __MACTYPES__
  78023. #ifdef _MSC_VER
  78024. #pragma warning (disable : 4131 4127 4244 4267)
  78025. #endif
  78026. /*
  78027. * If you *really* need a unique prefix for all types and library functions,
  78028. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78029. */
  78030. #ifdef Z_PREFIX
  78031. # define deflateInit_ z_deflateInit_
  78032. # define deflate z_deflate
  78033. # define deflateEnd z_deflateEnd
  78034. # define inflateInit_ z_inflateInit_
  78035. # define inflate z_inflate
  78036. # define inflateEnd z_inflateEnd
  78037. # define inflatePrime z_inflatePrime
  78038. # define inflateGetHeader z_inflateGetHeader
  78039. # define adler32_combine z_adler32_combine
  78040. # define crc32_combine z_crc32_combine
  78041. # define deflateInit2_ z_deflateInit2_
  78042. # define deflateSetDictionary z_deflateSetDictionary
  78043. # define deflateCopy z_deflateCopy
  78044. # define deflateReset z_deflateReset
  78045. # define deflateParams z_deflateParams
  78046. # define deflateBound z_deflateBound
  78047. # define deflatePrime z_deflatePrime
  78048. # define inflateInit2_ z_inflateInit2_
  78049. # define inflateSetDictionary z_inflateSetDictionary
  78050. # define inflateSync z_inflateSync
  78051. # define inflateSyncPoint z_inflateSyncPoint
  78052. # define inflateCopy z_inflateCopy
  78053. # define inflateReset z_inflateReset
  78054. # define inflateBack z_inflateBack
  78055. # define inflateBackEnd z_inflateBackEnd
  78056. # define compress z_compress
  78057. # define compress2 z_compress2
  78058. # define compressBound z_compressBound
  78059. # define uncompress z_uncompress
  78060. # define adler32 z_adler32
  78061. # define crc32 z_crc32
  78062. # define get_crc_table z_get_crc_table
  78063. # define zError z_zError
  78064. # define alloc_func z_alloc_func
  78065. # define free_func z_free_func
  78066. # define in_func z_in_func
  78067. # define out_func z_out_func
  78068. # define Byte z_Byte
  78069. # define uInt z_uInt
  78070. # define uLong z_uLong
  78071. # define Bytef z_Bytef
  78072. # define charf z_charf
  78073. # define intf z_intf
  78074. # define uIntf z_uIntf
  78075. # define uLongf z_uLongf
  78076. # define voidpf z_voidpf
  78077. # define voidp z_voidp
  78078. #endif
  78079. #if defined(__MSDOS__) && !defined(MSDOS)
  78080. # define MSDOS
  78081. #endif
  78082. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78083. # define OS2
  78084. #endif
  78085. #if defined(_WINDOWS) && !defined(WINDOWS)
  78086. # define WINDOWS
  78087. #endif
  78088. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78089. # ifndef WIN32
  78090. # define WIN32
  78091. # endif
  78092. #endif
  78093. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78094. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78095. # ifndef SYS16BIT
  78096. # define SYS16BIT
  78097. # endif
  78098. # endif
  78099. #endif
  78100. /*
  78101. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78102. * than 64k bytes at a time (needed on systems with 16-bit int).
  78103. */
  78104. #ifdef SYS16BIT
  78105. # define MAXSEG_64K
  78106. #endif
  78107. #ifdef MSDOS
  78108. # define UNALIGNED_OK
  78109. #endif
  78110. #ifdef __STDC_VERSION__
  78111. # ifndef STDC
  78112. # define STDC
  78113. # endif
  78114. # if __STDC_VERSION__ >= 199901L
  78115. # ifndef STDC99
  78116. # define STDC99
  78117. # endif
  78118. # endif
  78119. #endif
  78120. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78121. # define STDC
  78122. #endif
  78123. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78124. # define STDC
  78125. #endif
  78126. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78127. # define STDC
  78128. #endif
  78129. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78130. # define STDC
  78131. #endif
  78132. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78133. # define STDC
  78134. #endif
  78135. #ifndef STDC
  78136. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78137. # define const /* note: need a more gentle solution here */
  78138. # endif
  78139. #endif
  78140. /* Some Mac compilers merge all .h files incorrectly: */
  78141. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78142. # define NO_DUMMY_DECL
  78143. #endif
  78144. /* Maximum value for memLevel in deflateInit2 */
  78145. #ifndef MAX_MEM_LEVEL
  78146. # ifdef MAXSEG_64K
  78147. # define MAX_MEM_LEVEL 8
  78148. # else
  78149. # define MAX_MEM_LEVEL 9
  78150. # endif
  78151. #endif
  78152. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78153. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78154. * created by gzip. (Files created by minigzip can still be extracted by
  78155. * gzip.)
  78156. */
  78157. #ifndef MAX_WBITS
  78158. # define MAX_WBITS 15 /* 32K LZ77 window */
  78159. #endif
  78160. /* The memory requirements for deflate are (in bytes):
  78161. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78162. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78163. plus a few kilobytes for small objects. For example, if you want to reduce
  78164. the default memory requirements from 256K to 128K, compile with
  78165. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78166. Of course this will generally degrade compression (there's no free lunch).
  78167. The memory requirements for inflate are (in bytes) 1 << windowBits
  78168. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78169. for small objects.
  78170. */
  78171. /* Type declarations */
  78172. #ifndef OF /* function prototypes */
  78173. # ifdef STDC
  78174. # define OF(args) args
  78175. # else
  78176. # define OF(args) ()
  78177. # endif
  78178. #endif
  78179. /* The following definitions for FAR are needed only for MSDOS mixed
  78180. * model programming (small or medium model with some far allocations).
  78181. * This was tested only with MSC; for other MSDOS compilers you may have
  78182. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78183. * just define FAR to be empty.
  78184. */
  78185. #ifdef SYS16BIT
  78186. # if defined(M_I86SM) || defined(M_I86MM)
  78187. /* MSC small or medium model */
  78188. # define SMALL_MEDIUM
  78189. # ifdef _MSC_VER
  78190. # define FAR _far
  78191. # else
  78192. # define FAR far
  78193. # endif
  78194. # endif
  78195. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78196. /* Turbo C small or medium model */
  78197. # define SMALL_MEDIUM
  78198. # ifdef __BORLANDC__
  78199. # define FAR _far
  78200. # else
  78201. # define FAR far
  78202. # endif
  78203. # endif
  78204. #endif
  78205. #if defined(WINDOWS) || defined(WIN32)
  78206. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78207. * This is not mandatory, but it offers a little performance increase.
  78208. */
  78209. # ifdef ZLIB_DLL
  78210. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78211. # ifdef ZLIB_INTERNAL
  78212. # define ZEXTERN extern __declspec(dllexport)
  78213. # else
  78214. # define ZEXTERN extern __declspec(dllimport)
  78215. # endif
  78216. # endif
  78217. # endif /* ZLIB_DLL */
  78218. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78219. * define ZLIB_WINAPI.
  78220. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78221. */
  78222. # ifdef ZLIB_WINAPI
  78223. # ifdef FAR
  78224. # undef FAR
  78225. # endif
  78226. # include <windows.h>
  78227. /* No need for _export, use ZLIB.DEF instead. */
  78228. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78229. # define ZEXPORT WINAPI
  78230. # ifdef WIN32
  78231. # define ZEXPORTVA WINAPIV
  78232. # else
  78233. # define ZEXPORTVA FAR CDECL
  78234. # endif
  78235. # endif
  78236. #endif
  78237. #if defined (__BEOS__)
  78238. # ifdef ZLIB_DLL
  78239. # ifdef ZLIB_INTERNAL
  78240. # define ZEXPORT __declspec(dllexport)
  78241. # define ZEXPORTVA __declspec(dllexport)
  78242. # else
  78243. # define ZEXPORT __declspec(dllimport)
  78244. # define ZEXPORTVA __declspec(dllimport)
  78245. # endif
  78246. # endif
  78247. #endif
  78248. #ifndef ZEXTERN
  78249. # define ZEXTERN extern
  78250. #endif
  78251. #ifndef ZEXPORT
  78252. # define ZEXPORT
  78253. #endif
  78254. #ifndef ZEXPORTVA
  78255. # define ZEXPORTVA
  78256. #endif
  78257. #ifndef FAR
  78258. # define FAR
  78259. #endif
  78260. #if !defined(__MACTYPES__)
  78261. typedef unsigned char Byte; /* 8 bits */
  78262. #endif
  78263. typedef unsigned int uInt; /* 16 bits or more */
  78264. typedef unsigned long uLong; /* 32 bits or more */
  78265. #ifdef SMALL_MEDIUM
  78266. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78267. # define Bytef Byte FAR
  78268. #else
  78269. typedef Byte FAR Bytef;
  78270. #endif
  78271. typedef char FAR charf;
  78272. typedef int FAR intf;
  78273. typedef uInt FAR uIntf;
  78274. typedef uLong FAR uLongf;
  78275. #ifdef STDC
  78276. typedef void const *voidpc;
  78277. typedef void FAR *voidpf;
  78278. typedef void *voidp;
  78279. #else
  78280. typedef Byte const *voidpc;
  78281. typedef Byte FAR *voidpf;
  78282. typedef Byte *voidp;
  78283. #endif
  78284. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78285. # include <sys/types.h> /* for off_t */
  78286. # include <unistd.h> /* for SEEK_* and off_t */
  78287. # ifdef VMS
  78288. # include <unixio.h> /* for off_t */
  78289. # endif
  78290. # define z_off_t off_t
  78291. #endif
  78292. #ifndef SEEK_SET
  78293. # define SEEK_SET 0 /* Seek from beginning of file. */
  78294. # define SEEK_CUR 1 /* Seek from current position. */
  78295. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78296. #endif
  78297. #ifndef z_off_t
  78298. # define z_off_t long
  78299. #endif
  78300. #if defined(__OS400__)
  78301. # define NO_vsnprintf
  78302. #endif
  78303. #if defined(__MVS__)
  78304. # define NO_vsnprintf
  78305. # ifdef FAR
  78306. # undef FAR
  78307. # endif
  78308. #endif
  78309. /* MVS linker does not support external names larger than 8 bytes */
  78310. #if defined(__MVS__)
  78311. # pragma map(deflateInit_,"DEIN")
  78312. # pragma map(deflateInit2_,"DEIN2")
  78313. # pragma map(deflateEnd,"DEEND")
  78314. # pragma map(deflateBound,"DEBND")
  78315. # pragma map(inflateInit_,"ININ")
  78316. # pragma map(inflateInit2_,"ININ2")
  78317. # pragma map(inflateEnd,"INEND")
  78318. # pragma map(inflateSync,"INSY")
  78319. # pragma map(inflateSetDictionary,"INSEDI")
  78320. # pragma map(compressBound,"CMBND")
  78321. # pragma map(inflate_table,"INTABL")
  78322. # pragma map(inflate_fast,"INFA")
  78323. # pragma map(inflate_copyright,"INCOPY")
  78324. #endif
  78325. #endif /* ZCONF_H */
  78326. /*** End of inlined file: zconf.h ***/
  78327. #ifdef __cplusplus
  78328. //extern "C" {
  78329. #endif
  78330. #define ZLIB_VERSION "1.2.3"
  78331. #define ZLIB_VERNUM 0x1230
  78332. /*
  78333. The 'zlib' compression library provides in-memory compression and
  78334. decompression functions, including integrity checks of the uncompressed
  78335. data. This version of the library supports only one compression method
  78336. (deflation) but other algorithms will be added later and will have the same
  78337. stream interface.
  78338. Compression can be done in a single step if the buffers are large
  78339. enough (for example if an input file is mmap'ed), or can be done by
  78340. repeated calls of the compression function. In the latter case, the
  78341. application must provide more input and/or consume the output
  78342. (providing more output space) before each call.
  78343. The compressed data format used by default by the in-memory functions is
  78344. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78345. around a deflate stream, which is itself documented in RFC 1951.
  78346. The library also supports reading and writing files in gzip (.gz) format
  78347. with an interface similar to that of stdio using the functions that start
  78348. with "gz". The gzip format is different from the zlib format. gzip is a
  78349. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78350. This library can optionally read and write gzip streams in memory as well.
  78351. The zlib format was designed to be compact and fast for use in memory
  78352. and on communications channels. The gzip format was designed for single-
  78353. file compression on file systems, has a larger header than zlib to maintain
  78354. directory information, and uses a different, slower check method than zlib.
  78355. The library does not install any signal handler. The decoder checks
  78356. the consistency of the compressed data, so the library should never
  78357. crash even in case of corrupted input.
  78358. */
  78359. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78360. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78361. struct internal_state;
  78362. typedef struct z_stream_s {
  78363. Bytef *next_in; /* next input byte */
  78364. uInt avail_in; /* number of bytes available at next_in */
  78365. uLong total_in; /* total nb of input bytes read so far */
  78366. Bytef *next_out; /* next output byte should be put there */
  78367. uInt avail_out; /* remaining free space at next_out */
  78368. uLong total_out; /* total nb of bytes output so far */
  78369. char *msg; /* last error message, NULL if no error */
  78370. struct internal_state FAR *state; /* not visible by applications */
  78371. alloc_func zalloc; /* used to allocate the internal state */
  78372. free_func zfree; /* used to free the internal state */
  78373. voidpf opaque; /* private data object passed to zalloc and zfree */
  78374. int data_type; /* best guess about the data type: binary or text */
  78375. uLong adler; /* adler32 value of the uncompressed data */
  78376. uLong reserved; /* reserved for future use */
  78377. } z_stream;
  78378. typedef z_stream FAR *z_streamp;
  78379. /*
  78380. gzip header information passed to and from zlib routines. See RFC 1952
  78381. for more details on the meanings of these fields.
  78382. */
  78383. typedef struct gz_header_s {
  78384. int text; /* true if compressed data believed to be text */
  78385. uLong time; /* modification time */
  78386. int xflags; /* extra flags (not used when writing a gzip file) */
  78387. int os; /* operating system */
  78388. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78389. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78390. uInt extra_max; /* space at extra (only when reading header) */
  78391. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78392. uInt name_max; /* space at name (only when reading header) */
  78393. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78394. uInt comm_max; /* space at comment (only when reading header) */
  78395. int hcrc; /* true if there was or will be a header crc */
  78396. int done; /* true when done reading gzip header (not used
  78397. when writing a gzip file) */
  78398. } gz_header;
  78399. typedef gz_header FAR *gz_headerp;
  78400. /*
  78401. The application must update next_in and avail_in when avail_in has
  78402. dropped to zero. It must update next_out and avail_out when avail_out
  78403. has dropped to zero. The application must initialize zalloc, zfree and
  78404. opaque before calling the init function. All other fields are set by the
  78405. compression library and must not be updated by the application.
  78406. The opaque value provided by the application will be passed as the first
  78407. parameter for calls of zalloc and zfree. This can be useful for custom
  78408. memory management. The compression library attaches no meaning to the
  78409. opaque value.
  78410. zalloc must return Z_NULL if there is not enough memory for the object.
  78411. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78412. thread safe.
  78413. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78414. exactly 65536 bytes, but will not be required to allocate more than this
  78415. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78416. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78417. have their offset normalized to zero. The default allocation function
  78418. provided by this library ensures this (see zutil.c). To reduce memory
  78419. requirements and avoid any allocation of 64K objects, at the expense of
  78420. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78421. The fields total_in and total_out can be used for statistics or
  78422. progress reports. After compression, total_in holds the total size of
  78423. the uncompressed data and may be saved for use in the decompressor
  78424. (particularly if the decompressor wants to decompress everything in
  78425. a single step).
  78426. */
  78427. /* constants */
  78428. #define Z_NO_FLUSH 0
  78429. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78430. #define Z_SYNC_FLUSH 2
  78431. #define Z_FULL_FLUSH 3
  78432. #define Z_FINISH 4
  78433. #define Z_BLOCK 5
  78434. /* Allowed flush values; see deflate() and inflate() below for details */
  78435. #define Z_OK 0
  78436. #define Z_STREAM_END 1
  78437. #define Z_NEED_DICT 2
  78438. #define Z_ERRNO (-1)
  78439. #define Z_STREAM_ERROR (-2)
  78440. #define Z_DATA_ERROR (-3)
  78441. #define Z_MEM_ERROR (-4)
  78442. #define Z_BUF_ERROR (-5)
  78443. #define Z_VERSION_ERROR (-6)
  78444. /* Return codes for the compression/decompression functions. Negative
  78445. * values are errors, positive values are used for special but normal events.
  78446. */
  78447. #define Z_NO_COMPRESSION 0
  78448. #define Z_BEST_SPEED 1
  78449. #define Z_BEST_COMPRESSION 9
  78450. #define Z_DEFAULT_COMPRESSION (-1)
  78451. /* compression levels */
  78452. #define Z_FILTERED 1
  78453. #define Z_HUFFMAN_ONLY 2
  78454. #define Z_RLE 3
  78455. #define Z_FIXED 4
  78456. #define Z_DEFAULT_STRATEGY 0
  78457. /* compression strategy; see deflateInit2() below for details */
  78458. #define Z_BINARY 0
  78459. #define Z_TEXT 1
  78460. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78461. #define Z_UNKNOWN 2
  78462. /* Possible values of the data_type field (though see inflate()) */
  78463. #define Z_DEFLATED 8
  78464. /* The deflate compression method (the only one supported in this version) */
  78465. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78466. #define zlib_version zlibVersion()
  78467. /* for compatibility with versions < 1.0.2 */
  78468. /* basic functions */
  78469. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78470. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78471. If the first character differs, the library code actually used is
  78472. not compatible with the zlib.h header file used by the application.
  78473. This check is automatically made by deflateInit and inflateInit.
  78474. */
  78475. /*
  78476. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78477. Initializes the internal stream state for compression. The fields
  78478. zalloc, zfree and opaque must be initialized before by the caller.
  78479. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78480. use default allocation functions.
  78481. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78482. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78483. all (the input data is simply copied a block at a time).
  78484. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78485. compression (currently equivalent to level 6).
  78486. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78487. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78488. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78489. with the version assumed by the caller (ZLIB_VERSION).
  78490. msg is set to null if there is no error message. deflateInit does not
  78491. perform any compression: this will be done by deflate().
  78492. */
  78493. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78494. /*
  78495. deflate compresses as much data as possible, and stops when the input
  78496. buffer becomes empty or the output buffer becomes full. It may introduce some
  78497. output latency (reading input without producing any output) except when
  78498. forced to flush.
  78499. The detailed semantics are as follows. deflate performs one or both of the
  78500. following actions:
  78501. - Compress more input starting at next_in and update next_in and avail_in
  78502. accordingly. If not all input can be processed (because there is not
  78503. enough room in the output buffer), next_in and avail_in are updated and
  78504. processing will resume at this point for the next call of deflate().
  78505. - Provide more output starting at next_out and update next_out and avail_out
  78506. accordingly. This action is forced if the parameter flush is non zero.
  78507. Forcing flush frequently degrades the compression ratio, so this parameter
  78508. should be set only when necessary (in interactive applications).
  78509. Some output may be provided even if flush is not set.
  78510. Before the call of deflate(), the application should ensure that at least
  78511. one of the actions is possible, by providing more input and/or consuming
  78512. more output, and updating avail_in or avail_out accordingly; avail_out
  78513. should never be zero before the call. The application can consume the
  78514. compressed output when it wants, for example when the output buffer is full
  78515. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78516. and with zero avail_out, it must be called again after making room in the
  78517. output buffer because there might be more output pending.
  78518. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78519. decide how much data to accumualte before producing output, in order to
  78520. maximize compression.
  78521. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78522. flushed to the output buffer and the output is aligned on a byte boundary, so
  78523. that the decompressor can get all input data available so far. (In particular
  78524. avail_in is zero after the call if enough output space has been provided
  78525. before the call.) Flushing may degrade compression for some compression
  78526. algorithms and so it should be used only when necessary.
  78527. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78528. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78529. restart from this point if previous compressed data has been damaged or if
  78530. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78531. compression.
  78532. If deflate returns with avail_out == 0, this function must be called again
  78533. with the same value of the flush parameter and more output space (updated
  78534. avail_out), until the flush is complete (deflate returns with non-zero
  78535. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78536. avail_out is greater than six to avoid repeated flush markers due to
  78537. avail_out == 0 on return.
  78538. If the parameter flush is set to Z_FINISH, pending input is processed,
  78539. pending output is flushed and deflate returns with Z_STREAM_END if there
  78540. was enough output space; if deflate returns with Z_OK, this function must be
  78541. called again with Z_FINISH and more output space (updated avail_out) but no
  78542. more input data, until it returns with Z_STREAM_END or an error. After
  78543. deflate has returned Z_STREAM_END, the only possible operations on the
  78544. stream are deflateReset or deflateEnd.
  78545. Z_FINISH can be used immediately after deflateInit if all the compression
  78546. is to be done in a single step. In this case, avail_out must be at least
  78547. the value returned by deflateBound (see below). If deflate does not return
  78548. Z_STREAM_END, then it must be called again as described above.
  78549. deflate() sets strm->adler to the adler32 checksum of all input read
  78550. so far (that is, total_in bytes).
  78551. deflate() may update strm->data_type if it can make a good guess about
  78552. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78553. binary. This field is only for information purposes and does not affect
  78554. the compression algorithm in any manner.
  78555. deflate() returns Z_OK if some progress has been made (more input
  78556. processed or more output produced), Z_STREAM_END if all input has been
  78557. consumed and all output has been produced (only when flush is set to
  78558. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78559. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78560. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78561. fatal, and deflate() can be called again with more input and more output
  78562. space to continue compressing.
  78563. */
  78564. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78565. /*
  78566. All dynamically allocated data structures for this stream are freed.
  78567. This function discards any unprocessed input and does not flush any
  78568. pending output.
  78569. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78570. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78571. prematurely (some input or output was discarded). In the error case,
  78572. msg may be set but then points to a static string (which must not be
  78573. deallocated).
  78574. */
  78575. /*
  78576. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78577. Initializes the internal stream state for decompression. The fields
  78578. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78579. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78580. value depends on the compression method), inflateInit determines the
  78581. compression method from the zlib header and allocates all data structures
  78582. accordingly; otherwise the allocation will be deferred to the first call of
  78583. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78584. use default allocation functions.
  78585. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78586. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78587. version assumed by the caller. msg is set to null if there is no error
  78588. message. inflateInit does not perform any decompression apart from reading
  78589. the zlib header if present: this will be done by inflate(). (So next_in and
  78590. avail_in may be modified, but next_out and avail_out are unchanged.)
  78591. */
  78592. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78593. /*
  78594. inflate decompresses as much data as possible, and stops when the input
  78595. buffer becomes empty or the output buffer becomes full. It may introduce
  78596. some output latency (reading input without producing any output) except when
  78597. forced to flush.
  78598. The detailed semantics are as follows. inflate performs one or both of the
  78599. following actions:
  78600. - Decompress more input starting at next_in and update next_in and avail_in
  78601. accordingly. If not all input can be processed (because there is not
  78602. enough room in the output buffer), next_in is updated and processing
  78603. will resume at this point for the next call of inflate().
  78604. - Provide more output starting at next_out and update next_out and avail_out
  78605. accordingly. inflate() provides as much output as possible, until there
  78606. is no more input data or no more space in the output buffer (see below
  78607. about the flush parameter).
  78608. Before the call of inflate(), the application should ensure that at least
  78609. one of the actions is possible, by providing more input and/or consuming
  78610. more output, and updating the next_* and avail_* values accordingly.
  78611. The application can consume the uncompressed output when it wants, for
  78612. example when the output buffer is full (avail_out == 0), or after each
  78613. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78614. must be called again after making room in the output buffer because there
  78615. might be more output pending.
  78616. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78617. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78618. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78619. if and when it gets to the next deflate block boundary. When decoding the
  78620. zlib or gzip format, this will cause inflate() to return immediately after
  78621. the header and before the first block. When doing a raw inflate, inflate()
  78622. will go ahead and process the first block, and will return when it gets to
  78623. the end of that block, or when it runs out of data.
  78624. The Z_BLOCK option assists in appending to or combining deflate streams.
  78625. Also to assist in this, on return inflate() will set strm->data_type to the
  78626. number of unused bits in the last byte taken from strm->next_in, plus 64
  78627. if inflate() is currently decoding the last block in the deflate stream,
  78628. plus 128 if inflate() returned immediately after decoding an end-of-block
  78629. code or decoding the complete header up to just before the first byte of the
  78630. deflate stream. The end-of-block will not be indicated until all of the
  78631. uncompressed data from that block has been written to strm->next_out. The
  78632. number of unused bits may in general be greater than seven, except when
  78633. bit 7 of data_type is set, in which case the number of unused bits will be
  78634. less than eight.
  78635. inflate() should normally be called until it returns Z_STREAM_END or an
  78636. error. However if all decompression is to be performed in a single step
  78637. (a single call of inflate), the parameter flush should be set to
  78638. Z_FINISH. In this case all pending input is processed and all pending
  78639. output is flushed; avail_out must be large enough to hold all the
  78640. uncompressed data. (The size of the uncompressed data may have been saved
  78641. by the compressor for this purpose.) The next operation on this stream must
  78642. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78643. is never required, but can be used to inform inflate that a faster approach
  78644. may be used for the single inflate() call.
  78645. In this implementation, inflate() always flushes as much output as
  78646. possible to the output buffer, and always uses the faster approach on the
  78647. first call. So the only effect of the flush parameter in this implementation
  78648. is on the return value of inflate(), as noted below, or when it returns early
  78649. because Z_BLOCK is used.
  78650. If a preset dictionary is needed after this call (see inflateSetDictionary
  78651. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78652. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78653. strm->adler to the adler32 checksum of all output produced so far (that is,
  78654. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78655. below. At the end of the stream, inflate() checks that its computed adler32
  78656. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78657. only if the checksum is correct.
  78658. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78659. deflate data. The header type is detected automatically. Any information
  78660. contained in the gzip header is not retained, so applications that need that
  78661. information should instead use raw inflate, see inflateInit2() below, or
  78662. inflateBack() and perform their own processing of the gzip header and
  78663. trailer.
  78664. inflate() returns Z_OK if some progress has been made (more input processed
  78665. or more output produced), Z_STREAM_END if the end of the compressed data has
  78666. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78667. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78668. corrupted (input stream not conforming to the zlib format or incorrect check
  78669. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78670. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78671. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78672. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78673. inflate() can be called again with more input and more output space to
  78674. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78675. call inflateSync() to look for a good compression block if a partial recovery
  78676. of the data is desired.
  78677. */
  78678. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78679. /*
  78680. All dynamically allocated data structures for this stream are freed.
  78681. This function discards any unprocessed input and does not flush any
  78682. pending output.
  78683. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78684. was inconsistent. In the error case, msg may be set but then points to a
  78685. static string (which must not be deallocated).
  78686. */
  78687. /* Advanced functions */
  78688. /*
  78689. The following functions are needed only in some special applications.
  78690. */
  78691. /*
  78692. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78693. int level,
  78694. int method,
  78695. int windowBits,
  78696. int memLevel,
  78697. int strategy));
  78698. This is another version of deflateInit with more compression options. The
  78699. fields next_in, zalloc, zfree and opaque must be initialized before by
  78700. the caller.
  78701. The method parameter is the compression method. It must be Z_DEFLATED in
  78702. this version of the library.
  78703. The windowBits parameter is the base two logarithm of the window size
  78704. (the size of the history buffer). It should be in the range 8..15 for this
  78705. version of the library. Larger values of this parameter result in better
  78706. compression at the expense of memory usage. The default value is 15 if
  78707. deflateInit is used instead.
  78708. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78709. determines the window size. deflate() will then generate raw deflate data
  78710. with no zlib header or trailer, and will not compute an adler32 check value.
  78711. windowBits can also be greater than 15 for optional gzip encoding. Add
  78712. 16 to windowBits to write a simple gzip header and trailer around the
  78713. compressed data instead of a zlib wrapper. The gzip header will have no
  78714. file name, no extra data, no comment, no modification time (set to zero),
  78715. no header crc, and the operating system will be set to 255 (unknown). If a
  78716. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78717. The memLevel parameter specifies how much memory should be allocated
  78718. for the internal compression state. memLevel=1 uses minimum memory but
  78719. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78720. for optimal speed. The default value is 8. See zconf.h for total memory
  78721. usage as a function of windowBits and memLevel.
  78722. The strategy parameter is used to tune the compression algorithm. Use the
  78723. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78724. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78725. string match), or Z_RLE to limit match distances to one (run-length
  78726. encoding). Filtered data consists mostly of small values with a somewhat
  78727. random distribution. In this case, the compression algorithm is tuned to
  78728. compress them better. The effect of Z_FILTERED is to force more Huffman
  78729. coding and less string matching; it is somewhat intermediate between
  78730. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78731. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78732. parameter only affects the compression ratio but not the correctness of the
  78733. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78734. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78735. applications.
  78736. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78737. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78738. method). msg is set to null if there is no error message. deflateInit2 does
  78739. not perform any compression: this will be done by deflate().
  78740. */
  78741. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78742. const Bytef *dictionary,
  78743. uInt dictLength));
  78744. /*
  78745. Initializes the compression dictionary from the given byte sequence
  78746. without producing any compressed output. This function must be called
  78747. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78748. call of deflate. The compressor and decompressor must use exactly the same
  78749. dictionary (see inflateSetDictionary).
  78750. The dictionary should consist of strings (byte sequences) that are likely
  78751. to be encountered later in the data to be compressed, with the most commonly
  78752. used strings preferably put towards the end of the dictionary. Using a
  78753. dictionary is most useful when the data to be compressed is short and can be
  78754. predicted with good accuracy; the data can then be compressed better than
  78755. with the default empty dictionary.
  78756. Depending on the size of the compression data structures selected by
  78757. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78758. discarded, for example if the dictionary is larger than the window size in
  78759. deflate or deflate2. Thus the strings most likely to be useful should be
  78760. put at the end of the dictionary, not at the front. In addition, the
  78761. current implementation of deflate will use at most the window size minus
  78762. 262 bytes of the provided dictionary.
  78763. Upon return of this function, strm->adler is set to the adler32 value
  78764. of the dictionary; the decompressor may later use this value to determine
  78765. which dictionary has been used by the compressor. (The adler32 value
  78766. applies to the whole dictionary even if only a subset of the dictionary is
  78767. actually used by the compressor.) If a raw deflate was requested, then the
  78768. adler32 value is not computed and strm->adler is not set.
  78769. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78770. parameter is invalid (such as NULL dictionary) or the stream state is
  78771. inconsistent (for example if deflate has already been called for this stream
  78772. or if the compression method is bsort). deflateSetDictionary does not
  78773. perform any compression: this will be done by deflate().
  78774. */
  78775. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78776. z_streamp source));
  78777. /*
  78778. Sets the destination stream as a complete copy of the source stream.
  78779. This function can be useful when several compression strategies will be
  78780. tried, for example when there are several ways of pre-processing the input
  78781. data with a filter. The streams that will be discarded should then be freed
  78782. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78783. compression state which can be quite large, so this strategy is slow and
  78784. can consume lots of memory.
  78785. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78786. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78787. (such as zalloc being NULL). msg is left unchanged in both source and
  78788. destination.
  78789. */
  78790. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78791. /*
  78792. This function is equivalent to deflateEnd followed by deflateInit,
  78793. but does not free and reallocate all the internal compression state.
  78794. The stream will keep the same compression level and any other attributes
  78795. that may have been set by deflateInit2.
  78796. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78797. stream state was inconsistent (such as zalloc or state being NULL).
  78798. */
  78799. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78800. int level,
  78801. int strategy));
  78802. /*
  78803. Dynamically update the compression level and compression strategy. The
  78804. interpretation of level and strategy is as in deflateInit2. This can be
  78805. used to switch between compression and straight copy of the input data, or
  78806. to switch to a different kind of input data requiring a different
  78807. strategy. If the compression level is changed, the input available so far
  78808. is compressed with the old level (and may be flushed); the new level will
  78809. take effect only at the next call of deflate().
  78810. Before the call of deflateParams, the stream state must be set as for
  78811. a call of deflate(), since the currently available input may have to
  78812. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78813. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78814. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78815. if strm->avail_out was zero.
  78816. */
  78817. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78818. int good_length,
  78819. int max_lazy,
  78820. int nice_length,
  78821. int max_chain));
  78822. /*
  78823. Fine tune deflate's internal compression parameters. This should only be
  78824. used by someone who understands the algorithm used by zlib's deflate for
  78825. searching for the best matching string, and even then only by the most
  78826. fanatic optimizer trying to squeeze out the last compressed bit for their
  78827. specific input data. Read the deflate.c source code for the meaning of the
  78828. max_lazy, good_length, nice_length, and max_chain parameters.
  78829. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78830. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78831. */
  78832. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78833. uLong sourceLen));
  78834. /*
  78835. deflateBound() returns an upper bound on the compressed size after
  78836. deflation of sourceLen bytes. It must be called after deflateInit()
  78837. or deflateInit2(). This would be used to allocate an output buffer
  78838. for deflation in a single pass, and so would be called before deflate().
  78839. */
  78840. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78841. int bits,
  78842. int value));
  78843. /*
  78844. deflatePrime() inserts bits in the deflate output stream. The intent
  78845. is that this function is used to start off the deflate output with the
  78846. bits leftover from a previous deflate stream when appending to it. As such,
  78847. this function can only be used for raw deflate, and must be used before the
  78848. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78849. less than or equal to 16, and that many of the least significant bits of
  78850. value will be inserted in the output.
  78851. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78852. stream state was inconsistent.
  78853. */
  78854. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78855. gz_headerp head));
  78856. /*
  78857. deflateSetHeader() provides gzip header information for when a gzip
  78858. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78859. after deflateInit2() or deflateReset() and before the first call of
  78860. deflate(). The text, time, os, extra field, name, and comment information
  78861. in the provided gz_header structure are written to the gzip header (xflag is
  78862. ignored -- the extra flags are set according to the compression level). The
  78863. caller must assure that, if not Z_NULL, name and comment are terminated with
  78864. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78865. available there. If hcrc is true, a gzip header crc is included. Note that
  78866. the current versions of the command-line version of gzip (up through version
  78867. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78868. gzip file" and give up.
  78869. If deflateSetHeader is not used, the default gzip header has text false,
  78870. the time set to zero, and os set to 255, with no extra, name, or comment
  78871. fields. The gzip header is returned to the default state by deflateReset().
  78872. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78873. stream state was inconsistent.
  78874. */
  78875. /*
  78876. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78877. int windowBits));
  78878. This is another version of inflateInit with an extra parameter. The
  78879. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78880. before by the caller.
  78881. The windowBits parameter is the base two logarithm of the maximum window
  78882. size (the size of the history buffer). It should be in the range 8..15 for
  78883. this version of the library. The default value is 15 if inflateInit is used
  78884. instead. windowBits must be greater than or equal to the windowBits value
  78885. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78886. deflateInit2() was not used. If a compressed stream with a larger window
  78887. size is given as input, inflate() will return with the error code
  78888. Z_DATA_ERROR instead of trying to allocate a larger window.
  78889. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78890. determines the window size. inflate() will then process raw deflate data,
  78891. not looking for a zlib or gzip header, not generating a check value, and not
  78892. looking for any check values for comparison at the end of the stream. This
  78893. is for use with other formats that use the deflate compressed data format
  78894. such as zip. Those formats provide their own check values. If a custom
  78895. format is developed using the raw deflate format for compressed data, it is
  78896. recommended that a check value such as an adler32 or a crc32 be applied to
  78897. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78898. most applications, the zlib format should be used as is. Note that comments
  78899. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78900. windowBits can also be greater than 15 for optional gzip decoding. Add
  78901. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78902. detection, or add 16 to decode only the gzip format (the zlib format will
  78903. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78904. a crc32 instead of an adler32.
  78905. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78906. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78907. is set to null if there is no error message. inflateInit2 does not perform
  78908. any decompression apart from reading the zlib header if present: this will
  78909. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78910. and avail_out are unchanged.)
  78911. */
  78912. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78913. const Bytef *dictionary,
  78914. uInt dictLength));
  78915. /*
  78916. Initializes the decompression dictionary from the given uncompressed byte
  78917. sequence. This function must be called immediately after a call of inflate,
  78918. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78919. can be determined from the adler32 value returned by that call of inflate.
  78920. The compressor and decompressor must use exactly the same dictionary (see
  78921. deflateSetDictionary). For raw inflate, this function can be called
  78922. immediately after inflateInit2() or inflateReset() and before any call of
  78923. inflate() to set the dictionary. The application must insure that the
  78924. dictionary that was used for compression is provided.
  78925. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78926. parameter is invalid (such as NULL dictionary) or the stream state is
  78927. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78928. expected one (incorrect adler32 value). inflateSetDictionary does not
  78929. perform any decompression: this will be done by subsequent calls of
  78930. inflate().
  78931. */
  78932. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78933. /*
  78934. Skips invalid compressed data until a full flush point (see above the
  78935. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78936. available input is skipped. No output is provided.
  78937. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78938. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78939. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78940. case, the application may save the current current value of total_in which
  78941. indicates where valid compressed data was found. In the error case, the
  78942. application may repeatedly call inflateSync, providing more input each time,
  78943. until success or end of the input data.
  78944. */
  78945. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78946. z_streamp source));
  78947. /*
  78948. Sets the destination stream as a complete copy of the source stream.
  78949. This function can be useful when randomly accessing a large stream. The
  78950. first pass through the stream can periodically record the inflate state,
  78951. allowing restarting inflate at those points when randomly accessing the
  78952. stream.
  78953. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78954. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78955. (such as zalloc being NULL). msg is left unchanged in both source and
  78956. destination.
  78957. */
  78958. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78959. /*
  78960. This function is equivalent to inflateEnd followed by inflateInit,
  78961. but does not free and reallocate all the internal decompression state.
  78962. The stream will keep attributes that may have been set by inflateInit2.
  78963. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78964. stream state was inconsistent (such as zalloc or state being NULL).
  78965. */
  78966. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78967. int bits,
  78968. int value));
  78969. /*
  78970. This function inserts bits in the inflate input stream. The intent is
  78971. that this function is used to start inflating at a bit position in the
  78972. middle of a byte. The provided bits will be used before any bytes are used
  78973. from next_in. This function should only be used with raw inflate, and
  78974. should be used before the first inflate() call after inflateInit2() or
  78975. inflateReset(). bits must be less than or equal to 16, and that many of the
  78976. least significant bits of value will be inserted in the input.
  78977. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78978. stream state was inconsistent.
  78979. */
  78980. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78981. gz_headerp head));
  78982. /*
  78983. inflateGetHeader() requests that gzip header information be stored in the
  78984. provided gz_header structure. inflateGetHeader() may be called after
  78985. inflateInit2() or inflateReset(), and before the first call of inflate().
  78986. As inflate() processes the gzip stream, head->done is zero until the header
  78987. is completed, at which time head->done is set to one. If a zlib stream is
  78988. being decoded, then head->done is set to -1 to indicate that there will be
  78989. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78990. force inflate() to return immediately after header processing is complete
  78991. and before any actual data is decompressed.
  78992. The text, time, xflags, and os fields are filled in with the gzip header
  78993. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78994. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78995. contains the maximum number of bytes to write to extra. Once done is true,
  78996. extra_len contains the actual extra field length, and extra contains the
  78997. extra field, or that field truncated if extra_max is less than extra_len.
  78998. If name is not Z_NULL, then up to name_max characters are written there,
  78999. terminated with a zero unless the length is greater than name_max. If
  79000. comment is not Z_NULL, then up to comm_max characters are written there,
  79001. terminated with a zero unless the length is greater than comm_max. When
  79002. any of extra, name, or comment are not Z_NULL and the respective field is
  79003. not present in the header, then that field is set to Z_NULL to signal its
  79004. absence. This allows the use of deflateSetHeader() with the returned
  79005. structure to duplicate the header. However if those fields are set to
  79006. allocated memory, then the application will need to save those pointers
  79007. elsewhere so that they can be eventually freed.
  79008. If inflateGetHeader is not used, then the header information is simply
  79009. discarded. The header is always checked for validity, including the header
  79010. CRC if present. inflateReset() will reset the process to discard the header
  79011. information. The application would need to call inflateGetHeader() again to
  79012. retrieve the header from the next gzip stream.
  79013. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79014. stream state was inconsistent.
  79015. */
  79016. /*
  79017. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79018. unsigned char FAR *window));
  79019. Initialize the internal stream state for decompression using inflateBack()
  79020. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79021. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79022. derived memory allocation routines are used. windowBits is the base two
  79023. logarithm of the window size, in the range 8..15. window is a caller
  79024. supplied buffer of that size. Except for special applications where it is
  79025. assured that deflate was used with small window sizes, windowBits must be 15
  79026. and a 32K byte window must be supplied to be able to decompress general
  79027. deflate streams.
  79028. See inflateBack() for the usage of these routines.
  79029. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79030. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79031. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79032. match the version of the header file.
  79033. */
  79034. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79035. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79036. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79037. in_func in, void FAR *in_desc,
  79038. out_func out, void FAR *out_desc));
  79039. /*
  79040. inflateBack() does a raw inflate with a single call using a call-back
  79041. interface for input and output. This is more efficient than inflate() for
  79042. file i/o applications in that it avoids copying between the output and the
  79043. sliding window by simply making the window itself the output buffer. This
  79044. function trusts the application to not change the output buffer passed by
  79045. the output function, at least until inflateBack() returns.
  79046. inflateBackInit() must be called first to allocate the internal state
  79047. and to initialize the state with the user-provided window buffer.
  79048. inflateBack() may then be used multiple times to inflate a complete, raw
  79049. deflate stream with each call. inflateBackEnd() is then called to free
  79050. the allocated state.
  79051. A raw deflate stream is one with no zlib or gzip header or trailer.
  79052. This routine would normally be used in a utility that reads zip or gzip
  79053. files and writes out uncompressed files. The utility would decode the
  79054. header and process the trailer on its own, hence this routine expects
  79055. only the raw deflate stream to decompress. This is different from the
  79056. normal behavior of inflate(), which expects either a zlib or gzip header and
  79057. trailer around the deflate stream.
  79058. inflateBack() uses two subroutines supplied by the caller that are then
  79059. called by inflateBack() for input and output. inflateBack() calls those
  79060. routines until it reads a complete deflate stream and writes out all of the
  79061. uncompressed data, or until it encounters an error. The function's
  79062. parameters and return types are defined above in the in_func and out_func
  79063. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79064. number of bytes of provided input, and a pointer to that input in buf. If
  79065. there is no input available, in() must return zero--buf is ignored in that
  79066. case--and inflateBack() will return a buffer error. inflateBack() will call
  79067. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79068. should return zero on success, or non-zero on failure. If out() returns
  79069. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79070. are permitted to change the contents of the window provided to
  79071. inflateBackInit(), which is also the buffer that out() uses to write from.
  79072. The length written by out() will be at most the window size. Any non-zero
  79073. amount of input may be provided by in().
  79074. For convenience, inflateBack() can be provided input on the first call by
  79075. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79076. in() will be called. Therefore strm->next_in must be initialized before
  79077. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79078. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79079. must also be initialized, and then if strm->avail_in is not zero, input will
  79080. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79081. The in_desc and out_desc parameters of inflateBack() is passed as the
  79082. first parameter of in() and out() respectively when they are called. These
  79083. descriptors can be optionally used to pass any information that the caller-
  79084. supplied in() and out() functions need to do their job.
  79085. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79086. pass back any unused input that was provided by the last in() call. The
  79087. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79088. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79089. error in the deflate stream (in which case strm->msg is set to indicate the
  79090. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79091. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79092. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79093. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79094. out() returning non-zero. (in() will always be called before out(), so
  79095. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79096. that inflateBack() cannot return Z_OK.
  79097. */
  79098. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79099. /*
  79100. All memory allocated by inflateBackInit() is freed.
  79101. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79102. state was inconsistent.
  79103. */
  79104. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79105. /* Return flags indicating compile-time options.
  79106. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79107. 1.0: size of uInt
  79108. 3.2: size of uLong
  79109. 5.4: size of voidpf (pointer)
  79110. 7.6: size of z_off_t
  79111. Compiler, assembler, and debug options:
  79112. 8: DEBUG
  79113. 9: ASMV or ASMINF -- use ASM code
  79114. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79115. 11: 0 (reserved)
  79116. One-time table building (smaller code, but not thread-safe if true):
  79117. 12: BUILDFIXED -- build static block decoding tables when needed
  79118. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79119. 14,15: 0 (reserved)
  79120. Library content (indicates missing functionality):
  79121. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79122. deflate code when not needed)
  79123. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79124. and decode gzip streams (to avoid linking crc code)
  79125. 18-19: 0 (reserved)
  79126. Operation variations (changes in library functionality):
  79127. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79128. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79129. 22,23: 0 (reserved)
  79130. The sprintf variant used by gzprintf (zero is best):
  79131. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79132. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79133. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79134. Remainder:
  79135. 27-31: 0 (reserved)
  79136. */
  79137. /* utility functions */
  79138. /*
  79139. The following utility functions are implemented on top of the
  79140. basic stream-oriented functions. To simplify the interface, some
  79141. default options are assumed (compression level and memory usage,
  79142. standard memory allocation functions). The source code of these
  79143. utility functions can easily be modified if you need special options.
  79144. */
  79145. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79146. const Bytef *source, uLong sourceLen));
  79147. /*
  79148. Compresses the source buffer into the destination buffer. sourceLen is
  79149. the byte length of the source buffer. Upon entry, destLen is the total
  79150. size of the destination buffer, which must be at least the value returned
  79151. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79152. compressed buffer.
  79153. This function can be used to compress a whole file at once if the
  79154. input file is mmap'ed.
  79155. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79156. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79157. buffer.
  79158. */
  79159. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79160. const Bytef *source, uLong sourceLen,
  79161. int level));
  79162. /*
  79163. Compresses the source buffer into the destination buffer. The level
  79164. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79165. length of the source buffer. Upon entry, destLen is the total size of the
  79166. destination buffer, which must be at least the value returned by
  79167. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79168. compressed buffer.
  79169. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79170. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79171. Z_STREAM_ERROR if the level parameter is invalid.
  79172. */
  79173. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79174. /*
  79175. compressBound() returns an upper bound on the compressed size after
  79176. compress() or compress2() on sourceLen bytes. It would be used before
  79177. a compress() or compress2() call to allocate the destination buffer.
  79178. */
  79179. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79180. const Bytef *source, uLong sourceLen));
  79181. /*
  79182. Decompresses the source buffer into the destination buffer. sourceLen is
  79183. the byte length of the source buffer. Upon entry, destLen is the total
  79184. size of the destination buffer, which must be large enough to hold the
  79185. entire uncompressed data. (The size of the uncompressed data must have
  79186. been saved previously by the compressor and transmitted to the decompressor
  79187. by some mechanism outside the scope of this compression library.)
  79188. Upon exit, destLen is the actual size of the compressed buffer.
  79189. This function can be used to decompress a whole file at once if the
  79190. input file is mmap'ed.
  79191. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79192. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79193. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79194. */
  79195. typedef voidp gzFile;
  79196. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79197. /*
  79198. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79199. is as in fopen ("rb" or "wb") but can also include a compression level
  79200. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79201. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79202. as in "wb1R". (See the description of deflateInit2 for more information
  79203. about the strategy parameter.)
  79204. gzopen can be used to read a file which is not in gzip format; in this
  79205. case gzread will directly read from the file without decompression.
  79206. gzopen returns NULL if the file could not be opened or if there was
  79207. insufficient memory to allocate the (de)compression state; errno
  79208. can be checked to distinguish the two cases (if errno is zero, the
  79209. zlib error is Z_MEM_ERROR). */
  79210. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79211. /*
  79212. gzdopen() associates a gzFile with the file descriptor fd. File
  79213. descriptors are obtained from calls like open, dup, creat, pipe or
  79214. fileno (in the file has been previously opened with fopen).
  79215. The mode parameter is as in gzopen.
  79216. The next call of gzclose on the returned gzFile will also close the
  79217. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79218. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79219. gzdopen returns NULL if there was insufficient memory to allocate
  79220. the (de)compression state.
  79221. */
  79222. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79223. /*
  79224. Dynamically update the compression level or strategy. See the description
  79225. of deflateInit2 for the meaning of these parameters.
  79226. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79227. opened for writing.
  79228. */
  79229. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79230. /*
  79231. Reads the given number of uncompressed bytes from the compressed file.
  79232. If the input file was not in gzip format, gzread copies the given number
  79233. of bytes into the buffer.
  79234. gzread returns the number of uncompressed bytes actually read (0 for
  79235. end of file, -1 for error). */
  79236. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79237. voidpc buf, unsigned len));
  79238. /*
  79239. Writes the given number of uncompressed bytes into the compressed file.
  79240. gzwrite returns the number of uncompressed bytes actually written
  79241. (0 in case of error).
  79242. */
  79243. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79244. /*
  79245. Converts, formats, and writes the args to the compressed file under
  79246. control of the format string, as in fprintf. gzprintf returns the number of
  79247. uncompressed bytes actually written (0 in case of error). The number of
  79248. uncompressed bytes written is limited to 4095. The caller should assure that
  79249. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79250. return an error (0) with nothing written. In this case, there may also be a
  79251. buffer overflow with unpredictable consequences, which is possible only if
  79252. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79253. because the secure snprintf() or vsnprintf() functions were not available.
  79254. */
  79255. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79256. /*
  79257. Writes the given null-terminated string to the compressed file, excluding
  79258. the terminating null character.
  79259. gzputs returns the number of characters written, or -1 in case of error.
  79260. */
  79261. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79262. /*
  79263. Reads bytes from the compressed file until len-1 characters are read, or
  79264. a newline character is read and transferred to buf, or an end-of-file
  79265. condition is encountered. The string is then terminated with a null
  79266. character.
  79267. gzgets returns buf, or Z_NULL in case of error.
  79268. */
  79269. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79270. /*
  79271. Writes c, converted to an unsigned char, into the compressed file.
  79272. gzputc returns the value that was written, or -1 in case of error.
  79273. */
  79274. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79275. /*
  79276. Reads one byte from the compressed file. gzgetc returns this byte
  79277. or -1 in case of end of file or error.
  79278. */
  79279. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79280. /*
  79281. Push one character back onto the stream to be read again later.
  79282. Only one character of push-back is allowed. gzungetc() returns the
  79283. character pushed, or -1 on failure. gzungetc() will fail if a
  79284. character has been pushed but not read yet, or if c is -1. The pushed
  79285. character will be discarded if the stream is repositioned with gzseek()
  79286. or gzrewind().
  79287. */
  79288. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79289. /*
  79290. Flushes all pending output into the compressed file. The parameter
  79291. flush is as in the deflate() function. The return value is the zlib
  79292. error number (see function gzerror below). gzflush returns Z_OK if
  79293. the flush parameter is Z_FINISH and all output could be flushed.
  79294. gzflush should be called only when strictly necessary because it can
  79295. degrade compression.
  79296. */
  79297. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79298. z_off_t offset, int whence));
  79299. /*
  79300. Sets the starting position for the next gzread or gzwrite on the
  79301. given compressed file. The offset represents a number of bytes in the
  79302. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79303. the value SEEK_END is not supported.
  79304. If the file is opened for reading, this function is emulated but can be
  79305. extremely slow. If the file is opened for writing, only forward seeks are
  79306. supported; gzseek then compresses a sequence of zeroes up to the new
  79307. starting position.
  79308. gzseek returns the resulting offset location as measured in bytes from
  79309. the beginning of the uncompressed stream, or -1 in case of error, in
  79310. particular if the file is opened for writing and the new starting position
  79311. would be before the current position.
  79312. */
  79313. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79314. /*
  79315. Rewinds the given file. This function is supported only for reading.
  79316. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79317. */
  79318. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79319. /*
  79320. Returns the starting position for the next gzread or gzwrite on the
  79321. given compressed file. This position represents a number of bytes in the
  79322. uncompressed data stream.
  79323. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79324. */
  79325. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79326. /*
  79327. Returns 1 when EOF has previously been detected reading the given
  79328. input stream, otherwise zero.
  79329. */
  79330. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79331. /*
  79332. Returns 1 if file is being read directly without decompression, otherwise
  79333. zero.
  79334. */
  79335. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79336. /*
  79337. Flushes all pending output if necessary, closes the compressed file
  79338. and deallocates all the (de)compression state. The return value is the zlib
  79339. error number (see function gzerror below).
  79340. */
  79341. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79342. /*
  79343. Returns the error message for the last error which occurred on the
  79344. given compressed file. errnum is set to zlib error number. If an
  79345. error occurred in the file system and not in the compression library,
  79346. errnum is set to Z_ERRNO and the application may consult errno
  79347. to get the exact error code.
  79348. */
  79349. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79350. /*
  79351. Clears the error and end-of-file flags for file. This is analogous to the
  79352. clearerr() function in stdio. This is useful for continuing to read a gzip
  79353. file that is being written concurrently.
  79354. */
  79355. /* checksum functions */
  79356. /*
  79357. These functions are not related to compression but are exported
  79358. anyway because they might be useful in applications using the
  79359. compression library.
  79360. */
  79361. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79362. /*
  79363. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79364. return the updated checksum. If buf is NULL, this function returns
  79365. the required initial value for the checksum.
  79366. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79367. much faster. Usage example:
  79368. uLong adler = adler32(0L, Z_NULL, 0);
  79369. while (read_buffer(buffer, length) != EOF) {
  79370. adler = adler32(adler, buffer, length);
  79371. }
  79372. if (adler != original_adler) error();
  79373. */
  79374. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79375. z_off_t len2));
  79376. /*
  79377. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79378. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79379. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79380. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79381. */
  79382. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79383. /*
  79384. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79385. updated CRC-32. If buf is NULL, this function returns the required initial
  79386. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79387. performed within this function so it shouldn't be done by the application.
  79388. Usage example:
  79389. uLong crc = crc32(0L, Z_NULL, 0);
  79390. while (read_buffer(buffer, length) != EOF) {
  79391. crc = crc32(crc, buffer, length);
  79392. }
  79393. if (crc != original_crc) error();
  79394. */
  79395. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79396. /*
  79397. Combine two CRC-32 check values into one. For two sequences of bytes,
  79398. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79399. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79400. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79401. len2.
  79402. */
  79403. /* various hacks, don't look :) */
  79404. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79405. * and the compiler's view of z_stream:
  79406. */
  79407. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79408. const char *version, int stream_size));
  79409. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79410. const char *version, int stream_size));
  79411. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79412. int windowBits, int memLevel,
  79413. int strategy, const char *version,
  79414. int stream_size));
  79415. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79416. const char *version, int stream_size));
  79417. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79418. unsigned char FAR *window,
  79419. const char *version,
  79420. int stream_size));
  79421. #define deflateInit(strm, level) \
  79422. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79423. #define inflateInit(strm) \
  79424. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79425. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79426. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79427. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79428. #define inflateInit2(strm, windowBits) \
  79429. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79430. #define inflateBackInit(strm, windowBits, window) \
  79431. inflateBackInit_((strm), (windowBits), (window), \
  79432. ZLIB_VERSION, sizeof(z_stream))
  79433. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79434. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79435. #endif
  79436. ZEXTERN const char * ZEXPORT zError OF((int));
  79437. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79438. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79439. #ifdef __cplusplus
  79440. //}
  79441. #endif
  79442. #endif /* ZLIB_H */
  79443. /*** End of inlined file: zlib.h ***/
  79444. #undef OS_CODE
  79445. #else
  79446. #include <zlib.h>
  79447. #endif
  79448. }
  79449. BEGIN_JUCE_NAMESPACE
  79450. // internal helper object that holds the zlib structures so they don't have to be
  79451. // included publicly.
  79452. class GZIPCompressorHelper
  79453. {
  79454. public:
  79455. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79456. : data (0),
  79457. dataSize (0),
  79458. compLevel (compressionLevel),
  79459. strategy (0),
  79460. setParams (true),
  79461. streamIsValid (false),
  79462. finished (false),
  79463. shouldFinish (false)
  79464. {
  79465. using namespace zlibNamespace;
  79466. zerostruct (stream);
  79467. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79468. nowrap ? -MAX_WBITS : MAX_WBITS,
  79469. 8, strategy) == Z_OK);
  79470. }
  79471. ~GZIPCompressorHelper()
  79472. {
  79473. using namespace zlibNamespace;
  79474. if (streamIsValid)
  79475. deflateEnd (&stream);
  79476. }
  79477. bool needsInput() const throw()
  79478. {
  79479. return dataSize <= 0;
  79480. }
  79481. void setInput (const uint8* const newData, const int size) throw()
  79482. {
  79483. data = newData;
  79484. dataSize = size;
  79485. }
  79486. int doNextBlock (uint8* const dest, const int destSize) throw()
  79487. {
  79488. using namespace zlibNamespace;
  79489. if (streamIsValid)
  79490. {
  79491. stream.next_in = const_cast <uint8*> (data);
  79492. stream.next_out = dest;
  79493. stream.avail_in = dataSize;
  79494. stream.avail_out = destSize;
  79495. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79496. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79497. setParams = false;
  79498. switch (result)
  79499. {
  79500. case Z_STREAM_END:
  79501. finished = true;
  79502. // Deliberate fall-through..
  79503. case Z_OK:
  79504. data += dataSize - stream.avail_in;
  79505. dataSize = stream.avail_in;
  79506. return destSize - stream.avail_out;
  79507. default:
  79508. break;
  79509. }
  79510. }
  79511. return 0;
  79512. }
  79513. private:
  79514. zlibNamespace::z_stream stream;
  79515. const uint8* data;
  79516. int dataSize, compLevel, strategy;
  79517. bool setParams, streamIsValid;
  79518. public:
  79519. bool finished, shouldFinish;
  79520. };
  79521. const int gzipCompBufferSize = 32768;
  79522. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79523. int compressionLevel,
  79524. const bool deleteDestStream,
  79525. const bool noWrap)
  79526. : destStream (destStream_),
  79527. streamToDelete (deleteDestStream ? destStream_ : 0),
  79528. buffer (gzipCompBufferSize)
  79529. {
  79530. if (compressionLevel < 1 || compressionLevel > 9)
  79531. compressionLevel = -1;
  79532. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79533. }
  79534. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79535. {
  79536. flush();
  79537. }
  79538. void GZIPCompressorOutputStream::flush()
  79539. {
  79540. if (! helper->finished)
  79541. {
  79542. helper->shouldFinish = true;
  79543. while (! helper->finished)
  79544. doNextBlock();
  79545. }
  79546. destStream->flush();
  79547. }
  79548. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79549. {
  79550. if (! helper->finished)
  79551. {
  79552. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79553. while (! helper->needsInput())
  79554. {
  79555. if (! doNextBlock())
  79556. return false;
  79557. }
  79558. }
  79559. return true;
  79560. }
  79561. bool GZIPCompressorOutputStream::doNextBlock()
  79562. {
  79563. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79564. if (len > 0)
  79565. return destStream->write (buffer, len);
  79566. else
  79567. return true;
  79568. }
  79569. int64 GZIPCompressorOutputStream::getPosition()
  79570. {
  79571. return destStream->getPosition();
  79572. }
  79573. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79574. {
  79575. jassertfalse; // can't do it!
  79576. return false;
  79577. }
  79578. END_JUCE_NAMESPACE
  79579. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79580. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79581. #if JUCE_MSVC
  79582. #pragma warning (push)
  79583. #pragma warning (disable: 4309 4305)
  79584. #endif
  79585. namespace zlibNamespace
  79586. {
  79587. #if JUCE_INCLUDE_ZLIB_CODE
  79588. #undef OS_CODE
  79589. #undef fdopen
  79590. #define ZLIB_INTERNAL
  79591. #define NO_DUMMY_DECL
  79592. /*** Start of inlined file: adler32.c ***/
  79593. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79594. #define ZLIB_INTERNAL
  79595. #define BASE 65521UL /* largest prime smaller than 65536 */
  79596. #define NMAX 5552
  79597. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79598. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79599. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79600. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79601. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79602. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79603. /* use NO_DIVIDE if your processor does not do division in hardware */
  79604. #ifdef NO_DIVIDE
  79605. # define MOD(a) \
  79606. do { \
  79607. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79608. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79609. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79610. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79611. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79612. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79613. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79614. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79615. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79616. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79617. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79618. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79619. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79620. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79621. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79622. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79623. if (a >= BASE) a -= BASE; \
  79624. } while (0)
  79625. # define MOD4(a) \
  79626. do { \
  79627. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79628. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79629. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79630. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79631. if (a >= BASE) a -= BASE; \
  79632. } while (0)
  79633. #else
  79634. # define MOD(a) a %= BASE
  79635. # define MOD4(a) a %= BASE
  79636. #endif
  79637. /* ========================================================================= */
  79638. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79639. {
  79640. unsigned long sum2;
  79641. unsigned n;
  79642. /* split Adler-32 into component sums */
  79643. sum2 = (adler >> 16) & 0xffff;
  79644. adler &= 0xffff;
  79645. /* in case user likes doing a byte at a time, keep it fast */
  79646. if (len == 1) {
  79647. adler += buf[0];
  79648. if (adler >= BASE)
  79649. adler -= BASE;
  79650. sum2 += adler;
  79651. if (sum2 >= BASE)
  79652. sum2 -= BASE;
  79653. return adler | (sum2 << 16);
  79654. }
  79655. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79656. if (buf == Z_NULL)
  79657. return 1L;
  79658. /* in case short lengths are provided, keep it somewhat fast */
  79659. if (len < 16) {
  79660. while (len--) {
  79661. adler += *buf++;
  79662. sum2 += adler;
  79663. }
  79664. if (adler >= BASE)
  79665. adler -= BASE;
  79666. MOD4(sum2); /* only added so many BASE's */
  79667. return adler | (sum2 << 16);
  79668. }
  79669. /* do length NMAX blocks -- requires just one modulo operation */
  79670. while (len >= NMAX) {
  79671. len -= NMAX;
  79672. n = NMAX / 16; /* NMAX is divisible by 16 */
  79673. do {
  79674. DO16(buf); /* 16 sums unrolled */
  79675. buf += 16;
  79676. } while (--n);
  79677. MOD(adler);
  79678. MOD(sum2);
  79679. }
  79680. /* do remaining bytes (less than NMAX, still just one modulo) */
  79681. if (len) { /* avoid modulos if none remaining */
  79682. while (len >= 16) {
  79683. len -= 16;
  79684. DO16(buf);
  79685. buf += 16;
  79686. }
  79687. while (len--) {
  79688. adler += *buf++;
  79689. sum2 += adler;
  79690. }
  79691. MOD(adler);
  79692. MOD(sum2);
  79693. }
  79694. /* return recombined sums */
  79695. return adler | (sum2 << 16);
  79696. }
  79697. /* ========================================================================= */
  79698. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79699. {
  79700. unsigned long sum1;
  79701. unsigned long sum2;
  79702. unsigned rem;
  79703. /* the derivation of this formula is left as an exercise for the reader */
  79704. rem = (unsigned)(len2 % BASE);
  79705. sum1 = adler1 & 0xffff;
  79706. sum2 = rem * sum1;
  79707. MOD(sum2);
  79708. sum1 += (adler2 & 0xffff) + BASE - 1;
  79709. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79710. if (sum1 > BASE) sum1 -= BASE;
  79711. if (sum1 > BASE) sum1 -= BASE;
  79712. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79713. if (sum2 > BASE) sum2 -= BASE;
  79714. return sum1 | (sum2 << 16);
  79715. }
  79716. /*** End of inlined file: adler32.c ***/
  79717. /*** Start of inlined file: compress.c ***/
  79718. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79719. #define ZLIB_INTERNAL
  79720. /* ===========================================================================
  79721. Compresses the source buffer into the destination buffer. The level
  79722. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79723. length of the source buffer. Upon entry, destLen is the total size of the
  79724. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79725. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79726. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79727. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79728. Z_STREAM_ERROR if the level parameter is invalid.
  79729. */
  79730. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79731. uLong sourceLen, int level)
  79732. {
  79733. z_stream stream;
  79734. int err;
  79735. stream.next_in = (Bytef*)source;
  79736. stream.avail_in = (uInt)sourceLen;
  79737. #ifdef MAXSEG_64K
  79738. /* Check for source > 64K on 16-bit machine: */
  79739. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79740. #endif
  79741. stream.next_out = dest;
  79742. stream.avail_out = (uInt)*destLen;
  79743. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79744. stream.zalloc = (alloc_func)0;
  79745. stream.zfree = (free_func)0;
  79746. stream.opaque = (voidpf)0;
  79747. err = deflateInit(&stream, level);
  79748. if (err != Z_OK) return err;
  79749. err = deflate(&stream, Z_FINISH);
  79750. if (err != Z_STREAM_END) {
  79751. deflateEnd(&stream);
  79752. return err == Z_OK ? Z_BUF_ERROR : err;
  79753. }
  79754. *destLen = stream.total_out;
  79755. err = deflateEnd(&stream);
  79756. return err;
  79757. }
  79758. /* ===========================================================================
  79759. */
  79760. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79761. {
  79762. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79763. }
  79764. /* ===========================================================================
  79765. If the default memLevel or windowBits for deflateInit() is changed, then
  79766. this function needs to be updated.
  79767. */
  79768. uLong ZEXPORT compressBound (uLong sourceLen)
  79769. {
  79770. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79771. }
  79772. /*** End of inlined file: compress.c ***/
  79773. #undef DO1
  79774. #undef DO8
  79775. /*** Start of inlined file: crc32.c ***/
  79776. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79777. /*
  79778. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79779. protection on the static variables used to control the first-use generation
  79780. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79781. first call get_crc_table() to initialize the tables before allowing more than
  79782. one thread to use crc32().
  79783. */
  79784. #ifdef MAKECRCH
  79785. # include <stdio.h>
  79786. # ifndef DYNAMIC_CRC_TABLE
  79787. # define DYNAMIC_CRC_TABLE
  79788. # endif /* !DYNAMIC_CRC_TABLE */
  79789. #endif /* MAKECRCH */
  79790. /*** Start of inlined file: zutil.h ***/
  79791. /* WARNING: this file should *not* be used by applications. It is
  79792. part of the implementation of the compression library and is
  79793. subject to change. Applications should only use zlib.h.
  79794. */
  79795. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79796. #ifndef ZUTIL_H
  79797. #define ZUTIL_H
  79798. #define ZLIB_INTERNAL
  79799. #ifdef STDC
  79800. # ifndef _WIN32_WCE
  79801. # include <stddef.h>
  79802. # endif
  79803. # include <string.h>
  79804. # include <stdlib.h>
  79805. #endif
  79806. #ifdef NO_ERRNO_H
  79807. # ifdef _WIN32_WCE
  79808. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79809. * errno. We define it as a global variable to simplify porting.
  79810. * Its value is always 0 and should not be used. We rename it to
  79811. * avoid conflict with other libraries that use the same workaround.
  79812. */
  79813. # define errno z_errno
  79814. # endif
  79815. extern int errno;
  79816. #else
  79817. # ifndef _WIN32_WCE
  79818. # include <errno.h>
  79819. # endif
  79820. #endif
  79821. #ifndef local
  79822. # define local static
  79823. #endif
  79824. /* compile with -Dlocal if your debugger can't find static symbols */
  79825. typedef unsigned char uch;
  79826. typedef uch FAR uchf;
  79827. typedef unsigned short ush;
  79828. typedef ush FAR ushf;
  79829. typedef unsigned long ulg;
  79830. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79831. /* (size given to avoid silly warnings with Visual C++) */
  79832. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79833. #define ERR_RETURN(strm,err) \
  79834. return (strm->msg = (char*)ERR_MSG(err), (err))
  79835. /* To be used only when the state is known to be valid */
  79836. /* common constants */
  79837. #ifndef DEF_WBITS
  79838. # define DEF_WBITS MAX_WBITS
  79839. #endif
  79840. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79841. #if MAX_MEM_LEVEL >= 8
  79842. # define DEF_MEM_LEVEL 8
  79843. #else
  79844. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79845. #endif
  79846. /* default memLevel */
  79847. #define STORED_BLOCK 0
  79848. #define STATIC_TREES 1
  79849. #define DYN_TREES 2
  79850. /* The three kinds of block type */
  79851. #define MIN_MATCH 3
  79852. #define MAX_MATCH 258
  79853. /* The minimum and maximum match lengths */
  79854. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79855. /* target dependencies */
  79856. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79857. # define OS_CODE 0x00
  79858. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79859. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79860. /* Allow compilation with ANSI keywords only enabled */
  79861. void _Cdecl farfree( void *block );
  79862. void *_Cdecl farmalloc( unsigned long nbytes );
  79863. # else
  79864. # include <alloc.h>
  79865. # endif
  79866. # else /* MSC or DJGPP */
  79867. # include <malloc.h>
  79868. # endif
  79869. #endif
  79870. #ifdef AMIGA
  79871. # define OS_CODE 0x01
  79872. #endif
  79873. #if defined(VAXC) || defined(VMS)
  79874. # define OS_CODE 0x02
  79875. # define F_OPEN(name, mode) \
  79876. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79877. #endif
  79878. #if defined(ATARI) || defined(atarist)
  79879. # define OS_CODE 0x05
  79880. #endif
  79881. #ifdef OS2
  79882. # define OS_CODE 0x06
  79883. # ifdef M_I86
  79884. #include <malloc.h>
  79885. # endif
  79886. #endif
  79887. #if defined(MACOS) || TARGET_OS_MAC
  79888. # define OS_CODE 0x07
  79889. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79890. # include <unix.h> /* for fdopen */
  79891. # else
  79892. # ifndef fdopen
  79893. # define fdopen(fd,mode) NULL /* No fdopen() */
  79894. # endif
  79895. # endif
  79896. #endif
  79897. #ifdef TOPS20
  79898. # define OS_CODE 0x0a
  79899. #endif
  79900. #ifdef WIN32
  79901. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79902. # define OS_CODE 0x0b
  79903. # endif
  79904. #endif
  79905. #ifdef __50SERIES /* Prime/PRIMOS */
  79906. # define OS_CODE 0x0f
  79907. #endif
  79908. #if defined(_BEOS_) || defined(RISCOS)
  79909. # define fdopen(fd,mode) NULL /* No fdopen() */
  79910. #endif
  79911. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79912. # if defined(_WIN32_WCE)
  79913. # define fdopen(fd,mode) NULL /* No fdopen() */
  79914. # ifndef _PTRDIFF_T_DEFINED
  79915. typedef int ptrdiff_t;
  79916. # define _PTRDIFF_T_DEFINED
  79917. # endif
  79918. # else
  79919. # define fdopen(fd,type) _fdopen(fd,type)
  79920. # endif
  79921. #endif
  79922. /* common defaults */
  79923. #ifndef OS_CODE
  79924. # define OS_CODE 0x03 /* assume Unix */
  79925. #endif
  79926. #ifndef F_OPEN
  79927. # define F_OPEN(name, mode) fopen((name), (mode))
  79928. #endif
  79929. /* functions */
  79930. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79931. # ifndef HAVE_VSNPRINTF
  79932. # define HAVE_VSNPRINTF
  79933. # endif
  79934. #endif
  79935. #if defined(__CYGWIN__)
  79936. # ifndef HAVE_VSNPRINTF
  79937. # define HAVE_VSNPRINTF
  79938. # endif
  79939. #endif
  79940. #ifndef HAVE_VSNPRINTF
  79941. # ifdef MSDOS
  79942. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79943. but for now we just assume it doesn't. */
  79944. # define NO_vsnprintf
  79945. # endif
  79946. # ifdef __TURBOC__
  79947. # define NO_vsnprintf
  79948. # endif
  79949. # ifdef WIN32
  79950. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79951. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79952. # define vsnprintf _vsnprintf
  79953. # endif
  79954. # endif
  79955. # ifdef __SASC
  79956. # define NO_vsnprintf
  79957. # endif
  79958. #endif
  79959. #ifdef VMS
  79960. # define NO_vsnprintf
  79961. #endif
  79962. #if defined(pyr)
  79963. # define NO_MEMCPY
  79964. #endif
  79965. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79966. /* Use our own functions for small and medium model with MSC <= 5.0.
  79967. * You may have to use the same strategy for Borland C (untested).
  79968. * The __SC__ check is for Symantec.
  79969. */
  79970. # define NO_MEMCPY
  79971. #endif
  79972. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79973. # define HAVE_MEMCPY
  79974. #endif
  79975. #ifdef HAVE_MEMCPY
  79976. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79977. # define zmemcpy _fmemcpy
  79978. # define zmemcmp _fmemcmp
  79979. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79980. # else
  79981. # define zmemcpy memcpy
  79982. # define zmemcmp memcmp
  79983. # define zmemzero(dest, len) memset(dest, 0, len)
  79984. # endif
  79985. #else
  79986. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79987. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79988. extern void zmemzero OF((Bytef* dest, uInt len));
  79989. #endif
  79990. /* Diagnostic functions */
  79991. #ifdef DEBUG
  79992. # include <stdio.h>
  79993. extern int z_verbose;
  79994. extern void z_error OF((const char *m));
  79995. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79996. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79997. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79998. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79999. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80000. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80001. #else
  80002. # define Assert(cond,msg)
  80003. # define Trace(x)
  80004. # define Tracev(x)
  80005. # define Tracevv(x)
  80006. # define Tracec(c,x)
  80007. # define Tracecv(c,x)
  80008. #endif
  80009. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80010. void zcfree OF((voidpf opaque, voidpf ptr));
  80011. #define ZALLOC(strm, items, size) \
  80012. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80013. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80014. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80015. #endif /* ZUTIL_H */
  80016. /*** End of inlined file: zutil.h ***/
  80017. /* for STDC and FAR definitions */
  80018. #define local static
  80019. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80020. #ifndef NOBYFOUR
  80021. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80022. # include <limits.h>
  80023. # define BYFOUR
  80024. # if (UINT_MAX == 0xffffffffUL)
  80025. typedef unsigned int u4;
  80026. # else
  80027. # if (ULONG_MAX == 0xffffffffUL)
  80028. typedef unsigned long u4;
  80029. # else
  80030. # if (USHRT_MAX == 0xffffffffUL)
  80031. typedef unsigned short u4;
  80032. # else
  80033. # undef BYFOUR /* can't find a four-byte integer type! */
  80034. # endif
  80035. # endif
  80036. # endif
  80037. # endif /* STDC */
  80038. #endif /* !NOBYFOUR */
  80039. /* Definitions for doing the crc four data bytes at a time. */
  80040. #ifdef BYFOUR
  80041. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80042. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80043. local unsigned long crc32_little OF((unsigned long,
  80044. const unsigned char FAR *, unsigned));
  80045. local unsigned long crc32_big OF((unsigned long,
  80046. const unsigned char FAR *, unsigned));
  80047. # define TBLS 8
  80048. #else
  80049. # define TBLS 1
  80050. #endif /* BYFOUR */
  80051. /* Local functions for crc concatenation */
  80052. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80053. unsigned long vec));
  80054. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80055. #ifdef DYNAMIC_CRC_TABLE
  80056. local volatile int crc_table_empty = 1;
  80057. local unsigned long FAR crc_table[TBLS][256];
  80058. local void make_crc_table OF((void));
  80059. #ifdef MAKECRCH
  80060. local void write_table OF((FILE *, const unsigned long FAR *));
  80061. #endif /* MAKECRCH */
  80062. /*
  80063. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80064. 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.
  80065. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80066. with the lowest powers in the most significant bit. Then adding polynomials
  80067. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80068. one. If we call the above polynomial p, and represent a byte as the
  80069. polynomial q, also with the lowest power in the most significant bit (so the
  80070. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80071. where a mod b means the remainder after dividing a by b.
  80072. This calculation is done using the shift-register method of multiplying and
  80073. taking the remainder. The register is initialized to zero, and for each
  80074. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80075. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80076. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80077. out is a one). We start with the highest power (least significant bit) of
  80078. q and repeat for all eight bits of q.
  80079. The first table is simply the CRC of all possible eight bit values. This is
  80080. all the information needed to generate CRCs on data a byte at a time for all
  80081. combinations of CRC register values and incoming bytes. The remaining tables
  80082. allow for word-at-a-time CRC calculation for both big-endian and little-
  80083. endian machines, where a word is four bytes.
  80084. */
  80085. local void make_crc_table()
  80086. {
  80087. unsigned long c;
  80088. int n, k;
  80089. unsigned long poly; /* polynomial exclusive-or pattern */
  80090. /* terms of polynomial defining this crc (except x^32): */
  80091. static volatile int first = 1; /* flag to limit concurrent making */
  80092. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80093. /* See if another task is already doing this (not thread-safe, but better
  80094. than nothing -- significantly reduces duration of vulnerability in
  80095. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80096. if (first) {
  80097. first = 0;
  80098. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80099. poly = 0UL;
  80100. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80101. poly |= 1UL << (31 - p[n]);
  80102. /* generate a crc for every 8-bit value */
  80103. for (n = 0; n < 256; n++) {
  80104. c = (unsigned long)n;
  80105. for (k = 0; k < 8; k++)
  80106. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80107. crc_table[0][n] = c;
  80108. }
  80109. #ifdef BYFOUR
  80110. /* generate crc for each value followed by one, two, and three zeros,
  80111. and then the byte reversal of those as well as the first table */
  80112. for (n = 0; n < 256; n++) {
  80113. c = crc_table[0][n];
  80114. crc_table[4][n] = REV(c);
  80115. for (k = 1; k < 4; k++) {
  80116. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80117. crc_table[k][n] = c;
  80118. crc_table[k + 4][n] = REV(c);
  80119. }
  80120. }
  80121. #endif /* BYFOUR */
  80122. crc_table_empty = 0;
  80123. }
  80124. else { /* not first */
  80125. /* wait for the other guy to finish (not efficient, but rare) */
  80126. while (crc_table_empty)
  80127. ;
  80128. }
  80129. #ifdef MAKECRCH
  80130. /* write out CRC tables to crc32.h */
  80131. {
  80132. FILE *out;
  80133. out = fopen("crc32.h", "w");
  80134. if (out == NULL) return;
  80135. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80136. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80137. fprintf(out, "local const unsigned long FAR ");
  80138. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80139. write_table(out, crc_table[0]);
  80140. # ifdef BYFOUR
  80141. fprintf(out, "#ifdef BYFOUR\n");
  80142. for (k = 1; k < 8; k++) {
  80143. fprintf(out, " },\n {\n");
  80144. write_table(out, crc_table[k]);
  80145. }
  80146. fprintf(out, "#endif\n");
  80147. # endif /* BYFOUR */
  80148. fprintf(out, " }\n};\n");
  80149. fclose(out);
  80150. }
  80151. #endif /* MAKECRCH */
  80152. }
  80153. #ifdef MAKECRCH
  80154. local void write_table(out, table)
  80155. FILE *out;
  80156. const unsigned long FAR *table;
  80157. {
  80158. int n;
  80159. for (n = 0; n < 256; n++)
  80160. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80161. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80162. }
  80163. #endif /* MAKECRCH */
  80164. #else /* !DYNAMIC_CRC_TABLE */
  80165. /* ========================================================================
  80166. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80167. */
  80168. /*** Start of inlined file: crc32.h ***/
  80169. local const unsigned long FAR crc_table[TBLS][256] =
  80170. {
  80171. {
  80172. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80173. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80174. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80175. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80176. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80177. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80178. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80179. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80180. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80181. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80182. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80183. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80184. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80185. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80186. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80187. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80188. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80189. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80190. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80191. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80192. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80193. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80194. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80195. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80196. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80197. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80198. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80199. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80200. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80201. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80202. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80203. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80204. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80205. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80206. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80207. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80208. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80209. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80210. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80211. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80212. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80213. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80214. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80215. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80216. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80217. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80218. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80219. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80220. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80221. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80222. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80223. 0x2d02ef8dUL
  80224. #ifdef BYFOUR
  80225. },
  80226. {
  80227. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80228. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80229. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80230. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80231. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80232. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80233. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80234. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80235. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80236. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80237. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80238. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80239. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80240. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80241. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80242. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80243. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80244. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80245. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80246. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80247. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80248. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80249. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80250. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80251. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80252. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80253. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80254. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80255. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80256. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80257. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80258. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80259. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80260. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80261. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80262. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80263. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80264. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80265. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80266. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80267. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80268. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80269. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80270. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80271. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80272. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80273. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80274. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80275. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80276. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80277. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80278. 0x9324fd72UL
  80279. },
  80280. {
  80281. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80282. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80283. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80284. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80285. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80286. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80287. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80288. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80289. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80290. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80291. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80292. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80293. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80294. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80295. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80296. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80297. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80298. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80299. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80300. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80301. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80302. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80303. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80304. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80305. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80306. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80307. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80308. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80309. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80310. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80311. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80312. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80313. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80314. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80315. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80316. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80317. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80318. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80319. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80320. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80321. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80322. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80323. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80324. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80325. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80326. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80327. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80328. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80329. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80330. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80331. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80332. 0xbe9834edUL
  80333. },
  80334. {
  80335. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80336. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80337. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80338. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80339. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80340. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80341. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80342. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80343. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80344. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80345. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80346. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80347. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80348. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80349. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80350. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80351. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80352. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80353. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80354. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80355. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80356. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80357. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80358. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80359. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80360. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80361. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80362. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80363. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80364. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80365. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80366. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80367. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80368. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80369. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80370. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80371. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80372. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80373. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80374. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80375. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80376. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80377. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80378. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80379. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80380. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80381. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80382. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80383. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80384. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80385. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80386. 0xde0506f1UL
  80387. },
  80388. {
  80389. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80390. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80391. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80392. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80393. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80394. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80395. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80396. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80397. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80398. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80399. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80400. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80401. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80402. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80403. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80404. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80405. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80406. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80407. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80408. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80409. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80410. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80411. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80412. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80413. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80414. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80415. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80416. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80417. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80418. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80419. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80420. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80421. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80422. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80423. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80424. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80425. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80426. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80427. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80428. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80429. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80430. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80431. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80432. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80433. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80434. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80435. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80436. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80437. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80438. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80439. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80440. 0x8def022dUL
  80441. },
  80442. {
  80443. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80444. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80445. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80446. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80447. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80448. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80449. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80450. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80451. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80452. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80453. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80454. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80455. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80456. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80457. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80458. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80459. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80460. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80461. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80462. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80463. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80464. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80465. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80466. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80467. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80468. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80469. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80470. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80471. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80472. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80473. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80474. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80475. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80476. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80477. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80478. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80479. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80480. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80481. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80482. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80483. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80484. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80485. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80486. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80487. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80488. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80489. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80490. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80491. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80492. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80493. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80494. 0x72fd2493UL
  80495. },
  80496. {
  80497. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80498. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80499. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80500. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80501. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80502. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80503. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80504. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80505. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80506. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80507. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80508. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80509. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80510. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80511. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80512. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80513. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80514. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80515. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80516. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80517. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80518. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80519. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80520. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80521. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80522. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80523. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80524. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80525. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80526. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80527. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80528. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80529. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80530. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80531. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80532. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80533. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80534. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80535. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80536. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80537. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80538. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80539. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80540. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80541. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80542. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80543. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80544. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80545. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80546. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80547. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80548. 0xed3498beUL
  80549. },
  80550. {
  80551. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80552. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80553. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80554. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80555. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80556. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80557. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80558. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80559. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80560. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80561. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80562. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80563. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80564. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80565. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80566. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80567. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80568. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80569. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80570. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80571. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80572. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80573. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80574. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80575. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80576. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80577. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80578. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80579. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80580. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80581. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80582. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80583. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80584. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80585. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80586. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80587. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80588. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80589. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80590. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80591. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80592. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80593. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80594. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80595. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80596. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80597. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80598. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80599. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80600. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80601. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80602. 0xf10605deUL
  80603. #endif
  80604. }
  80605. };
  80606. /*** End of inlined file: crc32.h ***/
  80607. #endif /* DYNAMIC_CRC_TABLE */
  80608. /* =========================================================================
  80609. * This function can be used by asm versions of crc32()
  80610. */
  80611. const unsigned long FAR * ZEXPORT get_crc_table()
  80612. {
  80613. #ifdef DYNAMIC_CRC_TABLE
  80614. if (crc_table_empty)
  80615. make_crc_table();
  80616. #endif /* DYNAMIC_CRC_TABLE */
  80617. return (const unsigned long FAR *)crc_table;
  80618. }
  80619. /* ========================================================================= */
  80620. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80621. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80622. /* ========================================================================= */
  80623. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80624. {
  80625. if (buf == Z_NULL) return 0UL;
  80626. #ifdef DYNAMIC_CRC_TABLE
  80627. if (crc_table_empty)
  80628. make_crc_table();
  80629. #endif /* DYNAMIC_CRC_TABLE */
  80630. #ifdef BYFOUR
  80631. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80632. u4 endian;
  80633. endian = 1;
  80634. if (*((unsigned char *)(&endian)))
  80635. return crc32_little(crc, buf, len);
  80636. else
  80637. return crc32_big(crc, buf, len);
  80638. }
  80639. #endif /* BYFOUR */
  80640. crc = crc ^ 0xffffffffUL;
  80641. while (len >= 8) {
  80642. DO8;
  80643. len -= 8;
  80644. }
  80645. if (len) do {
  80646. DO1;
  80647. } while (--len);
  80648. return crc ^ 0xffffffffUL;
  80649. }
  80650. #ifdef BYFOUR
  80651. /* ========================================================================= */
  80652. #define DOLIT4 c ^= *buf4++; \
  80653. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80654. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80655. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80656. /* ========================================================================= */
  80657. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80658. {
  80659. register u4 c;
  80660. register const u4 FAR *buf4;
  80661. c = (u4)crc;
  80662. c = ~c;
  80663. while (len && ((ptrdiff_t)buf & 3)) {
  80664. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80665. len--;
  80666. }
  80667. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80668. while (len >= 32) {
  80669. DOLIT32;
  80670. len -= 32;
  80671. }
  80672. while (len >= 4) {
  80673. DOLIT4;
  80674. len -= 4;
  80675. }
  80676. buf = (const unsigned char FAR *)buf4;
  80677. if (len) do {
  80678. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80679. } while (--len);
  80680. c = ~c;
  80681. return (unsigned long)c;
  80682. }
  80683. /* ========================================================================= */
  80684. #define DOBIG4 c ^= *++buf4; \
  80685. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80686. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80687. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80688. /* ========================================================================= */
  80689. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80690. {
  80691. register u4 c;
  80692. register const u4 FAR *buf4;
  80693. c = REV((u4)crc);
  80694. c = ~c;
  80695. while (len && ((ptrdiff_t)buf & 3)) {
  80696. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80697. len--;
  80698. }
  80699. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80700. buf4--;
  80701. while (len >= 32) {
  80702. DOBIG32;
  80703. len -= 32;
  80704. }
  80705. while (len >= 4) {
  80706. DOBIG4;
  80707. len -= 4;
  80708. }
  80709. buf4++;
  80710. buf = (const unsigned char FAR *)buf4;
  80711. if (len) do {
  80712. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80713. } while (--len);
  80714. c = ~c;
  80715. return (unsigned long)(REV(c));
  80716. }
  80717. #endif /* BYFOUR */
  80718. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80719. /* ========================================================================= */
  80720. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80721. {
  80722. unsigned long sum;
  80723. sum = 0;
  80724. while (vec) {
  80725. if (vec & 1)
  80726. sum ^= *mat;
  80727. vec >>= 1;
  80728. mat++;
  80729. }
  80730. return sum;
  80731. }
  80732. /* ========================================================================= */
  80733. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80734. {
  80735. int n;
  80736. for (n = 0; n < GF2_DIM; n++)
  80737. square[n] = gf2_matrix_times(mat, mat[n]);
  80738. }
  80739. /* ========================================================================= */
  80740. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80741. {
  80742. int n;
  80743. unsigned long row;
  80744. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80745. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80746. /* degenerate case */
  80747. if (len2 == 0)
  80748. return crc1;
  80749. /* put operator for one zero bit in odd */
  80750. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80751. row = 1;
  80752. for (n = 1; n < GF2_DIM; n++) {
  80753. odd[n] = row;
  80754. row <<= 1;
  80755. }
  80756. /* put operator for two zero bits in even */
  80757. gf2_matrix_square(even, odd);
  80758. /* put operator for four zero bits in odd */
  80759. gf2_matrix_square(odd, even);
  80760. /* apply len2 zeros to crc1 (first square will put the operator for one
  80761. zero byte, eight zero bits, in even) */
  80762. do {
  80763. /* apply zeros operator for this bit of len2 */
  80764. gf2_matrix_square(even, odd);
  80765. if (len2 & 1)
  80766. crc1 = gf2_matrix_times(even, crc1);
  80767. len2 >>= 1;
  80768. /* if no more bits set, then done */
  80769. if (len2 == 0)
  80770. break;
  80771. /* another iteration of the loop with odd and even swapped */
  80772. gf2_matrix_square(odd, even);
  80773. if (len2 & 1)
  80774. crc1 = gf2_matrix_times(odd, crc1);
  80775. len2 >>= 1;
  80776. /* if no more bits set, then done */
  80777. } while (len2 != 0);
  80778. /* return combined crc */
  80779. crc1 ^= crc2;
  80780. return crc1;
  80781. }
  80782. /*** End of inlined file: crc32.c ***/
  80783. /*** Start of inlined file: deflate.c ***/
  80784. /*
  80785. * ALGORITHM
  80786. *
  80787. * The "deflation" process depends on being able to identify portions
  80788. * of the input text which are identical to earlier input (within a
  80789. * sliding window trailing behind the input currently being processed).
  80790. *
  80791. * The most straightforward technique turns out to be the fastest for
  80792. * most input files: try all possible matches and select the longest.
  80793. * The key feature of this algorithm is that insertions into the string
  80794. * dictionary are very simple and thus fast, and deletions are avoided
  80795. * completely. Insertions are performed at each input character, whereas
  80796. * string matches are performed only when the previous match ends. So it
  80797. * is preferable to spend more time in matches to allow very fast string
  80798. * insertions and avoid deletions. The matching algorithm for small
  80799. * strings is inspired from that of Rabin & Karp. A brute force approach
  80800. * is used to find longer strings when a small match has been found.
  80801. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80802. * (by Leonid Broukhis).
  80803. * A previous version of this file used a more sophisticated algorithm
  80804. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80805. * time, but has a larger average cost, uses more memory and is patented.
  80806. * However the F&G algorithm may be faster for some highly redundant
  80807. * files if the parameter max_chain_length (described below) is too large.
  80808. *
  80809. * ACKNOWLEDGEMENTS
  80810. *
  80811. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80812. * I found it in 'freeze' written by Leonid Broukhis.
  80813. * Thanks to many people for bug reports and testing.
  80814. *
  80815. * REFERENCES
  80816. *
  80817. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80818. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80819. *
  80820. * A description of the Rabin and Karp algorithm is given in the book
  80821. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80822. *
  80823. * Fiala,E.R., and Greene,D.H.
  80824. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80825. *
  80826. */
  80827. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80828. /*** Start of inlined file: deflate.h ***/
  80829. /* WARNING: this file should *not* be used by applications. It is
  80830. part of the implementation of the compression library and is
  80831. subject to change. Applications should only use zlib.h.
  80832. */
  80833. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80834. #ifndef DEFLATE_H
  80835. #define DEFLATE_H
  80836. /* define NO_GZIP when compiling if you want to disable gzip header and
  80837. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80838. the crc code when it is not needed. For shared libraries, gzip encoding
  80839. should be left enabled. */
  80840. #ifndef NO_GZIP
  80841. # define GZIP
  80842. #endif
  80843. #define NO_DUMMY_DECL
  80844. /* ===========================================================================
  80845. * Internal compression state.
  80846. */
  80847. #define LENGTH_CODES 29
  80848. /* number of length codes, not counting the special END_BLOCK code */
  80849. #define LITERALS 256
  80850. /* number of literal bytes 0..255 */
  80851. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80852. /* number of Literal or Length codes, including the END_BLOCK code */
  80853. #define D_CODES 30
  80854. /* number of distance codes */
  80855. #define BL_CODES 19
  80856. /* number of codes used to transfer the bit lengths */
  80857. #define HEAP_SIZE (2*L_CODES+1)
  80858. /* maximum heap size */
  80859. #define MAX_BITS 15
  80860. /* All codes must not exceed MAX_BITS bits */
  80861. #define INIT_STATE 42
  80862. #define EXTRA_STATE 69
  80863. #define NAME_STATE 73
  80864. #define COMMENT_STATE 91
  80865. #define HCRC_STATE 103
  80866. #define BUSY_STATE 113
  80867. #define FINISH_STATE 666
  80868. /* Stream status */
  80869. /* Data structure describing a single value and its code string. */
  80870. typedef struct ct_data_s {
  80871. union {
  80872. ush freq; /* frequency count */
  80873. ush code; /* bit string */
  80874. } fc;
  80875. union {
  80876. ush dad; /* father node in Huffman tree */
  80877. ush len; /* length of bit string */
  80878. } dl;
  80879. } FAR ct_data;
  80880. #define Freq fc.freq
  80881. #define Code fc.code
  80882. #define Dad dl.dad
  80883. #define Len dl.len
  80884. typedef struct static_tree_desc_s static_tree_desc;
  80885. typedef struct tree_desc_s {
  80886. ct_data *dyn_tree; /* the dynamic tree */
  80887. int max_code; /* largest code with non zero frequency */
  80888. static_tree_desc *stat_desc; /* the corresponding static tree */
  80889. } FAR tree_desc;
  80890. typedef ush Pos;
  80891. typedef Pos FAR Posf;
  80892. typedef unsigned IPos;
  80893. /* A Pos is an index in the character window. We use short instead of int to
  80894. * save space in the various tables. IPos is used only for parameter passing.
  80895. */
  80896. typedef struct internal_state {
  80897. z_streamp strm; /* pointer back to this zlib stream */
  80898. int status; /* as the name implies */
  80899. Bytef *pending_buf; /* output still pending */
  80900. ulg pending_buf_size; /* size of pending_buf */
  80901. Bytef *pending_out; /* next pending byte to output to the stream */
  80902. uInt pending; /* nb of bytes in the pending buffer */
  80903. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80904. gz_headerp gzhead; /* gzip header information to write */
  80905. uInt gzindex; /* where in extra, name, or comment */
  80906. Byte method; /* STORED (for zip only) or DEFLATED */
  80907. int last_flush; /* value of flush param for previous deflate call */
  80908. /* used by deflate.c: */
  80909. uInt w_size; /* LZ77 window size (32K by default) */
  80910. uInt w_bits; /* log2(w_size) (8..16) */
  80911. uInt w_mask; /* w_size - 1 */
  80912. Bytef *window;
  80913. /* Sliding window. Input bytes are read into the second half of the window,
  80914. * and move to the first half later to keep a dictionary of at least wSize
  80915. * bytes. With this organization, matches are limited to a distance of
  80916. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80917. * performed with a length multiple of the block size. Also, it limits
  80918. * the window size to 64K, which is quite useful on MSDOS.
  80919. * To do: use the user input buffer as sliding window.
  80920. */
  80921. ulg window_size;
  80922. /* Actual size of window: 2*wSize, except when the user input buffer
  80923. * is directly used as sliding window.
  80924. */
  80925. Posf *prev;
  80926. /* Link to older string with same hash index. To limit the size of this
  80927. * array to 64K, this link is maintained only for the last 32K strings.
  80928. * An index in this array is thus a window index modulo 32K.
  80929. */
  80930. Posf *head; /* Heads of the hash chains or NIL. */
  80931. uInt ins_h; /* hash index of string to be inserted */
  80932. uInt hash_size; /* number of elements in hash table */
  80933. uInt hash_bits; /* log2(hash_size) */
  80934. uInt hash_mask; /* hash_size-1 */
  80935. uInt hash_shift;
  80936. /* Number of bits by which ins_h must be shifted at each input
  80937. * step. It must be such that after MIN_MATCH steps, the oldest
  80938. * byte no longer takes part in the hash key, that is:
  80939. * hash_shift * MIN_MATCH >= hash_bits
  80940. */
  80941. long block_start;
  80942. /* Window position at the beginning of the current output block. Gets
  80943. * negative when the window is moved backwards.
  80944. */
  80945. uInt match_length; /* length of best match */
  80946. IPos prev_match; /* previous match */
  80947. int match_available; /* set if previous match exists */
  80948. uInt strstart; /* start of string to insert */
  80949. uInt match_start; /* start of matching string */
  80950. uInt lookahead; /* number of valid bytes ahead in window */
  80951. uInt prev_length;
  80952. /* Length of the best match at previous step. Matches not greater than this
  80953. * are discarded. This is used in the lazy match evaluation.
  80954. */
  80955. uInt max_chain_length;
  80956. /* To speed up deflation, hash chains are never searched beyond this
  80957. * length. A higher limit improves compression ratio but degrades the
  80958. * speed.
  80959. */
  80960. uInt max_lazy_match;
  80961. /* Attempt to find a better match only when the current match is strictly
  80962. * smaller than this value. This mechanism is used only for compression
  80963. * levels >= 4.
  80964. */
  80965. # define max_insert_length max_lazy_match
  80966. /* Insert new strings in the hash table only if the match length is not
  80967. * greater than this length. This saves time but degrades compression.
  80968. * max_insert_length is used only for compression levels <= 3.
  80969. */
  80970. int level; /* compression level (1..9) */
  80971. int strategy; /* favor or force Huffman coding*/
  80972. uInt good_match;
  80973. /* Use a faster search when the previous match is longer than this */
  80974. int nice_match; /* Stop searching when current match exceeds this */
  80975. /* used by trees.c: */
  80976. /* Didn't use ct_data typedef below to supress compiler warning */
  80977. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80978. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80979. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80980. struct tree_desc_s l_desc; /* desc. for literal tree */
  80981. struct tree_desc_s d_desc; /* desc. for distance tree */
  80982. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80983. ush bl_count[MAX_BITS+1];
  80984. /* number of codes at each bit length for an optimal tree */
  80985. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80986. int heap_len; /* number of elements in the heap */
  80987. int heap_max; /* element of largest frequency */
  80988. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80989. * The same heap array is used to build all trees.
  80990. */
  80991. uch depth[2*L_CODES+1];
  80992. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80993. */
  80994. uchf *l_buf; /* buffer for literals or lengths */
  80995. uInt lit_bufsize;
  80996. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80997. * limiting lit_bufsize to 64K:
  80998. * - frequencies can be kept in 16 bit counters
  80999. * - if compression is not successful for the first block, all input
  81000. * data is still in the window so we can still emit a stored block even
  81001. * when input comes from standard input. (This can also be done for
  81002. * all blocks if lit_bufsize is not greater than 32K.)
  81003. * - if compression is not successful for a file smaller than 64K, we can
  81004. * even emit a stored file instead of a stored block (saving 5 bytes).
  81005. * This is applicable only for zip (not gzip or zlib).
  81006. * - creating new Huffman trees less frequently may not provide fast
  81007. * adaptation to changes in the input data statistics. (Take for
  81008. * example a binary file with poorly compressible code followed by
  81009. * a highly compressible string table.) Smaller buffer sizes give
  81010. * fast adaptation but have of course the overhead of transmitting
  81011. * trees more frequently.
  81012. * - I can't count above 4
  81013. */
  81014. uInt last_lit; /* running index in l_buf */
  81015. ushf *d_buf;
  81016. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81017. * the same number of elements. To use different lengths, an extra flag
  81018. * array would be necessary.
  81019. */
  81020. ulg opt_len; /* bit length of current block with optimal trees */
  81021. ulg static_len; /* bit length of current block with static trees */
  81022. uInt matches; /* number of string matches in current block */
  81023. int last_eob_len; /* bit length of EOB code for last block */
  81024. #ifdef DEBUG
  81025. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81026. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81027. #endif
  81028. ush bi_buf;
  81029. /* Output buffer. bits are inserted starting at the bottom (least
  81030. * significant bits).
  81031. */
  81032. int bi_valid;
  81033. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81034. * are always zero.
  81035. */
  81036. } FAR deflate_state;
  81037. /* Output a byte on the stream.
  81038. * IN assertion: there is enough room in pending_buf.
  81039. */
  81040. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81041. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81042. /* Minimum amount of lookahead, except at the end of the input file.
  81043. * See deflate.c for comments about the MIN_MATCH+1.
  81044. */
  81045. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81046. /* In order to simplify the code, particularly on 16 bit machines, match
  81047. * distances are limited to MAX_DIST instead of WSIZE.
  81048. */
  81049. /* in trees.c */
  81050. void _tr_init OF((deflate_state *s));
  81051. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81052. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81053. int eof));
  81054. void _tr_align OF((deflate_state *s));
  81055. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81056. int eof));
  81057. #define d_code(dist) \
  81058. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81059. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81060. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81061. * used.
  81062. */
  81063. #ifndef DEBUG
  81064. /* Inline versions of _tr_tally for speed: */
  81065. #if defined(GEN_TREES_H) || !defined(STDC)
  81066. extern uch _length_code[];
  81067. extern uch _dist_code[];
  81068. #else
  81069. extern const uch _length_code[];
  81070. extern const uch _dist_code[];
  81071. #endif
  81072. # define _tr_tally_lit(s, c, flush) \
  81073. { uch cc = (c); \
  81074. s->d_buf[s->last_lit] = 0; \
  81075. s->l_buf[s->last_lit++] = cc; \
  81076. s->dyn_ltree[cc].Freq++; \
  81077. flush = (s->last_lit == s->lit_bufsize-1); \
  81078. }
  81079. # define _tr_tally_dist(s, distance, length, flush) \
  81080. { uch len = (length); \
  81081. ush dist = (distance); \
  81082. s->d_buf[s->last_lit] = dist; \
  81083. s->l_buf[s->last_lit++] = len; \
  81084. dist--; \
  81085. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81086. s->dyn_dtree[d_code(dist)].Freq++; \
  81087. flush = (s->last_lit == s->lit_bufsize-1); \
  81088. }
  81089. #else
  81090. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81091. # define _tr_tally_dist(s, distance, length, flush) \
  81092. flush = _tr_tally(s, distance, length)
  81093. #endif
  81094. #endif /* DEFLATE_H */
  81095. /*** End of inlined file: deflate.h ***/
  81096. const char deflate_copyright[] =
  81097. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81098. /*
  81099. If you use the zlib library in a product, an acknowledgment is welcome
  81100. in the documentation of your product. If for some reason you cannot
  81101. include such an acknowledgment, I would appreciate that you keep this
  81102. copyright string in the executable of your product.
  81103. */
  81104. /* ===========================================================================
  81105. * Function prototypes.
  81106. */
  81107. typedef enum {
  81108. need_more, /* block not completed, need more input or more output */
  81109. block_done, /* block flush performed */
  81110. finish_started, /* finish started, need only more output at next deflate */
  81111. finish_done /* finish done, accept no more input or output */
  81112. } block_state;
  81113. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81114. /* Compression function. Returns the block state after the call. */
  81115. local void fill_window OF((deflate_state *s));
  81116. local block_state deflate_stored OF((deflate_state *s, int flush));
  81117. local block_state deflate_fast OF((deflate_state *s, int flush));
  81118. #ifndef FASTEST
  81119. local block_state deflate_slow OF((deflate_state *s, int flush));
  81120. #endif
  81121. local void lm_init OF((deflate_state *s));
  81122. local void putShortMSB OF((deflate_state *s, uInt b));
  81123. local void flush_pending OF((z_streamp strm));
  81124. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81125. #ifndef FASTEST
  81126. #ifdef ASMV
  81127. void match_init OF((void)); /* asm code initialization */
  81128. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81129. #else
  81130. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81131. #endif
  81132. #endif
  81133. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81134. #ifdef DEBUG
  81135. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81136. int length));
  81137. #endif
  81138. /* ===========================================================================
  81139. * Local data
  81140. */
  81141. #define NIL 0
  81142. /* Tail of hash chains */
  81143. #ifndef TOO_FAR
  81144. # define TOO_FAR 4096
  81145. #endif
  81146. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81147. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81148. /* Minimum amount of lookahead, except at the end of the input file.
  81149. * See deflate.c for comments about the MIN_MATCH+1.
  81150. */
  81151. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81152. * the desired pack level (0..9). The values given below have been tuned to
  81153. * exclude worst case performance for pathological files. Better values may be
  81154. * found for specific files.
  81155. */
  81156. typedef struct config_s {
  81157. ush good_length; /* reduce lazy search above this match length */
  81158. ush max_lazy; /* do not perform lazy search above this match length */
  81159. ush nice_length; /* quit search above this match length */
  81160. ush max_chain;
  81161. compress_func func;
  81162. } config;
  81163. #ifdef FASTEST
  81164. local const config configuration_table[2] = {
  81165. /* good lazy nice chain */
  81166. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81167. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81168. #else
  81169. local const config configuration_table[10] = {
  81170. /* good lazy nice chain */
  81171. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81172. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81173. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81174. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81175. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81176. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81177. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81178. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81179. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81180. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81181. #endif
  81182. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81183. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81184. * meaning.
  81185. */
  81186. #define EQUAL 0
  81187. /* result of memcmp for equal strings */
  81188. #ifndef NO_DUMMY_DECL
  81189. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81190. #endif
  81191. /* ===========================================================================
  81192. * Update a hash value with the given input byte
  81193. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81194. * input characters, so that a running hash key can be computed from the
  81195. * previous key instead of complete recalculation each time.
  81196. */
  81197. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81198. /* ===========================================================================
  81199. * Insert string str in the dictionary and set match_head to the previous head
  81200. * of the hash chain (the most recent string with same hash key). Return
  81201. * the previous length of the hash chain.
  81202. * If this file is compiled with -DFASTEST, the compression level is forced
  81203. * to 1, and no hash chains are maintained.
  81204. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81205. * input characters and the first MIN_MATCH bytes of str are valid
  81206. * (except for the last MIN_MATCH-1 bytes of the input file).
  81207. */
  81208. #ifdef FASTEST
  81209. #define INSERT_STRING(s, str, match_head) \
  81210. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81211. match_head = s->head[s->ins_h], \
  81212. s->head[s->ins_h] = (Pos)(str))
  81213. #else
  81214. #define INSERT_STRING(s, str, match_head) \
  81215. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81216. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81217. s->head[s->ins_h] = (Pos)(str))
  81218. #endif
  81219. /* ===========================================================================
  81220. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81221. * prev[] will be initialized on the fly.
  81222. */
  81223. #define CLEAR_HASH(s) \
  81224. s->head[s->hash_size-1] = NIL; \
  81225. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81226. /* ========================================================================= */
  81227. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81228. {
  81229. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81230. Z_DEFAULT_STRATEGY, version, stream_size);
  81231. /* To do: ignore strm->next_in if we use it as window */
  81232. }
  81233. /* ========================================================================= */
  81234. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81235. {
  81236. deflate_state *s;
  81237. int wrap = 1;
  81238. static const char my_version[] = ZLIB_VERSION;
  81239. ushf *overlay;
  81240. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81241. * output size for (length,distance) codes is <= 24 bits.
  81242. */
  81243. if (version == Z_NULL || version[0] != my_version[0] ||
  81244. stream_size != sizeof(z_stream)) {
  81245. return Z_VERSION_ERROR;
  81246. }
  81247. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81248. strm->msg = Z_NULL;
  81249. if (strm->zalloc == (alloc_func)0) {
  81250. strm->zalloc = zcalloc;
  81251. strm->opaque = (voidpf)0;
  81252. }
  81253. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81254. #ifdef FASTEST
  81255. if (level != 0) level = 1;
  81256. #else
  81257. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81258. #endif
  81259. if (windowBits < 0) { /* suppress zlib wrapper */
  81260. wrap = 0;
  81261. windowBits = -windowBits;
  81262. }
  81263. #ifdef GZIP
  81264. else if (windowBits > 15) {
  81265. wrap = 2; /* write gzip wrapper instead */
  81266. windowBits -= 16;
  81267. }
  81268. #endif
  81269. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81270. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81271. strategy < 0 || strategy > Z_FIXED) {
  81272. return Z_STREAM_ERROR;
  81273. }
  81274. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81275. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81276. if (s == Z_NULL) return Z_MEM_ERROR;
  81277. strm->state = (struct internal_state FAR *)s;
  81278. s->strm = strm;
  81279. s->wrap = wrap;
  81280. s->gzhead = Z_NULL;
  81281. s->w_bits = windowBits;
  81282. s->w_size = 1 << s->w_bits;
  81283. s->w_mask = s->w_size - 1;
  81284. s->hash_bits = memLevel + 7;
  81285. s->hash_size = 1 << s->hash_bits;
  81286. s->hash_mask = s->hash_size - 1;
  81287. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81288. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81289. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81290. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81291. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81292. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81293. s->pending_buf = (uchf *) overlay;
  81294. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81295. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81296. s->pending_buf == Z_NULL) {
  81297. s->status = FINISH_STATE;
  81298. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81299. deflateEnd (strm);
  81300. return Z_MEM_ERROR;
  81301. }
  81302. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81303. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81304. s->level = level;
  81305. s->strategy = strategy;
  81306. s->method = (Byte)method;
  81307. return deflateReset(strm);
  81308. }
  81309. /* ========================================================================= */
  81310. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81311. {
  81312. deflate_state *s;
  81313. uInt length = dictLength;
  81314. uInt n;
  81315. IPos hash_head = 0;
  81316. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81317. strm->state->wrap == 2 ||
  81318. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81319. return Z_STREAM_ERROR;
  81320. s = strm->state;
  81321. if (s->wrap)
  81322. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81323. if (length < MIN_MATCH) return Z_OK;
  81324. if (length > MAX_DIST(s)) {
  81325. length = MAX_DIST(s);
  81326. dictionary += dictLength - length; /* use the tail of the dictionary */
  81327. }
  81328. zmemcpy(s->window, dictionary, length);
  81329. s->strstart = length;
  81330. s->block_start = (long)length;
  81331. /* Insert all strings in the hash table (except for the last two bytes).
  81332. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81333. * call of fill_window.
  81334. */
  81335. s->ins_h = s->window[0];
  81336. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81337. for (n = 0; n <= length - MIN_MATCH; n++) {
  81338. INSERT_STRING(s, n, hash_head);
  81339. }
  81340. if (hash_head) hash_head = 0; /* to make compiler happy */
  81341. return Z_OK;
  81342. }
  81343. /* ========================================================================= */
  81344. int ZEXPORT deflateReset (z_streamp strm)
  81345. {
  81346. deflate_state *s;
  81347. if (strm == Z_NULL || strm->state == Z_NULL ||
  81348. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81349. return Z_STREAM_ERROR;
  81350. }
  81351. strm->total_in = strm->total_out = 0;
  81352. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81353. strm->data_type = Z_UNKNOWN;
  81354. s = (deflate_state *)strm->state;
  81355. s->pending = 0;
  81356. s->pending_out = s->pending_buf;
  81357. if (s->wrap < 0) {
  81358. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81359. }
  81360. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81361. strm->adler =
  81362. #ifdef GZIP
  81363. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81364. #endif
  81365. adler32(0L, Z_NULL, 0);
  81366. s->last_flush = Z_NO_FLUSH;
  81367. _tr_init(s);
  81368. lm_init(s);
  81369. return Z_OK;
  81370. }
  81371. /* ========================================================================= */
  81372. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81373. {
  81374. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81375. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81376. strm->state->gzhead = head;
  81377. return Z_OK;
  81378. }
  81379. /* ========================================================================= */
  81380. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81381. {
  81382. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81383. strm->state->bi_valid = bits;
  81384. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81385. return Z_OK;
  81386. }
  81387. /* ========================================================================= */
  81388. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81389. {
  81390. deflate_state *s;
  81391. compress_func func;
  81392. int err = Z_OK;
  81393. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81394. s = strm->state;
  81395. #ifdef FASTEST
  81396. if (level != 0) level = 1;
  81397. #else
  81398. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81399. #endif
  81400. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81401. return Z_STREAM_ERROR;
  81402. }
  81403. func = configuration_table[s->level].func;
  81404. if (func != configuration_table[level].func && strm->total_in != 0) {
  81405. /* Flush the last buffer: */
  81406. err = deflate(strm, Z_PARTIAL_FLUSH);
  81407. }
  81408. if (s->level != level) {
  81409. s->level = level;
  81410. s->max_lazy_match = configuration_table[level].max_lazy;
  81411. s->good_match = configuration_table[level].good_length;
  81412. s->nice_match = configuration_table[level].nice_length;
  81413. s->max_chain_length = configuration_table[level].max_chain;
  81414. }
  81415. s->strategy = strategy;
  81416. return err;
  81417. }
  81418. /* ========================================================================= */
  81419. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81420. {
  81421. deflate_state *s;
  81422. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81423. s = strm->state;
  81424. s->good_match = good_length;
  81425. s->max_lazy_match = max_lazy;
  81426. s->nice_match = nice_length;
  81427. s->max_chain_length = max_chain;
  81428. return Z_OK;
  81429. }
  81430. /* =========================================================================
  81431. * For the default windowBits of 15 and memLevel of 8, this function returns
  81432. * a close to exact, as well as small, upper bound on the compressed size.
  81433. * They are coded as constants here for a reason--if the #define's are
  81434. * changed, then this function needs to be changed as well. The return
  81435. * value for 15 and 8 only works for those exact settings.
  81436. *
  81437. * For any setting other than those defaults for windowBits and memLevel,
  81438. * the value returned is a conservative worst case for the maximum expansion
  81439. * resulting from using fixed blocks instead of stored blocks, which deflate
  81440. * can emit on compressed data for some combinations of the parameters.
  81441. *
  81442. * This function could be more sophisticated to provide closer upper bounds
  81443. * for every combination of windowBits and memLevel, as well as wrap.
  81444. * But even the conservative upper bound of about 14% expansion does not
  81445. * seem onerous for output buffer allocation.
  81446. */
  81447. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81448. {
  81449. deflate_state *s;
  81450. uLong destLen;
  81451. /* conservative upper bound */
  81452. destLen = sourceLen +
  81453. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81454. /* if can't get parameters, return conservative bound */
  81455. if (strm == Z_NULL || strm->state == Z_NULL)
  81456. return destLen;
  81457. /* if not default parameters, return conservative bound */
  81458. s = strm->state;
  81459. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81460. return destLen;
  81461. /* default settings: return tight bound for that case */
  81462. return compressBound(sourceLen);
  81463. }
  81464. /* =========================================================================
  81465. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81466. * IN assertion: the stream state is correct and there is enough room in
  81467. * pending_buf.
  81468. */
  81469. local void putShortMSB (deflate_state *s, uInt b)
  81470. {
  81471. put_byte(s, (Byte)(b >> 8));
  81472. put_byte(s, (Byte)(b & 0xff));
  81473. }
  81474. /* =========================================================================
  81475. * Flush as much pending output as possible. All deflate() output goes
  81476. * through this function so some applications may wish to modify it
  81477. * to avoid allocating a large strm->next_out buffer and copying into it.
  81478. * (See also read_buf()).
  81479. */
  81480. local void flush_pending (z_streamp strm)
  81481. {
  81482. unsigned len = strm->state->pending;
  81483. if (len > strm->avail_out) len = strm->avail_out;
  81484. if (len == 0) return;
  81485. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81486. strm->next_out += len;
  81487. strm->state->pending_out += len;
  81488. strm->total_out += len;
  81489. strm->avail_out -= len;
  81490. strm->state->pending -= len;
  81491. if (strm->state->pending == 0) {
  81492. strm->state->pending_out = strm->state->pending_buf;
  81493. }
  81494. }
  81495. /* ========================================================================= */
  81496. int ZEXPORT deflate (z_streamp strm, int flush)
  81497. {
  81498. int old_flush; /* value of flush param for previous deflate call */
  81499. deflate_state *s;
  81500. if (strm == Z_NULL || strm->state == Z_NULL ||
  81501. flush > Z_FINISH || flush < 0) {
  81502. return Z_STREAM_ERROR;
  81503. }
  81504. s = strm->state;
  81505. if (strm->next_out == Z_NULL ||
  81506. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81507. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81508. ERR_RETURN(strm, Z_STREAM_ERROR);
  81509. }
  81510. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81511. s->strm = strm; /* just in case */
  81512. old_flush = s->last_flush;
  81513. s->last_flush = flush;
  81514. /* Write the header */
  81515. if (s->status == INIT_STATE) {
  81516. #ifdef GZIP
  81517. if (s->wrap == 2) {
  81518. strm->adler = crc32(0L, Z_NULL, 0);
  81519. put_byte(s, 31);
  81520. put_byte(s, 139);
  81521. put_byte(s, 8);
  81522. if (s->gzhead == NULL) {
  81523. put_byte(s, 0);
  81524. put_byte(s, 0);
  81525. put_byte(s, 0);
  81526. put_byte(s, 0);
  81527. put_byte(s, 0);
  81528. put_byte(s, s->level == 9 ? 2 :
  81529. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81530. 4 : 0));
  81531. put_byte(s, OS_CODE);
  81532. s->status = BUSY_STATE;
  81533. }
  81534. else {
  81535. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81536. (s->gzhead->hcrc ? 2 : 0) +
  81537. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81538. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81539. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81540. );
  81541. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81542. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81543. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81544. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81545. put_byte(s, s->level == 9 ? 2 :
  81546. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81547. 4 : 0));
  81548. put_byte(s, s->gzhead->os & 0xff);
  81549. if (s->gzhead->extra != NULL) {
  81550. put_byte(s, s->gzhead->extra_len & 0xff);
  81551. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81552. }
  81553. if (s->gzhead->hcrc)
  81554. strm->adler = crc32(strm->adler, s->pending_buf,
  81555. s->pending);
  81556. s->gzindex = 0;
  81557. s->status = EXTRA_STATE;
  81558. }
  81559. }
  81560. else
  81561. #endif
  81562. {
  81563. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81564. uInt level_flags;
  81565. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81566. level_flags = 0;
  81567. else if (s->level < 6)
  81568. level_flags = 1;
  81569. else if (s->level == 6)
  81570. level_flags = 2;
  81571. else
  81572. level_flags = 3;
  81573. header |= (level_flags << 6);
  81574. if (s->strstart != 0) header |= PRESET_DICT;
  81575. header += 31 - (header % 31);
  81576. s->status = BUSY_STATE;
  81577. putShortMSB(s, header);
  81578. /* Save the adler32 of the preset dictionary: */
  81579. if (s->strstart != 0) {
  81580. putShortMSB(s, (uInt)(strm->adler >> 16));
  81581. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81582. }
  81583. strm->adler = adler32(0L, Z_NULL, 0);
  81584. }
  81585. }
  81586. #ifdef GZIP
  81587. if (s->status == EXTRA_STATE) {
  81588. if (s->gzhead->extra != NULL) {
  81589. uInt beg = s->pending; /* start of bytes to update crc */
  81590. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81591. if (s->pending == s->pending_buf_size) {
  81592. if (s->gzhead->hcrc && s->pending > beg)
  81593. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81594. s->pending - beg);
  81595. flush_pending(strm);
  81596. beg = s->pending;
  81597. if (s->pending == s->pending_buf_size)
  81598. break;
  81599. }
  81600. put_byte(s, s->gzhead->extra[s->gzindex]);
  81601. s->gzindex++;
  81602. }
  81603. if (s->gzhead->hcrc && s->pending > beg)
  81604. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81605. s->pending - beg);
  81606. if (s->gzindex == s->gzhead->extra_len) {
  81607. s->gzindex = 0;
  81608. s->status = NAME_STATE;
  81609. }
  81610. }
  81611. else
  81612. s->status = NAME_STATE;
  81613. }
  81614. if (s->status == NAME_STATE) {
  81615. if (s->gzhead->name != NULL) {
  81616. uInt beg = s->pending; /* start of bytes to update crc */
  81617. int val;
  81618. do {
  81619. if (s->pending == s->pending_buf_size) {
  81620. if (s->gzhead->hcrc && s->pending > beg)
  81621. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81622. s->pending - beg);
  81623. flush_pending(strm);
  81624. beg = s->pending;
  81625. if (s->pending == s->pending_buf_size) {
  81626. val = 1;
  81627. break;
  81628. }
  81629. }
  81630. val = s->gzhead->name[s->gzindex++];
  81631. put_byte(s, val);
  81632. } while (val != 0);
  81633. if (s->gzhead->hcrc && s->pending > beg)
  81634. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81635. s->pending - beg);
  81636. if (val == 0) {
  81637. s->gzindex = 0;
  81638. s->status = COMMENT_STATE;
  81639. }
  81640. }
  81641. else
  81642. s->status = COMMENT_STATE;
  81643. }
  81644. if (s->status == COMMENT_STATE) {
  81645. if (s->gzhead->comment != NULL) {
  81646. uInt beg = s->pending; /* start of bytes to update crc */
  81647. int val;
  81648. do {
  81649. if (s->pending == s->pending_buf_size) {
  81650. if (s->gzhead->hcrc && s->pending > beg)
  81651. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81652. s->pending - beg);
  81653. flush_pending(strm);
  81654. beg = s->pending;
  81655. if (s->pending == s->pending_buf_size) {
  81656. val = 1;
  81657. break;
  81658. }
  81659. }
  81660. val = s->gzhead->comment[s->gzindex++];
  81661. put_byte(s, val);
  81662. } while (val != 0);
  81663. if (s->gzhead->hcrc && s->pending > beg)
  81664. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81665. s->pending - beg);
  81666. if (val == 0)
  81667. s->status = HCRC_STATE;
  81668. }
  81669. else
  81670. s->status = HCRC_STATE;
  81671. }
  81672. if (s->status == HCRC_STATE) {
  81673. if (s->gzhead->hcrc) {
  81674. if (s->pending + 2 > s->pending_buf_size)
  81675. flush_pending(strm);
  81676. if (s->pending + 2 <= s->pending_buf_size) {
  81677. put_byte(s, (Byte)(strm->adler & 0xff));
  81678. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81679. strm->adler = crc32(0L, Z_NULL, 0);
  81680. s->status = BUSY_STATE;
  81681. }
  81682. }
  81683. else
  81684. s->status = BUSY_STATE;
  81685. }
  81686. #endif
  81687. /* Flush as much pending output as possible */
  81688. if (s->pending != 0) {
  81689. flush_pending(strm);
  81690. if (strm->avail_out == 0) {
  81691. /* Since avail_out is 0, deflate will be called again with
  81692. * more output space, but possibly with both pending and
  81693. * avail_in equal to zero. There won't be anything to do,
  81694. * but this is not an error situation so make sure we
  81695. * return OK instead of BUF_ERROR at next call of deflate:
  81696. */
  81697. s->last_flush = -1;
  81698. return Z_OK;
  81699. }
  81700. /* Make sure there is something to do and avoid duplicate consecutive
  81701. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81702. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81703. */
  81704. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81705. flush != Z_FINISH) {
  81706. ERR_RETURN(strm, Z_BUF_ERROR);
  81707. }
  81708. /* User must not provide more input after the first FINISH: */
  81709. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81710. ERR_RETURN(strm, Z_BUF_ERROR);
  81711. }
  81712. /* Start a new block or continue the current one.
  81713. */
  81714. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81715. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81716. block_state bstate;
  81717. bstate = (*(configuration_table[s->level].func))(s, flush);
  81718. if (bstate == finish_started || bstate == finish_done) {
  81719. s->status = FINISH_STATE;
  81720. }
  81721. if (bstate == need_more || bstate == finish_started) {
  81722. if (strm->avail_out == 0) {
  81723. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81724. }
  81725. return Z_OK;
  81726. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81727. * of deflate should use the same flush parameter to make sure
  81728. * that the flush is complete. So we don't have to output an
  81729. * empty block here, this will be done at next call. This also
  81730. * ensures that for a very small output buffer, we emit at most
  81731. * one empty block.
  81732. */
  81733. }
  81734. if (bstate == block_done) {
  81735. if (flush == Z_PARTIAL_FLUSH) {
  81736. _tr_align(s);
  81737. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81738. _tr_stored_block(s, (char*)0, 0L, 0);
  81739. /* For a full flush, this empty block will be recognized
  81740. * as a special marker by inflate_sync().
  81741. */
  81742. if (flush == Z_FULL_FLUSH) {
  81743. CLEAR_HASH(s); /* forget history */
  81744. }
  81745. }
  81746. flush_pending(strm);
  81747. if (strm->avail_out == 0) {
  81748. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81749. return Z_OK;
  81750. }
  81751. }
  81752. }
  81753. Assert(strm->avail_out > 0, "bug2");
  81754. if (flush != Z_FINISH) return Z_OK;
  81755. if (s->wrap <= 0) return Z_STREAM_END;
  81756. /* Write the trailer */
  81757. #ifdef GZIP
  81758. if (s->wrap == 2) {
  81759. put_byte(s, (Byte)(strm->adler & 0xff));
  81760. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81761. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81762. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81763. put_byte(s, (Byte)(strm->total_in & 0xff));
  81764. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81765. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81766. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81767. }
  81768. else
  81769. #endif
  81770. {
  81771. putShortMSB(s, (uInt)(strm->adler >> 16));
  81772. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81773. }
  81774. flush_pending(strm);
  81775. /* If avail_out is zero, the application will call deflate again
  81776. * to flush the rest.
  81777. */
  81778. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81779. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81780. }
  81781. /* ========================================================================= */
  81782. int ZEXPORT deflateEnd (z_streamp strm)
  81783. {
  81784. int status;
  81785. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81786. status = strm->state->status;
  81787. if (status != INIT_STATE &&
  81788. status != EXTRA_STATE &&
  81789. status != NAME_STATE &&
  81790. status != COMMENT_STATE &&
  81791. status != HCRC_STATE &&
  81792. status != BUSY_STATE &&
  81793. status != FINISH_STATE) {
  81794. return Z_STREAM_ERROR;
  81795. }
  81796. /* Deallocate in reverse order of allocations: */
  81797. TRY_FREE(strm, strm->state->pending_buf);
  81798. TRY_FREE(strm, strm->state->head);
  81799. TRY_FREE(strm, strm->state->prev);
  81800. TRY_FREE(strm, strm->state->window);
  81801. ZFREE(strm, strm->state);
  81802. strm->state = Z_NULL;
  81803. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81804. }
  81805. /* =========================================================================
  81806. * Copy the source state to the destination state.
  81807. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81808. * doesn't have enough memory anyway to duplicate compression states).
  81809. */
  81810. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81811. {
  81812. #ifdef MAXSEG_64K
  81813. return Z_STREAM_ERROR;
  81814. #else
  81815. deflate_state *ds;
  81816. deflate_state *ss;
  81817. ushf *overlay;
  81818. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81819. return Z_STREAM_ERROR;
  81820. }
  81821. ss = source->state;
  81822. zmemcpy(dest, source, sizeof(z_stream));
  81823. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81824. if (ds == Z_NULL) return Z_MEM_ERROR;
  81825. dest->state = (struct internal_state FAR *) ds;
  81826. zmemcpy(ds, ss, sizeof(deflate_state));
  81827. ds->strm = dest;
  81828. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81829. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81830. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81831. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81832. ds->pending_buf = (uchf *) overlay;
  81833. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81834. ds->pending_buf == Z_NULL) {
  81835. deflateEnd (dest);
  81836. return Z_MEM_ERROR;
  81837. }
  81838. /* following zmemcpy do not work for 16-bit MSDOS */
  81839. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81840. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81841. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81842. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81843. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81844. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81845. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81846. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81847. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81848. ds->bl_desc.dyn_tree = ds->bl_tree;
  81849. return Z_OK;
  81850. #endif /* MAXSEG_64K */
  81851. }
  81852. /* ===========================================================================
  81853. * Read a new buffer from the current input stream, update the adler32
  81854. * and total number of bytes read. All deflate() input goes through
  81855. * this function so some applications may wish to modify it to avoid
  81856. * allocating a large strm->next_in buffer and copying from it.
  81857. * (See also flush_pending()).
  81858. */
  81859. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81860. {
  81861. unsigned len = strm->avail_in;
  81862. if (len > size) len = size;
  81863. if (len == 0) return 0;
  81864. strm->avail_in -= len;
  81865. if (strm->state->wrap == 1) {
  81866. strm->adler = adler32(strm->adler, strm->next_in, len);
  81867. }
  81868. #ifdef GZIP
  81869. else if (strm->state->wrap == 2) {
  81870. strm->adler = crc32(strm->adler, strm->next_in, len);
  81871. }
  81872. #endif
  81873. zmemcpy(buf, strm->next_in, len);
  81874. strm->next_in += len;
  81875. strm->total_in += len;
  81876. return (int)len;
  81877. }
  81878. /* ===========================================================================
  81879. * Initialize the "longest match" routines for a new zlib stream
  81880. */
  81881. local void lm_init (deflate_state *s)
  81882. {
  81883. s->window_size = (ulg)2L*s->w_size;
  81884. CLEAR_HASH(s);
  81885. /* Set the default configuration parameters:
  81886. */
  81887. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81888. s->good_match = configuration_table[s->level].good_length;
  81889. s->nice_match = configuration_table[s->level].nice_length;
  81890. s->max_chain_length = configuration_table[s->level].max_chain;
  81891. s->strstart = 0;
  81892. s->block_start = 0L;
  81893. s->lookahead = 0;
  81894. s->match_length = s->prev_length = MIN_MATCH-1;
  81895. s->match_available = 0;
  81896. s->ins_h = 0;
  81897. #ifndef FASTEST
  81898. #ifdef ASMV
  81899. match_init(); /* initialize the asm code */
  81900. #endif
  81901. #endif
  81902. }
  81903. #ifndef FASTEST
  81904. /* ===========================================================================
  81905. * Set match_start to the longest match starting at the given string and
  81906. * return its length. Matches shorter or equal to prev_length are discarded,
  81907. * in which case the result is equal to prev_length and match_start is
  81908. * garbage.
  81909. * IN assertions: cur_match is the head of the hash chain for the current
  81910. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81911. * OUT assertion: the match length is not greater than s->lookahead.
  81912. */
  81913. #ifndef ASMV
  81914. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81915. * match.S. The code will be functionally equivalent.
  81916. */
  81917. local uInt longest_match(deflate_state *s, IPos cur_match)
  81918. {
  81919. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81920. register Bytef *scan = s->window + s->strstart; /* current string */
  81921. register Bytef *match; /* matched string */
  81922. register int len; /* length of current match */
  81923. int best_len = s->prev_length; /* best match length so far */
  81924. int nice_match = s->nice_match; /* stop if match long enough */
  81925. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81926. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81927. /* Stop when cur_match becomes <= limit. To simplify the code,
  81928. * we prevent matches with the string of window index 0.
  81929. */
  81930. Posf *prev = s->prev;
  81931. uInt wmask = s->w_mask;
  81932. #ifdef UNALIGNED_OK
  81933. /* Compare two bytes at a time. Note: this is not always beneficial.
  81934. * Try with and without -DUNALIGNED_OK to check.
  81935. */
  81936. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81937. register ush scan_start = *(ushf*)scan;
  81938. register ush scan_end = *(ushf*)(scan+best_len-1);
  81939. #else
  81940. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81941. register Byte scan_end1 = scan[best_len-1];
  81942. register Byte scan_end = scan[best_len];
  81943. #endif
  81944. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81945. * It is easy to get rid of this optimization if necessary.
  81946. */
  81947. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81948. /* Do not waste too much time if we already have a good match: */
  81949. if (s->prev_length >= s->good_match) {
  81950. chain_length >>= 2;
  81951. }
  81952. /* Do not look for matches beyond the end of the input. This is necessary
  81953. * to make deflate deterministic.
  81954. */
  81955. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81956. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81957. do {
  81958. Assert(cur_match < s->strstart, "no future");
  81959. match = s->window + cur_match;
  81960. /* Skip to next match if the match length cannot increase
  81961. * or if the match length is less than 2. Note that the checks below
  81962. * for insufficient lookahead only occur occasionally for performance
  81963. * reasons. Therefore uninitialized memory will be accessed, and
  81964. * conditional jumps will be made that depend on those values.
  81965. * However the length of the match is limited to the lookahead, so
  81966. * the output of deflate is not affected by the uninitialized values.
  81967. */
  81968. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81969. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81970. * UNALIGNED_OK if your compiler uses a different size.
  81971. */
  81972. if (*(ushf*)(match+best_len-1) != scan_end ||
  81973. *(ushf*)match != scan_start) continue;
  81974. /* It is not necessary to compare scan[2] and match[2] since they are
  81975. * always equal when the other bytes match, given that the hash keys
  81976. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81977. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81978. * lookahead only every 4th comparison; the 128th check will be made
  81979. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81980. * necessary to put more guard bytes at the end of the window, or
  81981. * to check more often for insufficient lookahead.
  81982. */
  81983. Assert(scan[2] == match[2], "scan[2]?");
  81984. scan++, match++;
  81985. do {
  81986. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81987. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81988. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81989. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81990. scan < strend);
  81991. /* The funny "do {}" generates better code on most compilers */
  81992. /* Here, scan <= window+strstart+257 */
  81993. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81994. if (*scan == *match) scan++;
  81995. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81996. scan = strend - (MAX_MATCH-1);
  81997. #else /* UNALIGNED_OK */
  81998. if (match[best_len] != scan_end ||
  81999. match[best_len-1] != scan_end1 ||
  82000. *match != *scan ||
  82001. *++match != scan[1]) continue;
  82002. /* The check at best_len-1 can be removed because it will be made
  82003. * again later. (This heuristic is not always a win.)
  82004. * It is not necessary to compare scan[2] and match[2] since they
  82005. * are always equal when the other bytes match, given that
  82006. * the hash keys are equal and that HASH_BITS >= 8.
  82007. */
  82008. scan += 2, match++;
  82009. Assert(*scan == *match, "match[2]?");
  82010. /* We check for insufficient lookahead only every 8th comparison;
  82011. * the 256th check will be made at strstart+258.
  82012. */
  82013. do {
  82014. } while (*++scan == *++match && *++scan == *++match &&
  82015. *++scan == *++match && *++scan == *++match &&
  82016. *++scan == *++match && *++scan == *++match &&
  82017. *++scan == *++match && *++scan == *++match &&
  82018. scan < strend);
  82019. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82020. len = MAX_MATCH - (int)(strend - scan);
  82021. scan = strend - MAX_MATCH;
  82022. #endif /* UNALIGNED_OK */
  82023. if (len > best_len) {
  82024. s->match_start = cur_match;
  82025. best_len = len;
  82026. if (len >= nice_match) break;
  82027. #ifdef UNALIGNED_OK
  82028. scan_end = *(ushf*)(scan+best_len-1);
  82029. #else
  82030. scan_end1 = scan[best_len-1];
  82031. scan_end = scan[best_len];
  82032. #endif
  82033. }
  82034. } while ((cur_match = prev[cur_match & wmask]) > limit
  82035. && --chain_length != 0);
  82036. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82037. return s->lookahead;
  82038. }
  82039. #endif /* ASMV */
  82040. #endif /* FASTEST */
  82041. /* ---------------------------------------------------------------------------
  82042. * Optimized version for level == 1 or strategy == Z_RLE only
  82043. */
  82044. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82045. {
  82046. register Bytef *scan = s->window + s->strstart; /* current string */
  82047. register Bytef *match; /* matched string */
  82048. register int len; /* length of current match */
  82049. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82050. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82051. * It is easy to get rid of this optimization if necessary.
  82052. */
  82053. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82054. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82055. Assert(cur_match < s->strstart, "no future");
  82056. match = s->window + cur_match;
  82057. /* Return failure if the match length is less than 2:
  82058. */
  82059. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82060. /* The check at best_len-1 can be removed because it will be made
  82061. * again later. (This heuristic is not always a win.)
  82062. * It is not necessary to compare scan[2] and match[2] since they
  82063. * are always equal when the other bytes match, given that
  82064. * the hash keys are equal and that HASH_BITS >= 8.
  82065. */
  82066. scan += 2, match += 2;
  82067. Assert(*scan == *match, "match[2]?");
  82068. /* We check for insufficient lookahead only every 8th comparison;
  82069. * the 256th check will be made at strstart+258.
  82070. */
  82071. do {
  82072. } while (*++scan == *++match && *++scan == *++match &&
  82073. *++scan == *++match && *++scan == *++match &&
  82074. *++scan == *++match && *++scan == *++match &&
  82075. *++scan == *++match && *++scan == *++match &&
  82076. scan < strend);
  82077. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82078. len = MAX_MATCH - (int)(strend - scan);
  82079. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82080. s->match_start = cur_match;
  82081. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82082. }
  82083. #ifdef DEBUG
  82084. /* ===========================================================================
  82085. * Check that the match at match_start is indeed a match.
  82086. */
  82087. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82088. {
  82089. /* check that the match is indeed a match */
  82090. if (zmemcmp(s->window + match,
  82091. s->window + start, length) != EQUAL) {
  82092. fprintf(stderr, " start %u, match %u, length %d\n",
  82093. start, match, length);
  82094. do {
  82095. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82096. } while (--length != 0);
  82097. z_error("invalid match");
  82098. }
  82099. if (z_verbose > 1) {
  82100. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82101. do { putc(s->window[start++], stderr); } while (--length != 0);
  82102. }
  82103. }
  82104. #else
  82105. # define check_match(s, start, match, length)
  82106. #endif /* DEBUG */
  82107. /* ===========================================================================
  82108. * Fill the window when the lookahead becomes insufficient.
  82109. * Updates strstart and lookahead.
  82110. *
  82111. * IN assertion: lookahead < MIN_LOOKAHEAD
  82112. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82113. * At least one byte has been read, or avail_in == 0; reads are
  82114. * performed for at least two bytes (required for the zip translate_eol
  82115. * option -- not supported here).
  82116. */
  82117. local void fill_window (deflate_state *s)
  82118. {
  82119. register unsigned n, m;
  82120. register Posf *p;
  82121. unsigned more; /* Amount of free space at the end of the window. */
  82122. uInt wsize = s->w_size;
  82123. do {
  82124. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82125. /* Deal with !@#$% 64K limit: */
  82126. if (sizeof(int) <= 2) {
  82127. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82128. more = wsize;
  82129. } else if (more == (unsigned)(-1)) {
  82130. /* Very unlikely, but possible on 16 bit machine if
  82131. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82132. */
  82133. more--;
  82134. }
  82135. }
  82136. /* If the window is almost full and there is insufficient lookahead,
  82137. * move the upper half to the lower one to make room in the upper half.
  82138. */
  82139. if (s->strstart >= wsize+MAX_DIST(s)) {
  82140. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82141. s->match_start -= wsize;
  82142. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82143. s->block_start -= (long) wsize;
  82144. /* Slide the hash table (could be avoided with 32 bit values
  82145. at the expense of memory usage). We slide even when level == 0
  82146. to keep the hash table consistent if we switch back to level > 0
  82147. later. (Using level 0 permanently is not an optimal usage of
  82148. zlib, so we don't care about this pathological case.)
  82149. */
  82150. /* %%% avoid this when Z_RLE */
  82151. n = s->hash_size;
  82152. p = &s->head[n];
  82153. do {
  82154. m = *--p;
  82155. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82156. } while (--n);
  82157. n = wsize;
  82158. #ifndef FASTEST
  82159. p = &s->prev[n];
  82160. do {
  82161. m = *--p;
  82162. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82163. /* If n is not on any hash chain, prev[n] is garbage but
  82164. * its value will never be used.
  82165. */
  82166. } while (--n);
  82167. #endif
  82168. more += wsize;
  82169. }
  82170. if (s->strm->avail_in == 0) return;
  82171. /* If there was no sliding:
  82172. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82173. * more == window_size - lookahead - strstart
  82174. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82175. * => more >= window_size - 2*WSIZE + 2
  82176. * In the BIG_MEM or MMAP case (not yet supported),
  82177. * window_size == input_size + MIN_LOOKAHEAD &&
  82178. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82179. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82180. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82181. */
  82182. Assert(more >= 2, "more < 2");
  82183. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82184. s->lookahead += n;
  82185. /* Initialize the hash value now that we have some input: */
  82186. if (s->lookahead >= MIN_MATCH) {
  82187. s->ins_h = s->window[s->strstart];
  82188. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82189. #if MIN_MATCH != 3
  82190. Call UPDATE_HASH() MIN_MATCH-3 more times
  82191. #endif
  82192. }
  82193. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82194. * but this is not important since only literal bytes will be emitted.
  82195. */
  82196. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82197. }
  82198. /* ===========================================================================
  82199. * Flush the current block, with given end-of-file flag.
  82200. * IN assertion: strstart is set to the end of the current match.
  82201. */
  82202. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82203. _tr_flush_block(s, (s->block_start >= 0L ? \
  82204. (charf *)&s->window[(unsigned)s->block_start] : \
  82205. (charf *)Z_NULL), \
  82206. (ulg)((long)s->strstart - s->block_start), \
  82207. (eof)); \
  82208. s->block_start = s->strstart; \
  82209. flush_pending(s->strm); \
  82210. Tracev((stderr,"[FLUSH]")); \
  82211. }
  82212. /* Same but force premature exit if necessary. */
  82213. #define FLUSH_BLOCK(s, eof) { \
  82214. FLUSH_BLOCK_ONLY(s, eof); \
  82215. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82216. }
  82217. /* ===========================================================================
  82218. * Copy without compression as much as possible from the input stream, return
  82219. * the current block state.
  82220. * This function does not insert new strings in the dictionary since
  82221. * uncompressible data is probably not useful. This function is used
  82222. * only for the level=0 compression option.
  82223. * NOTE: this function should be optimized to avoid extra copying from
  82224. * window to pending_buf.
  82225. */
  82226. local block_state deflate_stored(deflate_state *s, int flush)
  82227. {
  82228. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82229. * to pending_buf_size, and each stored block has a 5 byte header:
  82230. */
  82231. ulg max_block_size = 0xffff;
  82232. ulg max_start;
  82233. if (max_block_size > s->pending_buf_size - 5) {
  82234. max_block_size = s->pending_buf_size - 5;
  82235. }
  82236. /* Copy as much as possible from input to output: */
  82237. for (;;) {
  82238. /* Fill the window as much as possible: */
  82239. if (s->lookahead <= 1) {
  82240. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82241. s->block_start >= (long)s->w_size, "slide too late");
  82242. fill_window(s);
  82243. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82244. if (s->lookahead == 0) break; /* flush the current block */
  82245. }
  82246. Assert(s->block_start >= 0L, "block gone");
  82247. s->strstart += s->lookahead;
  82248. s->lookahead = 0;
  82249. /* Emit a stored block if pending_buf will be full: */
  82250. max_start = s->block_start + max_block_size;
  82251. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82252. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82253. s->lookahead = (uInt)(s->strstart - max_start);
  82254. s->strstart = (uInt)max_start;
  82255. FLUSH_BLOCK(s, 0);
  82256. }
  82257. /* Flush if we may have to slide, otherwise block_start may become
  82258. * negative and the data will be gone:
  82259. */
  82260. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82261. FLUSH_BLOCK(s, 0);
  82262. }
  82263. }
  82264. FLUSH_BLOCK(s, flush == Z_FINISH);
  82265. return flush == Z_FINISH ? finish_done : block_done;
  82266. }
  82267. /* ===========================================================================
  82268. * Compress as much as possible from the input stream, return the current
  82269. * block state.
  82270. * This function does not perform lazy evaluation of matches and inserts
  82271. * new strings in the dictionary only for unmatched strings or for short
  82272. * matches. It is used only for the fast compression options.
  82273. */
  82274. local block_state deflate_fast(deflate_state *s, int flush)
  82275. {
  82276. IPos hash_head = NIL; /* head of the hash chain */
  82277. int bflush; /* set if current block must be flushed */
  82278. for (;;) {
  82279. /* Make sure that we always have enough lookahead, except
  82280. * at the end of the input file. We need MAX_MATCH bytes
  82281. * for the next match, plus MIN_MATCH bytes to insert the
  82282. * string following the next match.
  82283. */
  82284. if (s->lookahead < MIN_LOOKAHEAD) {
  82285. fill_window(s);
  82286. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82287. return need_more;
  82288. }
  82289. if (s->lookahead == 0) break; /* flush the current block */
  82290. }
  82291. /* Insert the string window[strstart .. strstart+2] in the
  82292. * dictionary, and set hash_head to the head of the hash chain:
  82293. */
  82294. if (s->lookahead >= MIN_MATCH) {
  82295. INSERT_STRING(s, s->strstart, hash_head);
  82296. }
  82297. /* Find the longest match, discarding those <= prev_length.
  82298. * At this point we have always match_length < MIN_MATCH
  82299. */
  82300. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82301. /* To simplify the code, we prevent matches with the string
  82302. * of window index 0 (in particular we have to avoid a match
  82303. * of the string with itself at the start of the input file).
  82304. */
  82305. #ifdef FASTEST
  82306. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82307. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82308. s->match_length = longest_match_fast (s, hash_head);
  82309. }
  82310. #else
  82311. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82312. s->match_length = longest_match (s, hash_head);
  82313. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82314. s->match_length = longest_match_fast (s, hash_head);
  82315. }
  82316. #endif
  82317. /* longest_match() or longest_match_fast() sets match_start */
  82318. }
  82319. if (s->match_length >= MIN_MATCH) {
  82320. check_match(s, s->strstart, s->match_start, s->match_length);
  82321. _tr_tally_dist(s, s->strstart - s->match_start,
  82322. s->match_length - MIN_MATCH, bflush);
  82323. s->lookahead -= s->match_length;
  82324. /* Insert new strings in the hash table only if the match length
  82325. * is not too large. This saves time but degrades compression.
  82326. */
  82327. #ifndef FASTEST
  82328. if (s->match_length <= s->max_insert_length &&
  82329. s->lookahead >= MIN_MATCH) {
  82330. s->match_length--; /* string at strstart already in table */
  82331. do {
  82332. s->strstart++;
  82333. INSERT_STRING(s, s->strstart, hash_head);
  82334. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82335. * always MIN_MATCH bytes ahead.
  82336. */
  82337. } while (--s->match_length != 0);
  82338. s->strstart++;
  82339. } else
  82340. #endif
  82341. {
  82342. s->strstart += s->match_length;
  82343. s->match_length = 0;
  82344. s->ins_h = s->window[s->strstart];
  82345. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82346. #if MIN_MATCH != 3
  82347. Call UPDATE_HASH() MIN_MATCH-3 more times
  82348. #endif
  82349. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82350. * matter since it will be recomputed at next deflate call.
  82351. */
  82352. }
  82353. } else {
  82354. /* No match, output a literal byte */
  82355. Tracevv((stderr,"%c", s->window[s->strstart]));
  82356. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82357. s->lookahead--;
  82358. s->strstart++;
  82359. }
  82360. if (bflush) FLUSH_BLOCK(s, 0);
  82361. }
  82362. FLUSH_BLOCK(s, flush == Z_FINISH);
  82363. return flush == Z_FINISH ? finish_done : block_done;
  82364. }
  82365. #ifndef FASTEST
  82366. /* ===========================================================================
  82367. * Same as above, but achieves better compression. We use a lazy
  82368. * evaluation for matches: a match is finally adopted only if there is
  82369. * no better match at the next window position.
  82370. */
  82371. local block_state deflate_slow(deflate_state *s, int flush)
  82372. {
  82373. IPos hash_head = NIL; /* head of hash chain */
  82374. int bflush; /* set if current block must be flushed */
  82375. /* Process the input block. */
  82376. for (;;) {
  82377. /* Make sure that we always have enough lookahead, except
  82378. * at the end of the input file. We need MAX_MATCH bytes
  82379. * for the next match, plus MIN_MATCH bytes to insert the
  82380. * string following the next match.
  82381. */
  82382. if (s->lookahead < MIN_LOOKAHEAD) {
  82383. fill_window(s);
  82384. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82385. return need_more;
  82386. }
  82387. if (s->lookahead == 0) break; /* flush the current block */
  82388. }
  82389. /* Insert the string window[strstart .. strstart+2] in the
  82390. * dictionary, and set hash_head to the head of the hash chain:
  82391. */
  82392. if (s->lookahead >= MIN_MATCH) {
  82393. INSERT_STRING(s, s->strstart, hash_head);
  82394. }
  82395. /* Find the longest match, discarding those <= prev_length.
  82396. */
  82397. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82398. s->match_length = MIN_MATCH-1;
  82399. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82400. s->strstart - hash_head <= MAX_DIST(s)) {
  82401. /* To simplify the code, we prevent matches with the string
  82402. * of window index 0 (in particular we have to avoid a match
  82403. * of the string with itself at the start of the input file).
  82404. */
  82405. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82406. s->match_length = longest_match (s, hash_head);
  82407. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82408. s->match_length = longest_match_fast (s, hash_head);
  82409. }
  82410. /* longest_match() or longest_match_fast() sets match_start */
  82411. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82412. #if TOO_FAR <= 32767
  82413. || (s->match_length == MIN_MATCH &&
  82414. s->strstart - s->match_start > TOO_FAR)
  82415. #endif
  82416. )) {
  82417. /* If prev_match is also MIN_MATCH, match_start is garbage
  82418. * but we will ignore the current match anyway.
  82419. */
  82420. s->match_length = MIN_MATCH-1;
  82421. }
  82422. }
  82423. /* If there was a match at the previous step and the current
  82424. * match is not better, output the previous match:
  82425. */
  82426. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82427. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82428. /* Do not insert strings in hash table beyond this. */
  82429. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82430. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82431. s->prev_length - MIN_MATCH, bflush);
  82432. /* Insert in hash table all strings up to the end of the match.
  82433. * strstart-1 and strstart are already inserted. If there is not
  82434. * enough lookahead, the last two strings are not inserted in
  82435. * the hash table.
  82436. */
  82437. s->lookahead -= s->prev_length-1;
  82438. s->prev_length -= 2;
  82439. do {
  82440. if (++s->strstart <= max_insert) {
  82441. INSERT_STRING(s, s->strstart, hash_head);
  82442. }
  82443. } while (--s->prev_length != 0);
  82444. s->match_available = 0;
  82445. s->match_length = MIN_MATCH-1;
  82446. s->strstart++;
  82447. if (bflush) FLUSH_BLOCK(s, 0);
  82448. } else if (s->match_available) {
  82449. /* If there was no match at the previous position, output a
  82450. * single literal. If there was a match but the current match
  82451. * is longer, truncate the previous match to a single literal.
  82452. */
  82453. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82454. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82455. if (bflush) {
  82456. FLUSH_BLOCK_ONLY(s, 0);
  82457. }
  82458. s->strstart++;
  82459. s->lookahead--;
  82460. if (s->strm->avail_out == 0) return need_more;
  82461. } else {
  82462. /* There is no previous match to compare with, wait for
  82463. * the next step to decide.
  82464. */
  82465. s->match_available = 1;
  82466. s->strstart++;
  82467. s->lookahead--;
  82468. }
  82469. }
  82470. Assert (flush != Z_NO_FLUSH, "no flush?");
  82471. if (s->match_available) {
  82472. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82473. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82474. s->match_available = 0;
  82475. }
  82476. FLUSH_BLOCK(s, flush == Z_FINISH);
  82477. return flush == Z_FINISH ? finish_done : block_done;
  82478. }
  82479. #endif /* FASTEST */
  82480. #if 0
  82481. /* ===========================================================================
  82482. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82483. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82484. * deflate switches away from Z_RLE.)
  82485. */
  82486. local block_state deflate_rle(s, flush)
  82487. deflate_state *s;
  82488. int flush;
  82489. {
  82490. int bflush; /* set if current block must be flushed */
  82491. uInt run; /* length of run */
  82492. uInt max; /* maximum length of run */
  82493. uInt prev; /* byte at distance one to match */
  82494. Bytef *scan; /* scan for end of run */
  82495. for (;;) {
  82496. /* Make sure that we always have enough lookahead, except
  82497. * at the end of the input file. We need MAX_MATCH bytes
  82498. * for the longest encodable run.
  82499. */
  82500. if (s->lookahead < MAX_MATCH) {
  82501. fill_window(s);
  82502. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82503. return need_more;
  82504. }
  82505. if (s->lookahead == 0) break; /* flush the current block */
  82506. }
  82507. /* See how many times the previous byte repeats */
  82508. run = 0;
  82509. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82510. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82511. scan = s->window + s->strstart - 1;
  82512. prev = *scan++;
  82513. do {
  82514. if (*scan++ != prev)
  82515. break;
  82516. } while (++run < max);
  82517. }
  82518. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82519. if (run >= MIN_MATCH) {
  82520. check_match(s, s->strstart, s->strstart - 1, run);
  82521. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82522. s->lookahead -= run;
  82523. s->strstart += run;
  82524. } else {
  82525. /* No match, output a literal byte */
  82526. Tracevv((stderr,"%c", s->window[s->strstart]));
  82527. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82528. s->lookahead--;
  82529. s->strstart++;
  82530. }
  82531. if (bflush) FLUSH_BLOCK(s, 0);
  82532. }
  82533. FLUSH_BLOCK(s, flush == Z_FINISH);
  82534. return flush == Z_FINISH ? finish_done : block_done;
  82535. }
  82536. #endif
  82537. /*** End of inlined file: deflate.c ***/
  82538. /*** Start of inlined file: inffast.c ***/
  82539. /*** Start of inlined file: inftrees.h ***/
  82540. /* WARNING: this file should *not* be used by applications. It is
  82541. part of the implementation of the compression library and is
  82542. subject to change. Applications should only use zlib.h.
  82543. */
  82544. #ifndef _INFTREES_H_
  82545. #define _INFTREES_H_
  82546. /* Structure for decoding tables. Each entry provides either the
  82547. information needed to do the operation requested by the code that
  82548. indexed that table entry, or it provides a pointer to another
  82549. table that indexes more bits of the code. op indicates whether
  82550. the entry is a pointer to another table, a literal, a length or
  82551. distance, an end-of-block, or an invalid code. For a table
  82552. pointer, the low four bits of op is the number of index bits of
  82553. that table. For a length or distance, the low four bits of op
  82554. is the number of extra bits to get after the code. bits is
  82555. the number of bits in this code or part of the code to drop off
  82556. of the bit buffer. val is the actual byte to output in the case
  82557. of a literal, the base length or distance, or the offset from
  82558. the current table to the next table. Each entry is four bytes. */
  82559. typedef struct {
  82560. unsigned char op; /* operation, extra bits, table bits */
  82561. unsigned char bits; /* bits in this part of the code */
  82562. unsigned short val; /* offset in table or code value */
  82563. } code;
  82564. /* op values as set by inflate_table():
  82565. 00000000 - literal
  82566. 0000tttt - table link, tttt != 0 is the number of table index bits
  82567. 0001eeee - length or distance, eeee is the number of extra bits
  82568. 01100000 - end of block
  82569. 01000000 - invalid code
  82570. */
  82571. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82572. exhaustive search was 1444 code structures (852 for length/literals
  82573. and 592 for distances, the latter actually the result of an
  82574. exhaustive search). The true maximum is not known, but the value
  82575. below is more than safe. */
  82576. #define ENOUGH 2048
  82577. #define MAXD 592
  82578. /* Type of code to build for inftable() */
  82579. typedef enum {
  82580. CODES,
  82581. LENS,
  82582. DISTS
  82583. } codetype;
  82584. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82585. unsigned codes, code FAR * FAR *table,
  82586. unsigned FAR *bits, unsigned short FAR *work));
  82587. #endif
  82588. /*** End of inlined file: inftrees.h ***/
  82589. /*** Start of inlined file: inflate.h ***/
  82590. /* WARNING: this file should *not* be used by applications. It is
  82591. part of the implementation of the compression library and is
  82592. subject to change. Applications should only use zlib.h.
  82593. */
  82594. #ifndef _INFLATE_H_
  82595. #define _INFLATE_H_
  82596. /* define NO_GZIP when compiling if you want to disable gzip header and
  82597. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82598. the crc code when it is not needed. For shared libraries, gzip decoding
  82599. should be left enabled. */
  82600. #ifndef NO_GZIP
  82601. # define GUNZIP
  82602. #endif
  82603. /* Possible inflate modes between inflate() calls */
  82604. typedef enum {
  82605. HEAD, /* i: waiting for magic header */
  82606. FLAGS, /* i: waiting for method and flags (gzip) */
  82607. TIME, /* i: waiting for modification time (gzip) */
  82608. OS, /* i: waiting for extra flags and operating system (gzip) */
  82609. EXLEN, /* i: waiting for extra length (gzip) */
  82610. EXTRA, /* i: waiting for extra bytes (gzip) */
  82611. NAME, /* i: waiting for end of file name (gzip) */
  82612. COMMENT, /* i: waiting for end of comment (gzip) */
  82613. HCRC, /* i: waiting for header crc (gzip) */
  82614. DICTID, /* i: waiting for dictionary check value */
  82615. DICT, /* waiting for inflateSetDictionary() call */
  82616. TYPE, /* i: waiting for type bits, including last-flag bit */
  82617. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82618. STORED, /* i: waiting for stored size (length and complement) */
  82619. COPY, /* i/o: waiting for input or output to copy stored block */
  82620. TABLE, /* i: waiting for dynamic block table lengths */
  82621. LENLENS, /* i: waiting for code length code lengths */
  82622. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82623. LEN, /* i: waiting for length/lit code */
  82624. LENEXT, /* i: waiting for length extra bits */
  82625. DIST, /* i: waiting for distance code */
  82626. DISTEXT, /* i: waiting for distance extra bits */
  82627. MATCH, /* o: waiting for output space to copy string */
  82628. LIT, /* o: waiting for output space to write literal */
  82629. CHECK, /* i: waiting for 32-bit check value */
  82630. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82631. DONE, /* finished check, done -- remain here until reset */
  82632. BAD, /* got a data error -- remain here until reset */
  82633. MEM, /* got an inflate() memory error -- remain here until reset */
  82634. SYNC /* looking for synchronization bytes to restart inflate() */
  82635. } inflate_mode;
  82636. /*
  82637. State transitions between above modes -
  82638. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82639. Process header:
  82640. HEAD -> (gzip) or (zlib)
  82641. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82642. NAME -> COMMENT -> HCRC -> TYPE
  82643. (zlib) -> DICTID or TYPE
  82644. DICTID -> DICT -> TYPE
  82645. Read deflate blocks:
  82646. TYPE -> STORED or TABLE or LEN or CHECK
  82647. STORED -> COPY -> TYPE
  82648. TABLE -> LENLENS -> CODELENS -> LEN
  82649. Read deflate codes:
  82650. LEN -> LENEXT or LIT or TYPE
  82651. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82652. LIT -> LEN
  82653. Process trailer:
  82654. CHECK -> LENGTH -> DONE
  82655. */
  82656. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82657. struct inflate_state {
  82658. inflate_mode mode; /* current inflate mode */
  82659. int last; /* true if processing last block */
  82660. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82661. int havedict; /* true if dictionary provided */
  82662. int flags; /* gzip header method and flags (0 if zlib) */
  82663. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82664. unsigned long check; /* protected copy of check value */
  82665. unsigned long total; /* protected copy of output count */
  82666. gz_headerp head; /* where to save gzip header information */
  82667. /* sliding window */
  82668. unsigned wbits; /* log base 2 of requested window size */
  82669. unsigned wsize; /* window size or zero if not using window */
  82670. unsigned whave; /* valid bytes in the window */
  82671. unsigned write; /* window write index */
  82672. unsigned char FAR *window; /* allocated sliding window, if needed */
  82673. /* bit accumulator */
  82674. unsigned long hold; /* input bit accumulator */
  82675. unsigned bits; /* number of bits in "in" */
  82676. /* for string and stored block copying */
  82677. unsigned length; /* literal or length of data to copy */
  82678. unsigned offset; /* distance back to copy string from */
  82679. /* for table and code decoding */
  82680. unsigned extra; /* extra bits needed */
  82681. /* fixed and dynamic code tables */
  82682. code const FAR *lencode; /* starting table for length/literal codes */
  82683. code const FAR *distcode; /* starting table for distance codes */
  82684. unsigned lenbits; /* index bits for lencode */
  82685. unsigned distbits; /* index bits for distcode */
  82686. /* dynamic table building */
  82687. unsigned ncode; /* number of code length code lengths */
  82688. unsigned nlen; /* number of length code lengths */
  82689. unsigned ndist; /* number of distance code lengths */
  82690. unsigned have; /* number of code lengths in lens[] */
  82691. code FAR *next; /* next available space in codes[] */
  82692. unsigned short lens[320]; /* temporary storage for code lengths */
  82693. unsigned short work[288]; /* work area for code table building */
  82694. code codes[ENOUGH]; /* space for code tables */
  82695. };
  82696. #endif
  82697. /*** End of inlined file: inflate.h ***/
  82698. /*** Start of inlined file: inffast.h ***/
  82699. /* WARNING: this file should *not* be used by applications. It is
  82700. part of the implementation of the compression library and is
  82701. subject to change. Applications should only use zlib.h.
  82702. */
  82703. void inflate_fast OF((z_streamp strm, unsigned start));
  82704. /*** End of inlined file: inffast.h ***/
  82705. #ifndef ASMINF
  82706. /* Allow machine dependent optimization for post-increment or pre-increment.
  82707. Based on testing to date,
  82708. Pre-increment preferred for:
  82709. - PowerPC G3 (Adler)
  82710. - MIPS R5000 (Randers-Pehrson)
  82711. Post-increment preferred for:
  82712. - none
  82713. No measurable difference:
  82714. - Pentium III (Anderson)
  82715. - M68060 (Nikl)
  82716. */
  82717. #ifdef POSTINC
  82718. # define OFF 0
  82719. # define PUP(a) *(a)++
  82720. #else
  82721. # define OFF 1
  82722. # define PUP(a) *++(a)
  82723. #endif
  82724. /*
  82725. Decode literal, length, and distance codes and write out the resulting
  82726. literal and match bytes until either not enough input or output is
  82727. available, an end-of-block is encountered, or a data error is encountered.
  82728. When large enough input and output buffers are supplied to inflate(), for
  82729. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82730. inflate execution time is spent in this routine.
  82731. Entry assumptions:
  82732. state->mode == LEN
  82733. strm->avail_in >= 6
  82734. strm->avail_out >= 258
  82735. start >= strm->avail_out
  82736. state->bits < 8
  82737. On return, state->mode is one of:
  82738. LEN -- ran out of enough output space or enough available input
  82739. TYPE -- reached end of block code, inflate() to interpret next block
  82740. BAD -- error in block data
  82741. Notes:
  82742. - The maximum input bits used by a length/distance pair is 15 bits for the
  82743. length code, 5 bits for the length extra, 15 bits for the distance code,
  82744. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82745. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82746. checking for available input while decoding.
  82747. - The maximum bytes that a single length/distance pair can output is 258
  82748. bytes, which is the maximum length that can be coded. inflate_fast()
  82749. requires strm->avail_out >= 258 for each loop to avoid checking for
  82750. output space.
  82751. */
  82752. void inflate_fast (z_streamp strm, unsigned start)
  82753. {
  82754. struct inflate_state FAR *state;
  82755. unsigned char FAR *in; /* local strm->next_in */
  82756. unsigned char FAR *last; /* while in < last, enough input available */
  82757. unsigned char FAR *out; /* local strm->next_out */
  82758. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82759. unsigned char FAR *end; /* while out < end, enough space available */
  82760. #ifdef INFLATE_STRICT
  82761. unsigned dmax; /* maximum distance from zlib header */
  82762. #endif
  82763. unsigned wsize; /* window size or zero if not using window */
  82764. unsigned whave; /* valid bytes in the window */
  82765. unsigned write; /* window write index */
  82766. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82767. unsigned long hold; /* local strm->hold */
  82768. unsigned bits; /* local strm->bits */
  82769. code const FAR *lcode; /* local strm->lencode */
  82770. code const FAR *dcode; /* local strm->distcode */
  82771. unsigned lmask; /* mask for first level of length codes */
  82772. unsigned dmask; /* mask for first level of distance codes */
  82773. code thisx; /* retrieved table entry */
  82774. unsigned op; /* code bits, operation, extra bits, or */
  82775. /* window position, window bytes to copy */
  82776. unsigned len; /* match length, unused bytes */
  82777. unsigned dist; /* match distance */
  82778. unsigned char FAR *from; /* where to copy match from */
  82779. /* copy state to local variables */
  82780. state = (struct inflate_state FAR *)strm->state;
  82781. in = strm->next_in - OFF;
  82782. last = in + (strm->avail_in - 5);
  82783. out = strm->next_out - OFF;
  82784. beg = out - (start - strm->avail_out);
  82785. end = out + (strm->avail_out - 257);
  82786. #ifdef INFLATE_STRICT
  82787. dmax = state->dmax;
  82788. #endif
  82789. wsize = state->wsize;
  82790. whave = state->whave;
  82791. write = state->write;
  82792. window = state->window;
  82793. hold = state->hold;
  82794. bits = state->bits;
  82795. lcode = state->lencode;
  82796. dcode = state->distcode;
  82797. lmask = (1U << state->lenbits) - 1;
  82798. dmask = (1U << state->distbits) - 1;
  82799. /* decode literals and length/distances until end-of-block or not enough
  82800. input data or output space */
  82801. do {
  82802. if (bits < 15) {
  82803. hold += (unsigned long)(PUP(in)) << bits;
  82804. bits += 8;
  82805. hold += (unsigned long)(PUP(in)) << bits;
  82806. bits += 8;
  82807. }
  82808. thisx = lcode[hold & lmask];
  82809. dolen:
  82810. op = (unsigned)(thisx.bits);
  82811. hold >>= op;
  82812. bits -= op;
  82813. op = (unsigned)(thisx.op);
  82814. if (op == 0) { /* literal */
  82815. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82816. "inflate: literal '%c'\n" :
  82817. "inflate: literal 0x%02x\n", thisx.val));
  82818. PUP(out) = (unsigned char)(thisx.val);
  82819. }
  82820. else if (op & 16) { /* length base */
  82821. len = (unsigned)(thisx.val);
  82822. op &= 15; /* number of extra bits */
  82823. if (op) {
  82824. if (bits < op) {
  82825. hold += (unsigned long)(PUP(in)) << bits;
  82826. bits += 8;
  82827. }
  82828. len += (unsigned)hold & ((1U << op) - 1);
  82829. hold >>= op;
  82830. bits -= op;
  82831. }
  82832. Tracevv((stderr, "inflate: length %u\n", len));
  82833. if (bits < 15) {
  82834. hold += (unsigned long)(PUP(in)) << bits;
  82835. bits += 8;
  82836. hold += (unsigned long)(PUP(in)) << bits;
  82837. bits += 8;
  82838. }
  82839. thisx = dcode[hold & dmask];
  82840. dodist:
  82841. op = (unsigned)(thisx.bits);
  82842. hold >>= op;
  82843. bits -= op;
  82844. op = (unsigned)(thisx.op);
  82845. if (op & 16) { /* distance base */
  82846. dist = (unsigned)(thisx.val);
  82847. op &= 15; /* number of extra bits */
  82848. if (bits < op) {
  82849. hold += (unsigned long)(PUP(in)) << bits;
  82850. bits += 8;
  82851. if (bits < op) {
  82852. hold += (unsigned long)(PUP(in)) << bits;
  82853. bits += 8;
  82854. }
  82855. }
  82856. dist += (unsigned)hold & ((1U << op) - 1);
  82857. #ifdef INFLATE_STRICT
  82858. if (dist > dmax) {
  82859. strm->msg = (char *)"invalid distance too far back";
  82860. state->mode = BAD;
  82861. break;
  82862. }
  82863. #endif
  82864. hold >>= op;
  82865. bits -= op;
  82866. Tracevv((stderr, "inflate: distance %u\n", dist));
  82867. op = (unsigned)(out - beg); /* max distance in output */
  82868. if (dist > op) { /* see if copy from window */
  82869. op = dist - op; /* distance back in window */
  82870. if (op > whave) {
  82871. strm->msg = (char *)"invalid distance too far back";
  82872. state->mode = BAD;
  82873. break;
  82874. }
  82875. from = window - OFF;
  82876. if (write == 0) { /* very common case */
  82877. from += wsize - op;
  82878. if (op < len) { /* some from window */
  82879. len -= op;
  82880. do {
  82881. PUP(out) = PUP(from);
  82882. } while (--op);
  82883. from = out - dist; /* rest from output */
  82884. }
  82885. }
  82886. else if (write < op) { /* wrap around window */
  82887. from += wsize + write - op;
  82888. op -= write;
  82889. if (op < len) { /* some from end of window */
  82890. len -= op;
  82891. do {
  82892. PUP(out) = PUP(from);
  82893. } while (--op);
  82894. from = window - OFF;
  82895. if (write < len) { /* some from start of window */
  82896. op = write;
  82897. len -= op;
  82898. do {
  82899. PUP(out) = PUP(from);
  82900. } while (--op);
  82901. from = out - dist; /* rest from output */
  82902. }
  82903. }
  82904. }
  82905. else { /* contiguous in window */
  82906. from += write - op;
  82907. if (op < len) { /* some from window */
  82908. len -= op;
  82909. do {
  82910. PUP(out) = PUP(from);
  82911. } while (--op);
  82912. from = out - dist; /* rest from output */
  82913. }
  82914. }
  82915. while (len > 2) {
  82916. PUP(out) = PUP(from);
  82917. PUP(out) = PUP(from);
  82918. PUP(out) = PUP(from);
  82919. len -= 3;
  82920. }
  82921. if (len) {
  82922. PUP(out) = PUP(from);
  82923. if (len > 1)
  82924. PUP(out) = PUP(from);
  82925. }
  82926. }
  82927. else {
  82928. from = out - dist; /* copy direct from output */
  82929. do { /* minimum length is three */
  82930. PUP(out) = PUP(from);
  82931. PUP(out) = PUP(from);
  82932. PUP(out) = PUP(from);
  82933. len -= 3;
  82934. } while (len > 2);
  82935. if (len) {
  82936. PUP(out) = PUP(from);
  82937. if (len > 1)
  82938. PUP(out) = PUP(from);
  82939. }
  82940. }
  82941. }
  82942. else if ((op & 64) == 0) { /* 2nd level distance code */
  82943. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82944. goto dodist;
  82945. }
  82946. else {
  82947. strm->msg = (char *)"invalid distance code";
  82948. state->mode = BAD;
  82949. break;
  82950. }
  82951. }
  82952. else if ((op & 64) == 0) { /* 2nd level length code */
  82953. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82954. goto dolen;
  82955. }
  82956. else if (op & 32) { /* end-of-block */
  82957. Tracevv((stderr, "inflate: end of block\n"));
  82958. state->mode = TYPE;
  82959. break;
  82960. }
  82961. else {
  82962. strm->msg = (char *)"invalid literal/length code";
  82963. state->mode = BAD;
  82964. break;
  82965. }
  82966. } while (in < last && out < end);
  82967. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82968. len = bits >> 3;
  82969. in -= len;
  82970. bits -= len << 3;
  82971. hold &= (1U << bits) - 1;
  82972. /* update state and return */
  82973. strm->next_in = in + OFF;
  82974. strm->next_out = out + OFF;
  82975. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82976. strm->avail_out = (unsigned)(out < end ?
  82977. 257 + (end - out) : 257 - (out - end));
  82978. state->hold = hold;
  82979. state->bits = bits;
  82980. return;
  82981. }
  82982. /*
  82983. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82984. - Using bit fields for code structure
  82985. - Different op definition to avoid & for extra bits (do & for table bits)
  82986. - Three separate decoding do-loops for direct, window, and write == 0
  82987. - Special case for distance > 1 copies to do overlapped load and store copy
  82988. - Explicit branch predictions (based on measured branch probabilities)
  82989. - Deferring match copy and interspersed it with decoding subsequent codes
  82990. - Swapping literal/length else
  82991. - Swapping window/direct else
  82992. - Larger unrolled copy loops (three is about right)
  82993. - Moving len -= 3 statement into middle of loop
  82994. */
  82995. #endif /* !ASMINF */
  82996. /*** End of inlined file: inffast.c ***/
  82997. #undef PULLBYTE
  82998. #undef LOAD
  82999. #undef RESTORE
  83000. #undef INITBITS
  83001. #undef NEEDBITS
  83002. #undef DROPBITS
  83003. #undef BYTEBITS
  83004. /*** Start of inlined file: inflate.c ***/
  83005. /*
  83006. * Change history:
  83007. *
  83008. * 1.2.beta0 24 Nov 2002
  83009. * - First version -- complete rewrite of inflate to simplify code, avoid
  83010. * creation of window when not needed, minimize use of window when it is
  83011. * needed, make inffast.c even faster, implement gzip decoding, and to
  83012. * improve code readability and style over the previous zlib inflate code
  83013. *
  83014. * 1.2.beta1 25 Nov 2002
  83015. * - Use pointers for available input and output checking in inffast.c
  83016. * - Remove input and output counters in inffast.c
  83017. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83018. * - Remove unnecessary second byte pull from length extra in inffast.c
  83019. * - Unroll direct copy to three copies per loop in inffast.c
  83020. *
  83021. * 1.2.beta2 4 Dec 2002
  83022. * - Change external routine names to reduce potential conflicts
  83023. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83024. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83025. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83026. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83027. *
  83028. * 1.2.beta3 22 Dec 2002
  83029. * - Add comments on state->bits assertion in inffast.c
  83030. * - Add comments on op field in inftrees.h
  83031. * - Fix bug in reuse of allocated window after inflateReset()
  83032. * - Remove bit fields--back to byte structure for speed
  83033. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83034. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83035. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83036. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83037. * - Use local copies of stream next and avail values, as well as local bit
  83038. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83039. *
  83040. * 1.2.beta4 1 Jan 2003
  83041. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83042. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83043. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83044. * - Rearrange window copies in inflate_fast() for speed and simplification
  83045. * - Unroll last copy for window match in inflate_fast()
  83046. * - Use local copies of window variables in inflate_fast() for speed
  83047. * - Pull out common write == 0 case for speed in inflate_fast()
  83048. * - Make op and len in inflate_fast() unsigned for consistency
  83049. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83050. * - Simplified bad distance check in inflate_fast()
  83051. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83052. * source file infback.c to provide a call-back interface to inflate for
  83053. * programs like gzip and unzip -- uses window as output buffer to avoid
  83054. * window copying
  83055. *
  83056. * 1.2.beta5 1 Jan 2003
  83057. * - Improved inflateBack() interface to allow the caller to provide initial
  83058. * input in strm.
  83059. * - Fixed stored blocks bug in inflateBack()
  83060. *
  83061. * 1.2.beta6 4 Jan 2003
  83062. * - Added comments in inffast.c on effectiveness of POSTINC
  83063. * - Typecasting all around to reduce compiler warnings
  83064. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83065. * make compilers happy
  83066. * - Changed type of window in inflateBackInit() to unsigned char *
  83067. *
  83068. * 1.2.beta7 27 Jan 2003
  83069. * - Changed many types to unsigned or unsigned short to avoid warnings
  83070. * - Added inflateCopy() function
  83071. *
  83072. * 1.2.0 9 Mar 2003
  83073. * - Changed inflateBack() interface to provide separate opaque descriptors
  83074. * for the in() and out() functions
  83075. * - Changed inflateBack() argument and in_func typedef to swap the length
  83076. * and buffer address return values for the input function
  83077. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83078. *
  83079. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83080. */
  83081. /*** Start of inlined file: inffast.h ***/
  83082. /* WARNING: this file should *not* be used by applications. It is
  83083. part of the implementation of the compression library and is
  83084. subject to change. Applications should only use zlib.h.
  83085. */
  83086. void inflate_fast OF((z_streamp strm, unsigned start));
  83087. /*** End of inlined file: inffast.h ***/
  83088. #ifdef MAKEFIXED
  83089. # ifndef BUILDFIXED
  83090. # define BUILDFIXED
  83091. # endif
  83092. #endif
  83093. /* function prototypes */
  83094. local void fixedtables OF((struct inflate_state FAR *state));
  83095. local int updatewindow OF((z_streamp strm, unsigned out));
  83096. #ifdef BUILDFIXED
  83097. void makefixed OF((void));
  83098. #endif
  83099. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83100. unsigned len));
  83101. int ZEXPORT inflateReset (z_streamp strm)
  83102. {
  83103. struct inflate_state FAR *state;
  83104. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83105. state = (struct inflate_state FAR *)strm->state;
  83106. strm->total_in = strm->total_out = state->total = 0;
  83107. strm->msg = Z_NULL;
  83108. strm->adler = 1; /* to support ill-conceived Java test suite */
  83109. state->mode = HEAD;
  83110. state->last = 0;
  83111. state->havedict = 0;
  83112. state->dmax = 32768U;
  83113. state->head = Z_NULL;
  83114. state->wsize = 0;
  83115. state->whave = 0;
  83116. state->write = 0;
  83117. state->hold = 0;
  83118. state->bits = 0;
  83119. state->lencode = state->distcode = state->next = state->codes;
  83120. Tracev((stderr, "inflate: reset\n"));
  83121. return Z_OK;
  83122. }
  83123. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83124. {
  83125. struct inflate_state FAR *state;
  83126. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83127. state = (struct inflate_state FAR *)strm->state;
  83128. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83129. value &= (1L << bits) - 1;
  83130. state->hold += value << state->bits;
  83131. state->bits += bits;
  83132. return Z_OK;
  83133. }
  83134. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83135. {
  83136. struct inflate_state FAR *state;
  83137. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83138. stream_size != (int)(sizeof(z_stream)))
  83139. return Z_VERSION_ERROR;
  83140. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83141. strm->msg = Z_NULL; /* in case we return an error */
  83142. if (strm->zalloc == (alloc_func)0) {
  83143. strm->zalloc = zcalloc;
  83144. strm->opaque = (voidpf)0;
  83145. }
  83146. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83147. state = (struct inflate_state FAR *)
  83148. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83149. if (state == Z_NULL) return Z_MEM_ERROR;
  83150. Tracev((stderr, "inflate: allocated\n"));
  83151. strm->state = (struct internal_state FAR *)state;
  83152. if (windowBits < 0) {
  83153. state->wrap = 0;
  83154. windowBits = -windowBits;
  83155. }
  83156. else {
  83157. state->wrap = (windowBits >> 4) + 1;
  83158. #ifdef GUNZIP
  83159. if (windowBits < 48) windowBits &= 15;
  83160. #endif
  83161. }
  83162. if (windowBits < 8 || windowBits > 15) {
  83163. ZFREE(strm, state);
  83164. strm->state = Z_NULL;
  83165. return Z_STREAM_ERROR;
  83166. }
  83167. state->wbits = (unsigned)windowBits;
  83168. state->window = Z_NULL;
  83169. return inflateReset(strm);
  83170. }
  83171. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83172. {
  83173. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83174. }
  83175. /*
  83176. Return state with length and distance decoding tables and index sizes set to
  83177. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83178. If BUILDFIXED is defined, then instead this routine builds the tables the
  83179. first time it's called, and returns those tables the first time and
  83180. thereafter. This reduces the size of the code by about 2K bytes, in
  83181. exchange for a little execution time. However, BUILDFIXED should not be
  83182. used for threaded applications, since the rewriting of the tables and virgin
  83183. may not be thread-safe.
  83184. */
  83185. local void fixedtables (struct inflate_state FAR *state)
  83186. {
  83187. #ifdef BUILDFIXED
  83188. static int virgin = 1;
  83189. static code *lenfix, *distfix;
  83190. static code fixed[544];
  83191. /* build fixed huffman tables if first call (may not be thread safe) */
  83192. if (virgin) {
  83193. unsigned sym, bits;
  83194. static code *next;
  83195. /* literal/length table */
  83196. sym = 0;
  83197. while (sym < 144) state->lens[sym++] = 8;
  83198. while (sym < 256) state->lens[sym++] = 9;
  83199. while (sym < 280) state->lens[sym++] = 7;
  83200. while (sym < 288) state->lens[sym++] = 8;
  83201. next = fixed;
  83202. lenfix = next;
  83203. bits = 9;
  83204. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83205. /* distance table */
  83206. sym = 0;
  83207. while (sym < 32) state->lens[sym++] = 5;
  83208. distfix = next;
  83209. bits = 5;
  83210. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83211. /* do this just once */
  83212. virgin = 0;
  83213. }
  83214. #else /* !BUILDFIXED */
  83215. /*** Start of inlined file: inffixed.h ***/
  83216. /* WARNING: this file should *not* be used by applications. It
  83217. is part of the implementation of the compression library and
  83218. is subject to change. Applications should only use zlib.h.
  83219. */
  83220. static const code lenfix[512] = {
  83221. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83222. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83223. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83224. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83225. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83226. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83227. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83228. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83229. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83230. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83231. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83232. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83233. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83234. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83235. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83236. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83237. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83238. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83239. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83240. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83241. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83242. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83243. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83244. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83245. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83246. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83247. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83248. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83249. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83250. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83251. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83252. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83253. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83254. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83255. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83256. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83257. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83258. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83259. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83260. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83261. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83262. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83263. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83264. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83265. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83266. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83267. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83268. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83269. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83270. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83271. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83272. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83273. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83274. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83275. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83276. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83277. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83278. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83279. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83280. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83281. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83282. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83283. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83284. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83285. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83286. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83287. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83288. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83289. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83290. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83291. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83292. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83293. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83294. {0,9,255}
  83295. };
  83296. static const code distfix[32] = {
  83297. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83298. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83299. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83300. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83301. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83302. {22,5,193},{64,5,0}
  83303. };
  83304. /*** End of inlined file: inffixed.h ***/
  83305. #endif /* BUILDFIXED */
  83306. state->lencode = lenfix;
  83307. state->lenbits = 9;
  83308. state->distcode = distfix;
  83309. state->distbits = 5;
  83310. }
  83311. #ifdef MAKEFIXED
  83312. #include <stdio.h>
  83313. /*
  83314. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83315. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83316. those tables to stdout, which would be piped to inffixed.h. A small program
  83317. can simply call makefixed to do this:
  83318. void makefixed(void);
  83319. int main(void)
  83320. {
  83321. makefixed();
  83322. return 0;
  83323. }
  83324. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83325. a.out > inffixed.h
  83326. */
  83327. void makefixed()
  83328. {
  83329. unsigned low, size;
  83330. struct inflate_state state;
  83331. fixedtables(&state);
  83332. puts(" /* inffixed.h -- table for decoding fixed codes");
  83333. puts(" * Generated automatically by makefixed().");
  83334. puts(" */");
  83335. puts("");
  83336. puts(" /* WARNING: this file should *not* be used by applications.");
  83337. puts(" It is part of the implementation of this library and is");
  83338. puts(" subject to change. Applications should only use zlib.h.");
  83339. puts(" */");
  83340. puts("");
  83341. size = 1U << 9;
  83342. printf(" static const code lenfix[%u] = {", size);
  83343. low = 0;
  83344. for (;;) {
  83345. if ((low % 7) == 0) printf("\n ");
  83346. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83347. state.lencode[low].val);
  83348. if (++low == size) break;
  83349. putchar(',');
  83350. }
  83351. puts("\n };");
  83352. size = 1U << 5;
  83353. printf("\n static const code distfix[%u] = {", size);
  83354. low = 0;
  83355. for (;;) {
  83356. if ((low % 6) == 0) printf("\n ");
  83357. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83358. state.distcode[low].val);
  83359. if (++low == size) break;
  83360. putchar(',');
  83361. }
  83362. puts("\n };");
  83363. }
  83364. #endif /* MAKEFIXED */
  83365. /*
  83366. Update the window with the last wsize (normally 32K) bytes written before
  83367. returning. If window does not exist yet, create it. This is only called
  83368. when a window is already in use, or when output has been written during this
  83369. inflate call, but the end of the deflate stream has not been reached yet.
  83370. It is also called to create a window for dictionary data when a dictionary
  83371. is loaded.
  83372. Providing output buffers larger than 32K to inflate() should provide a speed
  83373. advantage, since only the last 32K of output is copied to the sliding window
  83374. upon return from inflate(), and since all distances after the first 32K of
  83375. output will fall in the output data, making match copies simpler and faster.
  83376. The advantage may be dependent on the size of the processor's data caches.
  83377. */
  83378. local int updatewindow (z_streamp strm, unsigned out)
  83379. {
  83380. struct inflate_state FAR *state;
  83381. unsigned copy, dist;
  83382. state = (struct inflate_state FAR *)strm->state;
  83383. /* if it hasn't been done already, allocate space for the window */
  83384. if (state->window == Z_NULL) {
  83385. state->window = (unsigned char FAR *)
  83386. ZALLOC(strm, 1U << state->wbits,
  83387. sizeof(unsigned char));
  83388. if (state->window == Z_NULL) return 1;
  83389. }
  83390. /* if window not in use yet, initialize */
  83391. if (state->wsize == 0) {
  83392. state->wsize = 1U << state->wbits;
  83393. state->write = 0;
  83394. state->whave = 0;
  83395. }
  83396. /* copy state->wsize or less output bytes into the circular window */
  83397. copy = out - strm->avail_out;
  83398. if (copy >= state->wsize) {
  83399. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83400. state->write = 0;
  83401. state->whave = state->wsize;
  83402. }
  83403. else {
  83404. dist = state->wsize - state->write;
  83405. if (dist > copy) dist = copy;
  83406. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83407. copy -= dist;
  83408. if (copy) {
  83409. zmemcpy(state->window, strm->next_out - copy, copy);
  83410. state->write = copy;
  83411. state->whave = state->wsize;
  83412. }
  83413. else {
  83414. state->write += dist;
  83415. if (state->write == state->wsize) state->write = 0;
  83416. if (state->whave < state->wsize) state->whave += dist;
  83417. }
  83418. }
  83419. return 0;
  83420. }
  83421. /* Macros for inflate(): */
  83422. /* check function to use adler32() for zlib or crc32() for gzip */
  83423. #ifdef GUNZIP
  83424. # define UPDATE(check, buf, len) \
  83425. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83426. #else
  83427. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83428. #endif
  83429. /* check macros for header crc */
  83430. #ifdef GUNZIP
  83431. # define CRC2(check, word) \
  83432. do { \
  83433. hbuf[0] = (unsigned char)(word); \
  83434. hbuf[1] = (unsigned char)((word) >> 8); \
  83435. check = crc32(check, hbuf, 2); \
  83436. } while (0)
  83437. # define CRC4(check, word) \
  83438. do { \
  83439. hbuf[0] = (unsigned char)(word); \
  83440. hbuf[1] = (unsigned char)((word) >> 8); \
  83441. hbuf[2] = (unsigned char)((word) >> 16); \
  83442. hbuf[3] = (unsigned char)((word) >> 24); \
  83443. check = crc32(check, hbuf, 4); \
  83444. } while (0)
  83445. #endif
  83446. /* Load registers with state in inflate() for speed */
  83447. #define LOAD() \
  83448. do { \
  83449. put = strm->next_out; \
  83450. left = strm->avail_out; \
  83451. next = strm->next_in; \
  83452. have = strm->avail_in; \
  83453. hold = state->hold; \
  83454. bits = state->bits; \
  83455. } while (0)
  83456. /* Restore state from registers in inflate() */
  83457. #define RESTORE() \
  83458. do { \
  83459. strm->next_out = put; \
  83460. strm->avail_out = left; \
  83461. strm->next_in = next; \
  83462. strm->avail_in = have; \
  83463. state->hold = hold; \
  83464. state->bits = bits; \
  83465. } while (0)
  83466. /* Clear the input bit accumulator */
  83467. #define INITBITS() \
  83468. do { \
  83469. hold = 0; \
  83470. bits = 0; \
  83471. } while (0)
  83472. /* Get a byte of input into the bit accumulator, or return from inflate()
  83473. if there is no input available. */
  83474. #define PULLBYTE() \
  83475. do { \
  83476. if (have == 0) goto inf_leave; \
  83477. have--; \
  83478. hold += (unsigned long)(*next++) << bits; \
  83479. bits += 8; \
  83480. } while (0)
  83481. /* Assure that there are at least n bits in the bit accumulator. If there is
  83482. not enough available input to do that, then return from inflate(). */
  83483. #define NEEDBITS(n) \
  83484. do { \
  83485. while (bits < (unsigned)(n)) \
  83486. PULLBYTE(); \
  83487. } while (0)
  83488. /* Return the low n bits of the bit accumulator (n < 16) */
  83489. #define BITS(n) \
  83490. ((unsigned)hold & ((1U << (n)) - 1))
  83491. /* Remove n bits from the bit accumulator */
  83492. #define DROPBITS(n) \
  83493. do { \
  83494. hold >>= (n); \
  83495. bits -= (unsigned)(n); \
  83496. } while (0)
  83497. /* Remove zero to seven bits as needed to go to a byte boundary */
  83498. #define BYTEBITS() \
  83499. do { \
  83500. hold >>= bits & 7; \
  83501. bits -= bits & 7; \
  83502. } while (0)
  83503. /* Reverse the bytes in a 32-bit value */
  83504. #define REVERSE(q) \
  83505. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83506. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83507. /*
  83508. inflate() uses a state machine to process as much input data and generate as
  83509. much output data as possible before returning. The state machine is
  83510. structured roughly as follows:
  83511. for (;;) switch (state) {
  83512. ...
  83513. case STATEn:
  83514. if (not enough input data or output space to make progress)
  83515. return;
  83516. ... make progress ...
  83517. state = STATEm;
  83518. break;
  83519. ...
  83520. }
  83521. so when inflate() is called again, the same case is attempted again, and
  83522. if the appropriate resources are provided, the machine proceeds to the
  83523. next state. The NEEDBITS() macro is usually the way the state evaluates
  83524. whether it can proceed or should return. NEEDBITS() does the return if
  83525. the requested bits are not available. The typical use of the BITS macros
  83526. is:
  83527. NEEDBITS(n);
  83528. ... do something with BITS(n) ...
  83529. DROPBITS(n);
  83530. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83531. input left to load n bits into the accumulator, or it continues. BITS(n)
  83532. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83533. the low n bits off the accumulator. INITBITS() clears the accumulator
  83534. and sets the number of available bits to zero. BYTEBITS() discards just
  83535. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83536. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83537. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83538. if there is no input available. The decoding of variable length codes uses
  83539. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83540. code, and no more.
  83541. Some states loop until they get enough input, making sure that enough
  83542. state information is maintained to continue the loop where it left off
  83543. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83544. would all have to actually be part of the saved state in case NEEDBITS()
  83545. returns:
  83546. case STATEw:
  83547. while (want < need) {
  83548. NEEDBITS(n);
  83549. keep[want++] = BITS(n);
  83550. DROPBITS(n);
  83551. }
  83552. state = STATEx;
  83553. case STATEx:
  83554. As shown above, if the next state is also the next case, then the break
  83555. is omitted.
  83556. A state may also return if there is not enough output space available to
  83557. complete that state. Those states are copying stored data, writing a
  83558. literal byte, and copying a matching string.
  83559. When returning, a "goto inf_leave" is used to update the total counters,
  83560. update the check value, and determine whether any progress has been made
  83561. during that inflate() call in order to return the proper return code.
  83562. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83563. When there is a window, goto inf_leave will update the window with the last
  83564. output written. If a goto inf_leave occurs in the middle of decompression
  83565. and there is no window currently, goto inf_leave will create one and copy
  83566. output to the window for the next call of inflate().
  83567. In this implementation, the flush parameter of inflate() only affects the
  83568. return code (per zlib.h). inflate() always writes as much as possible to
  83569. strm->next_out, given the space available and the provided input--the effect
  83570. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83571. the allocation of and copying into a sliding window until necessary, which
  83572. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83573. stream available. So the only thing the flush parameter actually does is:
  83574. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83575. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83576. */
  83577. int ZEXPORT inflate (z_streamp strm, int flush)
  83578. {
  83579. struct inflate_state FAR *state;
  83580. unsigned char FAR *next; /* next input */
  83581. unsigned char FAR *put; /* next output */
  83582. unsigned have, left; /* available input and output */
  83583. unsigned long hold; /* bit buffer */
  83584. unsigned bits; /* bits in bit buffer */
  83585. unsigned in, out; /* save starting available input and output */
  83586. unsigned copy; /* number of stored or match bytes to copy */
  83587. unsigned char FAR *from; /* where to copy match bytes from */
  83588. code thisx; /* current decoding table entry */
  83589. code last; /* parent table entry */
  83590. unsigned len; /* length to copy for repeats, bits to drop */
  83591. int ret; /* return code */
  83592. #ifdef GUNZIP
  83593. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83594. #endif
  83595. static const unsigned short order[19] = /* permutation of code lengths */
  83596. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83597. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83598. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83599. return Z_STREAM_ERROR;
  83600. state = (struct inflate_state FAR *)strm->state;
  83601. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83602. LOAD();
  83603. in = have;
  83604. out = left;
  83605. ret = Z_OK;
  83606. for (;;)
  83607. switch (state->mode) {
  83608. case HEAD:
  83609. if (state->wrap == 0) {
  83610. state->mode = TYPEDO;
  83611. break;
  83612. }
  83613. NEEDBITS(16);
  83614. #ifdef GUNZIP
  83615. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83616. state->check = crc32(0L, Z_NULL, 0);
  83617. CRC2(state->check, hold);
  83618. INITBITS();
  83619. state->mode = FLAGS;
  83620. break;
  83621. }
  83622. state->flags = 0; /* expect zlib header */
  83623. if (state->head != Z_NULL)
  83624. state->head->done = -1;
  83625. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83626. #else
  83627. if (
  83628. #endif
  83629. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83630. strm->msg = (char *)"incorrect header check";
  83631. state->mode = BAD;
  83632. break;
  83633. }
  83634. if (BITS(4) != Z_DEFLATED) {
  83635. strm->msg = (char *)"unknown compression method";
  83636. state->mode = BAD;
  83637. break;
  83638. }
  83639. DROPBITS(4);
  83640. len = BITS(4) + 8;
  83641. if (len > state->wbits) {
  83642. strm->msg = (char *)"invalid window size";
  83643. state->mode = BAD;
  83644. break;
  83645. }
  83646. state->dmax = 1U << len;
  83647. Tracev((stderr, "inflate: zlib header ok\n"));
  83648. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83649. state->mode = hold & 0x200 ? DICTID : TYPE;
  83650. INITBITS();
  83651. break;
  83652. #ifdef GUNZIP
  83653. case FLAGS:
  83654. NEEDBITS(16);
  83655. state->flags = (int)(hold);
  83656. if ((state->flags & 0xff) != Z_DEFLATED) {
  83657. strm->msg = (char *)"unknown compression method";
  83658. state->mode = BAD;
  83659. break;
  83660. }
  83661. if (state->flags & 0xe000) {
  83662. strm->msg = (char *)"unknown header flags set";
  83663. state->mode = BAD;
  83664. break;
  83665. }
  83666. if (state->head != Z_NULL)
  83667. state->head->text = (int)((hold >> 8) & 1);
  83668. if (state->flags & 0x0200) CRC2(state->check, hold);
  83669. INITBITS();
  83670. state->mode = TIME;
  83671. case TIME:
  83672. NEEDBITS(32);
  83673. if (state->head != Z_NULL)
  83674. state->head->time = hold;
  83675. if (state->flags & 0x0200) CRC4(state->check, hold);
  83676. INITBITS();
  83677. state->mode = OS;
  83678. case OS:
  83679. NEEDBITS(16);
  83680. if (state->head != Z_NULL) {
  83681. state->head->xflags = (int)(hold & 0xff);
  83682. state->head->os = (int)(hold >> 8);
  83683. }
  83684. if (state->flags & 0x0200) CRC2(state->check, hold);
  83685. INITBITS();
  83686. state->mode = EXLEN;
  83687. case EXLEN:
  83688. if (state->flags & 0x0400) {
  83689. NEEDBITS(16);
  83690. state->length = (unsigned)(hold);
  83691. if (state->head != Z_NULL)
  83692. state->head->extra_len = (unsigned)hold;
  83693. if (state->flags & 0x0200) CRC2(state->check, hold);
  83694. INITBITS();
  83695. }
  83696. else if (state->head != Z_NULL)
  83697. state->head->extra = Z_NULL;
  83698. state->mode = EXTRA;
  83699. case EXTRA:
  83700. if (state->flags & 0x0400) {
  83701. copy = state->length;
  83702. if (copy > have) copy = have;
  83703. if (copy) {
  83704. if (state->head != Z_NULL &&
  83705. state->head->extra != Z_NULL) {
  83706. len = state->head->extra_len - state->length;
  83707. zmemcpy(state->head->extra + len, next,
  83708. len + copy > state->head->extra_max ?
  83709. state->head->extra_max - len : copy);
  83710. }
  83711. if (state->flags & 0x0200)
  83712. state->check = crc32(state->check, next, copy);
  83713. have -= copy;
  83714. next += copy;
  83715. state->length -= copy;
  83716. }
  83717. if (state->length) goto inf_leave;
  83718. }
  83719. state->length = 0;
  83720. state->mode = NAME;
  83721. case NAME:
  83722. if (state->flags & 0x0800) {
  83723. if (have == 0) goto inf_leave;
  83724. copy = 0;
  83725. do {
  83726. len = (unsigned)(next[copy++]);
  83727. if (state->head != Z_NULL &&
  83728. state->head->name != Z_NULL &&
  83729. state->length < state->head->name_max)
  83730. state->head->name[state->length++] = len;
  83731. } while (len && copy < have);
  83732. if (state->flags & 0x0200)
  83733. state->check = crc32(state->check, next, copy);
  83734. have -= copy;
  83735. next += copy;
  83736. if (len) goto inf_leave;
  83737. }
  83738. else if (state->head != Z_NULL)
  83739. state->head->name = Z_NULL;
  83740. state->length = 0;
  83741. state->mode = COMMENT;
  83742. case COMMENT:
  83743. if (state->flags & 0x1000) {
  83744. if (have == 0) goto inf_leave;
  83745. copy = 0;
  83746. do {
  83747. len = (unsigned)(next[copy++]);
  83748. if (state->head != Z_NULL &&
  83749. state->head->comment != Z_NULL &&
  83750. state->length < state->head->comm_max)
  83751. state->head->comment[state->length++] = len;
  83752. } while (len && copy < have);
  83753. if (state->flags & 0x0200)
  83754. state->check = crc32(state->check, next, copy);
  83755. have -= copy;
  83756. next += copy;
  83757. if (len) goto inf_leave;
  83758. }
  83759. else if (state->head != Z_NULL)
  83760. state->head->comment = Z_NULL;
  83761. state->mode = HCRC;
  83762. case HCRC:
  83763. if (state->flags & 0x0200) {
  83764. NEEDBITS(16);
  83765. if (hold != (state->check & 0xffff)) {
  83766. strm->msg = (char *)"header crc mismatch";
  83767. state->mode = BAD;
  83768. break;
  83769. }
  83770. INITBITS();
  83771. }
  83772. if (state->head != Z_NULL) {
  83773. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83774. state->head->done = 1;
  83775. }
  83776. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83777. state->mode = TYPE;
  83778. break;
  83779. #endif
  83780. case DICTID:
  83781. NEEDBITS(32);
  83782. strm->adler = state->check = REVERSE(hold);
  83783. INITBITS();
  83784. state->mode = DICT;
  83785. case DICT:
  83786. if (state->havedict == 0) {
  83787. RESTORE();
  83788. return Z_NEED_DICT;
  83789. }
  83790. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83791. state->mode = TYPE;
  83792. case TYPE:
  83793. if (flush == Z_BLOCK) goto inf_leave;
  83794. case TYPEDO:
  83795. if (state->last) {
  83796. BYTEBITS();
  83797. state->mode = CHECK;
  83798. break;
  83799. }
  83800. NEEDBITS(3);
  83801. state->last = BITS(1);
  83802. DROPBITS(1);
  83803. switch (BITS(2)) {
  83804. case 0: /* stored block */
  83805. Tracev((stderr, "inflate: stored block%s\n",
  83806. state->last ? " (last)" : ""));
  83807. state->mode = STORED;
  83808. break;
  83809. case 1: /* fixed block */
  83810. fixedtables(state);
  83811. Tracev((stderr, "inflate: fixed codes block%s\n",
  83812. state->last ? " (last)" : ""));
  83813. state->mode = LEN; /* decode codes */
  83814. break;
  83815. case 2: /* dynamic block */
  83816. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83817. state->last ? " (last)" : ""));
  83818. state->mode = TABLE;
  83819. break;
  83820. case 3:
  83821. strm->msg = (char *)"invalid block type";
  83822. state->mode = BAD;
  83823. }
  83824. DROPBITS(2);
  83825. break;
  83826. case STORED:
  83827. BYTEBITS(); /* go to byte boundary */
  83828. NEEDBITS(32);
  83829. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83830. strm->msg = (char *)"invalid stored block lengths";
  83831. state->mode = BAD;
  83832. break;
  83833. }
  83834. state->length = (unsigned)hold & 0xffff;
  83835. Tracev((stderr, "inflate: stored length %u\n",
  83836. state->length));
  83837. INITBITS();
  83838. state->mode = COPY;
  83839. case COPY:
  83840. copy = state->length;
  83841. if (copy) {
  83842. if (copy > have) copy = have;
  83843. if (copy > left) copy = left;
  83844. if (copy == 0) goto inf_leave;
  83845. zmemcpy(put, next, copy);
  83846. have -= copy;
  83847. next += copy;
  83848. left -= copy;
  83849. put += copy;
  83850. state->length -= copy;
  83851. break;
  83852. }
  83853. Tracev((stderr, "inflate: stored end\n"));
  83854. state->mode = TYPE;
  83855. break;
  83856. case TABLE:
  83857. NEEDBITS(14);
  83858. state->nlen = BITS(5) + 257;
  83859. DROPBITS(5);
  83860. state->ndist = BITS(5) + 1;
  83861. DROPBITS(5);
  83862. state->ncode = BITS(4) + 4;
  83863. DROPBITS(4);
  83864. #ifndef PKZIP_BUG_WORKAROUND
  83865. if (state->nlen > 286 || state->ndist > 30) {
  83866. strm->msg = (char *)"too many length or distance symbols";
  83867. state->mode = BAD;
  83868. break;
  83869. }
  83870. #endif
  83871. Tracev((stderr, "inflate: table sizes ok\n"));
  83872. state->have = 0;
  83873. state->mode = LENLENS;
  83874. case LENLENS:
  83875. while (state->have < state->ncode) {
  83876. NEEDBITS(3);
  83877. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83878. DROPBITS(3);
  83879. }
  83880. while (state->have < 19)
  83881. state->lens[order[state->have++]] = 0;
  83882. state->next = state->codes;
  83883. state->lencode = (code const FAR *)(state->next);
  83884. state->lenbits = 7;
  83885. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83886. &(state->lenbits), state->work);
  83887. if (ret) {
  83888. strm->msg = (char *)"invalid code lengths set";
  83889. state->mode = BAD;
  83890. break;
  83891. }
  83892. Tracev((stderr, "inflate: code lengths ok\n"));
  83893. state->have = 0;
  83894. state->mode = CODELENS;
  83895. case CODELENS:
  83896. while (state->have < state->nlen + state->ndist) {
  83897. for (;;) {
  83898. thisx = state->lencode[BITS(state->lenbits)];
  83899. if ((unsigned)(thisx.bits) <= bits) break;
  83900. PULLBYTE();
  83901. }
  83902. if (thisx.val < 16) {
  83903. NEEDBITS(thisx.bits);
  83904. DROPBITS(thisx.bits);
  83905. state->lens[state->have++] = thisx.val;
  83906. }
  83907. else {
  83908. if (thisx.val == 16) {
  83909. NEEDBITS(thisx.bits + 2);
  83910. DROPBITS(thisx.bits);
  83911. if (state->have == 0) {
  83912. strm->msg = (char *)"invalid bit length repeat";
  83913. state->mode = BAD;
  83914. break;
  83915. }
  83916. len = state->lens[state->have - 1];
  83917. copy = 3 + BITS(2);
  83918. DROPBITS(2);
  83919. }
  83920. else if (thisx.val == 17) {
  83921. NEEDBITS(thisx.bits + 3);
  83922. DROPBITS(thisx.bits);
  83923. len = 0;
  83924. copy = 3 + BITS(3);
  83925. DROPBITS(3);
  83926. }
  83927. else {
  83928. NEEDBITS(thisx.bits + 7);
  83929. DROPBITS(thisx.bits);
  83930. len = 0;
  83931. copy = 11 + BITS(7);
  83932. DROPBITS(7);
  83933. }
  83934. if (state->have + copy > state->nlen + state->ndist) {
  83935. strm->msg = (char *)"invalid bit length repeat";
  83936. state->mode = BAD;
  83937. break;
  83938. }
  83939. while (copy--)
  83940. state->lens[state->have++] = (unsigned short)len;
  83941. }
  83942. }
  83943. /* handle error breaks in while */
  83944. if (state->mode == BAD) break;
  83945. /* build code tables */
  83946. state->next = state->codes;
  83947. state->lencode = (code const FAR *)(state->next);
  83948. state->lenbits = 9;
  83949. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83950. &(state->lenbits), state->work);
  83951. if (ret) {
  83952. strm->msg = (char *)"invalid literal/lengths set";
  83953. state->mode = BAD;
  83954. break;
  83955. }
  83956. state->distcode = (code const FAR *)(state->next);
  83957. state->distbits = 6;
  83958. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83959. &(state->next), &(state->distbits), state->work);
  83960. if (ret) {
  83961. strm->msg = (char *)"invalid distances set";
  83962. state->mode = BAD;
  83963. break;
  83964. }
  83965. Tracev((stderr, "inflate: codes ok\n"));
  83966. state->mode = LEN;
  83967. case LEN:
  83968. if (have >= 6 && left >= 258) {
  83969. RESTORE();
  83970. inflate_fast(strm, out);
  83971. LOAD();
  83972. break;
  83973. }
  83974. for (;;) {
  83975. thisx = state->lencode[BITS(state->lenbits)];
  83976. if ((unsigned)(thisx.bits) <= bits) break;
  83977. PULLBYTE();
  83978. }
  83979. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83980. last = thisx;
  83981. for (;;) {
  83982. thisx = state->lencode[last.val +
  83983. (BITS(last.bits + last.op) >> last.bits)];
  83984. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83985. PULLBYTE();
  83986. }
  83987. DROPBITS(last.bits);
  83988. }
  83989. DROPBITS(thisx.bits);
  83990. state->length = (unsigned)thisx.val;
  83991. if ((int)(thisx.op) == 0) {
  83992. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83993. "inflate: literal '%c'\n" :
  83994. "inflate: literal 0x%02x\n", thisx.val));
  83995. state->mode = LIT;
  83996. break;
  83997. }
  83998. if (thisx.op & 32) {
  83999. Tracevv((stderr, "inflate: end of block\n"));
  84000. state->mode = TYPE;
  84001. break;
  84002. }
  84003. if (thisx.op & 64) {
  84004. strm->msg = (char *)"invalid literal/length code";
  84005. state->mode = BAD;
  84006. break;
  84007. }
  84008. state->extra = (unsigned)(thisx.op) & 15;
  84009. state->mode = LENEXT;
  84010. case LENEXT:
  84011. if (state->extra) {
  84012. NEEDBITS(state->extra);
  84013. state->length += BITS(state->extra);
  84014. DROPBITS(state->extra);
  84015. }
  84016. Tracevv((stderr, "inflate: length %u\n", state->length));
  84017. state->mode = DIST;
  84018. case DIST:
  84019. for (;;) {
  84020. thisx = state->distcode[BITS(state->distbits)];
  84021. if ((unsigned)(thisx.bits) <= bits) break;
  84022. PULLBYTE();
  84023. }
  84024. if ((thisx.op & 0xf0) == 0) {
  84025. last = thisx;
  84026. for (;;) {
  84027. thisx = state->distcode[last.val +
  84028. (BITS(last.bits + last.op) >> last.bits)];
  84029. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84030. PULLBYTE();
  84031. }
  84032. DROPBITS(last.bits);
  84033. }
  84034. DROPBITS(thisx.bits);
  84035. if (thisx.op & 64) {
  84036. strm->msg = (char *)"invalid distance code";
  84037. state->mode = BAD;
  84038. break;
  84039. }
  84040. state->offset = (unsigned)thisx.val;
  84041. state->extra = (unsigned)(thisx.op) & 15;
  84042. state->mode = DISTEXT;
  84043. case DISTEXT:
  84044. if (state->extra) {
  84045. NEEDBITS(state->extra);
  84046. state->offset += BITS(state->extra);
  84047. DROPBITS(state->extra);
  84048. }
  84049. #ifdef INFLATE_STRICT
  84050. if (state->offset > state->dmax) {
  84051. strm->msg = (char *)"invalid distance too far back";
  84052. state->mode = BAD;
  84053. break;
  84054. }
  84055. #endif
  84056. if (state->offset > state->whave + out - left) {
  84057. strm->msg = (char *)"invalid distance too far back";
  84058. state->mode = BAD;
  84059. break;
  84060. }
  84061. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84062. state->mode = MATCH;
  84063. case MATCH:
  84064. if (left == 0) goto inf_leave;
  84065. copy = out - left;
  84066. if (state->offset > copy) { /* copy from window */
  84067. copy = state->offset - copy;
  84068. if (copy > state->write) {
  84069. copy -= state->write;
  84070. from = state->window + (state->wsize - copy);
  84071. }
  84072. else
  84073. from = state->window + (state->write - copy);
  84074. if (copy > state->length) copy = state->length;
  84075. }
  84076. else { /* copy from output */
  84077. from = put - state->offset;
  84078. copy = state->length;
  84079. }
  84080. if (copy > left) copy = left;
  84081. left -= copy;
  84082. state->length -= copy;
  84083. do {
  84084. *put++ = *from++;
  84085. } while (--copy);
  84086. if (state->length == 0) state->mode = LEN;
  84087. break;
  84088. case LIT:
  84089. if (left == 0) goto inf_leave;
  84090. *put++ = (unsigned char)(state->length);
  84091. left--;
  84092. state->mode = LEN;
  84093. break;
  84094. case CHECK:
  84095. if (state->wrap) {
  84096. NEEDBITS(32);
  84097. out -= left;
  84098. strm->total_out += out;
  84099. state->total += out;
  84100. if (out)
  84101. strm->adler = state->check =
  84102. UPDATE(state->check, put - out, out);
  84103. out = left;
  84104. if ((
  84105. #ifdef GUNZIP
  84106. state->flags ? hold :
  84107. #endif
  84108. REVERSE(hold)) != state->check) {
  84109. strm->msg = (char *)"incorrect data check";
  84110. state->mode = BAD;
  84111. break;
  84112. }
  84113. INITBITS();
  84114. Tracev((stderr, "inflate: check matches trailer\n"));
  84115. }
  84116. #ifdef GUNZIP
  84117. state->mode = LENGTH;
  84118. case LENGTH:
  84119. if (state->wrap && state->flags) {
  84120. NEEDBITS(32);
  84121. if (hold != (state->total & 0xffffffffUL)) {
  84122. strm->msg = (char *)"incorrect length check";
  84123. state->mode = BAD;
  84124. break;
  84125. }
  84126. INITBITS();
  84127. Tracev((stderr, "inflate: length matches trailer\n"));
  84128. }
  84129. #endif
  84130. state->mode = DONE;
  84131. case DONE:
  84132. ret = Z_STREAM_END;
  84133. goto inf_leave;
  84134. case BAD:
  84135. ret = Z_DATA_ERROR;
  84136. goto inf_leave;
  84137. case MEM:
  84138. return Z_MEM_ERROR;
  84139. case SYNC:
  84140. default:
  84141. return Z_STREAM_ERROR;
  84142. }
  84143. /*
  84144. Return from inflate(), updating the total counts and the check value.
  84145. If there was no progress during the inflate() call, return a buffer
  84146. error. Call updatewindow() to create and/or update the window state.
  84147. Note: a memory error from inflate() is non-recoverable.
  84148. */
  84149. inf_leave:
  84150. RESTORE();
  84151. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84152. if (updatewindow(strm, out)) {
  84153. state->mode = MEM;
  84154. return Z_MEM_ERROR;
  84155. }
  84156. in -= strm->avail_in;
  84157. out -= strm->avail_out;
  84158. strm->total_in += in;
  84159. strm->total_out += out;
  84160. state->total += out;
  84161. if (state->wrap && out)
  84162. strm->adler = state->check =
  84163. UPDATE(state->check, strm->next_out - out, out);
  84164. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84165. (state->mode == TYPE ? 128 : 0);
  84166. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84167. ret = Z_BUF_ERROR;
  84168. return ret;
  84169. }
  84170. int ZEXPORT inflateEnd (z_streamp strm)
  84171. {
  84172. struct inflate_state FAR *state;
  84173. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84174. return Z_STREAM_ERROR;
  84175. state = (struct inflate_state FAR *)strm->state;
  84176. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84177. ZFREE(strm, strm->state);
  84178. strm->state = Z_NULL;
  84179. Tracev((stderr, "inflate: end\n"));
  84180. return Z_OK;
  84181. }
  84182. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84183. {
  84184. struct inflate_state FAR *state;
  84185. unsigned long id_;
  84186. /* check state */
  84187. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84188. state = (struct inflate_state FAR *)strm->state;
  84189. if (state->wrap != 0 && state->mode != DICT)
  84190. return Z_STREAM_ERROR;
  84191. /* check for correct dictionary id */
  84192. if (state->mode == DICT) {
  84193. id_ = adler32(0L, Z_NULL, 0);
  84194. id_ = adler32(id_, dictionary, dictLength);
  84195. if (id_ != state->check)
  84196. return Z_DATA_ERROR;
  84197. }
  84198. /* copy dictionary to window */
  84199. if (updatewindow(strm, strm->avail_out)) {
  84200. state->mode = MEM;
  84201. return Z_MEM_ERROR;
  84202. }
  84203. if (dictLength > state->wsize) {
  84204. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84205. state->wsize);
  84206. state->whave = state->wsize;
  84207. }
  84208. else {
  84209. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84210. dictLength);
  84211. state->whave = dictLength;
  84212. }
  84213. state->havedict = 1;
  84214. Tracev((stderr, "inflate: dictionary set\n"));
  84215. return Z_OK;
  84216. }
  84217. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84218. {
  84219. struct inflate_state FAR *state;
  84220. /* check state */
  84221. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84222. state = (struct inflate_state FAR *)strm->state;
  84223. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84224. /* save header structure */
  84225. state->head = head;
  84226. head->done = 0;
  84227. return Z_OK;
  84228. }
  84229. /*
  84230. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84231. or when out of input. When called, *have is the number of pattern bytes
  84232. found in order so far, in 0..3. On return *have is updated to the new
  84233. state. If on return *have equals four, then the pattern was found and the
  84234. return value is how many bytes were read including the last byte of the
  84235. pattern. If *have is less than four, then the pattern has not been found
  84236. yet and the return value is len. In the latter case, syncsearch() can be
  84237. called again with more data and the *have state. *have is initialized to
  84238. zero for the first call.
  84239. */
  84240. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84241. {
  84242. unsigned got;
  84243. unsigned next;
  84244. got = *have;
  84245. next = 0;
  84246. while (next < len && got < 4) {
  84247. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84248. got++;
  84249. else if (buf[next])
  84250. got = 0;
  84251. else
  84252. got = 4 - got;
  84253. next++;
  84254. }
  84255. *have = got;
  84256. return next;
  84257. }
  84258. int ZEXPORT inflateSync (z_streamp strm)
  84259. {
  84260. unsigned len; /* number of bytes to look at or looked at */
  84261. unsigned long in, out; /* temporary to save total_in and total_out */
  84262. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84263. struct inflate_state FAR *state;
  84264. /* check parameters */
  84265. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84266. state = (struct inflate_state FAR *)strm->state;
  84267. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84268. /* if first time, start search in bit buffer */
  84269. if (state->mode != SYNC) {
  84270. state->mode = SYNC;
  84271. state->hold <<= state->bits & 7;
  84272. state->bits -= state->bits & 7;
  84273. len = 0;
  84274. while (state->bits >= 8) {
  84275. buf[len++] = (unsigned char)(state->hold);
  84276. state->hold >>= 8;
  84277. state->bits -= 8;
  84278. }
  84279. state->have = 0;
  84280. syncsearch(&(state->have), buf, len);
  84281. }
  84282. /* search available input */
  84283. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84284. strm->avail_in -= len;
  84285. strm->next_in += len;
  84286. strm->total_in += len;
  84287. /* return no joy or set up to restart inflate() on a new block */
  84288. if (state->have != 4) return Z_DATA_ERROR;
  84289. in = strm->total_in; out = strm->total_out;
  84290. inflateReset(strm);
  84291. strm->total_in = in; strm->total_out = out;
  84292. state->mode = TYPE;
  84293. return Z_OK;
  84294. }
  84295. /*
  84296. Returns true if inflate is currently at the end of a block generated by
  84297. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84298. implementation to provide an additional safety check. PPP uses
  84299. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84300. block. When decompressing, PPP checks that at the end of input packet,
  84301. inflate is waiting for these length bytes.
  84302. */
  84303. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84304. {
  84305. struct inflate_state FAR *state;
  84306. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84307. state = (struct inflate_state FAR *)strm->state;
  84308. return state->mode == STORED && state->bits == 0;
  84309. }
  84310. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84311. {
  84312. struct inflate_state FAR *state;
  84313. struct inflate_state FAR *copy;
  84314. unsigned char FAR *window;
  84315. unsigned wsize;
  84316. /* check input */
  84317. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84318. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84319. return Z_STREAM_ERROR;
  84320. state = (struct inflate_state FAR *)source->state;
  84321. /* allocate space */
  84322. copy = (struct inflate_state FAR *)
  84323. ZALLOC(source, 1, sizeof(struct inflate_state));
  84324. if (copy == Z_NULL) return Z_MEM_ERROR;
  84325. window = Z_NULL;
  84326. if (state->window != Z_NULL) {
  84327. window = (unsigned char FAR *)
  84328. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84329. if (window == Z_NULL) {
  84330. ZFREE(source, copy);
  84331. return Z_MEM_ERROR;
  84332. }
  84333. }
  84334. /* copy state */
  84335. zmemcpy(dest, source, sizeof(z_stream));
  84336. zmemcpy(copy, state, sizeof(struct inflate_state));
  84337. if (state->lencode >= state->codes &&
  84338. state->lencode <= state->codes + ENOUGH - 1) {
  84339. copy->lencode = copy->codes + (state->lencode - state->codes);
  84340. copy->distcode = copy->codes + (state->distcode - state->codes);
  84341. }
  84342. copy->next = copy->codes + (state->next - state->codes);
  84343. if (window != Z_NULL) {
  84344. wsize = 1U << state->wbits;
  84345. zmemcpy(window, state->window, wsize);
  84346. }
  84347. copy->window = window;
  84348. dest->state = (struct internal_state FAR *)copy;
  84349. return Z_OK;
  84350. }
  84351. /*** End of inlined file: inflate.c ***/
  84352. /*** Start of inlined file: inftrees.c ***/
  84353. #define MAXBITS 15
  84354. const char inflate_copyright[] =
  84355. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84356. /*
  84357. If you use the zlib library in a product, an acknowledgment is welcome
  84358. in the documentation of your product. If for some reason you cannot
  84359. include such an acknowledgment, I would appreciate that you keep this
  84360. copyright string in the executable of your product.
  84361. */
  84362. /*
  84363. Build a set of tables to decode the provided canonical Huffman code.
  84364. The code lengths are lens[0..codes-1]. The result starts at *table,
  84365. whose indices are 0..2^bits-1. work is a writable array of at least
  84366. lens shorts, which is used as a work area. type is the type of code
  84367. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84368. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84369. on return points to the next available entry's address. bits is the
  84370. requested root table index bits, and on return it is the actual root
  84371. table index bits. It will differ if the request is greater than the
  84372. longest code or if it is less than the shortest code.
  84373. */
  84374. int inflate_table (codetype type,
  84375. unsigned short FAR *lens,
  84376. unsigned codes,
  84377. code FAR * FAR *table,
  84378. unsigned FAR *bits,
  84379. unsigned short FAR *work)
  84380. {
  84381. unsigned len; /* a code's length in bits */
  84382. unsigned sym; /* index of code symbols */
  84383. unsigned min, max; /* minimum and maximum code lengths */
  84384. unsigned root; /* number of index bits for root table */
  84385. unsigned curr; /* number of index bits for current table */
  84386. unsigned drop; /* code bits to drop for sub-table */
  84387. int left; /* number of prefix codes available */
  84388. unsigned used; /* code entries in table used */
  84389. unsigned huff; /* Huffman code */
  84390. unsigned incr; /* for incrementing code, index */
  84391. unsigned fill; /* index for replicating entries */
  84392. unsigned low; /* low bits for current root entry */
  84393. unsigned mask; /* mask for low root bits */
  84394. code thisx; /* table entry for duplication */
  84395. code FAR *next; /* next available space in table */
  84396. const unsigned short FAR *base; /* base value table to use */
  84397. const unsigned short FAR *extra; /* extra bits table to use */
  84398. int end; /* use base and extra for symbol > end */
  84399. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84400. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84401. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84402. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84403. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84404. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84405. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84406. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84407. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84408. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84409. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84410. 8193, 12289, 16385, 24577, 0, 0};
  84411. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84412. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84413. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84414. 28, 28, 29, 29, 64, 64};
  84415. /*
  84416. Process a set of code lengths to create a canonical Huffman code. The
  84417. code lengths are lens[0..codes-1]. Each length corresponds to the
  84418. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84419. symbols by length from short to long, and retaining the symbol order
  84420. for codes with equal lengths. Then the code starts with all zero bits
  84421. for the first code of the shortest length, and the codes are integer
  84422. increments for the same length, and zeros are appended as the length
  84423. increases. For the deflate format, these bits are stored backwards
  84424. from their more natural integer increment ordering, and so when the
  84425. decoding tables are built in the large loop below, the integer codes
  84426. are incremented backwards.
  84427. This routine assumes, but does not check, that all of the entries in
  84428. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84429. 1..MAXBITS is interpreted as that code length. zero means that that
  84430. symbol does not occur in this code.
  84431. The codes are sorted by computing a count of codes for each length,
  84432. creating from that a table of starting indices for each length in the
  84433. sorted table, and then entering the symbols in order in the sorted
  84434. table. The sorted table is work[], with that space being provided by
  84435. the caller.
  84436. The length counts are used for other purposes as well, i.e. finding
  84437. the minimum and maximum length codes, determining if there are any
  84438. codes at all, checking for a valid set of lengths, and looking ahead
  84439. at length counts to determine sub-table sizes when building the
  84440. decoding tables.
  84441. */
  84442. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84443. for (len = 0; len <= MAXBITS; len++)
  84444. count[len] = 0;
  84445. for (sym = 0; sym < codes; sym++)
  84446. count[lens[sym]]++;
  84447. /* bound code lengths, force root to be within code lengths */
  84448. root = *bits;
  84449. for (max = MAXBITS; max >= 1; max--)
  84450. if (count[max] != 0) break;
  84451. if (root > max) root = max;
  84452. if (max == 0) { /* no symbols to code at all */
  84453. thisx.op = (unsigned char)64; /* invalid code marker */
  84454. thisx.bits = (unsigned char)1;
  84455. thisx.val = (unsigned short)0;
  84456. *(*table)++ = thisx; /* make a table to force an error */
  84457. *(*table)++ = thisx;
  84458. *bits = 1;
  84459. return 0; /* no symbols, but wait for decoding to report error */
  84460. }
  84461. for (min = 1; min <= MAXBITS; min++)
  84462. if (count[min] != 0) break;
  84463. if (root < min) root = min;
  84464. /* check for an over-subscribed or incomplete set of lengths */
  84465. left = 1;
  84466. for (len = 1; len <= MAXBITS; len++) {
  84467. left <<= 1;
  84468. left -= count[len];
  84469. if (left < 0) return -1; /* over-subscribed */
  84470. }
  84471. if (left > 0 && (type == CODES || max != 1))
  84472. return -1; /* incomplete set */
  84473. /* generate offsets into symbol table for each length for sorting */
  84474. offs[1] = 0;
  84475. for (len = 1; len < MAXBITS; len++)
  84476. offs[len + 1] = offs[len] + count[len];
  84477. /* sort symbols by length, by symbol order within each length */
  84478. for (sym = 0; sym < codes; sym++)
  84479. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84480. /*
  84481. Create and fill in decoding tables. In this loop, the table being
  84482. filled is at next and has curr index bits. The code being used is huff
  84483. with length len. That code is converted to an index by dropping drop
  84484. bits off of the bottom. For codes where len is less than drop + curr,
  84485. those top drop + curr - len bits are incremented through all values to
  84486. fill the table with replicated entries.
  84487. root is the number of index bits for the root table. When len exceeds
  84488. root, sub-tables are created pointed to by the root entry with an index
  84489. of the low root bits of huff. This is saved in low to check for when a
  84490. new sub-table should be started. drop is zero when the root table is
  84491. being filled, and drop is root when sub-tables are being filled.
  84492. When a new sub-table is needed, it is necessary to look ahead in the
  84493. code lengths to determine what size sub-table is needed. The length
  84494. counts are used for this, and so count[] is decremented as codes are
  84495. entered in the tables.
  84496. used keeps track of how many table entries have been allocated from the
  84497. provided *table space. It is checked when a LENS table is being made
  84498. against the space in *table, ENOUGH, minus the maximum space needed by
  84499. the worst case distance code, MAXD. This should never happen, but the
  84500. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84501. This assumes that when type == LENS, bits == 9.
  84502. sym increments through all symbols, and the loop terminates when
  84503. all codes of length max, i.e. all codes, have been processed. This
  84504. routine permits incomplete codes, so another loop after this one fills
  84505. in the rest of the decoding tables with invalid code markers.
  84506. */
  84507. /* set up for code type */
  84508. switch (type) {
  84509. case CODES:
  84510. base = extra = work; /* dummy value--not used */
  84511. end = 19;
  84512. break;
  84513. case LENS:
  84514. base = lbase;
  84515. base -= 257;
  84516. extra = lext;
  84517. extra -= 257;
  84518. end = 256;
  84519. break;
  84520. default: /* DISTS */
  84521. base = dbase;
  84522. extra = dext;
  84523. end = -1;
  84524. }
  84525. /* initialize state for loop */
  84526. huff = 0; /* starting code */
  84527. sym = 0; /* starting code symbol */
  84528. len = min; /* starting code length */
  84529. next = *table; /* current table to fill in */
  84530. curr = root; /* current table index bits */
  84531. drop = 0; /* current bits to drop from code for index */
  84532. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84533. used = 1U << root; /* use root table entries */
  84534. mask = used - 1; /* mask for comparing low */
  84535. /* check available table space */
  84536. if (type == LENS && used >= ENOUGH - MAXD)
  84537. return 1;
  84538. /* process all codes and make table entries */
  84539. for (;;) {
  84540. /* create table entry */
  84541. thisx.bits = (unsigned char)(len - drop);
  84542. if ((int)(work[sym]) < end) {
  84543. thisx.op = (unsigned char)0;
  84544. thisx.val = work[sym];
  84545. }
  84546. else if ((int)(work[sym]) > end) {
  84547. thisx.op = (unsigned char)(extra[work[sym]]);
  84548. thisx.val = base[work[sym]];
  84549. }
  84550. else {
  84551. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84552. thisx.val = 0;
  84553. }
  84554. /* replicate for those indices with low len bits equal to huff */
  84555. incr = 1U << (len - drop);
  84556. fill = 1U << curr;
  84557. min = fill; /* save offset to next table */
  84558. do {
  84559. fill -= incr;
  84560. next[(huff >> drop) + fill] = thisx;
  84561. } while (fill != 0);
  84562. /* backwards increment the len-bit code huff */
  84563. incr = 1U << (len - 1);
  84564. while (huff & incr)
  84565. incr >>= 1;
  84566. if (incr != 0) {
  84567. huff &= incr - 1;
  84568. huff += incr;
  84569. }
  84570. else
  84571. huff = 0;
  84572. /* go to next symbol, update count, len */
  84573. sym++;
  84574. if (--(count[len]) == 0) {
  84575. if (len == max) break;
  84576. len = lens[work[sym]];
  84577. }
  84578. /* create new sub-table if needed */
  84579. if (len > root && (huff & mask) != low) {
  84580. /* if first time, transition to sub-tables */
  84581. if (drop == 0)
  84582. drop = root;
  84583. /* increment past last table */
  84584. next += min; /* here min is 1 << curr */
  84585. /* determine length of next table */
  84586. curr = len - drop;
  84587. left = (int)(1 << curr);
  84588. while (curr + drop < max) {
  84589. left -= count[curr + drop];
  84590. if (left <= 0) break;
  84591. curr++;
  84592. left <<= 1;
  84593. }
  84594. /* check for enough space */
  84595. used += 1U << curr;
  84596. if (type == LENS && used >= ENOUGH - MAXD)
  84597. return 1;
  84598. /* point entry in root table to sub-table */
  84599. low = huff & mask;
  84600. (*table)[low].op = (unsigned char)curr;
  84601. (*table)[low].bits = (unsigned char)root;
  84602. (*table)[low].val = (unsigned short)(next - *table);
  84603. }
  84604. }
  84605. /*
  84606. Fill in rest of table for incomplete codes. This loop is similar to the
  84607. loop above in incrementing huff for table indices. It is assumed that
  84608. len is equal to curr + drop, so there is no loop needed to increment
  84609. through high index bits. When the current sub-table is filled, the loop
  84610. drops back to the root table to fill in any remaining entries there.
  84611. */
  84612. thisx.op = (unsigned char)64; /* invalid code marker */
  84613. thisx.bits = (unsigned char)(len - drop);
  84614. thisx.val = (unsigned short)0;
  84615. while (huff != 0) {
  84616. /* when done with sub-table, drop back to root table */
  84617. if (drop != 0 && (huff & mask) != low) {
  84618. drop = 0;
  84619. len = root;
  84620. next = *table;
  84621. thisx.bits = (unsigned char)len;
  84622. }
  84623. /* put invalid code marker in table */
  84624. next[huff >> drop] = thisx;
  84625. /* backwards increment the len-bit code huff */
  84626. incr = 1U << (len - 1);
  84627. while (huff & incr)
  84628. incr >>= 1;
  84629. if (incr != 0) {
  84630. huff &= incr - 1;
  84631. huff += incr;
  84632. }
  84633. else
  84634. huff = 0;
  84635. }
  84636. /* set return parameters */
  84637. *table += used;
  84638. *bits = root;
  84639. return 0;
  84640. }
  84641. /*** End of inlined file: inftrees.c ***/
  84642. /*** Start of inlined file: trees.c ***/
  84643. /*
  84644. * ALGORITHM
  84645. *
  84646. * The "deflation" process uses several Huffman trees. The more
  84647. * common source values are represented by shorter bit sequences.
  84648. *
  84649. * Each code tree is stored in a compressed form which is itself
  84650. * a Huffman encoding of the lengths of all the code strings (in
  84651. * ascending order by source values). The actual code strings are
  84652. * reconstructed from the lengths in the inflate process, as described
  84653. * in the deflate specification.
  84654. *
  84655. * REFERENCES
  84656. *
  84657. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84658. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84659. *
  84660. * Storer, James A.
  84661. * Data Compression: Methods and Theory, pp. 49-50.
  84662. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84663. *
  84664. * Sedgewick, R.
  84665. * Algorithms, p290.
  84666. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84667. */
  84668. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84669. /* #define GEN_TREES_H */
  84670. #ifdef DEBUG
  84671. # include <ctype.h>
  84672. #endif
  84673. /* ===========================================================================
  84674. * Constants
  84675. */
  84676. #define MAX_BL_BITS 7
  84677. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84678. #define END_BLOCK 256
  84679. /* end of block literal code */
  84680. #define REP_3_6 16
  84681. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84682. #define REPZ_3_10 17
  84683. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84684. #define REPZ_11_138 18
  84685. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84686. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84687. = {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};
  84688. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84689. = {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};
  84690. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84691. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84692. local const uch bl_order[BL_CODES]
  84693. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84694. /* The lengths of the bit length codes are sent in order of decreasing
  84695. * probability, to avoid transmitting the lengths for unused bit length codes.
  84696. */
  84697. #define Buf_size (8 * 2*sizeof(char))
  84698. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84699. * more than 16 bits on some systems.)
  84700. */
  84701. /* ===========================================================================
  84702. * Local data. These are initialized only once.
  84703. */
  84704. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84705. #if defined(GEN_TREES_H) || !defined(STDC)
  84706. /* non ANSI compilers may not accept trees.h */
  84707. local ct_data static_ltree[L_CODES+2];
  84708. /* The static literal tree. Since the bit lengths are imposed, there is no
  84709. * need for the L_CODES extra codes used during heap construction. However
  84710. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84711. * below).
  84712. */
  84713. local ct_data static_dtree[D_CODES];
  84714. /* The static distance tree. (Actually a trivial tree since all codes use
  84715. * 5 bits.)
  84716. */
  84717. uch _dist_code[DIST_CODE_LEN];
  84718. /* Distance codes. The first 256 values correspond to the distances
  84719. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84720. * the 15 bit distances.
  84721. */
  84722. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84723. /* length code for each normalized match length (0 == MIN_MATCH) */
  84724. local int base_length[LENGTH_CODES];
  84725. /* First normalized length for each code (0 = MIN_MATCH) */
  84726. local int base_dist[D_CODES];
  84727. /* First normalized distance for each code (0 = distance of 1) */
  84728. #else
  84729. /*** Start of inlined file: trees.h ***/
  84730. local const ct_data static_ltree[L_CODES+2] = {
  84731. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84732. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84733. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84734. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84735. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84736. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84737. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84738. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84739. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84740. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84741. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84742. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84743. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84744. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84745. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84746. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84747. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84748. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84749. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84750. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84751. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84752. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84753. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84754. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84755. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84756. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84757. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84758. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84759. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84760. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84761. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84762. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84763. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84764. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84765. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84766. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84767. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84768. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84769. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84770. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84771. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84772. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84773. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84774. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84775. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84776. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84777. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84778. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84779. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84780. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84781. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84782. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84783. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84784. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84785. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84786. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84787. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84788. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84789. };
  84790. local const ct_data static_dtree[D_CODES] = {
  84791. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84792. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84793. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84794. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84795. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84796. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84797. };
  84798. const uch _dist_code[DIST_CODE_LEN] = {
  84799. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84800. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84801. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84802. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84803. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84804. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84805. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84806. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84807. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84808. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84809. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84810. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84811. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84812. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84813. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84814. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84815. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84816. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84817. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84818. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84819. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84820. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84821. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84822. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84823. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84824. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84825. };
  84826. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84827. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84828. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84829. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84830. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84831. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84832. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84833. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84834. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84835. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84836. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84837. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84838. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84839. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84840. };
  84841. local const int base_length[LENGTH_CODES] = {
  84842. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84843. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84844. };
  84845. local const int base_dist[D_CODES] = {
  84846. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84847. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84848. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84849. };
  84850. /*** End of inlined file: trees.h ***/
  84851. #endif /* GEN_TREES_H */
  84852. struct static_tree_desc_s {
  84853. const ct_data *static_tree; /* static tree or NULL */
  84854. const intf *extra_bits; /* extra bits for each code or NULL */
  84855. int extra_base; /* base index for extra_bits */
  84856. int elems; /* max number of elements in the tree */
  84857. int max_length; /* max bit length for the codes */
  84858. };
  84859. local static_tree_desc static_l_desc =
  84860. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84861. local static_tree_desc static_d_desc =
  84862. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84863. local static_tree_desc static_bl_desc =
  84864. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84865. /* ===========================================================================
  84866. * Local (static) routines in this file.
  84867. */
  84868. local void tr_static_init OF((void));
  84869. local void init_block OF((deflate_state *s));
  84870. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84871. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84872. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84873. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84874. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84875. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84876. local int build_bl_tree OF((deflate_state *s));
  84877. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84878. int blcodes));
  84879. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84880. ct_data *dtree));
  84881. local void set_data_type OF((deflate_state *s));
  84882. local unsigned bi_reverse OF((unsigned value, int length));
  84883. local void bi_windup OF((deflate_state *s));
  84884. local void bi_flush OF((deflate_state *s));
  84885. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84886. int header));
  84887. #ifdef GEN_TREES_H
  84888. local void gen_trees_header OF((void));
  84889. #endif
  84890. #ifndef DEBUG
  84891. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84892. /* Send a code of the given tree. c and tree must not have side effects */
  84893. #else /* DEBUG */
  84894. # define send_code(s, c, tree) \
  84895. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84896. send_bits(s, tree[c].Code, tree[c].Len); }
  84897. #endif
  84898. /* ===========================================================================
  84899. * Output a short LSB first on the stream.
  84900. * IN assertion: there is enough room in pendingBuf.
  84901. */
  84902. #define put_short(s, w) { \
  84903. put_byte(s, (uch)((w) & 0xff)); \
  84904. put_byte(s, (uch)((ush)(w) >> 8)); \
  84905. }
  84906. /* ===========================================================================
  84907. * Send a value on a given number of bits.
  84908. * IN assertion: length <= 16 and value fits in length bits.
  84909. */
  84910. #ifdef DEBUG
  84911. local void send_bits OF((deflate_state *s, int value, int length));
  84912. local void send_bits (deflate_state *s, int value, int length)
  84913. {
  84914. Tracevv((stderr," l %2d v %4x ", length, value));
  84915. Assert(length > 0 && length <= 15, "invalid length");
  84916. s->bits_sent += (ulg)length;
  84917. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84918. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84919. * unused bits in value.
  84920. */
  84921. if (s->bi_valid > (int)Buf_size - length) {
  84922. s->bi_buf |= (value << s->bi_valid);
  84923. put_short(s, s->bi_buf);
  84924. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84925. s->bi_valid += length - Buf_size;
  84926. } else {
  84927. s->bi_buf |= value << s->bi_valid;
  84928. s->bi_valid += length;
  84929. }
  84930. }
  84931. #else /* !DEBUG */
  84932. #define send_bits(s, value, length) \
  84933. { int len = length;\
  84934. if (s->bi_valid > (int)Buf_size - len) {\
  84935. int val = value;\
  84936. s->bi_buf |= (val << s->bi_valid);\
  84937. put_short(s, s->bi_buf);\
  84938. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84939. s->bi_valid += len - Buf_size;\
  84940. } else {\
  84941. s->bi_buf |= (value) << s->bi_valid;\
  84942. s->bi_valid += len;\
  84943. }\
  84944. }
  84945. #endif /* DEBUG */
  84946. /* the arguments must not have side effects */
  84947. /* ===========================================================================
  84948. * Initialize the various 'constant' tables.
  84949. */
  84950. local void tr_static_init()
  84951. {
  84952. #if defined(GEN_TREES_H) || !defined(STDC)
  84953. static int static_init_done = 0;
  84954. int n; /* iterates over tree elements */
  84955. int bits; /* bit counter */
  84956. int length; /* length value */
  84957. int code; /* code value */
  84958. int dist; /* distance index */
  84959. ush bl_count[MAX_BITS+1];
  84960. /* number of codes at each bit length for an optimal tree */
  84961. if (static_init_done) return;
  84962. /* For some embedded targets, global variables are not initialized: */
  84963. static_l_desc.static_tree = static_ltree;
  84964. static_l_desc.extra_bits = extra_lbits;
  84965. static_d_desc.static_tree = static_dtree;
  84966. static_d_desc.extra_bits = extra_dbits;
  84967. static_bl_desc.extra_bits = extra_blbits;
  84968. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84969. length = 0;
  84970. for (code = 0; code < LENGTH_CODES-1; code++) {
  84971. base_length[code] = length;
  84972. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84973. _length_code[length++] = (uch)code;
  84974. }
  84975. }
  84976. Assert (length == 256, "tr_static_init: length != 256");
  84977. /* Note that the length 255 (match length 258) can be represented
  84978. * in two different ways: code 284 + 5 bits or code 285, so we
  84979. * overwrite length_code[255] to use the best encoding:
  84980. */
  84981. _length_code[length-1] = (uch)code;
  84982. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84983. dist = 0;
  84984. for (code = 0 ; code < 16; code++) {
  84985. base_dist[code] = dist;
  84986. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84987. _dist_code[dist++] = (uch)code;
  84988. }
  84989. }
  84990. Assert (dist == 256, "tr_static_init: dist != 256");
  84991. dist >>= 7; /* from now on, all distances are divided by 128 */
  84992. for ( ; code < D_CODES; code++) {
  84993. base_dist[code] = dist << 7;
  84994. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84995. _dist_code[256 + dist++] = (uch)code;
  84996. }
  84997. }
  84998. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84999. /* Construct the codes of the static literal tree */
  85000. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85001. n = 0;
  85002. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85003. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85004. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85005. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85006. /* Codes 286 and 287 do not exist, but we must include them in the
  85007. * tree construction to get a canonical Huffman tree (longest code
  85008. * all ones)
  85009. */
  85010. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85011. /* The static distance tree is trivial: */
  85012. for (n = 0; n < D_CODES; n++) {
  85013. static_dtree[n].Len = 5;
  85014. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85015. }
  85016. static_init_done = 1;
  85017. # ifdef GEN_TREES_H
  85018. gen_trees_header();
  85019. # endif
  85020. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85021. }
  85022. /* ===========================================================================
  85023. * Genererate the file trees.h describing the static trees.
  85024. */
  85025. #ifdef GEN_TREES_H
  85026. # ifndef DEBUG
  85027. # include <stdio.h>
  85028. # endif
  85029. # define SEPARATOR(i, last, width) \
  85030. ((i) == (last)? "\n};\n\n" : \
  85031. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85032. void gen_trees_header()
  85033. {
  85034. FILE *header = fopen("trees.h", "w");
  85035. int i;
  85036. Assert (header != NULL, "Can't open trees.h");
  85037. fprintf(header,
  85038. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85039. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85040. for (i = 0; i < L_CODES+2; i++) {
  85041. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85042. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85043. }
  85044. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85045. for (i = 0; i < D_CODES; i++) {
  85046. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85047. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85048. }
  85049. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85050. for (i = 0; i < DIST_CODE_LEN; i++) {
  85051. fprintf(header, "%2u%s", _dist_code[i],
  85052. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85053. }
  85054. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85055. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85056. fprintf(header, "%2u%s", _length_code[i],
  85057. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85058. }
  85059. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85060. for (i = 0; i < LENGTH_CODES; i++) {
  85061. fprintf(header, "%1u%s", base_length[i],
  85062. SEPARATOR(i, LENGTH_CODES-1, 20));
  85063. }
  85064. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85065. for (i = 0; i < D_CODES; i++) {
  85066. fprintf(header, "%5u%s", base_dist[i],
  85067. SEPARATOR(i, D_CODES-1, 10));
  85068. }
  85069. fclose(header);
  85070. }
  85071. #endif /* GEN_TREES_H */
  85072. /* ===========================================================================
  85073. * Initialize the tree data structures for a new zlib stream.
  85074. */
  85075. void _tr_init(deflate_state *s)
  85076. {
  85077. tr_static_init();
  85078. s->l_desc.dyn_tree = s->dyn_ltree;
  85079. s->l_desc.stat_desc = &static_l_desc;
  85080. s->d_desc.dyn_tree = s->dyn_dtree;
  85081. s->d_desc.stat_desc = &static_d_desc;
  85082. s->bl_desc.dyn_tree = s->bl_tree;
  85083. s->bl_desc.stat_desc = &static_bl_desc;
  85084. s->bi_buf = 0;
  85085. s->bi_valid = 0;
  85086. s->last_eob_len = 8; /* enough lookahead for inflate */
  85087. #ifdef DEBUG
  85088. s->compressed_len = 0L;
  85089. s->bits_sent = 0L;
  85090. #endif
  85091. /* Initialize the first block of the first file: */
  85092. init_block(s);
  85093. }
  85094. /* ===========================================================================
  85095. * Initialize a new block.
  85096. */
  85097. local void init_block (deflate_state *s)
  85098. {
  85099. int n; /* iterates over tree elements */
  85100. /* Initialize the trees. */
  85101. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85102. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85103. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85104. s->dyn_ltree[END_BLOCK].Freq = 1;
  85105. s->opt_len = s->static_len = 0L;
  85106. s->last_lit = s->matches = 0;
  85107. }
  85108. #define SMALLEST 1
  85109. /* Index within the heap array of least frequent node in the Huffman tree */
  85110. /* ===========================================================================
  85111. * Remove the smallest element from the heap and recreate the heap with
  85112. * one less element. Updates heap and heap_len.
  85113. */
  85114. #define pqremove(s, tree, top) \
  85115. {\
  85116. top = s->heap[SMALLEST]; \
  85117. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85118. pqdownheap(s, tree, SMALLEST); \
  85119. }
  85120. /* ===========================================================================
  85121. * Compares to subtrees, using the tree depth as tie breaker when
  85122. * the subtrees have equal frequency. This minimizes the worst case length.
  85123. */
  85124. #define smaller(tree, n, m, depth) \
  85125. (tree[n].Freq < tree[m].Freq || \
  85126. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85127. /* ===========================================================================
  85128. * Restore the heap property by moving down the tree starting at node k,
  85129. * exchanging a node with the smallest of its two sons if necessary, stopping
  85130. * when the heap property is re-established (each father smaller than its
  85131. * two sons).
  85132. */
  85133. local void pqdownheap (deflate_state *s,
  85134. ct_data *tree, /* the tree to restore */
  85135. int k) /* node to move down */
  85136. {
  85137. int v = s->heap[k];
  85138. int j = k << 1; /* left son of k */
  85139. while (j <= s->heap_len) {
  85140. /* Set j to the smallest of the two sons: */
  85141. if (j < s->heap_len &&
  85142. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85143. j++;
  85144. }
  85145. /* Exit if v is smaller than both sons */
  85146. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85147. /* Exchange v with the smallest son */
  85148. s->heap[k] = s->heap[j]; k = j;
  85149. /* And continue down the tree, setting j to the left son of k */
  85150. j <<= 1;
  85151. }
  85152. s->heap[k] = v;
  85153. }
  85154. /* ===========================================================================
  85155. * Compute the optimal bit lengths for a tree and update the total bit length
  85156. * for the current block.
  85157. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85158. * above are the tree nodes sorted by increasing frequency.
  85159. * OUT assertions: the field len is set to the optimal bit length, the
  85160. * array bl_count contains the frequencies for each bit length.
  85161. * The length opt_len is updated; static_len is also updated if stree is
  85162. * not null.
  85163. */
  85164. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85165. {
  85166. ct_data *tree = desc->dyn_tree;
  85167. int max_code = desc->max_code;
  85168. const ct_data *stree = desc->stat_desc->static_tree;
  85169. const intf *extra = desc->stat_desc->extra_bits;
  85170. int base = desc->stat_desc->extra_base;
  85171. int max_length = desc->stat_desc->max_length;
  85172. int h; /* heap index */
  85173. int n, m; /* iterate over the tree elements */
  85174. int bits; /* bit length */
  85175. int xbits; /* extra bits */
  85176. ush f; /* frequency */
  85177. int overflow = 0; /* number of elements with bit length too large */
  85178. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85179. /* In a first pass, compute the optimal bit lengths (which may
  85180. * overflow in the case of the bit length tree).
  85181. */
  85182. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85183. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85184. n = s->heap[h];
  85185. bits = tree[tree[n].Dad].Len + 1;
  85186. if (bits > max_length) bits = max_length, overflow++;
  85187. tree[n].Len = (ush)bits;
  85188. /* We overwrite tree[n].Dad which is no longer needed */
  85189. if (n > max_code) continue; /* not a leaf node */
  85190. s->bl_count[bits]++;
  85191. xbits = 0;
  85192. if (n >= base) xbits = extra[n-base];
  85193. f = tree[n].Freq;
  85194. s->opt_len += (ulg)f * (bits + xbits);
  85195. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85196. }
  85197. if (overflow == 0) return;
  85198. Trace((stderr,"\nbit length overflow\n"));
  85199. /* This happens for example on obj2 and pic of the Calgary corpus */
  85200. /* Find the first bit length which could increase: */
  85201. do {
  85202. bits = max_length-1;
  85203. while (s->bl_count[bits] == 0) bits--;
  85204. s->bl_count[bits]--; /* move one leaf down the tree */
  85205. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85206. s->bl_count[max_length]--;
  85207. /* The brother of the overflow item also moves one step up,
  85208. * but this does not affect bl_count[max_length]
  85209. */
  85210. overflow -= 2;
  85211. } while (overflow > 0);
  85212. /* Now recompute all bit lengths, scanning in increasing frequency.
  85213. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85214. * lengths instead of fixing only the wrong ones. This idea is taken
  85215. * from 'ar' written by Haruhiko Okumura.)
  85216. */
  85217. for (bits = max_length; bits != 0; bits--) {
  85218. n = s->bl_count[bits];
  85219. while (n != 0) {
  85220. m = s->heap[--h];
  85221. if (m > max_code) continue;
  85222. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85223. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85224. s->opt_len += ((long)bits - (long)tree[m].Len)
  85225. *(long)tree[m].Freq;
  85226. tree[m].Len = (ush)bits;
  85227. }
  85228. n--;
  85229. }
  85230. }
  85231. }
  85232. /* ===========================================================================
  85233. * Generate the codes for a given tree and bit counts (which need not be
  85234. * optimal).
  85235. * IN assertion: the array bl_count contains the bit length statistics for
  85236. * the given tree and the field len is set for all tree elements.
  85237. * OUT assertion: the field code is set for all tree elements of non
  85238. * zero code length.
  85239. */
  85240. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85241. int max_code, /* largest code with non zero frequency */
  85242. ushf *bl_count) /* number of codes at each bit length */
  85243. {
  85244. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85245. ush code = 0; /* running code value */
  85246. int bits; /* bit index */
  85247. int n; /* code index */
  85248. /* The distribution counts are first used to generate the code values
  85249. * without bit reversal.
  85250. */
  85251. for (bits = 1; bits <= MAX_BITS; bits++) {
  85252. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85253. }
  85254. /* Check that the bit counts in bl_count are consistent. The last code
  85255. * must be all ones.
  85256. */
  85257. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85258. "inconsistent bit counts");
  85259. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85260. for (n = 0; n <= max_code; n++) {
  85261. int len = tree[n].Len;
  85262. if (len == 0) continue;
  85263. /* Now reverse the bits */
  85264. tree[n].Code = bi_reverse(next_code[len]++, len);
  85265. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85266. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85267. }
  85268. }
  85269. /* ===========================================================================
  85270. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85271. * Update the total bit length for the current block.
  85272. * IN assertion: the field freq is set for all tree elements.
  85273. * OUT assertions: the fields len and code are set to the optimal bit length
  85274. * and corresponding code. The length opt_len is updated; static_len is
  85275. * also updated if stree is not null. The field max_code is set.
  85276. */
  85277. local void build_tree (deflate_state *s,
  85278. tree_desc *desc) /* the tree descriptor */
  85279. {
  85280. ct_data *tree = desc->dyn_tree;
  85281. const ct_data *stree = desc->stat_desc->static_tree;
  85282. int elems = desc->stat_desc->elems;
  85283. int n, m; /* iterate over heap elements */
  85284. int max_code = -1; /* largest code with non zero frequency */
  85285. int node; /* new node being created */
  85286. /* Construct the initial heap, with least frequent element in
  85287. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85288. * heap[0] is not used.
  85289. */
  85290. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85291. for (n = 0; n < elems; n++) {
  85292. if (tree[n].Freq != 0) {
  85293. s->heap[++(s->heap_len)] = max_code = n;
  85294. s->depth[n] = 0;
  85295. } else {
  85296. tree[n].Len = 0;
  85297. }
  85298. }
  85299. /* The pkzip format requires that at least one distance code exists,
  85300. * and that at least one bit should be sent even if there is only one
  85301. * possible code. So to avoid special checks later on we force at least
  85302. * two codes of non zero frequency.
  85303. */
  85304. while (s->heap_len < 2) {
  85305. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85306. tree[node].Freq = 1;
  85307. s->depth[node] = 0;
  85308. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85309. /* node is 0 or 1 so it does not have extra bits */
  85310. }
  85311. desc->max_code = max_code;
  85312. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85313. * establish sub-heaps of increasing lengths:
  85314. */
  85315. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85316. /* Construct the Huffman tree by repeatedly combining the least two
  85317. * frequent nodes.
  85318. */
  85319. node = elems; /* next internal node of the tree */
  85320. do {
  85321. pqremove(s, tree, n); /* n = node of least frequency */
  85322. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85323. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85324. s->heap[--(s->heap_max)] = m;
  85325. /* Create a new node father of n and m */
  85326. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85327. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85328. s->depth[n] : s->depth[m]) + 1);
  85329. tree[n].Dad = tree[m].Dad = (ush)node;
  85330. #ifdef DUMP_BL_TREE
  85331. if (tree == s->bl_tree) {
  85332. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85333. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85334. }
  85335. #endif
  85336. /* and insert the new node in the heap */
  85337. s->heap[SMALLEST] = node++;
  85338. pqdownheap(s, tree, SMALLEST);
  85339. } while (s->heap_len >= 2);
  85340. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85341. /* At this point, the fields freq and dad are set. We can now
  85342. * generate the bit lengths.
  85343. */
  85344. gen_bitlen(s, (tree_desc *)desc);
  85345. /* The field len is now set, we can generate the bit codes */
  85346. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85347. }
  85348. /* ===========================================================================
  85349. * Scan a literal or distance tree to determine the frequencies of the codes
  85350. * in the bit length tree.
  85351. */
  85352. local void scan_tree (deflate_state *s,
  85353. ct_data *tree, /* the tree to be scanned */
  85354. int max_code) /* and its largest code of non zero frequency */
  85355. {
  85356. int n; /* iterates over all tree elements */
  85357. int prevlen = -1; /* last emitted length */
  85358. int curlen; /* length of current code */
  85359. int nextlen = tree[0].Len; /* length of next code */
  85360. int count = 0; /* repeat count of the current code */
  85361. int max_count = 7; /* max repeat count */
  85362. int min_count = 4; /* min repeat count */
  85363. if (nextlen == 0) max_count = 138, min_count = 3;
  85364. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85365. for (n = 0; n <= max_code; n++) {
  85366. curlen = nextlen; nextlen = tree[n+1].Len;
  85367. if (++count < max_count && curlen == nextlen) {
  85368. continue;
  85369. } else if (count < min_count) {
  85370. s->bl_tree[curlen].Freq += count;
  85371. } else if (curlen != 0) {
  85372. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85373. s->bl_tree[REP_3_6].Freq++;
  85374. } else if (count <= 10) {
  85375. s->bl_tree[REPZ_3_10].Freq++;
  85376. } else {
  85377. s->bl_tree[REPZ_11_138].Freq++;
  85378. }
  85379. count = 0; prevlen = curlen;
  85380. if (nextlen == 0) {
  85381. max_count = 138, min_count = 3;
  85382. } else if (curlen == nextlen) {
  85383. max_count = 6, min_count = 3;
  85384. } else {
  85385. max_count = 7, min_count = 4;
  85386. }
  85387. }
  85388. }
  85389. /* ===========================================================================
  85390. * Send a literal or distance tree in compressed form, using the codes in
  85391. * bl_tree.
  85392. */
  85393. local void send_tree (deflate_state *s,
  85394. ct_data *tree, /* the tree to be scanned */
  85395. int max_code) /* and its largest code of non zero frequency */
  85396. {
  85397. int n; /* iterates over all tree elements */
  85398. int prevlen = -1; /* last emitted length */
  85399. int curlen; /* length of current code */
  85400. int nextlen = tree[0].Len; /* length of next code */
  85401. int count = 0; /* repeat count of the current code */
  85402. int max_count = 7; /* max repeat count */
  85403. int min_count = 4; /* min repeat count */
  85404. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85405. if (nextlen == 0) max_count = 138, min_count = 3;
  85406. for (n = 0; n <= max_code; n++) {
  85407. curlen = nextlen; nextlen = tree[n+1].Len;
  85408. if (++count < max_count && curlen == nextlen) {
  85409. continue;
  85410. } else if (count < min_count) {
  85411. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85412. } else if (curlen != 0) {
  85413. if (curlen != prevlen) {
  85414. send_code(s, curlen, s->bl_tree); count--;
  85415. }
  85416. Assert(count >= 3 && count <= 6, " 3_6?");
  85417. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85418. } else if (count <= 10) {
  85419. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85420. } else {
  85421. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85422. }
  85423. count = 0; prevlen = curlen;
  85424. if (nextlen == 0) {
  85425. max_count = 138, min_count = 3;
  85426. } else if (curlen == nextlen) {
  85427. max_count = 6, min_count = 3;
  85428. } else {
  85429. max_count = 7, min_count = 4;
  85430. }
  85431. }
  85432. }
  85433. /* ===========================================================================
  85434. * Construct the Huffman tree for the bit lengths and return the index in
  85435. * bl_order of the last bit length code to send.
  85436. */
  85437. local int build_bl_tree (deflate_state *s)
  85438. {
  85439. int max_blindex; /* index of last bit length code of non zero freq */
  85440. /* Determine the bit length frequencies for literal and distance trees */
  85441. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85442. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85443. /* Build the bit length tree: */
  85444. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85445. /* opt_len now includes the length of the tree representations, except
  85446. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85447. */
  85448. /* Determine the number of bit length codes to send. The pkzip format
  85449. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85450. * 3 but the actual value used is 4.)
  85451. */
  85452. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85453. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85454. }
  85455. /* Update opt_len to include the bit length tree and counts */
  85456. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85457. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85458. s->opt_len, s->static_len));
  85459. return max_blindex;
  85460. }
  85461. /* ===========================================================================
  85462. * Send the header for a block using dynamic Huffman trees: the counts, the
  85463. * lengths of the bit length codes, the literal tree and the distance tree.
  85464. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85465. */
  85466. local void send_all_trees (deflate_state *s,
  85467. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85468. {
  85469. int rank; /* index in bl_order */
  85470. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85471. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85472. "too many codes");
  85473. Tracev((stderr, "\nbl counts: "));
  85474. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85475. send_bits(s, dcodes-1, 5);
  85476. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85477. for (rank = 0; rank < blcodes; rank++) {
  85478. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85479. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85480. }
  85481. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85482. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85483. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85484. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85485. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85486. }
  85487. /* ===========================================================================
  85488. * Send a stored block
  85489. */
  85490. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85491. {
  85492. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85493. #ifdef DEBUG
  85494. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85495. s->compressed_len += (stored_len + 4) << 3;
  85496. #endif
  85497. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85498. }
  85499. /* ===========================================================================
  85500. * Send one empty static block to give enough lookahead for inflate.
  85501. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85502. * The current inflate code requires 9 bits of lookahead. If the
  85503. * last two codes for the previous block (real code plus EOB) were coded
  85504. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85505. * the last real code. In this case we send two empty static blocks instead
  85506. * of one. (There are no problems if the previous block is stored or fixed.)
  85507. * To simplify the code, we assume the worst case of last real code encoded
  85508. * on one bit only.
  85509. */
  85510. void _tr_align (deflate_state *s)
  85511. {
  85512. send_bits(s, STATIC_TREES<<1, 3);
  85513. send_code(s, END_BLOCK, static_ltree);
  85514. #ifdef DEBUG
  85515. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85516. #endif
  85517. bi_flush(s);
  85518. /* Of the 10 bits for the empty block, we have already sent
  85519. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85520. * the EOB of the previous block) was thus at least one plus the length
  85521. * of the EOB plus what we have just sent of the empty static block.
  85522. */
  85523. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85524. send_bits(s, STATIC_TREES<<1, 3);
  85525. send_code(s, END_BLOCK, static_ltree);
  85526. #ifdef DEBUG
  85527. s->compressed_len += 10L;
  85528. #endif
  85529. bi_flush(s);
  85530. }
  85531. s->last_eob_len = 7;
  85532. }
  85533. /* ===========================================================================
  85534. * Determine the best encoding for the current block: dynamic trees, static
  85535. * trees or store, and output the encoded block to the zip file.
  85536. */
  85537. void _tr_flush_block (deflate_state *s,
  85538. charf *buf, /* input block, or NULL if too old */
  85539. ulg stored_len, /* length of input block */
  85540. int eof) /* true if this is the last block for a file */
  85541. {
  85542. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85543. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85544. /* Build the Huffman trees unless a stored block is forced */
  85545. if (s->level > 0) {
  85546. /* Check if the file is binary or text */
  85547. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85548. set_data_type(s);
  85549. /* Construct the literal and distance trees */
  85550. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85551. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85552. s->static_len));
  85553. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85554. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85555. s->static_len));
  85556. /* At this point, opt_len and static_len are the total bit lengths of
  85557. * the compressed block data, excluding the tree representations.
  85558. */
  85559. /* Build the bit length tree for the above two trees, and get the index
  85560. * in bl_order of the last bit length code to send.
  85561. */
  85562. max_blindex = build_bl_tree(s);
  85563. /* Determine the best encoding. Compute the block lengths in bytes. */
  85564. opt_lenb = (s->opt_len+3+7)>>3;
  85565. static_lenb = (s->static_len+3+7)>>3;
  85566. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85567. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85568. s->last_lit));
  85569. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85570. } else {
  85571. Assert(buf != (char*)0, "lost buf");
  85572. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85573. }
  85574. #ifdef FORCE_STORED
  85575. if (buf != (char*)0) { /* force stored block */
  85576. #else
  85577. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85578. /* 4: two words for the lengths */
  85579. #endif
  85580. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85581. * Otherwise we can't have processed more than WSIZE input bytes since
  85582. * the last block flush, because compression would have been
  85583. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85584. * transform a block into a stored block.
  85585. */
  85586. _tr_stored_block(s, buf, stored_len, eof);
  85587. #ifdef FORCE_STATIC
  85588. } else if (static_lenb >= 0) { /* force static trees */
  85589. #else
  85590. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85591. #endif
  85592. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85593. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85594. #ifdef DEBUG
  85595. s->compressed_len += 3 + s->static_len;
  85596. #endif
  85597. } else {
  85598. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85599. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85600. max_blindex+1);
  85601. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85602. #ifdef DEBUG
  85603. s->compressed_len += 3 + s->opt_len;
  85604. #endif
  85605. }
  85606. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85607. /* The above check is made mod 2^32, for files larger than 512 MB
  85608. * and uLong implemented on 32 bits.
  85609. */
  85610. init_block(s);
  85611. if (eof) {
  85612. bi_windup(s);
  85613. #ifdef DEBUG
  85614. s->compressed_len += 7; /* align on byte boundary */
  85615. #endif
  85616. }
  85617. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85618. s->compressed_len-7*eof));
  85619. }
  85620. /* ===========================================================================
  85621. * Save the match info and tally the frequency counts. Return true if
  85622. * the current block must be flushed.
  85623. */
  85624. int _tr_tally (deflate_state *s,
  85625. unsigned dist, /* distance of matched string */
  85626. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85627. {
  85628. s->d_buf[s->last_lit] = (ush)dist;
  85629. s->l_buf[s->last_lit++] = (uch)lc;
  85630. if (dist == 0) {
  85631. /* lc is the unmatched char */
  85632. s->dyn_ltree[lc].Freq++;
  85633. } else {
  85634. s->matches++;
  85635. /* Here, lc is the match length - MIN_MATCH */
  85636. dist--; /* dist = match distance - 1 */
  85637. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85638. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85639. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85640. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85641. s->dyn_dtree[d_code(dist)].Freq++;
  85642. }
  85643. #ifdef TRUNCATE_BLOCK
  85644. /* Try to guess if it is profitable to stop the current block here */
  85645. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85646. /* Compute an upper bound for the compressed length */
  85647. ulg out_length = (ulg)s->last_lit*8L;
  85648. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85649. int dcode;
  85650. for (dcode = 0; dcode < D_CODES; dcode++) {
  85651. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85652. (5L+extra_dbits[dcode]);
  85653. }
  85654. out_length >>= 3;
  85655. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85656. s->last_lit, in_length, out_length,
  85657. 100L - out_length*100L/in_length));
  85658. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85659. }
  85660. #endif
  85661. return (s->last_lit == s->lit_bufsize-1);
  85662. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85663. * on 16 bit machines and because stored blocks are restricted to
  85664. * 64K-1 bytes.
  85665. */
  85666. }
  85667. /* ===========================================================================
  85668. * Send the block data compressed using the given Huffman trees
  85669. */
  85670. local void compress_block (deflate_state *s,
  85671. ct_data *ltree, /* literal tree */
  85672. ct_data *dtree) /* distance tree */
  85673. {
  85674. unsigned dist; /* distance of matched string */
  85675. int lc; /* match length or unmatched char (if dist == 0) */
  85676. unsigned lx = 0; /* running index in l_buf */
  85677. unsigned code; /* the code to send */
  85678. int extra; /* number of extra bits to send */
  85679. if (s->last_lit != 0) do {
  85680. dist = s->d_buf[lx];
  85681. lc = s->l_buf[lx++];
  85682. if (dist == 0) {
  85683. send_code(s, lc, ltree); /* send a literal byte */
  85684. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85685. } else {
  85686. /* Here, lc is the match length - MIN_MATCH */
  85687. code = _length_code[lc];
  85688. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85689. extra = extra_lbits[code];
  85690. if (extra != 0) {
  85691. lc -= base_length[code];
  85692. send_bits(s, lc, extra); /* send the extra length bits */
  85693. }
  85694. dist--; /* dist is now the match distance - 1 */
  85695. code = d_code(dist);
  85696. Assert (code < D_CODES, "bad d_code");
  85697. send_code(s, code, dtree); /* send the distance code */
  85698. extra = extra_dbits[code];
  85699. if (extra != 0) {
  85700. dist -= base_dist[code];
  85701. send_bits(s, dist, extra); /* send the extra distance bits */
  85702. }
  85703. } /* literal or match pair ? */
  85704. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85705. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85706. "pendingBuf overflow");
  85707. } while (lx < s->last_lit);
  85708. send_code(s, END_BLOCK, ltree);
  85709. s->last_eob_len = ltree[END_BLOCK].Len;
  85710. }
  85711. /* ===========================================================================
  85712. * Set the data type to BINARY or TEXT, using a crude approximation:
  85713. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85714. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85715. * IN assertion: the fields Freq of dyn_ltree are set.
  85716. */
  85717. local void set_data_type (deflate_state *s)
  85718. {
  85719. int n;
  85720. for (n = 0; n < 9; n++)
  85721. if (s->dyn_ltree[n].Freq != 0)
  85722. break;
  85723. if (n == 9)
  85724. for (n = 14; n < 32; n++)
  85725. if (s->dyn_ltree[n].Freq != 0)
  85726. break;
  85727. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85728. }
  85729. /* ===========================================================================
  85730. * Reverse the first len bits of a code, using straightforward code (a faster
  85731. * method would use a table)
  85732. * IN assertion: 1 <= len <= 15
  85733. */
  85734. local unsigned bi_reverse (unsigned code, int len)
  85735. {
  85736. register unsigned res = 0;
  85737. do {
  85738. res |= code & 1;
  85739. code >>= 1, res <<= 1;
  85740. } while (--len > 0);
  85741. return res >> 1;
  85742. }
  85743. /* ===========================================================================
  85744. * Flush the bit buffer, keeping at most 7 bits in it.
  85745. */
  85746. local void bi_flush (deflate_state *s)
  85747. {
  85748. if (s->bi_valid == 16) {
  85749. put_short(s, s->bi_buf);
  85750. s->bi_buf = 0;
  85751. s->bi_valid = 0;
  85752. } else if (s->bi_valid >= 8) {
  85753. put_byte(s, (Byte)s->bi_buf);
  85754. s->bi_buf >>= 8;
  85755. s->bi_valid -= 8;
  85756. }
  85757. }
  85758. /* ===========================================================================
  85759. * Flush the bit buffer and align the output on a byte boundary
  85760. */
  85761. local void bi_windup (deflate_state *s)
  85762. {
  85763. if (s->bi_valid > 8) {
  85764. put_short(s, s->bi_buf);
  85765. } else if (s->bi_valid > 0) {
  85766. put_byte(s, (Byte)s->bi_buf);
  85767. }
  85768. s->bi_buf = 0;
  85769. s->bi_valid = 0;
  85770. #ifdef DEBUG
  85771. s->bits_sent = (s->bits_sent+7) & ~7;
  85772. #endif
  85773. }
  85774. /* ===========================================================================
  85775. * Copy a stored block, storing first the length and its
  85776. * one's complement if requested.
  85777. */
  85778. local void copy_block(deflate_state *s,
  85779. charf *buf, /* the input data */
  85780. unsigned len, /* its length */
  85781. int header) /* true if block header must be written */
  85782. {
  85783. bi_windup(s); /* align on byte boundary */
  85784. s->last_eob_len = 8; /* enough lookahead for inflate */
  85785. if (header) {
  85786. put_short(s, (ush)len);
  85787. put_short(s, (ush)~len);
  85788. #ifdef DEBUG
  85789. s->bits_sent += 2*16;
  85790. #endif
  85791. }
  85792. #ifdef DEBUG
  85793. s->bits_sent += (ulg)len<<3;
  85794. #endif
  85795. while (len--) {
  85796. put_byte(s, *buf++);
  85797. }
  85798. }
  85799. /*** End of inlined file: trees.c ***/
  85800. /*** Start of inlined file: zutil.c ***/
  85801. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85802. #ifndef NO_DUMMY_DECL
  85803. struct internal_state {int dummy;}; /* for buggy compilers */
  85804. #endif
  85805. const char * const z_errmsg[10] = {
  85806. "need dictionary", /* Z_NEED_DICT 2 */
  85807. "stream end", /* Z_STREAM_END 1 */
  85808. "", /* Z_OK 0 */
  85809. "file error", /* Z_ERRNO (-1) */
  85810. "stream error", /* Z_STREAM_ERROR (-2) */
  85811. "data error", /* Z_DATA_ERROR (-3) */
  85812. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85813. "buffer error", /* Z_BUF_ERROR (-5) */
  85814. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85815. ""};
  85816. /*const char * ZEXPORT zlibVersion()
  85817. {
  85818. return ZLIB_VERSION;
  85819. }
  85820. uLong ZEXPORT zlibCompileFlags()
  85821. {
  85822. uLong flags;
  85823. flags = 0;
  85824. switch (sizeof(uInt)) {
  85825. case 2: break;
  85826. case 4: flags += 1; break;
  85827. case 8: flags += 2; break;
  85828. default: flags += 3;
  85829. }
  85830. switch (sizeof(uLong)) {
  85831. case 2: break;
  85832. case 4: flags += 1 << 2; break;
  85833. case 8: flags += 2 << 2; break;
  85834. default: flags += 3 << 2;
  85835. }
  85836. switch (sizeof(voidpf)) {
  85837. case 2: break;
  85838. case 4: flags += 1 << 4; break;
  85839. case 8: flags += 2 << 4; break;
  85840. default: flags += 3 << 4;
  85841. }
  85842. switch (sizeof(z_off_t)) {
  85843. case 2: break;
  85844. case 4: flags += 1 << 6; break;
  85845. case 8: flags += 2 << 6; break;
  85846. default: flags += 3 << 6;
  85847. }
  85848. #ifdef DEBUG
  85849. flags += 1 << 8;
  85850. #endif
  85851. #if defined(ASMV) || defined(ASMINF)
  85852. flags += 1 << 9;
  85853. #endif
  85854. #ifdef ZLIB_WINAPI
  85855. flags += 1 << 10;
  85856. #endif
  85857. #ifdef BUILDFIXED
  85858. flags += 1 << 12;
  85859. #endif
  85860. #ifdef DYNAMIC_CRC_TABLE
  85861. flags += 1 << 13;
  85862. #endif
  85863. #ifdef NO_GZCOMPRESS
  85864. flags += 1L << 16;
  85865. #endif
  85866. #ifdef NO_GZIP
  85867. flags += 1L << 17;
  85868. #endif
  85869. #ifdef PKZIP_BUG_WORKAROUND
  85870. flags += 1L << 20;
  85871. #endif
  85872. #ifdef FASTEST
  85873. flags += 1L << 21;
  85874. #endif
  85875. #ifdef STDC
  85876. # ifdef NO_vsnprintf
  85877. flags += 1L << 25;
  85878. # ifdef HAS_vsprintf_void
  85879. flags += 1L << 26;
  85880. # endif
  85881. # else
  85882. # ifdef HAS_vsnprintf_void
  85883. flags += 1L << 26;
  85884. # endif
  85885. # endif
  85886. #else
  85887. flags += 1L << 24;
  85888. # ifdef NO_snprintf
  85889. flags += 1L << 25;
  85890. # ifdef HAS_sprintf_void
  85891. flags += 1L << 26;
  85892. # endif
  85893. # else
  85894. # ifdef HAS_snprintf_void
  85895. flags += 1L << 26;
  85896. # endif
  85897. # endif
  85898. #endif
  85899. return flags;
  85900. }*/
  85901. #ifdef DEBUG
  85902. # ifndef verbose
  85903. # define verbose 0
  85904. # endif
  85905. int z_verbose = verbose;
  85906. void z_error (const char *m)
  85907. {
  85908. fprintf(stderr, "%s\n", m);
  85909. exit(1);
  85910. }
  85911. #endif
  85912. /* exported to allow conversion of error code to string for compress() and
  85913. * uncompress()
  85914. */
  85915. const char * ZEXPORT zError(int err)
  85916. {
  85917. return ERR_MSG(err);
  85918. }
  85919. #if defined(_WIN32_WCE)
  85920. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85921. * errno. We define it as a global variable to simplify porting.
  85922. * Its value is always 0 and should not be used.
  85923. */
  85924. int errno = 0;
  85925. #endif
  85926. #ifndef HAVE_MEMCPY
  85927. void zmemcpy(dest, source, len)
  85928. Bytef* dest;
  85929. const Bytef* source;
  85930. uInt len;
  85931. {
  85932. if (len == 0) return;
  85933. do {
  85934. *dest++ = *source++; /* ??? to be unrolled */
  85935. } while (--len != 0);
  85936. }
  85937. int zmemcmp(s1, s2, len)
  85938. const Bytef* s1;
  85939. const Bytef* s2;
  85940. uInt len;
  85941. {
  85942. uInt j;
  85943. for (j = 0; j < len; j++) {
  85944. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85945. }
  85946. return 0;
  85947. }
  85948. void zmemzero(dest, len)
  85949. Bytef* dest;
  85950. uInt len;
  85951. {
  85952. if (len == 0) return;
  85953. do {
  85954. *dest++ = 0; /* ??? to be unrolled */
  85955. } while (--len != 0);
  85956. }
  85957. #endif
  85958. #ifdef SYS16BIT
  85959. #ifdef __TURBOC__
  85960. /* Turbo C in 16-bit mode */
  85961. # define MY_ZCALLOC
  85962. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85963. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85964. * must fix the pointer. Warning: the pointer must be put back to its
  85965. * original form in order to free it, use zcfree().
  85966. */
  85967. #define MAX_PTR 10
  85968. /* 10*64K = 640K */
  85969. local int next_ptr = 0;
  85970. typedef struct ptr_table_s {
  85971. voidpf org_ptr;
  85972. voidpf new_ptr;
  85973. } ptr_table;
  85974. local ptr_table table[MAX_PTR];
  85975. /* This table is used to remember the original form of pointers
  85976. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85977. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85978. * protected from concurrent access. This hack doesn't work anyway on
  85979. * a protected system like OS/2. Use Microsoft C instead.
  85980. */
  85981. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85982. {
  85983. voidpf buf = opaque; /* just to make some compilers happy */
  85984. ulg bsize = (ulg)items*size;
  85985. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85986. * will return a usable pointer which doesn't have to be normalized.
  85987. */
  85988. if (bsize < 65520L) {
  85989. buf = farmalloc(bsize);
  85990. if (*(ush*)&buf != 0) return buf;
  85991. } else {
  85992. buf = farmalloc(bsize + 16L);
  85993. }
  85994. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85995. table[next_ptr].org_ptr = buf;
  85996. /* Normalize the pointer to seg:0 */
  85997. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85998. *(ush*)&buf = 0;
  85999. table[next_ptr++].new_ptr = buf;
  86000. return buf;
  86001. }
  86002. void zcfree (voidpf opaque, voidpf ptr)
  86003. {
  86004. int n;
  86005. if (*(ush*)&ptr != 0) { /* object < 64K */
  86006. farfree(ptr);
  86007. return;
  86008. }
  86009. /* Find the original pointer */
  86010. for (n = 0; n < next_ptr; n++) {
  86011. if (ptr != table[n].new_ptr) continue;
  86012. farfree(table[n].org_ptr);
  86013. while (++n < next_ptr) {
  86014. table[n-1] = table[n];
  86015. }
  86016. next_ptr--;
  86017. return;
  86018. }
  86019. ptr = opaque; /* just to make some compilers happy */
  86020. Assert(0, "zcfree: ptr not found");
  86021. }
  86022. #endif /* __TURBOC__ */
  86023. #ifdef M_I86
  86024. /* Microsoft C in 16-bit mode */
  86025. # define MY_ZCALLOC
  86026. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86027. # define _halloc halloc
  86028. # define _hfree hfree
  86029. #endif
  86030. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86031. {
  86032. if (opaque) opaque = 0; /* to make compiler happy */
  86033. return _halloc((long)items, size);
  86034. }
  86035. void zcfree (voidpf opaque, voidpf ptr)
  86036. {
  86037. if (opaque) opaque = 0; /* to make compiler happy */
  86038. _hfree(ptr);
  86039. }
  86040. #endif /* M_I86 */
  86041. #endif /* SYS16BIT */
  86042. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86043. #ifndef STDC
  86044. extern voidp malloc OF((uInt size));
  86045. extern voidp calloc OF((uInt items, uInt size));
  86046. extern void free OF((voidpf ptr));
  86047. #endif
  86048. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86049. {
  86050. if (opaque) items += size - size; /* make compiler happy */
  86051. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86052. (voidpf)calloc(items, size);
  86053. }
  86054. void zcfree (voidpf opaque, voidpf ptr)
  86055. {
  86056. free(ptr);
  86057. if (opaque) return; /* make compiler happy */
  86058. }
  86059. #endif /* MY_ZCALLOC */
  86060. /*** End of inlined file: zutil.c ***/
  86061. #undef Byte
  86062. #else
  86063. #include <zlib.h>
  86064. #endif
  86065. }
  86066. #if JUCE_MSVC
  86067. #pragma warning (pop)
  86068. #endif
  86069. BEGIN_JUCE_NAMESPACE
  86070. // internal helper object that holds the zlib structures so they don't have to be
  86071. // included publicly.
  86072. class GZIPDecompressHelper
  86073. {
  86074. public:
  86075. GZIPDecompressHelper (const bool noWrap)
  86076. : finished (true),
  86077. needsDictionary (false),
  86078. error (true),
  86079. streamIsValid (false),
  86080. data (0),
  86081. dataSize (0)
  86082. {
  86083. using namespace zlibNamespace;
  86084. zerostruct (stream);
  86085. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86086. finished = error = ! streamIsValid;
  86087. }
  86088. ~GZIPDecompressHelper()
  86089. {
  86090. using namespace zlibNamespace;
  86091. if (streamIsValid)
  86092. inflateEnd (&stream);
  86093. }
  86094. bool needsInput() const throw() { return dataSize <= 0; }
  86095. void setInput (uint8* const data_, const int size) throw()
  86096. {
  86097. data = data_;
  86098. dataSize = size;
  86099. }
  86100. int doNextBlock (uint8* const dest, const int destSize)
  86101. {
  86102. using namespace zlibNamespace;
  86103. if (streamIsValid && data != 0 && ! finished)
  86104. {
  86105. stream.next_in = data;
  86106. stream.next_out = dest;
  86107. stream.avail_in = dataSize;
  86108. stream.avail_out = destSize;
  86109. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86110. {
  86111. case Z_STREAM_END:
  86112. finished = true;
  86113. // deliberate fall-through
  86114. case Z_OK:
  86115. data += dataSize - stream.avail_in;
  86116. dataSize = stream.avail_in;
  86117. return destSize - stream.avail_out;
  86118. case Z_NEED_DICT:
  86119. needsDictionary = true;
  86120. data += dataSize - stream.avail_in;
  86121. dataSize = stream.avail_in;
  86122. break;
  86123. case Z_DATA_ERROR:
  86124. case Z_MEM_ERROR:
  86125. error = true;
  86126. default:
  86127. break;
  86128. }
  86129. }
  86130. return 0;
  86131. }
  86132. bool finished, needsDictionary, error, streamIsValid;
  86133. private:
  86134. zlibNamespace::z_stream stream;
  86135. uint8* data;
  86136. int dataSize;
  86137. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86138. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86139. };
  86140. const int gzipDecompBufferSize = 32768;
  86141. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86142. const bool deleteSourceWhenDestroyed,
  86143. const bool noWrap_,
  86144. const int64 uncompressedStreamLength_)
  86145. : sourceStream (sourceStream_),
  86146. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86147. uncompressedStreamLength (uncompressedStreamLength_),
  86148. noWrap (noWrap_),
  86149. isEof (false),
  86150. activeBufferSize (0),
  86151. originalSourcePos (sourceStream_->getPosition()),
  86152. currentPos (0),
  86153. buffer (gzipDecompBufferSize),
  86154. helper (new GZIPDecompressHelper (noWrap_))
  86155. {
  86156. }
  86157. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86158. {
  86159. }
  86160. int64 GZIPDecompressorInputStream::getTotalLength()
  86161. {
  86162. return uncompressedStreamLength;
  86163. }
  86164. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86165. {
  86166. if ((howMany > 0) && ! isEof)
  86167. {
  86168. jassert (destBuffer != 0);
  86169. if (destBuffer != 0)
  86170. {
  86171. int numRead = 0;
  86172. uint8* d = static_cast <uint8*> (destBuffer);
  86173. while (! helper->error)
  86174. {
  86175. const int n = helper->doNextBlock (d, howMany);
  86176. currentPos += n;
  86177. if (n == 0)
  86178. {
  86179. if (helper->finished || helper->needsDictionary)
  86180. {
  86181. isEof = true;
  86182. return numRead;
  86183. }
  86184. if (helper->needsInput())
  86185. {
  86186. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86187. if (activeBufferSize > 0)
  86188. {
  86189. helper->setInput (buffer, activeBufferSize);
  86190. }
  86191. else
  86192. {
  86193. isEof = true;
  86194. return numRead;
  86195. }
  86196. }
  86197. }
  86198. else
  86199. {
  86200. numRead += n;
  86201. howMany -= n;
  86202. d += n;
  86203. if (howMany <= 0)
  86204. return numRead;
  86205. }
  86206. }
  86207. }
  86208. }
  86209. return 0;
  86210. }
  86211. bool GZIPDecompressorInputStream::isExhausted()
  86212. {
  86213. return helper->error || isEof;
  86214. }
  86215. int64 GZIPDecompressorInputStream::getPosition()
  86216. {
  86217. return currentPos;
  86218. }
  86219. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86220. {
  86221. if (newPos < currentPos)
  86222. {
  86223. // to go backwards, reset the stream and start again..
  86224. isEof = false;
  86225. activeBufferSize = 0;
  86226. currentPos = 0;
  86227. helper = new GZIPDecompressHelper (noWrap);
  86228. sourceStream->setPosition (originalSourcePos);
  86229. }
  86230. skipNextBytes (newPos - currentPos);
  86231. return true;
  86232. }
  86233. END_JUCE_NAMESPACE
  86234. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86235. #endif
  86236. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86237. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86238. #if JUCE_USE_FLAC
  86239. #if JUCE_WINDOWS
  86240. #include <windows.h>
  86241. #endif
  86242. namespace FlacNamespace
  86243. {
  86244. #if JUCE_INCLUDE_FLAC_CODE
  86245. #if JUCE_MSVC
  86246. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86247. #endif
  86248. #define FLAC__NO_DLL 1
  86249. #if ! defined (SIZE_MAX)
  86250. #define SIZE_MAX 0xffffffff
  86251. #endif
  86252. #define __STDC_LIMIT_MACROS 1
  86253. /*** Start of inlined file: all.h ***/
  86254. #ifndef FLAC__ALL_H
  86255. #define FLAC__ALL_H
  86256. /*** Start of inlined file: export.h ***/
  86257. #ifndef FLAC__EXPORT_H
  86258. #define FLAC__EXPORT_H
  86259. /** \file include/FLAC/export.h
  86260. *
  86261. * \brief
  86262. * This module contains #defines and symbols for exporting function
  86263. * calls, and providing version information and compiled-in features.
  86264. *
  86265. * See the \link flac_export export \endlink module.
  86266. */
  86267. /** \defgroup flac_export FLAC/export.h: export symbols
  86268. * \ingroup flac
  86269. *
  86270. * \brief
  86271. * This module contains #defines and symbols for exporting function
  86272. * calls, and providing version information and compiled-in features.
  86273. *
  86274. * If you are compiling with MSVC and will link to the static library
  86275. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86276. * make sure the symbols are exported properly.
  86277. *
  86278. * \{
  86279. */
  86280. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86281. #define FLAC_API
  86282. #else
  86283. #ifdef FLAC_API_EXPORTS
  86284. #define FLAC_API _declspec(dllexport)
  86285. #else
  86286. #define FLAC_API _declspec(dllimport)
  86287. #endif
  86288. #endif
  86289. /** These #defines will mirror the libtool-based library version number, see
  86290. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86291. */
  86292. #define FLAC_API_VERSION_CURRENT 10
  86293. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86294. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86295. #ifdef __cplusplus
  86296. extern "C" {
  86297. #endif
  86298. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86299. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86300. #ifdef __cplusplus
  86301. }
  86302. #endif
  86303. /* \} */
  86304. #endif
  86305. /*** End of inlined file: export.h ***/
  86306. /*** Start of inlined file: assert.h ***/
  86307. #ifndef FLAC__ASSERT_H
  86308. #define FLAC__ASSERT_H
  86309. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86310. #ifdef DEBUG
  86311. #include <assert.h>
  86312. #define FLAC__ASSERT(x) assert(x)
  86313. #define FLAC__ASSERT_DECLARATION(x) x
  86314. #else
  86315. #define FLAC__ASSERT(x)
  86316. #define FLAC__ASSERT_DECLARATION(x)
  86317. #endif
  86318. #endif
  86319. /*** End of inlined file: assert.h ***/
  86320. /*** Start of inlined file: callback.h ***/
  86321. #ifndef FLAC__CALLBACK_H
  86322. #define FLAC__CALLBACK_H
  86323. /*** Start of inlined file: ordinals.h ***/
  86324. #ifndef FLAC__ORDINALS_H
  86325. #define FLAC__ORDINALS_H
  86326. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86327. #include <inttypes.h>
  86328. #endif
  86329. typedef signed char FLAC__int8;
  86330. typedef unsigned char FLAC__uint8;
  86331. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86332. typedef __int16 FLAC__int16;
  86333. typedef __int32 FLAC__int32;
  86334. typedef __int64 FLAC__int64;
  86335. typedef unsigned __int16 FLAC__uint16;
  86336. typedef unsigned __int32 FLAC__uint32;
  86337. typedef unsigned __int64 FLAC__uint64;
  86338. #elif defined(__EMX__)
  86339. typedef short FLAC__int16;
  86340. typedef long FLAC__int32;
  86341. typedef long long FLAC__int64;
  86342. typedef unsigned short FLAC__uint16;
  86343. typedef unsigned long FLAC__uint32;
  86344. typedef unsigned long long FLAC__uint64;
  86345. #else
  86346. typedef int16_t FLAC__int16;
  86347. typedef int32_t FLAC__int32;
  86348. typedef int64_t FLAC__int64;
  86349. typedef uint16_t FLAC__uint16;
  86350. typedef uint32_t FLAC__uint32;
  86351. typedef uint64_t FLAC__uint64;
  86352. #endif
  86353. typedef int FLAC__bool;
  86354. typedef FLAC__uint8 FLAC__byte;
  86355. #ifdef true
  86356. #undef true
  86357. #endif
  86358. #ifdef false
  86359. #undef false
  86360. #endif
  86361. #ifndef __cplusplus
  86362. #define true 1
  86363. #define false 0
  86364. #endif
  86365. #endif
  86366. /*** End of inlined file: ordinals.h ***/
  86367. #include <stdlib.h> /* for size_t */
  86368. /** \file include/FLAC/callback.h
  86369. *
  86370. * \brief
  86371. * This module defines the structures for describing I/O callbacks
  86372. * to the other FLAC interfaces.
  86373. *
  86374. * See the detailed documentation for callbacks in the
  86375. * \link flac_callbacks callbacks \endlink module.
  86376. */
  86377. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86378. * \ingroup flac
  86379. *
  86380. * \brief
  86381. * This module defines the structures for describing I/O callbacks
  86382. * to the other FLAC interfaces.
  86383. *
  86384. * The purpose of the I/O callback functions is to create a common way
  86385. * for the metadata interfaces to handle I/O.
  86386. *
  86387. * Originally the metadata interfaces required filenames as the way of
  86388. * specifying FLAC files to operate on. This is problematic in some
  86389. * environments so there is an additional option to specify a set of
  86390. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86391. *
  86392. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86393. * opaque structure for a data source.
  86394. *
  86395. * The callback function prototypes are similar (but not identical) to the
  86396. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86397. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86398. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86399. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86400. * is required. \warning You generally CANNOT directly use fseek or ftell
  86401. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86402. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86403. * large files. You will have to find an equivalent function (e.g. ftello),
  86404. * or write a wrapper. The same is true for feof() since this is usually
  86405. * implemented as a macro, not as a function whose address can be taken.
  86406. *
  86407. * \{
  86408. */
  86409. #ifdef __cplusplus
  86410. extern "C" {
  86411. #endif
  86412. /** This is the opaque handle type used by the callbacks. Typically
  86413. * this is a \c FILE* or address of a file descriptor.
  86414. */
  86415. typedef void* FLAC__IOHandle;
  86416. /** Signature for the read callback.
  86417. * The signature and semantics match POSIX fread() implementations
  86418. * and can generally be used interchangeably.
  86419. *
  86420. * \param ptr The address of the read buffer.
  86421. * \param size The size of the records to be read.
  86422. * \param nmemb The number of records to be read.
  86423. * \param handle The handle to the data source.
  86424. * \retval size_t
  86425. * The number of records read.
  86426. */
  86427. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86428. /** Signature for the write callback.
  86429. * The signature and semantics match POSIX fwrite() implementations
  86430. * and can generally be used interchangeably.
  86431. *
  86432. * \param ptr The address of the write buffer.
  86433. * \param size The size of the records to be written.
  86434. * \param nmemb The number of records to be written.
  86435. * \param handle The handle to the data source.
  86436. * \retval size_t
  86437. * The number of records written.
  86438. */
  86439. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86440. /** Signature for the seek callback.
  86441. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86442. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86443. * and 32-bits wide.
  86444. *
  86445. * \param handle The handle to the data source.
  86446. * \param offset The new position, relative to \a whence
  86447. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86448. * \retval int
  86449. * \c 0 on success, \c -1 on error.
  86450. */
  86451. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86452. /** Signature for the tell callback.
  86453. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86454. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86455. * and 32-bits wide.
  86456. *
  86457. * \param handle The handle to the data source.
  86458. * \retval FLAC__int64
  86459. * The current position on success, \c -1 on error.
  86460. */
  86461. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86462. /** Signature for the EOF callback.
  86463. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86464. * on many systems, feof() is a macro, so in this case a wrapper function
  86465. * must be provided instead.
  86466. *
  86467. * \param handle The handle to the data source.
  86468. * \retval int
  86469. * \c 0 if not at end of file, nonzero if at end of file.
  86470. */
  86471. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86472. /** Signature for the close callback.
  86473. * The signature and semantics match POSIX fclose() implementations
  86474. * and can generally be used interchangeably.
  86475. *
  86476. * \param handle The handle to the data source.
  86477. * \retval int
  86478. * \c 0 on success, \c EOF on error.
  86479. */
  86480. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86481. /** A structure for holding a set of callbacks.
  86482. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86483. * describe which of the callbacks are required. The ones that are not
  86484. * required may be set to NULL.
  86485. *
  86486. * If the seek requirement for an interface is optional, you can signify that
  86487. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86488. */
  86489. typedef struct {
  86490. FLAC__IOCallback_Read read;
  86491. FLAC__IOCallback_Write write;
  86492. FLAC__IOCallback_Seek seek;
  86493. FLAC__IOCallback_Tell tell;
  86494. FLAC__IOCallback_Eof eof;
  86495. FLAC__IOCallback_Close close;
  86496. } FLAC__IOCallbacks;
  86497. /* \} */
  86498. #ifdef __cplusplus
  86499. }
  86500. #endif
  86501. #endif
  86502. /*** End of inlined file: callback.h ***/
  86503. /*** Start of inlined file: format.h ***/
  86504. #ifndef FLAC__FORMAT_H
  86505. #define FLAC__FORMAT_H
  86506. #ifdef __cplusplus
  86507. extern "C" {
  86508. #endif
  86509. /** \file include/FLAC/format.h
  86510. *
  86511. * \brief
  86512. * This module contains structure definitions for the representation
  86513. * of FLAC format components in memory. These are the basic
  86514. * structures used by the rest of the interfaces.
  86515. *
  86516. * See the detailed documentation in the
  86517. * \link flac_format format \endlink module.
  86518. */
  86519. /** \defgroup flac_format FLAC/format.h: format components
  86520. * \ingroup flac
  86521. *
  86522. * \brief
  86523. * This module contains structure definitions for the representation
  86524. * of FLAC format components in memory. These are the basic
  86525. * structures used by the rest of the interfaces.
  86526. *
  86527. * First, you should be familiar with the
  86528. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86529. * follow directly from the specification. As a user of libFLAC, the
  86530. * interesting parts really are the structures that describe the frame
  86531. * header and metadata blocks.
  86532. *
  86533. * The format structures here are very primitive, designed to store
  86534. * information in an efficient way. Reading information from the
  86535. * structures is easy but creating or modifying them directly is
  86536. * more complex. For the most part, as a user of a library, editing
  86537. * is not necessary; however, for metadata blocks it is, so there are
  86538. * convenience functions provided in the \link flac_metadata metadata
  86539. * module \endlink to simplify the manipulation of metadata blocks.
  86540. *
  86541. * \note
  86542. * It's not the best convention, but symbols ending in _LEN are in bits
  86543. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86544. * global variables because they are usually used when declaring byte
  86545. * arrays and some compilers require compile-time knowledge of array
  86546. * sizes when declared on the stack.
  86547. *
  86548. * \{
  86549. */
  86550. /*
  86551. Most of the values described in this file are defined by the FLAC
  86552. format specification. There is nothing to tune here.
  86553. */
  86554. /** The largest legal metadata type code. */
  86555. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86556. /** The minimum block size, in samples, permitted by the format. */
  86557. #define FLAC__MIN_BLOCK_SIZE (16u)
  86558. /** The maximum block size, in samples, permitted by the format. */
  86559. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86560. /** The maximum block size, in samples, permitted by the FLAC subset for
  86561. * sample rates up to 48kHz. */
  86562. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86563. /** The maximum number of channels permitted by the format. */
  86564. #define FLAC__MAX_CHANNELS (8u)
  86565. /** The minimum sample resolution permitted by the format. */
  86566. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86567. /** The maximum sample resolution permitted by the format. */
  86568. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86569. /** The maximum sample resolution permitted by libFLAC.
  86570. *
  86571. * \warning
  86572. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86573. * the reference encoder/decoder is currently limited to 24 bits because
  86574. * of prevalent 32-bit math, so make sure and use this value when
  86575. * appropriate.
  86576. */
  86577. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86578. /** The maximum sample rate permitted by the format. The value is
  86579. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86580. * as to why.
  86581. */
  86582. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86583. /** The maximum LPC order permitted by the format. */
  86584. #define FLAC__MAX_LPC_ORDER (32u)
  86585. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86586. * up to 48kHz. */
  86587. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86588. /** The minimum quantized linear predictor coefficient precision
  86589. * permitted by the format.
  86590. */
  86591. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86592. /** The maximum quantized linear predictor coefficient precision
  86593. * permitted by the format.
  86594. */
  86595. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86596. /** The maximum order of the fixed predictors permitted by the format. */
  86597. #define FLAC__MAX_FIXED_ORDER (4u)
  86598. /** The maximum Rice partition order permitted by the format. */
  86599. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86600. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86601. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86602. /** The version string of the release, stamped onto the libraries and binaries.
  86603. *
  86604. * \note
  86605. * This does not correspond to the shared library version number, which
  86606. * is used to determine binary compatibility.
  86607. */
  86608. extern FLAC_API const char *FLAC__VERSION_STRING;
  86609. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86610. * This is a NUL-terminated ASCII string; when inserted into the
  86611. * VORBIS_COMMENT the trailing null is stripped.
  86612. */
  86613. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86614. /** The byte string representation of the beginning of a FLAC stream. */
  86615. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86616. /** The 32-bit integer big-endian representation of the beginning of
  86617. * a FLAC stream.
  86618. */
  86619. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86620. /** The length of the FLAC signature in bits. */
  86621. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86622. /** The length of the FLAC signature in bytes. */
  86623. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86624. /*****************************************************************************
  86625. *
  86626. * Subframe structures
  86627. *
  86628. *****************************************************************************/
  86629. /*****************************************************************************/
  86630. /** An enumeration of the available entropy coding methods. */
  86631. typedef enum {
  86632. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86633. /**< Residual is coded by partitioning into contexts, each with it's own
  86634. * 4-bit Rice parameter. */
  86635. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86636. /**< Residual is coded by partitioning into contexts, each with it's own
  86637. * 5-bit Rice parameter. */
  86638. } FLAC__EntropyCodingMethodType;
  86639. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86640. *
  86641. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86642. * give the string equivalent. The contents should not be modified.
  86643. */
  86644. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86645. /** Contents of a Rice partitioned residual
  86646. */
  86647. typedef struct {
  86648. unsigned *parameters;
  86649. /**< The Rice parameters for each context. */
  86650. unsigned *raw_bits;
  86651. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86652. * partitions and zero for unescaped partitions.
  86653. */
  86654. unsigned capacity_by_order;
  86655. /**< The capacity of the \a parameters and \a raw_bits arrays
  86656. * specified as an order, i.e. the number of array elements
  86657. * allocated is 2 ^ \a capacity_by_order.
  86658. */
  86659. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86660. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86661. */
  86662. typedef struct {
  86663. unsigned order;
  86664. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86665. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86666. /**< The context's Rice parameters and/or raw bits. */
  86667. } FLAC__EntropyCodingMethod_PartitionedRice;
  86668. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86669. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86670. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86671. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86672. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86673. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86674. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86675. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86676. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86677. */
  86678. typedef struct {
  86679. FLAC__EntropyCodingMethodType type;
  86680. union {
  86681. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86682. } data;
  86683. } FLAC__EntropyCodingMethod;
  86684. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86685. /*****************************************************************************/
  86686. /** An enumeration of the available subframe types. */
  86687. typedef enum {
  86688. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86689. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86690. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86691. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86692. } FLAC__SubframeType;
  86693. /** Maps a FLAC__SubframeType to a C string.
  86694. *
  86695. * Using a FLAC__SubframeType as the index to this array will
  86696. * give the string equivalent. The contents should not be modified.
  86697. */
  86698. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86699. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86700. */
  86701. typedef struct {
  86702. FLAC__int32 value; /**< The constant signal value. */
  86703. } FLAC__Subframe_Constant;
  86704. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86705. */
  86706. typedef struct {
  86707. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86708. } FLAC__Subframe_Verbatim;
  86709. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86710. */
  86711. typedef struct {
  86712. FLAC__EntropyCodingMethod entropy_coding_method;
  86713. /**< The residual coding method. */
  86714. unsigned order;
  86715. /**< The polynomial order. */
  86716. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86717. /**< Warmup samples to prime the predictor, length == order. */
  86718. const FLAC__int32 *residual;
  86719. /**< The residual signal, length == (blocksize minus order) samples. */
  86720. } FLAC__Subframe_Fixed;
  86721. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86722. */
  86723. typedef struct {
  86724. FLAC__EntropyCodingMethod entropy_coding_method;
  86725. /**< The residual coding method. */
  86726. unsigned order;
  86727. /**< The FIR order. */
  86728. unsigned qlp_coeff_precision;
  86729. /**< Quantized FIR filter coefficient precision in bits. */
  86730. int quantization_level;
  86731. /**< The qlp coeff shift needed. */
  86732. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86733. /**< FIR filter coefficients. */
  86734. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86735. /**< Warmup samples to prime the predictor, length == order. */
  86736. const FLAC__int32 *residual;
  86737. /**< The residual signal, length == (blocksize minus order) samples. */
  86738. } FLAC__Subframe_LPC;
  86739. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86740. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86741. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86742. */
  86743. typedef struct {
  86744. FLAC__SubframeType type;
  86745. union {
  86746. FLAC__Subframe_Constant constant;
  86747. FLAC__Subframe_Fixed fixed;
  86748. FLAC__Subframe_LPC lpc;
  86749. FLAC__Subframe_Verbatim verbatim;
  86750. } data;
  86751. unsigned wasted_bits;
  86752. } FLAC__Subframe;
  86753. /** == 1 (bit)
  86754. *
  86755. * This used to be a zero-padding bit (hence the name
  86756. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86757. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86758. * to mean something else.
  86759. */
  86760. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86761. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86762. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86763. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86764. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86765. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86766. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86767. /*****************************************************************************/
  86768. /*****************************************************************************
  86769. *
  86770. * Frame structures
  86771. *
  86772. *****************************************************************************/
  86773. /** An enumeration of the available channel assignments. */
  86774. typedef enum {
  86775. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86776. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86777. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86778. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86779. } FLAC__ChannelAssignment;
  86780. /** Maps a FLAC__ChannelAssignment to a C string.
  86781. *
  86782. * Using a FLAC__ChannelAssignment as the index to this array will
  86783. * give the string equivalent. The contents should not be modified.
  86784. */
  86785. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86786. /** An enumeration of the possible frame numbering methods. */
  86787. typedef enum {
  86788. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86789. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86790. } FLAC__FrameNumberType;
  86791. /** Maps a FLAC__FrameNumberType to a C string.
  86792. *
  86793. * Using a FLAC__FrameNumberType as the index to this array will
  86794. * give the string equivalent. The contents should not be modified.
  86795. */
  86796. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86797. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86798. */
  86799. typedef struct {
  86800. unsigned blocksize;
  86801. /**< The number of samples per subframe. */
  86802. unsigned sample_rate;
  86803. /**< The sample rate in Hz. */
  86804. unsigned channels;
  86805. /**< The number of channels (== number of subframes). */
  86806. FLAC__ChannelAssignment channel_assignment;
  86807. /**< The channel assignment for the frame. */
  86808. unsigned bits_per_sample;
  86809. /**< The sample resolution. */
  86810. FLAC__FrameNumberType number_type;
  86811. /**< The numbering scheme used for the frame. As a convenience, the
  86812. * decoder will always convert a frame number to a sample number because
  86813. * the rules are complex. */
  86814. union {
  86815. FLAC__uint32 frame_number;
  86816. FLAC__uint64 sample_number;
  86817. } number;
  86818. /**< The frame number or sample number of first sample in frame;
  86819. * use the \a number_type value to determine which to use. */
  86820. FLAC__uint8 crc;
  86821. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86822. * of the raw frame header bytes, meaning everything before the CRC byte
  86823. * including the sync code.
  86824. */
  86825. } FLAC__FrameHeader;
  86826. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86827. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86828. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86829. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86830. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86831. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86832. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86833. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86834. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86835. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86836. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86837. */
  86838. typedef struct {
  86839. FLAC__uint16 crc;
  86840. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86841. * 0) of the bytes before the crc, back to and including the frame header
  86842. * sync code.
  86843. */
  86844. } FLAC__FrameFooter;
  86845. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86846. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86847. */
  86848. typedef struct {
  86849. FLAC__FrameHeader header;
  86850. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86851. FLAC__FrameFooter footer;
  86852. } FLAC__Frame;
  86853. /*****************************************************************************/
  86854. /*****************************************************************************
  86855. *
  86856. * Meta-data structures
  86857. *
  86858. *****************************************************************************/
  86859. /** An enumeration of the available metadata block types. */
  86860. typedef enum {
  86861. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86862. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86863. FLAC__METADATA_TYPE_PADDING = 1,
  86864. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86865. FLAC__METADATA_TYPE_APPLICATION = 2,
  86866. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86867. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86868. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86869. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86870. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86871. FLAC__METADATA_TYPE_CUESHEET = 5,
  86872. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86873. FLAC__METADATA_TYPE_PICTURE = 6,
  86874. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86875. FLAC__METADATA_TYPE_UNDEFINED = 7
  86876. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86877. } FLAC__MetadataType;
  86878. /** Maps a FLAC__MetadataType to a C string.
  86879. *
  86880. * Using a FLAC__MetadataType as the index to this array will
  86881. * give the string equivalent. The contents should not be modified.
  86882. */
  86883. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86884. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86885. */
  86886. typedef struct {
  86887. unsigned min_blocksize, max_blocksize;
  86888. unsigned min_framesize, max_framesize;
  86889. unsigned sample_rate;
  86890. unsigned channels;
  86891. unsigned bits_per_sample;
  86892. FLAC__uint64 total_samples;
  86893. FLAC__byte md5sum[16];
  86894. } FLAC__StreamMetadata_StreamInfo;
  86895. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86896. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86897. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86898. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86899. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86900. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86901. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86902. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86903. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86904. /** The total stream length of the STREAMINFO block in bytes. */
  86905. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86906. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86907. */
  86908. typedef struct {
  86909. int dummy;
  86910. /**< Conceptually this is an empty struct since we don't store the
  86911. * padding bytes. Empty structs are not allowed by some C compilers,
  86912. * hence the dummy.
  86913. */
  86914. } FLAC__StreamMetadata_Padding;
  86915. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86916. */
  86917. typedef struct {
  86918. FLAC__byte id[4];
  86919. FLAC__byte *data;
  86920. } FLAC__StreamMetadata_Application;
  86921. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86922. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86923. */
  86924. typedef struct {
  86925. FLAC__uint64 sample_number;
  86926. /**< The sample number of the target frame. */
  86927. FLAC__uint64 stream_offset;
  86928. /**< The offset, in bytes, of the target frame with respect to
  86929. * beginning of the first frame. */
  86930. unsigned frame_samples;
  86931. /**< The number of samples in the target frame. */
  86932. } FLAC__StreamMetadata_SeekPoint;
  86933. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86934. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86935. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86936. /** The total stream length of a seek point in bytes. */
  86937. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86938. /** The value used in the \a sample_number field of
  86939. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86940. * point (== 0xffffffffffffffff).
  86941. */
  86942. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86943. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86944. *
  86945. * \note From the format specification:
  86946. * - The seek points must be sorted by ascending sample number.
  86947. * - Each seek point's sample number must be the first sample of the
  86948. * target frame.
  86949. * - Each seek point's sample number must be unique within the table.
  86950. * - Existence of a SEEKTABLE block implies a correct setting of
  86951. * total_samples in the stream_info block.
  86952. * - Behavior is undefined when more than one SEEKTABLE block is
  86953. * present in a stream.
  86954. */
  86955. typedef struct {
  86956. unsigned num_points;
  86957. FLAC__StreamMetadata_SeekPoint *points;
  86958. } FLAC__StreamMetadata_SeekTable;
  86959. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86960. *
  86961. * For convenience, the APIs maintain a trailing NUL character at the end of
  86962. * \a entry which is not counted toward \a length, i.e.
  86963. * \code strlen(entry) == length \endcode
  86964. */
  86965. typedef struct {
  86966. FLAC__uint32 length;
  86967. FLAC__byte *entry;
  86968. } FLAC__StreamMetadata_VorbisComment_Entry;
  86969. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86970. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86971. */
  86972. typedef struct {
  86973. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86974. FLAC__uint32 num_comments;
  86975. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86976. } FLAC__StreamMetadata_VorbisComment;
  86977. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86978. /** FLAC CUESHEET track index structure. (See the
  86979. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86980. * the full description of each field.)
  86981. */
  86982. typedef struct {
  86983. FLAC__uint64 offset;
  86984. /**< Offset in samples, relative to the track offset, of the index
  86985. * point.
  86986. */
  86987. FLAC__byte number;
  86988. /**< The index point number. */
  86989. } FLAC__StreamMetadata_CueSheet_Index;
  86990. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86991. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86992. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86993. /** FLAC CUESHEET track structure. (See the
  86994. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86995. * the full description of each field.)
  86996. */
  86997. typedef struct {
  86998. FLAC__uint64 offset;
  86999. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87000. FLAC__byte number;
  87001. /**< The track number. */
  87002. char isrc[13];
  87003. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87004. unsigned type:1;
  87005. /**< The track type: 0 for audio, 1 for non-audio. */
  87006. unsigned pre_emphasis:1;
  87007. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87008. FLAC__byte num_indices;
  87009. /**< The number of track index points. */
  87010. FLAC__StreamMetadata_CueSheet_Index *indices;
  87011. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87012. } FLAC__StreamMetadata_CueSheet_Track;
  87013. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87014. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87015. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87016. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87017. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87018. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87019. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87020. /** FLAC CUESHEET structure. (See the
  87021. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87022. * for the full description of each field.)
  87023. */
  87024. typedef struct {
  87025. char media_catalog_number[129];
  87026. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87027. * general, the media catalog number may be 0 to 128 bytes long; any
  87028. * unused characters should be right-padded with NUL characters.
  87029. */
  87030. FLAC__uint64 lead_in;
  87031. /**< The number of lead-in samples. */
  87032. FLAC__bool is_cd;
  87033. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87034. unsigned num_tracks;
  87035. /**< The number of tracks. */
  87036. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87037. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87038. } FLAC__StreamMetadata_CueSheet;
  87039. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87040. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87041. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87042. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87043. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87044. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87045. typedef enum {
  87046. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87047. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87048. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87049. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87050. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87051. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87052. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87053. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87054. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87055. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87056. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87057. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87058. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87059. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87060. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87061. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87062. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87063. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87064. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87065. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87066. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87067. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87068. } FLAC__StreamMetadata_Picture_Type;
  87069. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87070. *
  87071. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87072. * will give the string equivalent. The contents should not be
  87073. * modified.
  87074. */
  87075. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87076. /** FLAC PICTURE structure. (See the
  87077. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87078. * for the full description of each field.)
  87079. */
  87080. typedef struct {
  87081. FLAC__StreamMetadata_Picture_Type type;
  87082. /**< The kind of picture stored. */
  87083. char *mime_type;
  87084. /**< Picture data's MIME type, in ASCII printable characters
  87085. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87086. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87087. * MIME type of '-->' is also allowed, in which case the picture
  87088. * data should be a complete URL. In file storage, the MIME type is
  87089. * stored as a 32-bit length followed by the ASCII string with no NUL
  87090. * terminator, but is converted to a plain C string in this structure
  87091. * for convenience.
  87092. */
  87093. FLAC__byte *description;
  87094. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87095. * the description is stored as a 32-bit length followed by the UTF-8
  87096. * string with no NUL terminator, but is converted to a plain C string
  87097. * in this structure for convenience.
  87098. */
  87099. FLAC__uint32 width;
  87100. /**< Picture's width in pixels. */
  87101. FLAC__uint32 height;
  87102. /**< Picture's height in pixels. */
  87103. FLAC__uint32 depth;
  87104. /**< Picture's color depth in bits-per-pixel. */
  87105. FLAC__uint32 colors;
  87106. /**< For indexed palettes (like GIF), picture's number of colors (the
  87107. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87108. */
  87109. FLAC__uint32 data_length;
  87110. /**< Length of binary picture data in bytes. */
  87111. FLAC__byte *data;
  87112. /**< Binary picture data. */
  87113. } FLAC__StreamMetadata_Picture;
  87114. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87115. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87116. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87117. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87118. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87119. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87120. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87121. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87122. /** Structure that is used when a metadata block of unknown type is loaded.
  87123. * The contents are opaque. The structure is used only internally to
  87124. * correctly handle unknown metadata.
  87125. */
  87126. typedef struct {
  87127. FLAC__byte *data;
  87128. } FLAC__StreamMetadata_Unknown;
  87129. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87130. */
  87131. typedef struct {
  87132. FLAC__MetadataType type;
  87133. /**< The type of the metadata block; used determine which member of the
  87134. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87135. * then \a data.unknown must be used. */
  87136. FLAC__bool is_last;
  87137. /**< \c true if this metadata block is the last, else \a false */
  87138. unsigned length;
  87139. /**< Length, in bytes, of the block data as it appears in the stream. */
  87140. union {
  87141. FLAC__StreamMetadata_StreamInfo stream_info;
  87142. FLAC__StreamMetadata_Padding padding;
  87143. FLAC__StreamMetadata_Application application;
  87144. FLAC__StreamMetadata_SeekTable seek_table;
  87145. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87146. FLAC__StreamMetadata_CueSheet cue_sheet;
  87147. FLAC__StreamMetadata_Picture picture;
  87148. FLAC__StreamMetadata_Unknown unknown;
  87149. } data;
  87150. /**< Polymorphic block data; use the \a type value to determine which
  87151. * to use. */
  87152. } FLAC__StreamMetadata;
  87153. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87154. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87155. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87156. /** The total stream length of a metadata block header in bytes. */
  87157. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87158. /*****************************************************************************/
  87159. /*****************************************************************************
  87160. *
  87161. * Utility functions
  87162. *
  87163. *****************************************************************************/
  87164. /** Tests that a sample rate is valid for FLAC.
  87165. *
  87166. * \param sample_rate The sample rate to test for compliance.
  87167. * \retval FLAC__bool
  87168. * \c true if the given sample rate conforms to the specification, else
  87169. * \c false.
  87170. */
  87171. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87172. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87173. * for valid sample rates are slightly more complex since the rate has to
  87174. * be expressible completely in the frame header.
  87175. *
  87176. * \param sample_rate The sample rate to test for compliance.
  87177. * \retval FLAC__bool
  87178. * \c true if the given sample rate conforms to the specification for the
  87179. * subset, else \c false.
  87180. */
  87181. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87182. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87183. * comment specification.
  87184. *
  87185. * Vorbis comment names must be composed only of characters from
  87186. * [0x20-0x3C,0x3E-0x7D].
  87187. *
  87188. * \param name A NUL-terminated string to be checked.
  87189. * \assert
  87190. * \code name != NULL \endcode
  87191. * \retval FLAC__bool
  87192. * \c false if entry name is illegal, else \c true.
  87193. */
  87194. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87195. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87196. * comment specification.
  87197. *
  87198. * Vorbis comment values must be valid UTF-8 sequences.
  87199. *
  87200. * \param value A string to be checked.
  87201. * \param length A the length of \a value in bytes. May be
  87202. * \c (unsigned)(-1) to indicate that \a value is a plain
  87203. * UTF-8 NUL-terminated string.
  87204. * \assert
  87205. * \code value != NULL \endcode
  87206. * \retval FLAC__bool
  87207. * \c false if entry name is illegal, else \c true.
  87208. */
  87209. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87210. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87211. * comment specification.
  87212. *
  87213. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87214. * 'value' must be legal according to
  87215. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87216. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87217. *
  87218. * \param entry An entry to be checked.
  87219. * \param length The length of \a entry in bytes.
  87220. * \assert
  87221. * \code value != NULL \endcode
  87222. * \retval FLAC__bool
  87223. * \c false if entry name is illegal, else \c true.
  87224. */
  87225. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87226. /** Check a seek table to see if it conforms to the FLAC specification.
  87227. * See the format specification for limits on the contents of the
  87228. * seek table.
  87229. *
  87230. * \param seek_table A pointer to a seek table to be checked.
  87231. * \assert
  87232. * \code seek_table != NULL \endcode
  87233. * \retval FLAC__bool
  87234. * \c false if seek table is illegal, else \c true.
  87235. */
  87236. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87237. /** Sort a seek table's seek points according to the format specification.
  87238. * This includes a "unique-ification" step to remove duplicates, i.e.
  87239. * seek points with identical \a sample_number values. Duplicate seek
  87240. * points are converted into placeholder points and sorted to the end of
  87241. * the table.
  87242. *
  87243. * \param seek_table A pointer to a seek table to be sorted.
  87244. * \assert
  87245. * \code seek_table != NULL \endcode
  87246. * \retval unsigned
  87247. * The number of duplicate seek points converted into placeholders.
  87248. */
  87249. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87250. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87251. * See the format specification for limits on the contents of the
  87252. * cue sheet.
  87253. *
  87254. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87255. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87256. * stringent requirements for a CD-DA (audio) disc.
  87257. * \param violation Address of a pointer to a string. If there is a
  87258. * violation, a pointer to a string explanation of the
  87259. * violation will be returned here. \a violation may be
  87260. * \c NULL if you don't need the returned string. Do not
  87261. * free the returned string; it will always point to static
  87262. * data.
  87263. * \assert
  87264. * \code cue_sheet != NULL \endcode
  87265. * \retval FLAC__bool
  87266. * \c false if cue sheet is illegal, else \c true.
  87267. */
  87268. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87269. /** Check picture data to see if it conforms to the FLAC specification.
  87270. * See the format specification for limits on the contents of the
  87271. * PICTURE block.
  87272. *
  87273. * \param picture A pointer to existing picture data to be checked.
  87274. * \param violation Address of a pointer to a string. If there is a
  87275. * violation, a pointer to a string explanation of the
  87276. * violation will be returned here. \a violation may be
  87277. * \c NULL if you don't need the returned string. Do not
  87278. * free the returned string; it will always point to static
  87279. * data.
  87280. * \assert
  87281. * \code picture != NULL \endcode
  87282. * \retval FLAC__bool
  87283. * \c false if picture data is illegal, else \c true.
  87284. */
  87285. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87286. /* \} */
  87287. #ifdef __cplusplus
  87288. }
  87289. #endif
  87290. #endif
  87291. /*** End of inlined file: format.h ***/
  87292. /*** Start of inlined file: metadata.h ***/
  87293. #ifndef FLAC__METADATA_H
  87294. #define FLAC__METADATA_H
  87295. #include <sys/types.h> /* for off_t */
  87296. /* --------------------------------------------------------------------
  87297. (For an example of how all these routines are used, see the source
  87298. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87299. metaflac in src/metaflac/)
  87300. ------------------------------------------------------------------*/
  87301. /** \file include/FLAC/metadata.h
  87302. *
  87303. * \brief
  87304. * This module provides functions for creating and manipulating FLAC
  87305. * metadata blocks in memory, and three progressively more powerful
  87306. * interfaces for traversing and editing metadata in FLAC files.
  87307. *
  87308. * See the detailed documentation for each interface in the
  87309. * \link flac_metadata metadata \endlink module.
  87310. */
  87311. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87312. * \ingroup flac
  87313. *
  87314. * \brief
  87315. * This module provides functions for creating and manipulating FLAC
  87316. * metadata blocks in memory, and three progressively more powerful
  87317. * interfaces for traversing and editing metadata in native FLAC files.
  87318. * Note that currently only the Chain interface (level 2) supports Ogg
  87319. * FLAC files, and it is read-only i.e. no writing back changed
  87320. * metadata to file.
  87321. *
  87322. * There are three metadata interfaces of increasing complexity:
  87323. *
  87324. * Level 0:
  87325. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87326. * PICTURE blocks.
  87327. *
  87328. * Level 1:
  87329. * Read-write access to all metadata blocks. This level is write-
  87330. * efficient in most cases (more on this below), and uses less memory
  87331. * than level 2.
  87332. *
  87333. * Level 2:
  87334. * Read-write access to all metadata blocks. This level is write-
  87335. * efficient in all cases, but uses more memory since all metadata for
  87336. * the whole file is read into memory and manipulated before writing
  87337. * out again.
  87338. *
  87339. * What do we mean by efficient? Since FLAC metadata appears at the
  87340. * beginning of the file, when writing metadata back to a FLAC file
  87341. * it is possible to grow or shrink the metadata such that the entire
  87342. * file must be rewritten. However, if the size remains the same during
  87343. * changes or PADDING blocks are utilized, only the metadata needs to be
  87344. * overwritten, which is much faster.
  87345. *
  87346. * Efficient means the whole file is rewritten at most one time, and only
  87347. * when necessary. Level 1 is not efficient only in the case that you
  87348. * cause more than one metadata block to grow or shrink beyond what can
  87349. * be accomodated by padding. In this case you should probably use level
  87350. * 2, which allows you to edit all the metadata for a file in memory and
  87351. * write it out all at once.
  87352. *
  87353. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87354. * front of the file.
  87355. *
  87356. * All levels access files via their filenames. In addition, level 2
  87357. * has additional alternative read and write functions that take an I/O
  87358. * handle and callbacks, for situations where access by filename is not
  87359. * possible.
  87360. *
  87361. * In addition to the three interfaces, this module defines functions for
  87362. * creating and manipulating various metadata objects in memory. As we see
  87363. * from the Format module, FLAC metadata blocks in memory are very primitive
  87364. * structures for storing information in an efficient way. Reading
  87365. * information from the structures is easy but creating or modifying them
  87366. * directly is more complex. The metadata object routines here facilitate
  87367. * this by taking care of the consistency and memory management drudgery.
  87368. *
  87369. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87370. * metadata however, you will not probably not need these.
  87371. *
  87372. * From a dependency standpoint, none of the encoders or decoders require
  87373. * the metadata module. This is so that embedded users can strip out the
  87374. * metadata module from libFLAC to reduce the size and complexity.
  87375. */
  87376. #ifdef __cplusplus
  87377. extern "C" {
  87378. #endif
  87379. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87380. * \ingroup flac_metadata
  87381. *
  87382. * \brief
  87383. * The level 0 interface consists of individual routines to read the
  87384. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87385. * only a filename.
  87386. *
  87387. * They try to skip any ID3v2 tag at the head of the file.
  87388. *
  87389. * \{
  87390. */
  87391. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87392. * will try to skip any ID3v2 tag at the head of the file.
  87393. *
  87394. * \param filename The path to the FLAC file to read.
  87395. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87396. * FLAC__StreamMetadata is a simple structure with no
  87397. * memory allocation involved, you pass the address of
  87398. * an existing structure. It need not be initialized.
  87399. * \assert
  87400. * \code filename != NULL \endcode
  87401. * \code streaminfo != NULL \endcode
  87402. * \retval FLAC__bool
  87403. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87404. * \c false if there was a memory allocation error, a file decoder error,
  87405. * or the file contained no STREAMINFO block. (A memory allocation error
  87406. * is possible because this function must set up a file decoder.)
  87407. */
  87408. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87409. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87410. * function will try to skip any ID3v2 tag at the head of the file.
  87411. *
  87412. * \param filename The path to the FLAC file to read.
  87413. * \param tags The address where the returned pointer will be
  87414. * stored. The \a tags object must be deleted by
  87415. * the caller using FLAC__metadata_object_delete().
  87416. * \assert
  87417. * \code filename != NULL \endcode
  87418. * \code tags != NULL \endcode
  87419. * \retval FLAC__bool
  87420. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87421. * and \a *tags will be set to the address of the metadata structure.
  87422. * Returns \c false if there was a memory allocation error, a file
  87423. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87424. * \a *tags will be set to \c NULL.
  87425. */
  87426. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87427. /** Read the CUESHEET metadata block of the given FLAC file. This
  87428. * function will try to skip any ID3v2 tag at the head of the file.
  87429. *
  87430. * \param filename The path to the FLAC file to read.
  87431. * \param cuesheet The address where the returned pointer will be
  87432. * stored. The \a cuesheet object must be deleted by
  87433. * the caller using FLAC__metadata_object_delete().
  87434. * \assert
  87435. * \code filename != NULL \endcode
  87436. * \code cuesheet != NULL \endcode
  87437. * \retval FLAC__bool
  87438. * \c true if a valid CUESHEET block was read from \a filename,
  87439. * and \a *cuesheet will be set to the address of the metadata
  87440. * structure. Returns \c false if there was a memory allocation
  87441. * error, a file decoder error, or the file contained no CUESHEET
  87442. * block, and \a *cuesheet will be set to \c NULL.
  87443. */
  87444. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87445. /** Read a PICTURE metadata block of the given FLAC file. This
  87446. * function will try to skip any ID3v2 tag at the head of the file.
  87447. * Since there can be more than one PICTURE block in a file, this
  87448. * function takes a number of parameters that act as constraints to
  87449. * the search. The PICTURE block with the largest area matching all
  87450. * the constraints will be returned, or \a *picture will be set to
  87451. * \c NULL if there was no such block.
  87452. *
  87453. * \param filename The path to the FLAC file to read.
  87454. * \param picture The address where the returned pointer will be
  87455. * stored. The \a picture object must be deleted by
  87456. * the caller using FLAC__metadata_object_delete().
  87457. * \param type The desired picture type. Use \c -1 to mean
  87458. * "any type".
  87459. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87460. * string will be matched exactly. Use \c NULL to
  87461. * mean "any MIME type".
  87462. * \param description The desired description. The string will be
  87463. * matched exactly. Use \c NULL to mean "any
  87464. * description".
  87465. * \param max_width The maximum width in pixels desired. Use
  87466. * \c (unsigned)(-1) to mean "any width".
  87467. * \param max_height The maximum height in pixels desired. Use
  87468. * \c (unsigned)(-1) to mean "any height".
  87469. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87470. * Use \c (unsigned)(-1) to mean "any depth".
  87471. * \param max_colors The maximum number of colors desired. Use
  87472. * \c (unsigned)(-1) to mean "any number of colors".
  87473. * \assert
  87474. * \code filename != NULL \endcode
  87475. * \code picture != NULL \endcode
  87476. * \retval FLAC__bool
  87477. * \c true if a valid PICTURE block was read from \a filename,
  87478. * and \a *picture will be set to the address of the metadata
  87479. * structure. Returns \c false if there was a memory allocation
  87480. * error, a file decoder error, or the file contained no PICTURE
  87481. * block, and \a *picture will be set to \c NULL.
  87482. */
  87483. 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);
  87484. /* \} */
  87485. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87486. * \ingroup flac_metadata
  87487. *
  87488. * \brief
  87489. * The level 1 interface provides read-write access to FLAC file metadata and
  87490. * operates directly on the FLAC file.
  87491. *
  87492. * The general usage of this interface is:
  87493. *
  87494. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87495. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87496. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87497. * see if the file is writable, or only read access is allowed.
  87498. * - Use FLAC__metadata_simple_iterator_next() and
  87499. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87500. * This is does not read the actual blocks themselves.
  87501. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87502. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87503. * forward from the front of the file.
  87504. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87505. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87506. * the current iterator position. The returned object is yours to modify
  87507. * and free.
  87508. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87509. * back. You must have write permission to the original file. Make sure to
  87510. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87511. * below.
  87512. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87513. * Use the object creation functions from
  87514. * \link flac_metadata_object here \endlink to generate new objects.
  87515. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87516. * currently referred to by the iterator, or replace it with padding.
  87517. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87518. * finished.
  87519. *
  87520. * \note
  87521. * The FLAC file remains open the whole time between
  87522. * FLAC__metadata_simple_iterator_init() and
  87523. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87524. * the file during this time.
  87525. *
  87526. * \note
  87527. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87528. * FLAC__StreamMetadata objects. These are managed automatically.
  87529. *
  87530. * \note
  87531. * If any of the modification functions
  87532. * (FLAC__metadata_simple_iterator_set_block(),
  87533. * FLAC__metadata_simple_iterator_delete_block(),
  87534. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87535. * you should delete the iterator as it may no longer be valid.
  87536. *
  87537. * \{
  87538. */
  87539. struct FLAC__Metadata_SimpleIterator;
  87540. /** The opaque structure definition for the level 1 iterator type.
  87541. * See the
  87542. * \link flac_metadata_level1 metadata level 1 module \endlink
  87543. * for a detailed description.
  87544. */
  87545. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87546. /** Status type for FLAC__Metadata_SimpleIterator.
  87547. *
  87548. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87549. */
  87550. typedef enum {
  87551. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87552. /**< The iterator is in the normal OK state */
  87553. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87554. /**< The data passed into a function violated the function's usage criteria */
  87555. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87556. /**< The iterator could not open the target file */
  87557. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87558. /**< The iterator could not find the FLAC signature at the start of the file */
  87559. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87560. /**< The iterator tried to write to a file that was not writable */
  87561. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87562. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87563. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87564. /**< The iterator encountered an error while reading the FLAC file */
  87565. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87566. /**< The iterator encountered an error while seeking in the FLAC file */
  87567. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87568. /**< The iterator encountered an error while writing the FLAC file */
  87569. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87570. /**< The iterator encountered an error renaming the FLAC file */
  87571. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87572. /**< The iterator encountered an error removing the temporary file */
  87573. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87574. /**< Memory allocation failed */
  87575. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87576. /**< The caller violated an assertion or an unexpected error occurred */
  87577. } FLAC__Metadata_SimpleIteratorStatus;
  87578. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87579. *
  87580. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87581. * will give the string equivalent. The contents should not be modified.
  87582. */
  87583. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87584. /** Create a new iterator instance.
  87585. *
  87586. * \retval FLAC__Metadata_SimpleIterator*
  87587. * \c NULL if there was an error allocating memory, else the new instance.
  87588. */
  87589. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87590. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87591. *
  87592. * \param iterator A pointer to an existing iterator.
  87593. * \assert
  87594. * \code iterator != NULL \endcode
  87595. */
  87596. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87597. /** Get the current status of the iterator. Call this after a function
  87598. * returns \c false to get the reason for the error. Also resets the status
  87599. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87600. *
  87601. * \param iterator A pointer to an existing iterator.
  87602. * \assert
  87603. * \code iterator != NULL \endcode
  87604. * \retval FLAC__Metadata_SimpleIteratorStatus
  87605. * The current status of the iterator.
  87606. */
  87607. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87608. /** Initialize the iterator to point to the first metadata block in the
  87609. * given FLAC file.
  87610. *
  87611. * \param iterator A pointer to an existing iterator.
  87612. * \param filename The path to the FLAC file.
  87613. * \param read_only If \c true, the FLAC file will be opened
  87614. * in read-only mode; if \c false, the FLAC
  87615. * file will be opened for edit even if no
  87616. * edits are performed.
  87617. * \param preserve_file_stats If \c true, the owner and modification
  87618. * time will be preserved even if the FLAC
  87619. * file is written to.
  87620. * \assert
  87621. * \code iterator != NULL \endcode
  87622. * \code filename != NULL \endcode
  87623. * \retval FLAC__bool
  87624. * \c false if a memory allocation error occurs, the file can't be
  87625. * opened, or another error occurs, else \c true.
  87626. */
  87627. 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);
  87628. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87629. * FLAC__metadata_simple_iterator_set_block() and
  87630. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87631. *
  87632. * \param iterator A pointer to an existing iterator.
  87633. * \assert
  87634. * \code iterator != NULL \endcode
  87635. * \retval FLAC__bool
  87636. * See above.
  87637. */
  87638. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87639. /** Moves the iterator forward one metadata block, returning \c false if
  87640. * already at the end.
  87641. *
  87642. * \param iterator A pointer to an existing initialized iterator.
  87643. * \assert
  87644. * \code iterator != NULL \endcode
  87645. * \a iterator has been successfully initialized with
  87646. * FLAC__metadata_simple_iterator_init()
  87647. * \retval FLAC__bool
  87648. * \c false if already at the last metadata block of the chain, else
  87649. * \c true.
  87650. */
  87651. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87652. /** Moves the iterator backward one metadata block, returning \c false if
  87653. * already at the beginning.
  87654. *
  87655. * \param iterator A pointer to an existing initialized iterator.
  87656. * \assert
  87657. * \code iterator != NULL \endcode
  87658. * \a iterator has been successfully initialized with
  87659. * FLAC__metadata_simple_iterator_init()
  87660. * \retval FLAC__bool
  87661. * \c false if already at the first metadata block of the chain, else
  87662. * \c true.
  87663. */
  87664. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87665. /** Returns a flag telling if the current metadata block is the last.
  87666. *
  87667. * \param iterator A pointer to an existing initialized iterator.
  87668. * \assert
  87669. * \code iterator != NULL \endcode
  87670. * \a iterator has been successfully initialized with
  87671. * FLAC__metadata_simple_iterator_init()
  87672. * \retval FLAC__bool
  87673. * \c true if the current metadata block is the last in the file,
  87674. * else \c false.
  87675. */
  87676. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87677. /** Get the offset of the metadata block at the current position. This
  87678. * avoids reading the actual block data which can save time for large
  87679. * blocks.
  87680. *
  87681. * \param iterator A pointer to an existing initialized iterator.
  87682. * \assert
  87683. * \code iterator != NULL \endcode
  87684. * \a iterator has been successfully initialized with
  87685. * FLAC__metadata_simple_iterator_init()
  87686. * \retval off_t
  87687. * The offset of the metadata block at the current iterator position.
  87688. * This is the byte offset relative to the beginning of the file of
  87689. * the current metadata block's header.
  87690. */
  87691. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87692. /** Get the type of the metadata block at the current position. This
  87693. * avoids reading the actual block data which can save time for large
  87694. * blocks.
  87695. *
  87696. * \param iterator A pointer to an existing initialized iterator.
  87697. * \assert
  87698. * \code iterator != NULL \endcode
  87699. * \a iterator has been successfully initialized with
  87700. * FLAC__metadata_simple_iterator_init()
  87701. * \retval FLAC__MetadataType
  87702. * The type of the metadata block at the current iterator position.
  87703. */
  87704. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87705. /** Get the length of the metadata block at the current position. This
  87706. * avoids reading the actual block data which can save time for large
  87707. * blocks.
  87708. *
  87709. * \param iterator A pointer to an existing initialized iterator.
  87710. * \assert
  87711. * \code iterator != NULL \endcode
  87712. * \a iterator has been successfully initialized with
  87713. * FLAC__metadata_simple_iterator_init()
  87714. * \retval unsigned
  87715. * The length of the metadata block at the current iterator position.
  87716. * The is same length as that in the
  87717. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87718. * i.e. the length of the metadata body that follows the header.
  87719. */
  87720. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87721. /** Get the application ID of the \c APPLICATION block at the current
  87722. * position. This avoids reading the actual block data which can save
  87723. * time for large blocks.
  87724. *
  87725. * \param iterator A pointer to an existing initialized iterator.
  87726. * \param id A pointer to a buffer of at least \c 4 bytes where
  87727. * the ID will be stored.
  87728. * \assert
  87729. * \code iterator != NULL \endcode
  87730. * \code id != NULL \endcode
  87731. * \a iterator has been successfully initialized with
  87732. * FLAC__metadata_simple_iterator_init()
  87733. * \retval FLAC__bool
  87734. * \c true if the ID was successfully read, else \c false, in which
  87735. * case you should check FLAC__metadata_simple_iterator_status() to
  87736. * find out why. If the status is
  87737. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87738. * current metadata block is not an \c APPLICATION block. Otherwise
  87739. * if the status is
  87740. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87741. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87742. * occurred and the iterator can no longer be used.
  87743. */
  87744. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87745. /** Get the metadata block at the current position. You can modify the
  87746. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87747. * write it back to the FLAC file.
  87748. *
  87749. * You must call FLAC__metadata_object_delete() on the returned object
  87750. * when you are finished with it.
  87751. *
  87752. * \param iterator A pointer to an existing initialized iterator.
  87753. * \assert
  87754. * \code iterator != NULL \endcode
  87755. * \a iterator has been successfully initialized with
  87756. * FLAC__metadata_simple_iterator_init()
  87757. * \retval FLAC__StreamMetadata*
  87758. * The current metadata block, or \c NULL if there was a memory
  87759. * allocation error.
  87760. */
  87761. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87762. /** Write a block back to the FLAC file. This function tries to be
  87763. * as efficient as possible; how the block is actually written is
  87764. * shown by the following:
  87765. *
  87766. * Existing block is a STREAMINFO block and the new block is a
  87767. * STREAMINFO block: the new block is written in place. Make sure
  87768. * you know what you're doing when changing the values of a
  87769. * STREAMINFO block.
  87770. *
  87771. * Existing block is a STREAMINFO block and the new block is a
  87772. * not a STREAMINFO block: this is an error since the first block
  87773. * must be a STREAMINFO block. Returns \c false without altering the
  87774. * file.
  87775. *
  87776. * Existing block is not a STREAMINFO block and the new block is a
  87777. * STREAMINFO block: this is an error since there may be only one
  87778. * STREAMINFO block. Returns \c false without altering the file.
  87779. *
  87780. * Existing block and new block are the same length: the existing
  87781. * block will be replaced by the new block, written in place.
  87782. *
  87783. * Existing block is longer than new block: if use_padding is \c true,
  87784. * the existing block will be overwritten in place with the new
  87785. * block followed by a PADDING block, if possible, to make the total
  87786. * size the same as the existing block. Remember that a padding
  87787. * block requires at least four bytes so if the difference in size
  87788. * between the new block and existing block is less than that, the
  87789. * entire file will have to be rewritten, using the new block's
  87790. * exact size. If use_padding is \c false, the entire file will be
  87791. * rewritten, replacing the existing block by the new block.
  87792. *
  87793. * Existing block is shorter than new block: if use_padding is \c true,
  87794. * the function will try and expand the new block into the following
  87795. * PADDING block, if it exists and doing so won't shrink the PADDING
  87796. * block to less than 4 bytes. If there is no following PADDING
  87797. * block, or it will shrink to less than 4 bytes, or use_padding is
  87798. * \c false, the entire file is rewritten, replacing the existing block
  87799. * with the new block. Note that in this case any following PADDING
  87800. * block is preserved as is.
  87801. *
  87802. * After writing the block, the iterator will remain in the same
  87803. * place, i.e. pointing to the new block.
  87804. *
  87805. * \param iterator A pointer to an existing initialized iterator.
  87806. * \param block The block to set.
  87807. * \param use_padding See above.
  87808. * \assert
  87809. * \code iterator != NULL \endcode
  87810. * \a iterator has been successfully initialized with
  87811. * FLAC__metadata_simple_iterator_init()
  87812. * \code block != NULL \endcode
  87813. * \retval FLAC__bool
  87814. * \c true if successful, else \c false.
  87815. */
  87816. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87817. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87818. * except that instead of writing over an existing block, it appends
  87819. * a block after the existing block. \a use_padding is again used to
  87820. * tell the function to try an expand into following padding in an
  87821. * attempt to avoid rewriting the entire file.
  87822. *
  87823. * This function will fail and return \c false if given a STREAMINFO
  87824. * block.
  87825. *
  87826. * After writing the block, the iterator will be pointing to the
  87827. * new block.
  87828. *
  87829. * \param iterator A pointer to an existing initialized iterator.
  87830. * \param block The block to set.
  87831. * \param use_padding See above.
  87832. * \assert
  87833. * \code iterator != NULL \endcode
  87834. * \a iterator has been successfully initialized with
  87835. * FLAC__metadata_simple_iterator_init()
  87836. * \code block != NULL \endcode
  87837. * \retval FLAC__bool
  87838. * \c true if successful, else \c false.
  87839. */
  87840. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87841. /** Deletes the block at the current position. This will cause the
  87842. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87843. * in which case the block will be replaced by an equal-sized PADDING
  87844. * block. The iterator will be left pointing to the block before the
  87845. * one just deleted.
  87846. *
  87847. * You may not delete the STREAMINFO block.
  87848. *
  87849. * \param iterator A pointer to an existing initialized iterator.
  87850. * \param use_padding See above.
  87851. * \assert
  87852. * \code iterator != NULL \endcode
  87853. * \a iterator has been successfully initialized with
  87854. * FLAC__metadata_simple_iterator_init()
  87855. * \retval FLAC__bool
  87856. * \c true if successful, else \c false.
  87857. */
  87858. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87859. /* \} */
  87860. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87861. * \ingroup flac_metadata
  87862. *
  87863. * \brief
  87864. * The level 2 interface provides read-write access to FLAC file metadata;
  87865. * all metadata is read into memory, operated on in memory, and then written
  87866. * to file, which is more efficient than level 1 when editing multiple blocks.
  87867. *
  87868. * Currently Ogg FLAC is supported for read only, via
  87869. * FLAC__metadata_chain_read_ogg() but a subsequent
  87870. * FLAC__metadata_chain_write() will fail.
  87871. *
  87872. * The general usage of this interface is:
  87873. *
  87874. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87875. * linked list of FLAC metadata blocks.
  87876. * - Read all metadata into the the chain from a FLAC file using
  87877. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87878. * check the status.
  87879. * - Optionally, consolidate the padding using
  87880. * FLAC__metadata_chain_merge_padding() or
  87881. * FLAC__metadata_chain_sort_padding().
  87882. * - Create a new iterator using FLAC__metadata_iterator_new()
  87883. * - Initialize the iterator to point to the first element in the chain
  87884. * using FLAC__metadata_iterator_init()
  87885. * - Traverse the chain using FLAC__metadata_iterator_next and
  87886. * FLAC__metadata_iterator_prev().
  87887. * - Get a block for reading or modification using
  87888. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87889. * inside the chain is returned, so the block is yours to modify.
  87890. * Changes will be reflected in the FLAC file when you write the
  87891. * chain. You can also add and delete blocks (see functions below).
  87892. * - When done, write out the chain using FLAC__metadata_chain_write().
  87893. * Make sure to read the whole comment to the function below.
  87894. * - Delete the chain using FLAC__metadata_chain_delete().
  87895. *
  87896. * \note
  87897. * Even though the FLAC file is not open while the chain is being
  87898. * manipulated, you must not alter the file externally during
  87899. * this time. The chain assumes the FLAC file will not change
  87900. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87901. * and FLAC__metadata_chain_write().
  87902. *
  87903. * \note
  87904. * Do not modify the is_last, length, or type fields of returned
  87905. * FLAC__StreamMetadata objects. These are managed automatically.
  87906. *
  87907. * \note
  87908. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87909. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87910. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87911. * become owned by the chain and they will be deleted when the chain is
  87912. * deleted.
  87913. *
  87914. * \{
  87915. */
  87916. struct FLAC__Metadata_Chain;
  87917. /** The opaque structure definition for the level 2 chain type.
  87918. */
  87919. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87920. struct FLAC__Metadata_Iterator;
  87921. /** The opaque structure definition for the level 2 iterator type.
  87922. */
  87923. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87924. typedef enum {
  87925. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87926. /**< The chain is in the normal OK state */
  87927. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87928. /**< The data passed into a function violated the function's usage criteria */
  87929. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87930. /**< The chain could not open the target file */
  87931. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87932. /**< The chain could not find the FLAC signature at the start of the file */
  87933. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87934. /**< The chain tried to write to a file that was not writable */
  87935. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87936. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87937. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87938. /**< The chain encountered an error while reading the FLAC file */
  87939. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87940. /**< The chain encountered an error while seeking in the FLAC file */
  87941. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87942. /**< The chain encountered an error while writing the FLAC file */
  87943. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87944. /**< The chain encountered an error renaming the FLAC file */
  87945. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87946. /**< The chain encountered an error removing the temporary file */
  87947. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87948. /**< Memory allocation failed */
  87949. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87950. /**< The caller violated an assertion or an unexpected error occurred */
  87951. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87952. /**< One or more of the required callbacks was NULL */
  87953. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87954. /**< FLAC__metadata_chain_write() was called on a chain read by
  87955. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87956. * or
  87957. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87958. * was called on a chain read by
  87959. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87960. * Matching read/write methods must always be used. */
  87961. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87962. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87963. * chain write requires a tempfile; use
  87964. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87965. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87966. * called when the chain write does not require a tempfile; use
  87967. * FLAC__metadata_chain_write_with_callbacks() instead.
  87968. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87969. * before writing via callbacks. */
  87970. } FLAC__Metadata_ChainStatus;
  87971. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87972. *
  87973. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87974. * will give the string equivalent. The contents should not be modified.
  87975. */
  87976. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87977. /*********** FLAC__Metadata_Chain ***********/
  87978. /** Create a new chain instance.
  87979. *
  87980. * \retval FLAC__Metadata_Chain*
  87981. * \c NULL if there was an error allocating memory, else the new instance.
  87982. */
  87983. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87984. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87985. *
  87986. * \param chain A pointer to an existing chain.
  87987. * \assert
  87988. * \code chain != NULL \endcode
  87989. */
  87990. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87991. /** Get the current status of the chain. Call this after a function
  87992. * returns \c false to get the reason for the error. Also resets the
  87993. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87994. *
  87995. * \param chain A pointer to an existing chain.
  87996. * \assert
  87997. * \code chain != NULL \endcode
  87998. * \retval FLAC__Metadata_ChainStatus
  87999. * The current status of the chain.
  88000. */
  88001. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88002. /** Read all metadata from a FLAC file into the chain.
  88003. *
  88004. * \param chain A pointer to an existing chain.
  88005. * \param filename The path to the FLAC file to read.
  88006. * \assert
  88007. * \code chain != NULL \endcode
  88008. * \code filename != NULL \endcode
  88009. * \retval FLAC__bool
  88010. * \c true if a valid list of metadata blocks was read from
  88011. * \a filename, else \c false. On failure, check the status with
  88012. * FLAC__metadata_chain_status().
  88013. */
  88014. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88015. /** Read all metadata from an Ogg FLAC file into the chain.
  88016. *
  88017. * \note Ogg FLAC metadata data writing is not supported yet and
  88018. * FLAC__metadata_chain_write() will fail.
  88019. *
  88020. * \param chain A pointer to an existing chain.
  88021. * \param filename The path to the Ogg FLAC file to read.
  88022. * \assert
  88023. * \code chain != NULL \endcode
  88024. * \code filename != NULL \endcode
  88025. * \retval FLAC__bool
  88026. * \c true if a valid list of metadata blocks was read from
  88027. * \a filename, else \c false. On failure, check the status with
  88028. * FLAC__metadata_chain_status().
  88029. */
  88030. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88031. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88032. *
  88033. * The \a handle need only be open for reading, but must be seekable.
  88034. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88035. * for Windows).
  88036. *
  88037. * \param chain A pointer to an existing chain.
  88038. * \param handle The I/O handle of the FLAC stream to read. The
  88039. * handle will NOT be closed after the metadata is read;
  88040. * that is the duty of the caller.
  88041. * \param callbacks
  88042. * A set of callbacks to use for I/O. The mandatory
  88043. * callbacks are \a read, \a seek, and \a tell.
  88044. * \assert
  88045. * \code chain != NULL \endcode
  88046. * \retval FLAC__bool
  88047. * \c true if a valid list of metadata blocks was read from
  88048. * \a handle, else \c false. On failure, check the status with
  88049. * FLAC__metadata_chain_status().
  88050. */
  88051. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88052. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88053. *
  88054. * The \a handle need only be open for reading, but must be seekable.
  88055. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88056. * for Windows).
  88057. *
  88058. * \note Ogg FLAC metadata data writing is not supported yet and
  88059. * FLAC__metadata_chain_write() will fail.
  88060. *
  88061. * \param chain A pointer to an existing chain.
  88062. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88063. * handle will NOT be closed after the metadata is read;
  88064. * that is the duty of the caller.
  88065. * \param callbacks
  88066. * A set of callbacks to use for I/O. The mandatory
  88067. * callbacks are \a read, \a seek, and \a tell.
  88068. * \assert
  88069. * \code chain != NULL \endcode
  88070. * \retval FLAC__bool
  88071. * \c true if a valid list of metadata blocks was read from
  88072. * \a handle, else \c false. On failure, check the status with
  88073. * FLAC__metadata_chain_status().
  88074. */
  88075. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88076. /** Checks if writing the given chain would require the use of a
  88077. * temporary file, or if it could be written in place.
  88078. *
  88079. * Under certain conditions, padding can be utilized so that writing
  88080. * edited metadata back to the FLAC file does not require rewriting the
  88081. * entire file. If rewriting is required, then a temporary workfile is
  88082. * required. When writing metadata using callbacks, you must check
  88083. * this function to know whether to call
  88084. * FLAC__metadata_chain_write_with_callbacks() or
  88085. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88086. * writing with FLAC__metadata_chain_write(), the temporary file is
  88087. * handled internally.
  88088. *
  88089. * \param chain A pointer to an existing chain.
  88090. * \param use_padding
  88091. * Whether or not padding will be allowed to be used
  88092. * during the write. The value of \a use_padding given
  88093. * here must match the value later passed to
  88094. * FLAC__metadata_chain_write_with_callbacks() or
  88095. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88096. * \assert
  88097. * \code chain != NULL \endcode
  88098. * \retval FLAC__bool
  88099. * \c true if writing the current chain would require a tempfile, or
  88100. * \c false if metadata can be written in place.
  88101. */
  88102. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88103. /** Write all metadata out to the FLAC file. This function tries to be as
  88104. * efficient as possible; how the metadata is actually written is shown by
  88105. * the following:
  88106. *
  88107. * If the current chain is the same size as the existing metadata, the new
  88108. * data is written in place.
  88109. *
  88110. * If the current chain is longer than the existing metadata, and
  88111. * \a use_padding is \c true, and the last block is a PADDING block of
  88112. * sufficient length, the function will truncate the final padding block
  88113. * so that the overall size of the metadata is the same as the existing
  88114. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88115. * the above conditions are met, the entire FLAC file must be rewritten.
  88116. * If you want to use padding this way it is a good idea to call
  88117. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88118. * amount of padding to work with, unless you need to preserve ordering
  88119. * of the PADDING blocks for some reason.
  88120. *
  88121. * If the current chain is shorter than the existing metadata, and
  88122. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88123. * is extended to make the overall size the same as the existing data. If
  88124. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88125. * PADDING block is added to the end of the new data to make it the same
  88126. * size as the existing data (if possible, see the note to
  88127. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88128. * and the new data is written in place. If none of the above apply or
  88129. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88130. *
  88131. * If \a preserve_file_stats is \c true, the owner and modification time will
  88132. * be preserved even if the FLAC file is written.
  88133. *
  88134. * For this write function to be used, the chain must have been read with
  88135. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88136. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88137. *
  88138. * \param chain A pointer to an existing chain.
  88139. * \param use_padding See above.
  88140. * \param preserve_file_stats See above.
  88141. * \assert
  88142. * \code chain != NULL \endcode
  88143. * \retval FLAC__bool
  88144. * \c true if the write succeeded, else \c false. On failure,
  88145. * check the status with FLAC__metadata_chain_status().
  88146. */
  88147. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88148. /** Write all metadata out to a FLAC stream via callbacks.
  88149. *
  88150. * (See FLAC__metadata_chain_write() for the details on how padding is
  88151. * used to write metadata in place if possible.)
  88152. *
  88153. * The \a handle must be open for updating and be seekable. The
  88154. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88155. * for Windows).
  88156. *
  88157. * For this write function to be used, the chain must have been read with
  88158. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88159. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88160. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88161. * \c false.
  88162. *
  88163. * \param chain A pointer to an existing chain.
  88164. * \param use_padding See FLAC__metadata_chain_write()
  88165. * \param handle The I/O handle of the FLAC stream to write. The
  88166. * handle will NOT be closed after the metadata is
  88167. * written; that is the duty of the caller.
  88168. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88169. * callbacks are \a write and \a seek.
  88170. * \assert
  88171. * \code chain != NULL \endcode
  88172. * \retval FLAC__bool
  88173. * \c true if the write succeeded, else \c false. On failure,
  88174. * check the status with FLAC__metadata_chain_status().
  88175. */
  88176. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88177. /** Write all metadata out to a FLAC stream via callbacks.
  88178. *
  88179. * (See FLAC__metadata_chain_write() for the details on how padding is
  88180. * used to write metadata in place if possible.)
  88181. *
  88182. * This version of the write-with-callbacks function must be used when
  88183. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88184. * this function, you must supply an I/O handle corresponding to the
  88185. * FLAC file to edit, and a temporary handle to which the new FLAC
  88186. * file will be written. It is the caller's job to move this temporary
  88187. * FLAC file on top of the original FLAC file to complete the metadata
  88188. * edit.
  88189. *
  88190. * The \a handle must be open for reading and be seekable. The
  88191. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88192. * for Windows).
  88193. *
  88194. * The \a temp_handle must be open for writing. The
  88195. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88196. * for Windows). It should be an empty stream, or at least positioned
  88197. * at the start-of-file (in which case it is the caller's duty to
  88198. * truncate it on return).
  88199. *
  88200. * For this write function to be used, the chain must have been read with
  88201. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88202. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88203. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88204. * \c true.
  88205. *
  88206. * \param chain A pointer to an existing chain.
  88207. * \param use_padding See FLAC__metadata_chain_write()
  88208. * \param handle The I/O handle of the original FLAC stream to read.
  88209. * The handle will NOT be closed after the metadata is
  88210. * written; that is the duty of the caller.
  88211. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88212. * The mandatory callbacks are \a read, \a seek, and
  88213. * \a eof.
  88214. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88215. * handle will NOT be closed after the metadata is
  88216. * written; that is the duty of the caller.
  88217. * \param temp_callbacks
  88218. * A set of callbacks to use for I/O on temp_handle.
  88219. * The only mandatory callback is \a write.
  88220. * \assert
  88221. * \code chain != NULL \endcode
  88222. * \retval FLAC__bool
  88223. * \c true if the write succeeded, else \c false. On failure,
  88224. * check the status with FLAC__metadata_chain_status().
  88225. */
  88226. 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);
  88227. /** Merge adjacent PADDING blocks into a single block.
  88228. *
  88229. * \note This function does not write to the FLAC file, it only
  88230. * modifies the chain.
  88231. *
  88232. * \warning Any iterator on the current chain will become invalid after this
  88233. * call. You should delete the iterator and get a new one.
  88234. *
  88235. * \param chain A pointer to an existing chain.
  88236. * \assert
  88237. * \code chain != NULL \endcode
  88238. */
  88239. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88240. /** This function will move all PADDING blocks to the end on the metadata,
  88241. * then merge them into a single block.
  88242. *
  88243. * \note This function does not write to the FLAC file, it only
  88244. * modifies the chain.
  88245. *
  88246. * \warning Any iterator on the current chain will become invalid after this
  88247. * call. You should delete the iterator and get a new one.
  88248. *
  88249. * \param chain A pointer to an existing chain.
  88250. * \assert
  88251. * \code chain != NULL \endcode
  88252. */
  88253. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88254. /*********** FLAC__Metadata_Iterator ***********/
  88255. /** Create a new iterator instance.
  88256. *
  88257. * \retval FLAC__Metadata_Iterator*
  88258. * \c NULL if there was an error allocating memory, else the new instance.
  88259. */
  88260. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88261. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88262. *
  88263. * \param iterator A pointer to an existing iterator.
  88264. * \assert
  88265. * \code iterator != NULL \endcode
  88266. */
  88267. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88268. /** Initialize the iterator to point to the first metadata block in the
  88269. * given chain.
  88270. *
  88271. * \param iterator A pointer to an existing iterator.
  88272. * \param chain A pointer to an existing and initialized (read) chain.
  88273. * \assert
  88274. * \code iterator != NULL \endcode
  88275. * \code chain != NULL \endcode
  88276. */
  88277. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88278. /** Moves the iterator forward one metadata block, returning \c false if
  88279. * already at the end.
  88280. *
  88281. * \param iterator A pointer to an existing initialized iterator.
  88282. * \assert
  88283. * \code iterator != NULL \endcode
  88284. * \a iterator has been successfully initialized with
  88285. * FLAC__metadata_iterator_init()
  88286. * \retval FLAC__bool
  88287. * \c false if already at the last metadata block of the chain, else
  88288. * \c true.
  88289. */
  88290. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88291. /** Moves the iterator backward one metadata block, returning \c false if
  88292. * already at the beginning.
  88293. *
  88294. * \param iterator A pointer to an existing initialized iterator.
  88295. * \assert
  88296. * \code iterator != NULL \endcode
  88297. * \a iterator has been successfully initialized with
  88298. * FLAC__metadata_iterator_init()
  88299. * \retval FLAC__bool
  88300. * \c false if already at the first metadata block of the chain, else
  88301. * \c true.
  88302. */
  88303. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88304. /** Get the type of the metadata block at the current position.
  88305. *
  88306. * \param iterator A pointer to an existing initialized iterator.
  88307. * \assert
  88308. * \code iterator != NULL \endcode
  88309. * \a iterator has been successfully initialized with
  88310. * FLAC__metadata_iterator_init()
  88311. * \retval FLAC__MetadataType
  88312. * The type of the metadata block at the current iterator position.
  88313. */
  88314. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88315. /** Get the metadata block at the current position. You can modify
  88316. * the block in place but must write the chain before the changes
  88317. * are reflected to the FLAC file. You do not need to call
  88318. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88319. * the pointer returned by FLAC__metadata_iterator_get_block()
  88320. * points directly into the chain.
  88321. *
  88322. * \warning
  88323. * Do not call FLAC__metadata_object_delete() on the returned object;
  88324. * to delete a block use FLAC__metadata_iterator_delete_block().
  88325. *
  88326. * \param iterator A pointer to an existing initialized iterator.
  88327. * \assert
  88328. * \code iterator != NULL \endcode
  88329. * \a iterator has been successfully initialized with
  88330. * FLAC__metadata_iterator_init()
  88331. * \retval FLAC__StreamMetadata*
  88332. * The current metadata block.
  88333. */
  88334. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88335. /** Set the metadata block at the current position, replacing the existing
  88336. * block. The new block passed in becomes owned by the chain and it will be
  88337. * deleted when the chain is deleted.
  88338. *
  88339. * \param iterator A pointer to an existing initialized iterator.
  88340. * \param block A pointer to a metadata block.
  88341. * \assert
  88342. * \code iterator != NULL \endcode
  88343. * \a iterator has been successfully initialized with
  88344. * FLAC__metadata_iterator_init()
  88345. * \code block != NULL \endcode
  88346. * \retval FLAC__bool
  88347. * \c false if the conditions in the above description are not met, or
  88348. * a memory allocation error occurs, otherwise \c true.
  88349. */
  88350. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88351. /** Removes the current block from the chain. If \a replace_with_padding is
  88352. * \c true, the block will instead be replaced with a padding block of equal
  88353. * size. You can not delete the STREAMINFO block. The iterator will be
  88354. * left pointing to the block before the one just "deleted", even if
  88355. * \a replace_with_padding is \c true.
  88356. *
  88357. * \param iterator A pointer to an existing initialized iterator.
  88358. * \param replace_with_padding See above.
  88359. * \assert
  88360. * \code iterator != NULL \endcode
  88361. * \a iterator has been successfully initialized with
  88362. * FLAC__metadata_iterator_init()
  88363. * \retval FLAC__bool
  88364. * \c false if the conditions in the above description are not met,
  88365. * otherwise \c true.
  88366. */
  88367. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88368. /** Insert a new block before the current block. You cannot insert a block
  88369. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88370. * as there can be only one, the one that already exists at the head when you
  88371. * read in a chain. The chain takes ownership of the new block and it will be
  88372. * deleted when the chain is deleted. The iterator will be left pointing to
  88373. * the new block.
  88374. *
  88375. * \param iterator A pointer to an existing initialized iterator.
  88376. * \param block A pointer to a metadata block to insert.
  88377. * \assert
  88378. * \code iterator != NULL \endcode
  88379. * \a iterator has been successfully initialized with
  88380. * FLAC__metadata_iterator_init()
  88381. * \retval FLAC__bool
  88382. * \c false if the conditions in the above description are not met, or
  88383. * a memory allocation error occurs, otherwise \c true.
  88384. */
  88385. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88386. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88387. * block as there can be only one, the one that already exists at the head when
  88388. * you read in a chain. The chain takes ownership of the new block and it will
  88389. * be deleted when the chain is deleted. The iterator will be left pointing to
  88390. * the new block.
  88391. *
  88392. * \param iterator A pointer to an existing initialized iterator.
  88393. * \param block A pointer to a metadata block to insert.
  88394. * \assert
  88395. * \code iterator != NULL \endcode
  88396. * \a iterator has been successfully initialized with
  88397. * FLAC__metadata_iterator_init()
  88398. * \retval FLAC__bool
  88399. * \c false if the conditions in the above description are not met, or
  88400. * a memory allocation error occurs, otherwise \c true.
  88401. */
  88402. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88403. /* \} */
  88404. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88405. * \ingroup flac_metadata
  88406. *
  88407. * \brief
  88408. * This module contains methods for manipulating FLAC metadata objects.
  88409. *
  88410. * Since many are variable length we have to be careful about the memory
  88411. * management. We decree that all pointers to data in the object are
  88412. * owned by the object and memory-managed by the object.
  88413. *
  88414. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88415. * functions to create all instances. When using the
  88416. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88417. * \a copy to \c true to have the function make it's own copy of the data, or
  88418. * to \c false to give the object ownership of your data. In the latter case
  88419. * your pointer must be freeable by free() and will be free()d when the object
  88420. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88421. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88422. * the length argument is 0 and the \a copy argument is \c false.
  88423. *
  88424. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88425. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88426. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88427. * case of a memory allocation error.
  88428. *
  88429. * We don't have the convenience of C++ here, so note that the library relies
  88430. * on you to keep the types straight. In other words, if you pass, for
  88431. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88432. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88433. * failure.
  88434. *
  88435. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88436. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88437. * toward the length or stored in the stream, but it can make working with plain
  88438. * comments (those that don't contain embedded-NULs in the value) easier.
  88439. * Entries passed into these functions have trailing NULs added if missing, and
  88440. * returned entries are guaranteed to have a trailing NUL.
  88441. *
  88442. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88443. * comment entry/name/value will first validate that it complies with the Vorbis
  88444. * comment specification and return false if it does not.
  88445. *
  88446. * There is no need to recalculate the length field on metadata blocks you
  88447. * have modified. They will be calculated automatically before they are
  88448. * written back to a file.
  88449. *
  88450. * \{
  88451. */
  88452. /** Create a new metadata object instance of the given type.
  88453. *
  88454. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88455. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88456. * the vendor string set (but zero comments).
  88457. *
  88458. * Do not pass in a value greater than or equal to
  88459. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88460. * doing.
  88461. *
  88462. * \param type Type of object to create
  88463. * \retval FLAC__StreamMetadata*
  88464. * \c NULL if there was an error allocating memory or the type code is
  88465. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88466. */
  88467. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88468. /** Create a copy of an existing metadata object.
  88469. *
  88470. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88471. * object is also copied. The caller takes ownership of the new block and
  88472. * is responsible for freeing it with FLAC__metadata_object_delete().
  88473. *
  88474. * \param object Pointer to object to copy.
  88475. * \assert
  88476. * \code object != NULL \endcode
  88477. * \retval FLAC__StreamMetadata*
  88478. * \c NULL if there was an error allocating memory, else the new instance.
  88479. */
  88480. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88481. /** Free a metadata object. Deletes the object pointed to by \a object.
  88482. *
  88483. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88484. * object is also deleted.
  88485. *
  88486. * \param object A pointer to an existing object.
  88487. * \assert
  88488. * \code object != NULL \endcode
  88489. */
  88490. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88491. /** Compares two metadata objects.
  88492. *
  88493. * The compare is "deep", i.e. dynamically allocated data within the
  88494. * object is also compared.
  88495. *
  88496. * \param block1 A pointer to an existing object.
  88497. * \param block2 A pointer to an existing object.
  88498. * \assert
  88499. * \code block1 != NULL \endcode
  88500. * \code block2 != NULL \endcode
  88501. * \retval FLAC__bool
  88502. * \c true if objects are identical, else \c false.
  88503. */
  88504. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88505. /** Sets the application data of an APPLICATION block.
  88506. *
  88507. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88508. * takes ownership of the pointer. The existing data will be freed if this
  88509. * function is successful, otherwise the original data will remain if \a copy
  88510. * is \c true and malloc() fails.
  88511. *
  88512. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88513. *
  88514. * \param object A pointer to an existing APPLICATION object.
  88515. * \param data A pointer to the data to set.
  88516. * \param length The length of \a data in bytes.
  88517. * \param copy See above.
  88518. * \assert
  88519. * \code object != NULL \endcode
  88520. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88521. * \code (data != NULL && length > 0) ||
  88522. * (data == NULL && length == 0 && copy == false) \endcode
  88523. * \retval FLAC__bool
  88524. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88525. */
  88526. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88527. /** Resize the seekpoint array.
  88528. *
  88529. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88530. * points will be added to the end.
  88531. *
  88532. * \param object A pointer to an existing SEEKTABLE object.
  88533. * \param new_num_points The desired length of the array; may be \c 0.
  88534. * \assert
  88535. * \code object != NULL \endcode
  88536. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88537. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88538. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88539. * \retval FLAC__bool
  88540. * \c false if memory allocation error, else \c true.
  88541. */
  88542. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88543. /** Set a seekpoint in a seektable.
  88544. *
  88545. * \param object A pointer to an existing SEEKTABLE object.
  88546. * \param point_num Index into seekpoint array to set.
  88547. * \param point The point to set.
  88548. * \assert
  88549. * \code object != NULL \endcode
  88550. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88551. * \code object->data.seek_table.num_points > point_num \endcode
  88552. */
  88553. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88554. /** Insert a seekpoint into a seektable.
  88555. *
  88556. * \param object A pointer to an existing SEEKTABLE object.
  88557. * \param point_num Index into seekpoint array to set.
  88558. * \param point The point to set.
  88559. * \assert
  88560. * \code object != NULL \endcode
  88561. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88562. * \code object->data.seek_table.num_points >= point_num \endcode
  88563. * \retval FLAC__bool
  88564. * \c false if memory allocation error, else \c true.
  88565. */
  88566. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88567. /** Delete a seekpoint from a seektable.
  88568. *
  88569. * \param object A pointer to an existing SEEKTABLE object.
  88570. * \param point_num Index into seekpoint array to set.
  88571. * \assert
  88572. * \code object != NULL \endcode
  88573. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88574. * \code object->data.seek_table.num_points > point_num \endcode
  88575. * \retval FLAC__bool
  88576. * \c false if memory allocation error, else \c true.
  88577. */
  88578. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88579. /** Check a seektable to see if it conforms to the FLAC specification.
  88580. * See the format specification for limits on the contents of the
  88581. * seektable.
  88582. *
  88583. * \param object A pointer to an existing SEEKTABLE object.
  88584. * \assert
  88585. * \code object != NULL \endcode
  88586. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88587. * \retval FLAC__bool
  88588. * \c false if seek table is illegal, else \c true.
  88589. */
  88590. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88591. /** Append a number of placeholder points to the end of a seek table.
  88592. *
  88593. * \note
  88594. * As with the other ..._seektable_template_... functions, you should
  88595. * call FLAC__metadata_object_seektable_template_sort() when finished
  88596. * to make the seek table legal.
  88597. *
  88598. * \param object A pointer to an existing SEEKTABLE object.
  88599. * \param num The number of placeholder points to append.
  88600. * \assert
  88601. * \code object != NULL \endcode
  88602. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88603. * \retval FLAC__bool
  88604. * \c false if memory allocation fails, else \c true.
  88605. */
  88606. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88607. /** Append a specific seek point template to the end of a seek table.
  88608. *
  88609. * \note
  88610. * As with the other ..._seektable_template_... functions, you should
  88611. * call FLAC__metadata_object_seektable_template_sort() when finished
  88612. * to make the seek table legal.
  88613. *
  88614. * \param object A pointer to an existing SEEKTABLE object.
  88615. * \param sample_number The sample number of the seek point template.
  88616. * \assert
  88617. * \code object != NULL \endcode
  88618. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88619. * \retval FLAC__bool
  88620. * \c false if memory allocation fails, else \c true.
  88621. */
  88622. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88623. /** Append specific seek point templates to the end of a seek table.
  88624. *
  88625. * \note
  88626. * As with the other ..._seektable_template_... functions, you should
  88627. * call FLAC__metadata_object_seektable_template_sort() when finished
  88628. * to make the seek table legal.
  88629. *
  88630. * \param object A pointer to an existing SEEKTABLE object.
  88631. * \param sample_numbers An array of sample numbers for the seek points.
  88632. * \param num The number of seek point templates to append.
  88633. * \assert
  88634. * \code object != NULL \endcode
  88635. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88636. * \retval FLAC__bool
  88637. * \c false if memory allocation fails, else \c true.
  88638. */
  88639. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88640. /** Append a set of evenly-spaced seek point templates to the end of a
  88641. * seek table.
  88642. *
  88643. * \note
  88644. * As with the other ..._seektable_template_... functions, you should
  88645. * call FLAC__metadata_object_seektable_template_sort() when finished
  88646. * to make the seek table legal.
  88647. *
  88648. * \param object A pointer to an existing SEEKTABLE object.
  88649. * \param num The number of placeholder points to append.
  88650. * \param total_samples The total number of samples to be encoded;
  88651. * the seekpoints will be spaced approximately
  88652. * \a total_samples / \a num samples apart.
  88653. * \assert
  88654. * \code object != NULL \endcode
  88655. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88656. * \code total_samples > 0 \endcode
  88657. * \retval FLAC__bool
  88658. * \c false if memory allocation fails, else \c true.
  88659. */
  88660. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88661. /** Append a set of evenly-spaced seek point templates to the end of a
  88662. * seek table.
  88663. *
  88664. * \note
  88665. * As with the other ..._seektable_template_... functions, you should
  88666. * call FLAC__metadata_object_seektable_template_sort() when finished
  88667. * to make the seek table legal.
  88668. *
  88669. * \param object A pointer to an existing SEEKTABLE object.
  88670. * \param samples The number of samples apart to space the placeholder
  88671. * points. The first point will be at sample \c 0, the
  88672. * second at sample \a samples, then 2*\a samples, and
  88673. * so on. As long as \a samples and \a total_samples
  88674. * are greater than \c 0, there will always be at least
  88675. * one seekpoint at sample \c 0.
  88676. * \param total_samples The total number of samples to be encoded;
  88677. * the seekpoints will be spaced
  88678. * \a samples samples apart.
  88679. * \assert
  88680. * \code object != NULL \endcode
  88681. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88682. * \code samples > 0 \endcode
  88683. * \code total_samples > 0 \endcode
  88684. * \retval FLAC__bool
  88685. * \c false if memory allocation fails, else \c true.
  88686. */
  88687. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88688. /** Sort a seek table's seek points according to the format specification,
  88689. * removing duplicates.
  88690. *
  88691. * \param object A pointer to a seek table to be sorted.
  88692. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88693. * If \c true, duplicates are deleted and the seek table is
  88694. * shrunk appropriately; the number of placeholder points
  88695. * present in the seek table will be the same after the call
  88696. * as before.
  88697. * \assert
  88698. * \code object != NULL \endcode
  88699. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88700. * \retval FLAC__bool
  88701. * \c false if realloc() fails, else \c true.
  88702. */
  88703. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88704. /** Sets the vendor string in a VORBIS_COMMENT block.
  88705. *
  88706. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88707. * one already.
  88708. *
  88709. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88710. * takes ownership of the \c entry.entry pointer.
  88711. *
  88712. * \note If this function returns \c false, the caller still owns the
  88713. * pointer.
  88714. *
  88715. * \param object A pointer to an existing VORBIS_COMMENT object.
  88716. * \param entry The entry to set the vendor string to.
  88717. * \param copy See above.
  88718. * \assert
  88719. * \code object != NULL \endcode
  88720. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88721. * \code (entry.entry != NULL && entry.length > 0) ||
  88722. * (entry.entry == NULL && entry.length == 0) \endcode
  88723. * \retval FLAC__bool
  88724. * \c false if memory allocation fails or \a entry does not comply with the
  88725. * Vorbis comment specification, else \c true.
  88726. */
  88727. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88728. /** Resize the comment array.
  88729. *
  88730. * If the size shrinks, elements will truncated; if it grows, new empty
  88731. * fields will be added to the end.
  88732. *
  88733. * \param object A pointer to an existing VORBIS_COMMENT object.
  88734. * \param new_num_comments The desired length of the array; may be \c 0.
  88735. * \assert
  88736. * \code object != NULL \endcode
  88737. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88738. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88739. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88740. * \retval FLAC__bool
  88741. * \c false if memory allocation fails, else \c true.
  88742. */
  88743. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88744. /** Sets a comment in a VORBIS_COMMENT block.
  88745. *
  88746. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88747. * one already.
  88748. *
  88749. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88750. * takes ownership of the \c entry.entry pointer.
  88751. *
  88752. * \note If this function returns \c false, the caller still owns the
  88753. * pointer.
  88754. *
  88755. * \param object A pointer to an existing VORBIS_COMMENT object.
  88756. * \param comment_num Index into comment array to set.
  88757. * \param entry The entry to set the comment to.
  88758. * \param copy See above.
  88759. * \assert
  88760. * \code object != NULL \endcode
  88761. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88762. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88763. * \code (entry.entry != NULL && entry.length > 0) ||
  88764. * (entry.entry == NULL && entry.length == 0) \endcode
  88765. * \retval FLAC__bool
  88766. * \c false if memory allocation fails or \a entry does not comply with the
  88767. * Vorbis comment specification, else \c true.
  88768. */
  88769. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88770. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88771. *
  88772. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88773. * one already.
  88774. *
  88775. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88776. * takes ownership of the \c entry.entry pointer.
  88777. *
  88778. * \note If this function returns \c false, the caller still owns the
  88779. * pointer.
  88780. *
  88781. * \param object A pointer to an existing VORBIS_COMMENT object.
  88782. * \param comment_num The index at which to insert the comment. The comments
  88783. * at and after \a comment_num move right one position.
  88784. * To append a comment to the end, set \a comment_num to
  88785. * \c object->data.vorbis_comment.num_comments .
  88786. * \param entry The comment to insert.
  88787. * \param copy See above.
  88788. * \assert
  88789. * \code object != NULL \endcode
  88790. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88791. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88792. * \code (entry.entry != NULL && entry.length > 0) ||
  88793. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88794. * \retval FLAC__bool
  88795. * \c false if memory allocation fails or \a entry does not comply with the
  88796. * Vorbis comment specification, else \c true.
  88797. */
  88798. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88799. /** Appends a comment to a VORBIS_COMMENT block.
  88800. *
  88801. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88802. * one already.
  88803. *
  88804. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88805. * takes ownership of the \c entry.entry pointer.
  88806. *
  88807. * \note If this function returns \c false, the caller still owns the
  88808. * pointer.
  88809. *
  88810. * \param object A pointer to an existing VORBIS_COMMENT object.
  88811. * \param entry The comment to insert.
  88812. * \param copy See above.
  88813. * \assert
  88814. * \code object != NULL \endcode
  88815. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88816. * \code (entry.entry != NULL && entry.length > 0) ||
  88817. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88818. * \retval FLAC__bool
  88819. * \c false if memory allocation fails or \a entry does not comply with the
  88820. * Vorbis comment specification, else \c true.
  88821. */
  88822. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88823. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88824. *
  88825. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88826. * one already.
  88827. *
  88828. * Depending on the the value of \a all, either all or just the first comment
  88829. * whose field name(s) match the given entry's name will be replaced by the
  88830. * given entry. If no comments match, \a entry will simply be appended.
  88831. *
  88832. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88833. * takes ownership of the \c entry.entry pointer.
  88834. *
  88835. * \note If this function returns \c false, the caller still owns the
  88836. * pointer.
  88837. *
  88838. * \param object A pointer to an existing VORBIS_COMMENT object.
  88839. * \param entry The comment to insert.
  88840. * \param all If \c true, all comments whose field name matches
  88841. * \a entry's field name will be removed, and \a entry will
  88842. * be inserted at the position of the first matching
  88843. * comment. If \c false, only the first comment whose
  88844. * field name matches \a entry's field name will be
  88845. * replaced with \a entry.
  88846. * \param copy See above.
  88847. * \assert
  88848. * \code object != NULL \endcode
  88849. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88850. * \code (entry.entry != NULL && entry.length > 0) ||
  88851. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88852. * \retval FLAC__bool
  88853. * \c false if memory allocation fails or \a entry does not comply with the
  88854. * Vorbis comment specification, else \c true.
  88855. */
  88856. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88857. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88858. *
  88859. * \param object A pointer to an existing VORBIS_COMMENT object.
  88860. * \param comment_num The index of the comment to delete.
  88861. * \assert
  88862. * \code object != NULL \endcode
  88863. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88864. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88865. * \retval FLAC__bool
  88866. * \c false if realloc() fails, else \c true.
  88867. */
  88868. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88869. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88870. *
  88871. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88872. * memory and shall be owned by the caller. For convenience the entry will
  88873. * have a terminating NUL.
  88874. *
  88875. * \param entry A pointer to a Vorbis comment entry. The entry's
  88876. * \c entry pointer should not point to allocated
  88877. * memory as it will be overwritten.
  88878. * \param field_name The field name in ASCII, \c NUL terminated.
  88879. * \param field_value The field value in UTF-8, \c NUL terminated.
  88880. * \assert
  88881. * \code entry != NULL \endcode
  88882. * \code field_name != NULL \endcode
  88883. * \code field_value != NULL \endcode
  88884. * \retval FLAC__bool
  88885. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88886. * not comply with the Vorbis comment specification, else \c true.
  88887. */
  88888. 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);
  88889. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88890. *
  88891. * The returned pointers to name and value will be allocated by malloc()
  88892. * and shall be owned by the caller.
  88893. *
  88894. * \param entry An existing Vorbis comment entry.
  88895. * \param field_name The address of where the returned pointer to the
  88896. * field name will be stored.
  88897. * \param field_value The address of where the returned pointer to the
  88898. * field value will be stored.
  88899. * \assert
  88900. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88901. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88902. * \code field_name != NULL \endcode
  88903. * \code field_value != NULL \endcode
  88904. * \retval FLAC__bool
  88905. * \c false if memory allocation fails or \a entry does not comply with the
  88906. * Vorbis comment specification, else \c true.
  88907. */
  88908. 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);
  88909. /** Check if the given Vorbis comment entry's field name matches the given
  88910. * field name.
  88911. *
  88912. * \param entry An existing Vorbis comment entry.
  88913. * \param field_name The field name to check.
  88914. * \param field_name_length The length of \a field_name, not including the
  88915. * terminating \c NUL.
  88916. * \assert
  88917. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88918. * \retval FLAC__bool
  88919. * \c true if the field names match, else \c false
  88920. */
  88921. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88922. /** Find a Vorbis comment with the given field name.
  88923. *
  88924. * The search begins at entry number \a offset; use an offset of 0 to
  88925. * search from the beginning of the comment array.
  88926. *
  88927. * \param object A pointer to an existing VORBIS_COMMENT object.
  88928. * \param offset The offset into the comment array from where to start
  88929. * the search.
  88930. * \param field_name The field name of the comment to find.
  88931. * \assert
  88932. * \code object != NULL \endcode
  88933. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88934. * \code field_name != NULL \endcode
  88935. * \retval int
  88936. * The offset in the comment array of the first comment whose field
  88937. * name matches \a field_name, or \c -1 if no match was found.
  88938. */
  88939. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88940. /** Remove first Vorbis comment matching the given field name.
  88941. *
  88942. * \param object A pointer to an existing VORBIS_COMMENT object.
  88943. * \param field_name The field name of comment to delete.
  88944. * \assert
  88945. * \code object != NULL \endcode
  88946. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88947. * \retval int
  88948. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88949. * \c 1 for one matching entry deleted.
  88950. */
  88951. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88952. /** Remove all Vorbis comments matching the given field name.
  88953. *
  88954. * \param object A pointer to an existing VORBIS_COMMENT object.
  88955. * \param field_name The field name of comments to delete.
  88956. * \assert
  88957. * \code object != NULL \endcode
  88958. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88959. * \retval int
  88960. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88961. * else the number of matching entries deleted.
  88962. */
  88963. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88964. /** Create a new CUESHEET track instance.
  88965. *
  88966. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88967. *
  88968. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88969. * \c NULL if there was an error allocating memory, else the new instance.
  88970. */
  88971. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88972. /** Create a copy of an existing CUESHEET track object.
  88973. *
  88974. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88975. * object is also copied. The caller takes ownership of the new object and
  88976. * is responsible for freeing it with
  88977. * FLAC__metadata_object_cuesheet_track_delete().
  88978. *
  88979. * \param object Pointer to object to copy.
  88980. * \assert
  88981. * \code object != NULL \endcode
  88982. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88983. * \c NULL if there was an error allocating memory, else the new instance.
  88984. */
  88985. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88986. /** Delete a CUESHEET track object
  88987. *
  88988. * \param object A pointer to an existing CUESHEET track object.
  88989. * \assert
  88990. * \code object != NULL \endcode
  88991. */
  88992. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88993. /** Resize a track's index point array.
  88994. *
  88995. * If the size shrinks, elements will truncated; if it grows, new blank
  88996. * indices will be added to the end.
  88997. *
  88998. * \param object A pointer to an existing CUESHEET object.
  88999. * \param track_num The index of the track to modify. NOTE: this is not
  89000. * necessarily the same as the track's \a number field.
  89001. * \param new_num_indices The desired length of the array; may be \c 0.
  89002. * \assert
  89003. * \code object != NULL \endcode
  89004. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89005. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89006. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89007. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89008. * \retval FLAC__bool
  89009. * \c false if memory allocation error, else \c true.
  89010. */
  89011. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89012. /** Insert an index point in a CUESHEET track at the given index.
  89013. *
  89014. * \param object A pointer to an existing CUESHEET object.
  89015. * \param track_num The index of the track to modify. NOTE: this is not
  89016. * necessarily the same as the track's \a number field.
  89017. * \param index_num The index into the track's index array at which to
  89018. * insert the index point. NOTE: this is not necessarily
  89019. * the same as the index point's \a number field. The
  89020. * indices at and after \a index_num move right one
  89021. * position. To append an index point to the end, set
  89022. * \a index_num to
  89023. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89024. * \param index The index point to insert.
  89025. * \assert
  89026. * \code object != NULL \endcode
  89027. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89028. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89029. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89030. * \retval FLAC__bool
  89031. * \c false if realloc() fails, else \c true.
  89032. */
  89033. 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);
  89034. /** Insert a blank index point in a CUESHEET track at the given index.
  89035. *
  89036. * A blank index point is one in which all field values are zero.
  89037. *
  89038. * \param object A pointer to an existing CUESHEET object.
  89039. * \param track_num The index of the track to modify. NOTE: this is not
  89040. * necessarily the same as the track's \a number field.
  89041. * \param index_num The index into the track's index array at which to
  89042. * insert the index point. NOTE: this is not necessarily
  89043. * the same as the index point's \a number field. The
  89044. * indices at and after \a index_num move right one
  89045. * position. To append an index point to the end, set
  89046. * \a index_num to
  89047. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89048. * \assert
  89049. * \code object != NULL \endcode
  89050. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89051. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89052. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89053. * \retval FLAC__bool
  89054. * \c false if realloc() fails, else \c true.
  89055. */
  89056. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89057. /** Delete an index point in a CUESHEET track at the given index.
  89058. *
  89059. * \param object A pointer to an existing CUESHEET object.
  89060. * \param track_num The index into the track array of the track to
  89061. * modify. NOTE: this is not necessarily the same
  89062. * as the track's \a number field.
  89063. * \param index_num The index into the track's index array of the index
  89064. * to delete. NOTE: this is not necessarily the same
  89065. * as the index's \a number field.
  89066. * \assert
  89067. * \code object != NULL \endcode
  89068. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89069. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89070. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89071. * \retval FLAC__bool
  89072. * \c false if realloc() fails, else \c true.
  89073. */
  89074. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89075. /** Resize the track array.
  89076. *
  89077. * If the size shrinks, elements will truncated; if it grows, new blank
  89078. * tracks will be added to the end.
  89079. *
  89080. * \param object A pointer to an existing CUESHEET object.
  89081. * \param new_num_tracks The desired length of the array; may be \c 0.
  89082. * \assert
  89083. * \code object != NULL \endcode
  89084. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89085. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89086. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89087. * \retval FLAC__bool
  89088. * \c false if memory allocation error, else \c true.
  89089. */
  89090. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89091. /** Sets a track in a CUESHEET block.
  89092. *
  89093. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89094. * takes ownership of the \a track pointer.
  89095. *
  89096. * \param object A pointer to an existing CUESHEET object.
  89097. * \param track_num Index into track array to set. NOTE: this is not
  89098. * necessarily the same as the track's \a number field.
  89099. * \param track The track to set the track to. You may safely pass in
  89100. * a const pointer if \a copy is \c true.
  89101. * \param copy See above.
  89102. * \assert
  89103. * \code object != NULL \endcode
  89104. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89105. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89106. * \code (track->indices != NULL && track->num_indices > 0) ||
  89107. * (track->indices == NULL && track->num_indices == 0)
  89108. * \retval FLAC__bool
  89109. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89110. */
  89111. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89112. /** Insert a track in a CUESHEET block at the given index.
  89113. *
  89114. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89115. * takes ownership of the \a track pointer.
  89116. *
  89117. * \param object A pointer to an existing CUESHEET object.
  89118. * \param track_num The index at which to insert the track. NOTE: this
  89119. * is not necessarily the same as the track's \a number
  89120. * field. The tracks at and after \a track_num move right
  89121. * one position. To append a track to the end, set
  89122. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89123. * \param track The track to insert. You may safely pass in a const
  89124. * pointer if \a copy is \c true.
  89125. * \param copy See above.
  89126. * \assert
  89127. * \code object != NULL \endcode
  89128. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89129. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89130. * \retval FLAC__bool
  89131. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89132. */
  89133. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89134. /** Insert a blank track in a CUESHEET block at the given index.
  89135. *
  89136. * A blank track is one in which all field values are zero.
  89137. *
  89138. * \param object A pointer to an existing CUESHEET object.
  89139. * \param track_num The index at which to insert the track. NOTE: this
  89140. * is not necessarily the same as the track's \a number
  89141. * field. The tracks at and after \a track_num move right
  89142. * one position. To append a track to the end, set
  89143. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89144. * \assert
  89145. * \code object != NULL \endcode
  89146. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89147. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89148. * \retval FLAC__bool
  89149. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89150. */
  89151. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89152. /** Delete a track in a CUESHEET block at the given index.
  89153. *
  89154. * \param object A pointer to an existing CUESHEET object.
  89155. * \param track_num The index into the track array of the track to
  89156. * delete. NOTE: this is not necessarily the same
  89157. * as the track's \a number field.
  89158. * \assert
  89159. * \code object != NULL \endcode
  89160. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89161. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89162. * \retval FLAC__bool
  89163. * \c false if realloc() fails, else \c true.
  89164. */
  89165. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89166. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89167. * See the format specification for limits on the contents of the
  89168. * cue sheet.
  89169. *
  89170. * \param object A pointer to an existing CUESHEET object.
  89171. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89172. * stringent requirements for a CD-DA (audio) disc.
  89173. * \param violation Address of a pointer to a string. If there is a
  89174. * violation, a pointer to a string explanation of the
  89175. * violation will be returned here. \a violation may be
  89176. * \c NULL if you don't need the returned string. Do not
  89177. * free the returned string; it will always point to static
  89178. * data.
  89179. * \assert
  89180. * \code object != NULL \endcode
  89181. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89182. * \retval FLAC__bool
  89183. * \c false if cue sheet is illegal, else \c true.
  89184. */
  89185. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89186. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89187. * assumes the cue sheet corresponds to a CD; the result is undefined
  89188. * if the cuesheet's is_cd bit is not set.
  89189. *
  89190. * \param object A pointer to an existing CUESHEET object.
  89191. * \assert
  89192. * \code object != NULL \endcode
  89193. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89194. * \retval FLAC__uint32
  89195. * The unsigned integer representation of the CDDB/freedb ID
  89196. */
  89197. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89198. /** Sets the MIME type of a PICTURE block.
  89199. *
  89200. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89201. * takes ownership of the pointer. The existing string will be freed if this
  89202. * function is successful, otherwise the original string will remain if \a copy
  89203. * is \c true and malloc() fails.
  89204. *
  89205. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89206. *
  89207. * \param object A pointer to an existing PICTURE object.
  89208. * \param mime_type A pointer to the MIME type string. The string must be
  89209. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89210. * is done.
  89211. * \param copy See above.
  89212. * \assert
  89213. * \code object != NULL \endcode
  89214. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89215. * \code (mime_type != NULL) \endcode
  89216. * \retval FLAC__bool
  89217. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89218. */
  89219. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89220. /** Sets the description of a PICTURE block.
  89221. *
  89222. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89223. * takes ownership of the pointer. The existing string will be freed if this
  89224. * function is successful, otherwise the original string will remain if \a copy
  89225. * is \c true and malloc() fails.
  89226. *
  89227. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89228. *
  89229. * \param object A pointer to an existing PICTURE object.
  89230. * \param description A pointer to the description string. The string must be
  89231. * valid UTF-8, NUL-terminated. No validation is done.
  89232. * \param copy See above.
  89233. * \assert
  89234. * \code object != NULL \endcode
  89235. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89236. * \code (description != NULL) \endcode
  89237. * \retval FLAC__bool
  89238. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89239. */
  89240. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89241. /** Sets the picture data of a PICTURE block.
  89242. *
  89243. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89244. * takes ownership of the pointer. Also sets the \a data_length field of the
  89245. * metadata object to what is passed in as the \a length parameter. The
  89246. * existing data will be freed if this function is successful, otherwise the
  89247. * original data and data_length will remain if \a copy is \c true and
  89248. * malloc() fails.
  89249. *
  89250. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89251. *
  89252. * \param object A pointer to an existing PICTURE object.
  89253. * \param data A pointer to the data to set.
  89254. * \param length The length of \a data in bytes.
  89255. * \param copy See above.
  89256. * \assert
  89257. * \code object != NULL \endcode
  89258. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89259. * \code (data != NULL && length > 0) ||
  89260. * (data == NULL && length == 0 && copy == false) \endcode
  89261. * \retval FLAC__bool
  89262. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89263. */
  89264. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89265. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89266. * See the format specification for limits on the contents of the
  89267. * PICTURE block.
  89268. *
  89269. * \param object A pointer to existing PICTURE block to be checked.
  89270. * \param violation Address of a pointer to a string. If there is a
  89271. * violation, a pointer to a string explanation of the
  89272. * violation will be returned here. \a violation may be
  89273. * \c NULL if you don't need the returned string. Do not
  89274. * free the returned string; it will always point to static
  89275. * data.
  89276. * \assert
  89277. * \code object != NULL \endcode
  89278. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89279. * \retval FLAC__bool
  89280. * \c false if PICTURE block is illegal, else \c true.
  89281. */
  89282. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89283. /* \} */
  89284. #ifdef __cplusplus
  89285. }
  89286. #endif
  89287. #endif
  89288. /*** End of inlined file: metadata.h ***/
  89289. /*** Start of inlined file: stream_decoder.h ***/
  89290. #ifndef FLAC__STREAM_DECODER_H
  89291. #define FLAC__STREAM_DECODER_H
  89292. #include <stdio.h> /* for FILE */
  89293. #ifdef __cplusplus
  89294. extern "C" {
  89295. #endif
  89296. /** \file include/FLAC/stream_decoder.h
  89297. *
  89298. * \brief
  89299. * This module contains the functions which implement the stream
  89300. * decoder.
  89301. *
  89302. * See the detailed documentation in the
  89303. * \link flac_stream_decoder stream decoder \endlink module.
  89304. */
  89305. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89306. * \ingroup flac
  89307. *
  89308. * \brief
  89309. * This module describes the decoder layers provided by libFLAC.
  89310. *
  89311. * The stream decoder can be used to decode complete streams either from
  89312. * the client via callbacks, or directly from a file, depending on how
  89313. * it is initialized. When decoding via callbacks, the client provides
  89314. * callbacks for reading FLAC data and writing decoded samples, and
  89315. * handling metadata and errors. If the client also supplies seek-related
  89316. * callback, the decoder function for sample-accurate seeking within the
  89317. * FLAC input is also available. When decoding from a file, the client
  89318. * needs only supply a filename or open \c FILE* and write/metadata/error
  89319. * callbacks; the rest of the callbacks are supplied internally. For more
  89320. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89321. */
  89322. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89323. * \ingroup flac_decoder
  89324. *
  89325. * \brief
  89326. * This module contains the functions which implement the stream
  89327. * decoder.
  89328. *
  89329. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89330. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89331. *
  89332. * The basic usage of this decoder is as follows:
  89333. * - The program creates an instance of a decoder using
  89334. * FLAC__stream_decoder_new().
  89335. * - The program overrides the default settings using
  89336. * FLAC__stream_decoder_set_*() functions.
  89337. * - The program initializes the instance to validate the settings and
  89338. * prepare for decoding using
  89339. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89340. * or FLAC__stream_decoder_init_file() for native FLAC,
  89341. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89342. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89343. * - The program calls the FLAC__stream_decoder_process_*() functions
  89344. * to decode data, which subsequently calls the callbacks.
  89345. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89346. * which flushes the input and output and resets the decoder to the
  89347. * uninitialized state.
  89348. * - The instance may be used again or deleted with
  89349. * FLAC__stream_decoder_delete().
  89350. *
  89351. * In more detail, the program will create a new instance by calling
  89352. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89353. * functions to override the default decoder options, and call
  89354. * one of the FLAC__stream_decoder_init_*() functions.
  89355. *
  89356. * There are three initialization functions for native FLAC, one for
  89357. * setting up the decoder to decode FLAC data from the client via
  89358. * callbacks, and two for decoding directly from a FLAC file.
  89359. *
  89360. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89361. * You must also supply several callbacks for handling I/O. Some (like
  89362. * seeking) are optional, depending on the capabilities of the input.
  89363. *
  89364. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89365. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89366. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89367. * the other callbacks internally.
  89368. *
  89369. * There are three similarly-named init functions for decoding from Ogg
  89370. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89371. * library has been built with Ogg support.
  89372. *
  89373. * Once the decoder is initialized, your program will call one of several
  89374. * functions to start the decoding process:
  89375. *
  89376. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89377. * most one metadata block or audio frame and return, calling either the
  89378. * metadata callback or write callback, respectively, once. If the decoder
  89379. * loses sync it will return with only the error callback being called.
  89380. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89381. * to process the stream from the current location and stop upon reaching
  89382. * the first audio frame. The client will get one metadata, write, or error
  89383. * callback per metadata block, audio frame, or sync error, respectively.
  89384. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89385. * to process the stream from the current location until the read callback
  89386. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89387. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89388. * write, or error callback per metadata block, audio frame, or sync error,
  89389. * respectively.
  89390. *
  89391. * When the decoder has finished decoding (normally or through an abort),
  89392. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89393. * ensures the decoder is in the correct state and frees memory. Then the
  89394. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89395. * again to decode another stream.
  89396. *
  89397. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89398. * At any point after the stream decoder has been initialized, the client can
  89399. * call this function to seek to an exact sample within the stream.
  89400. * Subsequently, the first time the write callback is called it will be
  89401. * passed a (possibly partial) block starting at that sample.
  89402. *
  89403. * If the client cannot seek via the callback interface provided, but still
  89404. * has another way of seeking, it can flush the decoder using
  89405. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89406. * through the read callback.
  89407. *
  89408. * The stream decoder also provides MD5 signature checking. If this is
  89409. * turned on before initialization, FLAC__stream_decoder_finish() will
  89410. * report when the decoded MD5 signature does not match the one stored
  89411. * in the STREAMINFO block. MD5 checking is automatically turned off
  89412. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89413. * in the STREAMINFO block or when a seek is attempted.
  89414. *
  89415. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89416. * attention. By default, the decoder only calls the metadata_callback for
  89417. * the STREAMINFO block. These functions allow you to tell the decoder
  89418. * explicitly which blocks to parse and return via the metadata_callback
  89419. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89420. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89421. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89422. * which blocks to return. Remember that metadata blocks can potentially
  89423. * be big (for example, cover art) so filtering out the ones you don't
  89424. * use can reduce the memory requirements of the decoder. Also note the
  89425. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89426. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89427. * filtering APPLICATION blocks based on the application ID.
  89428. *
  89429. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89430. * they still can legally be filtered from the metadata_callback.
  89431. *
  89432. * \note
  89433. * The "set" functions may only be called when the decoder is in the
  89434. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89435. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89436. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89437. * return \c true, otherwise \c false.
  89438. *
  89439. * \note
  89440. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89441. * defaults, including the callbacks.
  89442. *
  89443. * \{
  89444. */
  89445. /** State values for a FLAC__StreamDecoder
  89446. *
  89447. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89448. */
  89449. typedef enum {
  89450. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89451. /**< The decoder is ready to search for metadata. */
  89452. FLAC__STREAM_DECODER_READ_METADATA,
  89453. /**< The decoder is ready to or is in the process of reading metadata. */
  89454. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89455. /**< The decoder is ready to or is in the process of searching for the
  89456. * frame sync code.
  89457. */
  89458. FLAC__STREAM_DECODER_READ_FRAME,
  89459. /**< The decoder is ready to or is in the process of reading a frame. */
  89460. FLAC__STREAM_DECODER_END_OF_STREAM,
  89461. /**< The decoder has reached the end of the stream. */
  89462. FLAC__STREAM_DECODER_OGG_ERROR,
  89463. /**< An error occurred in the underlying Ogg layer. */
  89464. FLAC__STREAM_DECODER_SEEK_ERROR,
  89465. /**< An error occurred while seeking. The decoder must be flushed
  89466. * with FLAC__stream_decoder_flush() or reset with
  89467. * FLAC__stream_decoder_reset() before decoding can continue.
  89468. */
  89469. FLAC__STREAM_DECODER_ABORTED,
  89470. /**< The decoder was aborted by the read callback. */
  89471. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89472. /**< An error occurred allocating memory. The decoder is in an invalid
  89473. * state and can no longer be used.
  89474. */
  89475. FLAC__STREAM_DECODER_UNINITIALIZED
  89476. /**< The decoder is in the uninitialized state; one of the
  89477. * FLAC__stream_decoder_init_*() functions must be called before samples
  89478. * can be processed.
  89479. */
  89480. } FLAC__StreamDecoderState;
  89481. /** Maps a FLAC__StreamDecoderState to a C string.
  89482. *
  89483. * Using a FLAC__StreamDecoderState as the index to this array
  89484. * will give the string equivalent. The contents should not be modified.
  89485. */
  89486. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89487. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89488. */
  89489. typedef enum {
  89490. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89491. /**< Initialization was successful. */
  89492. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89493. /**< The library was not compiled with support for the given container
  89494. * format.
  89495. */
  89496. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89497. /**< A required callback was not supplied. */
  89498. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89499. /**< An error occurred allocating memory. */
  89500. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89501. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89502. * FLAC__stream_decoder_init_ogg_file(). */
  89503. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89504. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89505. * already initialized, usually because
  89506. * FLAC__stream_decoder_finish() was not called.
  89507. */
  89508. } FLAC__StreamDecoderInitStatus;
  89509. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89510. *
  89511. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89512. * will give the string equivalent. The contents should not be modified.
  89513. */
  89514. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89515. /** Return values for the FLAC__StreamDecoder read callback.
  89516. */
  89517. typedef enum {
  89518. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89519. /**< The read was OK and decoding can continue. */
  89520. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89521. /**< The read was attempted while at the end of the stream. Note that
  89522. * the client must only return this value when the read callback was
  89523. * called when already at the end of the stream. Otherwise, if the read
  89524. * itself moves to the end of the stream, the client should still return
  89525. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89526. * the next read callback it should return
  89527. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89528. * of \c 0.
  89529. */
  89530. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89531. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89532. } FLAC__StreamDecoderReadStatus;
  89533. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89534. *
  89535. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89536. * will give the string equivalent. The contents should not be modified.
  89537. */
  89538. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89539. /** Return values for the FLAC__StreamDecoder seek callback.
  89540. */
  89541. typedef enum {
  89542. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89543. /**< The seek was OK and decoding can continue. */
  89544. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89545. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89546. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89547. /**< Client does not support seeking. */
  89548. } FLAC__StreamDecoderSeekStatus;
  89549. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89550. *
  89551. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89552. * will give the string equivalent. The contents should not be modified.
  89553. */
  89554. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89555. /** Return values for the FLAC__StreamDecoder tell callback.
  89556. */
  89557. typedef enum {
  89558. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89559. /**< The tell was OK and decoding can continue. */
  89560. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89561. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89562. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89563. /**< Client does not support telling the position. */
  89564. } FLAC__StreamDecoderTellStatus;
  89565. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89566. *
  89567. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89568. * will give the string equivalent. The contents should not be modified.
  89569. */
  89570. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89571. /** Return values for the FLAC__StreamDecoder length callback.
  89572. */
  89573. typedef enum {
  89574. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89575. /**< The length call was OK and decoding can continue. */
  89576. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89577. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89578. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89579. /**< Client does not support reporting the length. */
  89580. } FLAC__StreamDecoderLengthStatus;
  89581. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89582. *
  89583. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89584. * will give the string equivalent. The contents should not be modified.
  89585. */
  89586. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89587. /** Return values for the FLAC__StreamDecoder write callback.
  89588. */
  89589. typedef enum {
  89590. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89591. /**< The write was OK and decoding can continue. */
  89592. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89593. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89594. } FLAC__StreamDecoderWriteStatus;
  89595. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89596. *
  89597. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89598. * will give the string equivalent. The contents should not be modified.
  89599. */
  89600. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89601. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89602. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89603. * all. The rest could be caused by bad sync (false synchronization on
  89604. * data that is not the start of a frame) or corrupted data. The error
  89605. * itself is the decoder's best guess at what happened assuming a correct
  89606. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89607. * could be caused by a correct sync on the start of a frame, but some
  89608. * data in the frame header was corrupted. Or it could be the result of
  89609. * syncing on a point the stream that looked like the starting of a frame
  89610. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89611. * could be because the decoder encountered a valid frame made by a future
  89612. * version of the encoder which it cannot parse, or because of a false
  89613. * sync making it appear as though an encountered frame was generated by
  89614. * a future encoder.
  89615. */
  89616. typedef enum {
  89617. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89618. /**< An error in the stream caused the decoder to lose synchronization. */
  89619. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89620. /**< The decoder encountered a corrupted frame header. */
  89621. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89622. /**< The frame's data did not match the CRC in the footer. */
  89623. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89624. /**< The decoder encountered reserved fields in use in the stream. */
  89625. } FLAC__StreamDecoderErrorStatus;
  89626. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89627. *
  89628. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89629. * will give the string equivalent. The contents should not be modified.
  89630. */
  89631. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89632. /***********************************************************************
  89633. *
  89634. * class FLAC__StreamDecoder
  89635. *
  89636. ***********************************************************************/
  89637. struct FLAC__StreamDecoderProtected;
  89638. struct FLAC__StreamDecoderPrivate;
  89639. /** The opaque structure definition for the stream decoder type.
  89640. * See the \link flac_stream_decoder stream decoder module \endlink
  89641. * for a detailed description.
  89642. */
  89643. typedef struct {
  89644. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89645. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89646. } FLAC__StreamDecoder;
  89647. /** Signature for the read callback.
  89648. *
  89649. * A function pointer matching this signature must be passed to
  89650. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89651. * called when the decoder needs more input data. The address of the
  89652. * buffer to be filled is supplied, along with the number of bytes the
  89653. * buffer can hold. The callback may choose to supply less data and
  89654. * modify the byte count but must be careful not to overflow the buffer.
  89655. * The callback then returns a status code chosen from
  89656. * FLAC__StreamDecoderReadStatus.
  89657. *
  89658. * Here is an example of a read callback for stdio streams:
  89659. * \code
  89660. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89661. * {
  89662. * FILE *file = ((MyClientData*)client_data)->file;
  89663. * if(*bytes > 0) {
  89664. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89665. * if(ferror(file))
  89666. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89667. * else if(*bytes == 0)
  89668. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89669. * else
  89670. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89671. * }
  89672. * else
  89673. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89674. * }
  89675. * \endcode
  89676. *
  89677. * \note In general, FLAC__StreamDecoder functions which change the
  89678. * state should not be called on the \a decoder while in the callback.
  89679. *
  89680. * \param decoder The decoder instance calling the callback.
  89681. * \param buffer A pointer to a location for the callee to store
  89682. * data to be decoded.
  89683. * \param bytes A pointer to the size of the buffer. On entry
  89684. * to the callback, it contains the maximum number
  89685. * of bytes that may be stored in \a buffer. The
  89686. * callee must set it to the actual number of bytes
  89687. * stored (0 in case of error or end-of-stream) before
  89688. * returning.
  89689. * \param client_data The callee's client data set through
  89690. * FLAC__stream_decoder_init_*().
  89691. * \retval FLAC__StreamDecoderReadStatus
  89692. * The callee's return status. Note that the callback should return
  89693. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89694. * zero bytes were read and there is no more data to be read.
  89695. */
  89696. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89697. /** Signature for the seek callback.
  89698. *
  89699. * A function pointer matching this signature may be passed to
  89700. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89701. * called when the decoder needs to seek the input stream. The decoder
  89702. * will pass the absolute byte offset to seek to, 0 meaning the
  89703. * beginning of the stream.
  89704. *
  89705. * Here is an example of a seek callback for stdio streams:
  89706. * \code
  89707. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89708. * {
  89709. * FILE *file = ((MyClientData*)client_data)->file;
  89710. * if(file == stdin)
  89711. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89712. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89713. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89714. * else
  89715. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89716. * }
  89717. * \endcode
  89718. *
  89719. * \note In general, FLAC__StreamDecoder functions which change the
  89720. * state should not be called on the \a decoder while in the callback.
  89721. *
  89722. * \param decoder The decoder instance calling the callback.
  89723. * \param absolute_byte_offset The offset from the beginning of the stream
  89724. * to seek to.
  89725. * \param client_data The callee's client data set through
  89726. * FLAC__stream_decoder_init_*().
  89727. * \retval FLAC__StreamDecoderSeekStatus
  89728. * The callee's return status.
  89729. */
  89730. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89731. /** Signature for the tell callback.
  89732. *
  89733. * A function pointer matching this signature may be passed to
  89734. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89735. * called when the decoder wants to know the current position of the
  89736. * stream. The callback should return the byte offset from the
  89737. * beginning of the stream.
  89738. *
  89739. * Here is an example of a tell callback for stdio streams:
  89740. * \code
  89741. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89742. * {
  89743. * FILE *file = ((MyClientData*)client_data)->file;
  89744. * off_t pos;
  89745. * if(file == stdin)
  89746. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89747. * else if((pos = ftello(file)) < 0)
  89748. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89749. * else {
  89750. * *absolute_byte_offset = (FLAC__uint64)pos;
  89751. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89752. * }
  89753. * }
  89754. * \endcode
  89755. *
  89756. * \note In general, FLAC__StreamDecoder functions which change the
  89757. * state should not be called on the \a decoder while in the callback.
  89758. *
  89759. * \param decoder The decoder instance calling the callback.
  89760. * \param absolute_byte_offset A pointer to storage for the current offset
  89761. * from the beginning of the stream.
  89762. * \param client_data The callee's client data set through
  89763. * FLAC__stream_decoder_init_*().
  89764. * \retval FLAC__StreamDecoderTellStatus
  89765. * The callee's return status.
  89766. */
  89767. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89768. /** Signature for the length callback.
  89769. *
  89770. * A function pointer matching this signature may be passed to
  89771. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89772. * called when the decoder wants to know the total length of the stream
  89773. * in bytes.
  89774. *
  89775. * Here is an example of a length callback for stdio streams:
  89776. * \code
  89777. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89778. * {
  89779. * FILE *file = ((MyClientData*)client_data)->file;
  89780. * struct stat filestats;
  89781. *
  89782. * if(file == stdin)
  89783. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89784. * else if(fstat(fileno(file), &filestats) != 0)
  89785. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89786. * else {
  89787. * *stream_length = (FLAC__uint64)filestats.st_size;
  89788. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89789. * }
  89790. * }
  89791. * \endcode
  89792. *
  89793. * \note In general, FLAC__StreamDecoder functions which change the
  89794. * state should not be called on the \a decoder while in the callback.
  89795. *
  89796. * \param decoder The decoder instance calling the callback.
  89797. * \param stream_length A pointer to storage for the length of the stream
  89798. * in bytes.
  89799. * \param client_data The callee's client data set through
  89800. * FLAC__stream_decoder_init_*().
  89801. * \retval FLAC__StreamDecoderLengthStatus
  89802. * The callee's return status.
  89803. */
  89804. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89805. /** Signature for the EOF callback.
  89806. *
  89807. * A function pointer matching this signature may be passed to
  89808. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89809. * called when the decoder needs to know if the end of the stream has
  89810. * been reached.
  89811. *
  89812. * Here is an example of a EOF callback for stdio streams:
  89813. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89814. * \code
  89815. * {
  89816. * FILE *file = ((MyClientData*)client_data)->file;
  89817. * return feof(file)? true : false;
  89818. * }
  89819. * \endcode
  89820. *
  89821. * \note In general, FLAC__StreamDecoder functions which change the
  89822. * state should not be called on the \a decoder while in the callback.
  89823. *
  89824. * \param decoder The decoder instance calling the callback.
  89825. * \param client_data The callee's client data set through
  89826. * FLAC__stream_decoder_init_*().
  89827. * \retval FLAC__bool
  89828. * \c true if the currently at the end of the stream, else \c false.
  89829. */
  89830. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89831. /** Signature for the write callback.
  89832. *
  89833. * A function pointer matching this signature must be passed to one of
  89834. * the FLAC__stream_decoder_init_*() functions.
  89835. * The supplied function will be called when the decoder has decoded a
  89836. * single audio frame. The decoder will pass the frame metadata as well
  89837. * as an array of pointers (one for each channel) pointing to the
  89838. * decoded audio.
  89839. *
  89840. * \note In general, FLAC__StreamDecoder functions which change the
  89841. * state should not be called on the \a decoder while in the callback.
  89842. *
  89843. * \param decoder The decoder instance calling the callback.
  89844. * \param frame The description of the decoded frame. See
  89845. * FLAC__Frame.
  89846. * \param buffer An array of pointers to decoded channels of data.
  89847. * Each pointer will point to an array of signed
  89848. * samples of length \a frame->header.blocksize.
  89849. * Channels will be ordered according to the FLAC
  89850. * specification; see the documentation for the
  89851. * <A HREF="../format.html#frame_header">frame header</A>.
  89852. * \param client_data The callee's client data set through
  89853. * FLAC__stream_decoder_init_*().
  89854. * \retval FLAC__StreamDecoderWriteStatus
  89855. * The callee's return status.
  89856. */
  89857. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89858. /** Signature for the metadata callback.
  89859. *
  89860. * A function pointer matching this signature must be passed to one of
  89861. * the FLAC__stream_decoder_init_*() functions.
  89862. * The supplied function will be called when the decoder has decoded a
  89863. * metadata block. In a valid FLAC file there will always be one
  89864. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89865. * These will be supplied by the decoder in the same order as they
  89866. * appear in the stream and always before the first audio frame (i.e.
  89867. * write callback). The metadata block that is passed in must not be
  89868. * modified, and it doesn't live beyond the callback, so you should make
  89869. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89870. * elsewhere. Since metadata blocks can potentially be large, by
  89871. * default the decoder only calls the metadata callback for the
  89872. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89873. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89874. *
  89875. * \note In general, FLAC__StreamDecoder functions which change the
  89876. * state should not be called on the \a decoder while in the callback.
  89877. *
  89878. * \param decoder The decoder instance calling the callback.
  89879. * \param metadata The decoded metadata block.
  89880. * \param client_data The callee's client data set through
  89881. * FLAC__stream_decoder_init_*().
  89882. */
  89883. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89884. /** Signature for the error callback.
  89885. *
  89886. * A function pointer matching this signature must be passed to one of
  89887. * the FLAC__stream_decoder_init_*() functions.
  89888. * The supplied function will be called whenever an error occurs during
  89889. * decoding.
  89890. *
  89891. * \note In general, FLAC__StreamDecoder functions which change the
  89892. * state should not be called on the \a decoder while in the callback.
  89893. *
  89894. * \param decoder The decoder instance calling the callback.
  89895. * \param status The error encountered by the decoder.
  89896. * \param client_data The callee's client data set through
  89897. * FLAC__stream_decoder_init_*().
  89898. */
  89899. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89900. /***********************************************************************
  89901. *
  89902. * Class constructor/destructor
  89903. *
  89904. ***********************************************************************/
  89905. /** Create a new stream decoder instance. The instance is created with
  89906. * default settings; see the individual FLAC__stream_decoder_set_*()
  89907. * functions for each setting's default.
  89908. *
  89909. * \retval FLAC__StreamDecoder*
  89910. * \c NULL if there was an error allocating memory, else the new instance.
  89911. */
  89912. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89913. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89914. *
  89915. * \param decoder A pointer to an existing decoder.
  89916. * \assert
  89917. * \code decoder != NULL \endcode
  89918. */
  89919. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89920. /***********************************************************************
  89921. *
  89922. * Public class method prototypes
  89923. *
  89924. ***********************************************************************/
  89925. /** Set the serial number for the FLAC stream within the Ogg container.
  89926. * The default behavior is to use the serial number of the first Ogg
  89927. * page. Setting a serial number here will explicitly specify which
  89928. * stream is to be decoded.
  89929. *
  89930. * \note
  89931. * This does not need to be set for native FLAC decoding.
  89932. *
  89933. * \default \c use serial number of first page
  89934. * \param decoder A decoder instance to set.
  89935. * \param serial_number See above.
  89936. * \assert
  89937. * \code decoder != NULL \endcode
  89938. * \retval FLAC__bool
  89939. * \c false if the decoder is already initialized, else \c true.
  89940. */
  89941. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89942. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89943. * compute the MD5 signature of the unencoded audio data while decoding
  89944. * and compare it to the signature from the STREAMINFO block, if it
  89945. * exists, during FLAC__stream_decoder_finish().
  89946. *
  89947. * MD5 signature checking will be turned off (until the next
  89948. * FLAC__stream_decoder_reset()) if there is no signature in the
  89949. * STREAMINFO block or when a seek is attempted.
  89950. *
  89951. * Clients that do not use the MD5 check should leave this off to speed
  89952. * up decoding.
  89953. *
  89954. * \default \c false
  89955. * \param decoder A decoder instance to set.
  89956. * \param value Flag value (see above).
  89957. * \assert
  89958. * \code decoder != NULL \endcode
  89959. * \retval FLAC__bool
  89960. * \c false if the decoder is already initialized, else \c true.
  89961. */
  89962. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89963. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89964. *
  89965. * \default By default, only the \c STREAMINFO block is returned via the
  89966. * metadata callback.
  89967. * \param decoder A decoder instance to set.
  89968. * \param type See above.
  89969. * \assert
  89970. * \code decoder != NULL \endcode
  89971. * \a type is valid
  89972. * \retval FLAC__bool
  89973. * \c false if the decoder is already initialized, else \c true.
  89974. */
  89975. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89976. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89977. * given \a id.
  89978. *
  89979. * \default By default, only the \c STREAMINFO block is returned via the
  89980. * metadata callback.
  89981. * \param decoder A decoder instance to set.
  89982. * \param id See above.
  89983. * \assert
  89984. * \code decoder != NULL \endcode
  89985. * \code id != NULL \endcode
  89986. * \retval FLAC__bool
  89987. * \c false if the decoder is already initialized, else \c true.
  89988. */
  89989. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89990. /** Direct the decoder to pass on all metadata blocks of any type.
  89991. *
  89992. * \default By default, only the \c STREAMINFO block is returned via the
  89993. * metadata callback.
  89994. * \param decoder A decoder instance to set.
  89995. * \assert
  89996. * \code decoder != NULL \endcode
  89997. * \retval FLAC__bool
  89998. * \c false if the decoder is already initialized, else \c true.
  89999. */
  90000. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90001. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90002. *
  90003. * \default By default, only the \c STREAMINFO block is returned via the
  90004. * metadata callback.
  90005. * \param decoder A decoder instance to set.
  90006. * \param type See above.
  90007. * \assert
  90008. * \code decoder != NULL \endcode
  90009. * \a type is valid
  90010. * \retval FLAC__bool
  90011. * \c false if the decoder is already initialized, else \c true.
  90012. */
  90013. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90014. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90015. * the given \a id.
  90016. *
  90017. * \default By default, only the \c STREAMINFO block is returned via the
  90018. * metadata callback.
  90019. * \param decoder A decoder instance to set.
  90020. * \param id See above.
  90021. * \assert
  90022. * \code decoder != NULL \endcode
  90023. * \code id != NULL \endcode
  90024. * \retval FLAC__bool
  90025. * \c false if the decoder is already initialized, else \c true.
  90026. */
  90027. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90028. /** Direct the decoder to filter out all metadata blocks of any type.
  90029. *
  90030. * \default By default, only the \c STREAMINFO block is returned via the
  90031. * metadata callback.
  90032. * \param decoder A decoder instance to set.
  90033. * \assert
  90034. * \code decoder != NULL \endcode
  90035. * \retval FLAC__bool
  90036. * \c false if the decoder is already initialized, else \c true.
  90037. */
  90038. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90039. /** Get the current decoder state.
  90040. *
  90041. * \param decoder A decoder instance to query.
  90042. * \assert
  90043. * \code decoder != NULL \endcode
  90044. * \retval FLAC__StreamDecoderState
  90045. * The current decoder state.
  90046. */
  90047. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90048. /** Get the current decoder state as a C string.
  90049. *
  90050. * \param decoder A decoder instance to query.
  90051. * \assert
  90052. * \code decoder != NULL \endcode
  90053. * \retval const char *
  90054. * The decoder state as a C string. Do not modify the contents.
  90055. */
  90056. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90057. /** Get the "MD5 signature checking" flag.
  90058. * This is the value of the setting, not whether or not the decoder is
  90059. * currently checking the MD5 (remember, it can be turned off automatically
  90060. * by a seek). When the decoder is reset the flag will be restored to the
  90061. * value returned by this function.
  90062. *
  90063. * \param decoder A decoder instance to query.
  90064. * \assert
  90065. * \code decoder != NULL \endcode
  90066. * \retval FLAC__bool
  90067. * See above.
  90068. */
  90069. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90070. /** Get the total number of samples in the stream being decoded.
  90071. * Will only be valid after decoding has started and will contain the
  90072. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90073. *
  90074. * \param decoder A decoder instance to query.
  90075. * \assert
  90076. * \code decoder != NULL \endcode
  90077. * \retval unsigned
  90078. * See above.
  90079. */
  90080. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90081. /** Get the current number of channels in the stream being decoded.
  90082. * Will only be valid after decoding has started and will contain the
  90083. * value from the most recently decoded frame header.
  90084. *
  90085. * \param decoder A decoder instance to query.
  90086. * \assert
  90087. * \code decoder != NULL \endcode
  90088. * \retval unsigned
  90089. * See above.
  90090. */
  90091. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90092. /** Get the current channel assignment in the stream being decoded.
  90093. * Will only be valid after decoding has started and will contain the
  90094. * value from the most recently decoded frame header.
  90095. *
  90096. * \param decoder A decoder instance to query.
  90097. * \assert
  90098. * \code decoder != NULL \endcode
  90099. * \retval FLAC__ChannelAssignment
  90100. * See above.
  90101. */
  90102. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90103. /** Get the current sample resolution in the stream being decoded.
  90104. * Will only be valid after decoding has started and will contain the
  90105. * value from the most recently decoded frame header.
  90106. *
  90107. * \param decoder A decoder instance to query.
  90108. * \assert
  90109. * \code decoder != NULL \endcode
  90110. * \retval unsigned
  90111. * See above.
  90112. */
  90113. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90114. /** Get the current sample rate in Hz of the stream being decoded.
  90115. * Will only be valid after decoding has started and will contain the
  90116. * value from the most recently decoded frame header.
  90117. *
  90118. * \param decoder A decoder instance to query.
  90119. * \assert
  90120. * \code decoder != NULL \endcode
  90121. * \retval unsigned
  90122. * See above.
  90123. */
  90124. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90125. /** Get the current blocksize of the stream being decoded.
  90126. * Will only be valid after decoding has started and will contain the
  90127. * value from the most recently decoded frame header.
  90128. *
  90129. * \param decoder A decoder instance to query.
  90130. * \assert
  90131. * \code decoder != NULL \endcode
  90132. * \retval unsigned
  90133. * See above.
  90134. */
  90135. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90136. /** Returns the decoder's current read position within the stream.
  90137. * The position is the byte offset from the start of the stream.
  90138. * Bytes before this position have been fully decoded. Note that
  90139. * there may still be undecoded bytes in the decoder's read FIFO.
  90140. * The returned position is correct even after a seek.
  90141. *
  90142. * \warning This function currently only works for native FLAC,
  90143. * not Ogg FLAC streams.
  90144. *
  90145. * \param decoder A decoder instance to query.
  90146. * \param position Address at which to return the desired position.
  90147. * \assert
  90148. * \code decoder != NULL \endcode
  90149. * \code position != NULL \endcode
  90150. * \retval FLAC__bool
  90151. * \c true if successful, \c false if the stream is not native FLAC,
  90152. * or there was an error from the 'tell' callback or it returned
  90153. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90154. */
  90155. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90156. /** Initialize the decoder instance to decode native FLAC streams.
  90157. *
  90158. * This flavor of initialization sets up the decoder to decode from a
  90159. * native FLAC stream. I/O is performed via callbacks to the client.
  90160. * For decoding from a plain file via filename or open FILE*,
  90161. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90162. * provide a simpler interface.
  90163. *
  90164. * This function should be called after FLAC__stream_decoder_new() and
  90165. * FLAC__stream_decoder_set_*() but before any of the
  90166. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90167. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90168. * if initialization succeeded.
  90169. *
  90170. * \param decoder An uninitialized decoder instance.
  90171. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90172. * pointer must not be \c NULL.
  90173. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90174. * pointer may be \c NULL if seeking is not
  90175. * supported. If \a seek_callback is not \c NULL then a
  90176. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90177. * Alternatively, a dummy seek callback that just
  90178. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90179. * may also be supplied, all though this is slightly
  90180. * less efficient for the decoder.
  90181. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90182. * pointer may be \c NULL if not supported by the client. If
  90183. * \a seek_callback is not \c NULL then a
  90184. * \a tell_callback must also be supplied.
  90185. * Alternatively, a dummy tell callback that just
  90186. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90187. * may also be supplied, all though this is slightly
  90188. * less efficient for the decoder.
  90189. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90190. * pointer may be \c NULL if not supported by the client. If
  90191. * \a seek_callback is not \c NULL then a
  90192. * \a length_callback must also be supplied.
  90193. * Alternatively, a dummy length callback that just
  90194. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90195. * may also be supplied, all though this is slightly
  90196. * less efficient for the decoder.
  90197. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90198. * pointer may be \c NULL if not supported by the client. If
  90199. * \a seek_callback is not \c NULL then a
  90200. * \a eof_callback must also be supplied.
  90201. * Alternatively, a dummy length callback that just
  90202. * returns \c false
  90203. * may also be supplied, all though this is slightly
  90204. * less efficient for the decoder.
  90205. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90206. * pointer must not be \c NULL.
  90207. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90208. * pointer may be \c NULL if the callback is not
  90209. * desired.
  90210. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90211. * pointer must not be \c NULL.
  90212. * \param client_data This value will be supplied to callbacks in their
  90213. * \a client_data argument.
  90214. * \assert
  90215. * \code decoder != NULL \endcode
  90216. * \retval FLAC__StreamDecoderInitStatus
  90217. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90218. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90219. */
  90220. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90221. FLAC__StreamDecoder *decoder,
  90222. FLAC__StreamDecoderReadCallback read_callback,
  90223. FLAC__StreamDecoderSeekCallback seek_callback,
  90224. FLAC__StreamDecoderTellCallback tell_callback,
  90225. FLAC__StreamDecoderLengthCallback length_callback,
  90226. FLAC__StreamDecoderEofCallback eof_callback,
  90227. FLAC__StreamDecoderWriteCallback write_callback,
  90228. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90229. FLAC__StreamDecoderErrorCallback error_callback,
  90230. void *client_data
  90231. );
  90232. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90233. *
  90234. * This flavor of initialization sets up the decoder to decode from a
  90235. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90236. * client. For decoding from a plain file via filename or open FILE*,
  90237. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90238. * provide a simpler interface.
  90239. *
  90240. * This function should be called after FLAC__stream_decoder_new() and
  90241. * FLAC__stream_decoder_set_*() but before any of the
  90242. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90243. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90244. * if initialization succeeded.
  90245. *
  90246. * \note Support for Ogg FLAC in the library is optional. If this
  90247. * library has been built without support for Ogg FLAC, this function
  90248. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90249. *
  90250. * \param decoder An uninitialized decoder instance.
  90251. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90252. * pointer must not be \c NULL.
  90253. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90254. * pointer may be \c NULL if seeking is not
  90255. * supported. If \a seek_callback is not \c NULL then a
  90256. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90257. * Alternatively, a dummy seek callback that just
  90258. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90259. * may also be supplied, all though this is slightly
  90260. * less efficient for the decoder.
  90261. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90262. * pointer may be \c NULL if not supported by the client. If
  90263. * \a seek_callback is not \c NULL then a
  90264. * \a tell_callback must also be supplied.
  90265. * Alternatively, a dummy tell callback that just
  90266. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90267. * may also be supplied, all though this is slightly
  90268. * less efficient for the decoder.
  90269. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90270. * pointer may be \c NULL if not supported by the client. If
  90271. * \a seek_callback is not \c NULL then a
  90272. * \a length_callback must also be supplied.
  90273. * Alternatively, a dummy length callback that just
  90274. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90275. * may also be supplied, all though this is slightly
  90276. * less efficient for the decoder.
  90277. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90278. * pointer may be \c NULL if not supported by the client. If
  90279. * \a seek_callback is not \c NULL then a
  90280. * \a eof_callback must also be supplied.
  90281. * Alternatively, a dummy length callback that just
  90282. * returns \c false
  90283. * may also be supplied, all though this is slightly
  90284. * less efficient for the decoder.
  90285. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90286. * pointer must not be \c NULL.
  90287. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90288. * pointer may be \c NULL if the callback is not
  90289. * desired.
  90290. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90291. * pointer must not be \c NULL.
  90292. * \param client_data This value will be supplied to callbacks in their
  90293. * \a client_data argument.
  90294. * \assert
  90295. * \code decoder != NULL \endcode
  90296. * \retval FLAC__StreamDecoderInitStatus
  90297. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90298. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90299. */
  90300. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90301. FLAC__StreamDecoder *decoder,
  90302. FLAC__StreamDecoderReadCallback read_callback,
  90303. FLAC__StreamDecoderSeekCallback seek_callback,
  90304. FLAC__StreamDecoderTellCallback tell_callback,
  90305. FLAC__StreamDecoderLengthCallback length_callback,
  90306. FLAC__StreamDecoderEofCallback eof_callback,
  90307. FLAC__StreamDecoderWriteCallback write_callback,
  90308. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90309. FLAC__StreamDecoderErrorCallback error_callback,
  90310. void *client_data
  90311. );
  90312. /** Initialize the decoder instance to decode native FLAC files.
  90313. *
  90314. * This flavor of initialization sets up the decoder to decode from a
  90315. * plain native FLAC file. For non-stdio streams, you must use
  90316. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90317. *
  90318. * This function should be called after FLAC__stream_decoder_new() and
  90319. * FLAC__stream_decoder_set_*() but before any of the
  90320. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90321. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90322. * if initialization succeeded.
  90323. *
  90324. * \param decoder An uninitialized decoder instance.
  90325. * \param file An open FLAC file. The file should have been
  90326. * opened with mode \c "rb" and rewound. The file
  90327. * becomes owned by the decoder and should not be
  90328. * manipulated by the client while decoding.
  90329. * Unless \a file is \c stdin, it will be closed
  90330. * when FLAC__stream_decoder_finish() is called.
  90331. * Note however that seeking will not work when
  90332. * decoding from \c stdout since it is not seekable.
  90333. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90334. * pointer must not be \c NULL.
  90335. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90336. * pointer may be \c NULL if the callback is not
  90337. * desired.
  90338. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90339. * pointer must not be \c NULL.
  90340. * \param client_data This value will be supplied to callbacks in their
  90341. * \a client_data argument.
  90342. * \assert
  90343. * \code decoder != NULL \endcode
  90344. * \code file != NULL \endcode
  90345. * \retval FLAC__StreamDecoderInitStatus
  90346. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90347. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90348. */
  90349. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90350. FLAC__StreamDecoder *decoder,
  90351. FILE *file,
  90352. FLAC__StreamDecoderWriteCallback write_callback,
  90353. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90354. FLAC__StreamDecoderErrorCallback error_callback,
  90355. void *client_data
  90356. );
  90357. /** Initialize the decoder instance to decode Ogg FLAC files.
  90358. *
  90359. * This flavor of initialization sets up the decoder to decode from a
  90360. * plain Ogg FLAC file. For non-stdio streams, you must use
  90361. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90362. *
  90363. * This function should be called after FLAC__stream_decoder_new() and
  90364. * FLAC__stream_decoder_set_*() but before any of the
  90365. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90366. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90367. * if initialization succeeded.
  90368. *
  90369. * \note Support for Ogg FLAC in the library is optional. If this
  90370. * library has been built without support for Ogg FLAC, this function
  90371. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90372. *
  90373. * \param decoder An uninitialized decoder instance.
  90374. * \param file An open FLAC file. The file should have been
  90375. * opened with mode \c "rb" and rewound. The file
  90376. * becomes owned by the decoder and should not be
  90377. * manipulated by the client while decoding.
  90378. * Unless \a file is \c stdin, it will be closed
  90379. * when FLAC__stream_decoder_finish() is called.
  90380. * Note however that seeking will not work when
  90381. * decoding from \c stdout since it is not seekable.
  90382. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90383. * pointer must not be \c NULL.
  90384. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90385. * pointer may be \c NULL if the callback is not
  90386. * desired.
  90387. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90388. * pointer must not be \c NULL.
  90389. * \param client_data This value will be supplied to callbacks in their
  90390. * \a client_data argument.
  90391. * \assert
  90392. * \code decoder != NULL \endcode
  90393. * \code file != NULL \endcode
  90394. * \retval FLAC__StreamDecoderInitStatus
  90395. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90396. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90397. */
  90398. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90399. FLAC__StreamDecoder *decoder,
  90400. FILE *file,
  90401. FLAC__StreamDecoderWriteCallback write_callback,
  90402. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90403. FLAC__StreamDecoderErrorCallback error_callback,
  90404. void *client_data
  90405. );
  90406. /** Initialize the decoder instance to decode native FLAC files.
  90407. *
  90408. * This flavor of initialization sets up the decoder to decode from a plain
  90409. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90410. * example, with Unicode filenames on Windows), you must use
  90411. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90412. * and provide callbacks for the I/O.
  90413. *
  90414. * This function should be called after FLAC__stream_decoder_new() and
  90415. * FLAC__stream_decoder_set_*() but before any of the
  90416. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90417. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90418. * if initialization succeeded.
  90419. *
  90420. * \param decoder An uninitialized decoder instance.
  90421. * \param filename The name of the file to decode from. The file will
  90422. * be opened with fopen(). Use \c NULL to decode from
  90423. * \c stdin. Note that \c stdin is not seekable.
  90424. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90425. * pointer must not be \c NULL.
  90426. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90427. * pointer may be \c NULL if the callback is not
  90428. * desired.
  90429. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90430. * pointer must not be \c NULL.
  90431. * \param client_data This value will be supplied to callbacks in their
  90432. * \a client_data argument.
  90433. * \assert
  90434. * \code decoder != NULL \endcode
  90435. * \retval FLAC__StreamDecoderInitStatus
  90436. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90437. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90438. */
  90439. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90440. FLAC__StreamDecoder *decoder,
  90441. const char *filename,
  90442. FLAC__StreamDecoderWriteCallback write_callback,
  90443. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90444. FLAC__StreamDecoderErrorCallback error_callback,
  90445. void *client_data
  90446. );
  90447. /** Initialize the decoder instance to decode Ogg FLAC files.
  90448. *
  90449. * This flavor of initialization sets up the decoder to decode from a plain
  90450. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90451. * example, with Unicode filenames on Windows), you must use
  90452. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90453. * and provide callbacks for the I/O.
  90454. *
  90455. * This function should be called after FLAC__stream_decoder_new() and
  90456. * FLAC__stream_decoder_set_*() but before any of the
  90457. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90458. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90459. * if initialization succeeded.
  90460. *
  90461. * \note Support for Ogg FLAC in the library is optional. If this
  90462. * library has been built without support for Ogg FLAC, this function
  90463. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90464. *
  90465. * \param decoder An uninitialized decoder instance.
  90466. * \param filename The name of the file to decode from. The file will
  90467. * be opened with fopen(). Use \c NULL to decode from
  90468. * \c stdin. Note that \c stdin is not seekable.
  90469. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90470. * pointer must not be \c NULL.
  90471. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90472. * pointer may be \c NULL if the callback is not
  90473. * desired.
  90474. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90475. * pointer must not be \c NULL.
  90476. * \param client_data This value will be supplied to callbacks in their
  90477. * \a client_data argument.
  90478. * \assert
  90479. * \code decoder != NULL \endcode
  90480. * \retval FLAC__StreamDecoderInitStatus
  90481. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90482. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90483. */
  90484. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90485. FLAC__StreamDecoder *decoder,
  90486. const char *filename,
  90487. FLAC__StreamDecoderWriteCallback write_callback,
  90488. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90489. FLAC__StreamDecoderErrorCallback error_callback,
  90490. void *client_data
  90491. );
  90492. /** Finish the decoding process.
  90493. * Flushes the decoding buffer, releases resources, resets the decoder
  90494. * settings to their defaults, and returns the decoder state to
  90495. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90496. *
  90497. * In the event of a prematurely-terminated decode, it is not strictly
  90498. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90499. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90500. * with a FLAC__stream_decoder_finish().
  90501. *
  90502. * \param decoder An uninitialized decoder instance.
  90503. * \assert
  90504. * \code decoder != NULL \endcode
  90505. * \retval FLAC__bool
  90506. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90507. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90508. * signature does not match the one computed by the decoder; else
  90509. * \c true.
  90510. */
  90511. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90512. /** Flush the stream input.
  90513. * The decoder's input buffer will be cleared and the state set to
  90514. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90515. * off MD5 checking.
  90516. *
  90517. * \param decoder A decoder instance.
  90518. * \assert
  90519. * \code decoder != NULL \endcode
  90520. * \retval FLAC__bool
  90521. * \c true if successful, else \c false if a memory allocation
  90522. * error occurs (in which case the state will be set to
  90523. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90524. */
  90525. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90526. /** Reset the decoding process.
  90527. * The decoder's input buffer will be cleared and the state set to
  90528. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90529. * FLAC__stream_decoder_finish() except that the settings are
  90530. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90531. * before decoding again. MD5 checking will be restored to its original
  90532. * setting.
  90533. *
  90534. * If the decoder is seekable, or was initialized with
  90535. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90536. * the decoder will also attempt to seek to the beginning of the file.
  90537. * If this rewind fails, this function will return \c false. It follows
  90538. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90539. * \c stdin.
  90540. *
  90541. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90542. * and is not seekable (i.e. no seek callback was provided or the seek
  90543. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90544. * is the duty of the client to start feeding data from the beginning of
  90545. * the stream on the next FLAC__stream_decoder_process() or
  90546. * FLAC__stream_decoder_process_interleaved() call.
  90547. *
  90548. * \param decoder A decoder instance.
  90549. * \assert
  90550. * \code decoder != NULL \endcode
  90551. * \retval FLAC__bool
  90552. * \c true if successful, else \c false if a memory allocation occurs
  90553. * (in which case the state will be set to
  90554. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90555. * occurs (the state will be unchanged).
  90556. */
  90557. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90558. /** Decode one metadata block or audio frame.
  90559. * This version instructs the decoder to decode a either a single metadata
  90560. * block or a single frame and stop, unless the callbacks return a fatal
  90561. * error or the read callback returns
  90562. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90563. *
  90564. * As the decoder needs more input it will call the read callback.
  90565. * Depending on what was decoded, the metadata or write callback will be
  90566. * called with the decoded metadata block or audio frame.
  90567. *
  90568. * Unless there is a fatal read error or end of stream, this function
  90569. * will return once one whole frame is decoded. In other words, if the
  90570. * stream is not synchronized or points to a corrupt frame header, the
  90571. * decoder will continue to try and resync until it gets to a valid
  90572. * frame, then decode one frame, then return. If the decoder points to
  90573. * a frame whose frame CRC in the frame footer does not match the
  90574. * computed frame CRC, this function will issue a
  90575. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90576. * error callback, and return, having decoded one complete, although
  90577. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90578. * correct length to the write callback.)
  90579. *
  90580. * \param decoder An initialized decoder instance.
  90581. * \assert
  90582. * \code decoder != NULL \endcode
  90583. * \retval FLAC__bool
  90584. * \c false if any fatal read, write, or memory allocation error
  90585. * occurred (meaning decoding must stop), else \c true; for more
  90586. * information about the decoder, check the decoder state with
  90587. * FLAC__stream_decoder_get_state().
  90588. */
  90589. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90590. /** Decode until the end of the metadata.
  90591. * This version instructs the decoder to decode from the current position
  90592. * and continue until all the metadata has been read, or until the
  90593. * callbacks return a fatal error or the read callback returns
  90594. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90595. *
  90596. * As the decoder needs more input it will call the read callback.
  90597. * As each metadata block is decoded, the metadata callback will be called
  90598. * with the decoded metadata.
  90599. *
  90600. * \param decoder An initialized decoder instance.
  90601. * \assert
  90602. * \code decoder != NULL \endcode
  90603. * \retval FLAC__bool
  90604. * \c false if any fatal read, write, or memory allocation error
  90605. * occurred (meaning decoding must stop), else \c true; for more
  90606. * information about the decoder, check the decoder state with
  90607. * FLAC__stream_decoder_get_state().
  90608. */
  90609. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90610. /** Decode until the end of the stream.
  90611. * This version instructs the decoder to decode from the current position
  90612. * and continue until the end of stream (the read callback returns
  90613. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90614. * callbacks return a fatal error.
  90615. *
  90616. * As the decoder needs more input it will call the read callback.
  90617. * As each metadata block and frame is decoded, the metadata or write
  90618. * callback will be called with the decoded metadata or frame.
  90619. *
  90620. * \param decoder An initialized decoder instance.
  90621. * \assert
  90622. * \code decoder != NULL \endcode
  90623. * \retval FLAC__bool
  90624. * \c false if any fatal read, write, or memory allocation error
  90625. * occurred (meaning decoding must stop), else \c true; for more
  90626. * information about the decoder, check the decoder state with
  90627. * FLAC__stream_decoder_get_state().
  90628. */
  90629. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90630. /** Skip one audio frame.
  90631. * This version instructs the decoder to 'skip' a single frame and stop,
  90632. * unless the callbacks return a fatal error or the read callback returns
  90633. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90634. *
  90635. * The decoding flow is the same as what occurs when
  90636. * FLAC__stream_decoder_process_single() is called to process an audio
  90637. * frame, except that this function does not decode the parsed data into
  90638. * PCM or call the write callback. The integrity of the frame is still
  90639. * checked the same way as in the other process functions.
  90640. *
  90641. * This function will return once one whole frame is skipped, in the
  90642. * same way that FLAC__stream_decoder_process_single() will return once
  90643. * one whole frame is decoded.
  90644. *
  90645. * This function can be used in more quickly determining FLAC frame
  90646. * boundaries when decoding of the actual data is not needed, for
  90647. * example when an application is separating a FLAC stream into frames
  90648. * for editing or storing in a container. To do this, the application
  90649. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90650. * to the next frame, then use
  90651. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90652. * boundary.
  90653. *
  90654. * This function should only be called when the stream has advanced
  90655. * past all the metadata, otherwise it will return \c false.
  90656. *
  90657. * \param decoder An initialized decoder instance not in a metadata
  90658. * state.
  90659. * \assert
  90660. * \code decoder != NULL \endcode
  90661. * \retval FLAC__bool
  90662. * \c false if any fatal read, write, or memory allocation error
  90663. * occurred (meaning decoding must stop), or if the decoder
  90664. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90665. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90666. * information about the decoder, check the decoder state with
  90667. * FLAC__stream_decoder_get_state().
  90668. */
  90669. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90670. /** Flush the input and seek to an absolute sample.
  90671. * Decoding will resume at the given sample. Note that because of
  90672. * this, the next write callback may contain a partial block. The
  90673. * client must support seeking the input or this function will fail
  90674. * and return \c false. Furthermore, if the decoder state is
  90675. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90676. * with FLAC__stream_decoder_flush() or reset with
  90677. * FLAC__stream_decoder_reset() before decoding can continue.
  90678. *
  90679. * \param decoder A decoder instance.
  90680. * \param sample The target sample number to seek to.
  90681. * \assert
  90682. * \code decoder != NULL \endcode
  90683. * \retval FLAC__bool
  90684. * \c true if successful, else \c false.
  90685. */
  90686. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90687. /* \} */
  90688. #ifdef __cplusplus
  90689. }
  90690. #endif
  90691. #endif
  90692. /*** End of inlined file: stream_decoder.h ***/
  90693. /*** Start of inlined file: stream_encoder.h ***/
  90694. #ifndef FLAC__STREAM_ENCODER_H
  90695. #define FLAC__STREAM_ENCODER_H
  90696. #include <stdio.h> /* for FILE */
  90697. #ifdef __cplusplus
  90698. extern "C" {
  90699. #endif
  90700. /** \file include/FLAC/stream_encoder.h
  90701. *
  90702. * \brief
  90703. * This module contains the functions which implement the stream
  90704. * encoder.
  90705. *
  90706. * See the detailed documentation in the
  90707. * \link flac_stream_encoder stream encoder \endlink module.
  90708. */
  90709. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90710. * \ingroup flac
  90711. *
  90712. * \brief
  90713. * This module describes the encoder layers provided by libFLAC.
  90714. *
  90715. * The stream encoder can be used to encode complete streams either to the
  90716. * client via callbacks, or directly to a file, depending on how it is
  90717. * initialized. When encoding via callbacks, the client provides a write
  90718. * callback which will be called whenever FLAC data is ready to be written.
  90719. * If the client also supplies a seek callback, the encoder will also
  90720. * automatically handle the writing back of metadata discovered while
  90721. * encoding, like stream info, seek points offsets, etc. When encoding to
  90722. * a file, the client needs only supply a filename or open \c FILE* and an
  90723. * optional progress callback for periodic notification of progress; the
  90724. * write and seek callbacks are supplied internally. For more info see the
  90725. * \link flac_stream_encoder stream encoder \endlink module.
  90726. */
  90727. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90728. * \ingroup flac_encoder
  90729. *
  90730. * \brief
  90731. * This module contains the functions which implement the stream
  90732. * encoder.
  90733. *
  90734. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90735. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90736. *
  90737. * The basic usage of this encoder is as follows:
  90738. * - The program creates an instance of an encoder using
  90739. * FLAC__stream_encoder_new().
  90740. * - The program overrides the default settings using
  90741. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90742. * functions should be called:
  90743. * - FLAC__stream_encoder_set_channels()
  90744. * - FLAC__stream_encoder_set_bits_per_sample()
  90745. * - FLAC__stream_encoder_set_sample_rate()
  90746. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90747. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90748. * - If the application wants to control the compression level or set its own
  90749. * metadata, then the following should also be called:
  90750. * - FLAC__stream_encoder_set_compression_level()
  90751. * - FLAC__stream_encoder_set_verify()
  90752. * - FLAC__stream_encoder_set_metadata()
  90753. * - The rest of the set functions should only be called if the client needs
  90754. * exact control over how the audio is compressed; thorough understanding
  90755. * of the FLAC format is necessary to achieve good results.
  90756. * - The program initializes the instance to validate the settings and
  90757. * prepare for encoding using
  90758. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90759. * or FLAC__stream_encoder_init_file() for native FLAC
  90760. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90761. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90762. * - The program calls FLAC__stream_encoder_process() or
  90763. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90764. * subsequently calls the callbacks when there is encoder data ready
  90765. * to be written.
  90766. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90767. * which causes the encoder to encode any data still in its input pipe,
  90768. * update the metadata with the final encoding statistics if output
  90769. * seeking is possible, and finally reset the encoder to the
  90770. * uninitialized state.
  90771. * - The instance may be used again or deleted with
  90772. * FLAC__stream_encoder_delete().
  90773. *
  90774. * In more detail, the stream encoder functions similarly to the
  90775. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90776. * callbacks and more options. Typically the client will create a new
  90777. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90778. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90779. * calling one of the FLAC__stream_encoder_init_*() functions.
  90780. *
  90781. * Unlike the decoders, the stream encoder has many options that can
  90782. * affect the speed and compression ratio. When setting these parameters
  90783. * you should have some basic knowledge of the format (see the
  90784. * <A HREF="../documentation.html#format">user-level documentation</A>
  90785. * or the <A HREF="../format.html">formal description</A>). The
  90786. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90787. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90788. * functions will do this, so make sure to pay attention to the state
  90789. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90790. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90791. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90792. * the constructor.
  90793. *
  90794. * There are three initialization functions for native FLAC, one for
  90795. * setting up the encoder to encode FLAC data to the client via
  90796. * callbacks, and two for encoding directly to a file.
  90797. *
  90798. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90799. * You must also supply a write callback which will be called anytime
  90800. * there is raw encoded data to write. If the client can seek the output
  90801. * it is best to also supply seek and tell callbacks, as this allows the
  90802. * encoder to go back after encoding is finished to write back
  90803. * information that was collected while encoding, like seek point offsets,
  90804. * frame sizes, etc.
  90805. *
  90806. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90807. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90808. * filename or open \c FILE*; the encoder will handle all the callbacks
  90809. * internally. You may also supply a progress callback for periodic
  90810. * notification of the encoding progress.
  90811. *
  90812. * There are three similarly-named init functions for encoding to Ogg
  90813. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90814. * library has been built with Ogg support.
  90815. *
  90816. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90817. * call the write callback several times, once with the \c fLaC signature,
  90818. * and once for each encoded metadata block. Note that for Ogg FLAC
  90819. * encoding you will usually get at least twice the number of callbacks than
  90820. * with native FLAC, one for the Ogg page header and one for the page body.
  90821. *
  90822. * After initializing the instance, the client may feed audio data to the
  90823. * encoder in one of two ways:
  90824. *
  90825. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90826. * will pass an array of pointers to buffers, one for each channel, to
  90827. * the encoder, each of the same length. The samples need not be
  90828. * block-aligned, but each channel should have the same number of samples.
  90829. * - Channel interleaved, through
  90830. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90831. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90832. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90833. * Again, the samples need not be block-aligned but they must be
  90834. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90835. * the last value channelN_sampleM.
  90836. *
  90837. * Note that for either process call, each sample in the buffers should be a
  90838. * signed integer, right-justified to the resolution set by
  90839. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90840. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90841. *
  90842. * When the client is finished encoding data, it calls
  90843. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90844. * data still in its input pipe, and call the metadata callback with the
  90845. * final encoding statistics. Then the instance may be deleted with
  90846. * FLAC__stream_encoder_delete() or initialized again to encode another
  90847. * stream.
  90848. *
  90849. * For programs that write their own metadata, but that do not know the
  90850. * actual metadata until after encoding, it is advantageous to instruct
  90851. * the encoder to write a PADDING block of the correct size, so that
  90852. * instead of rewriting the whole stream after encoding, the program can
  90853. * just overwrite the PADDING block. If only the maximum size of the
  90854. * metadata is known, the program can write a slightly larger padding
  90855. * block, then split it after encoding.
  90856. *
  90857. * Make sure you understand how lengths are calculated. All FLAC metadata
  90858. * blocks have a 4 byte header which contains the type and length. This
  90859. * length does not include the 4 bytes of the header. See the format page
  90860. * for the specification of metadata blocks and their lengths.
  90861. *
  90862. * \note
  90863. * If you are writing the FLAC data to a file via callbacks, make sure it
  90864. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90865. * after the first encoding pass, the encoder will try to seek back to the
  90866. * beginning of the stream, to the STREAMINFO block, to write some data
  90867. * there. (If using FLAC__stream_encoder_init*_file() or
  90868. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90869. *
  90870. * \note
  90871. * The "set" functions may only be called when the encoder is in the
  90872. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90873. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90874. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90875. * return \c true, otherwise \c false.
  90876. *
  90877. * \note
  90878. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90879. * defaults.
  90880. *
  90881. * \{
  90882. */
  90883. /** State values for a FLAC__StreamEncoder.
  90884. *
  90885. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90886. *
  90887. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90888. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90889. * must be deleted with FLAC__stream_encoder_delete().
  90890. */
  90891. typedef enum {
  90892. FLAC__STREAM_ENCODER_OK = 0,
  90893. /**< The encoder is in the normal OK state and samples can be processed. */
  90894. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90895. /**< The encoder is in the uninitialized state; one of the
  90896. * FLAC__stream_encoder_init_*() functions must be called before samples
  90897. * can be processed.
  90898. */
  90899. FLAC__STREAM_ENCODER_OGG_ERROR,
  90900. /**< An error occurred in the underlying Ogg layer. */
  90901. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90902. /**< An error occurred in the underlying verify stream decoder;
  90903. * check FLAC__stream_encoder_get_verify_decoder_state().
  90904. */
  90905. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90906. /**< The verify decoder detected a mismatch between the original
  90907. * audio signal and the decoded audio signal.
  90908. */
  90909. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90910. /**< One of the callbacks returned a fatal error. */
  90911. FLAC__STREAM_ENCODER_IO_ERROR,
  90912. /**< An I/O error occurred while opening/reading/writing a file.
  90913. * Check \c errno.
  90914. */
  90915. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90916. /**< An error occurred while writing the stream; usually, the
  90917. * write_callback returned an error.
  90918. */
  90919. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90920. /**< Memory allocation failed. */
  90921. } FLAC__StreamEncoderState;
  90922. /** Maps a FLAC__StreamEncoderState to a C string.
  90923. *
  90924. * Using a FLAC__StreamEncoderState as the index to this array
  90925. * will give the string equivalent. The contents should not be modified.
  90926. */
  90927. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90928. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90929. */
  90930. typedef enum {
  90931. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90932. /**< Initialization was successful. */
  90933. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90934. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90935. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90936. /**< The library was not compiled with support for the given container
  90937. * format.
  90938. */
  90939. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90940. /**< A required callback was not supplied. */
  90941. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90942. /**< The encoder has an invalid setting for number of channels. */
  90943. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90944. /**< The encoder has an invalid setting for bits-per-sample.
  90945. * FLAC supports 4-32 bps but the reference encoder currently supports
  90946. * only up to 24 bps.
  90947. */
  90948. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90949. /**< The encoder has an invalid setting for the input sample rate. */
  90950. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90951. /**< The encoder has an invalid setting for the block size. */
  90952. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90953. /**< The encoder has an invalid setting for the maximum LPC order. */
  90954. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90955. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90956. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90957. /**< The specified block size is less than the maximum LPC order. */
  90958. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90959. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90960. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90961. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90962. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90963. * - One of the metadata blocks contains an undefined type
  90964. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90965. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90966. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90967. */
  90968. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90969. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90970. * already initialized, usually because
  90971. * FLAC__stream_encoder_finish() was not called.
  90972. */
  90973. } FLAC__StreamEncoderInitStatus;
  90974. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90975. *
  90976. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90977. * will give the string equivalent. The contents should not be modified.
  90978. */
  90979. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90980. /** Return values for the FLAC__StreamEncoder read callback.
  90981. */
  90982. typedef enum {
  90983. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90984. /**< The read was OK and decoding can continue. */
  90985. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90986. /**< The read was attempted at the end of the stream. */
  90987. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90988. /**< An unrecoverable error occurred. */
  90989. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90990. /**< Client does not support reading back from the output. */
  90991. } FLAC__StreamEncoderReadStatus;
  90992. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90993. *
  90994. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90995. * will give the string equivalent. The contents should not be modified.
  90996. */
  90997. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90998. /** Return values for the FLAC__StreamEncoder write callback.
  90999. */
  91000. typedef enum {
  91001. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91002. /**< The write was OK and encoding can continue. */
  91003. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91004. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91005. } FLAC__StreamEncoderWriteStatus;
  91006. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91007. *
  91008. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91009. * will give the string equivalent. The contents should not be modified.
  91010. */
  91011. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91012. /** Return values for the FLAC__StreamEncoder seek callback.
  91013. */
  91014. typedef enum {
  91015. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91016. /**< The seek was OK and encoding can continue. */
  91017. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91018. /**< An unrecoverable error occurred. */
  91019. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91020. /**< Client does not support seeking. */
  91021. } FLAC__StreamEncoderSeekStatus;
  91022. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91023. *
  91024. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91025. * will give the string equivalent. The contents should not be modified.
  91026. */
  91027. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91028. /** Return values for the FLAC__StreamEncoder tell callback.
  91029. */
  91030. typedef enum {
  91031. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91032. /**< The tell was OK and encoding can continue. */
  91033. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91034. /**< An unrecoverable error occurred. */
  91035. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91036. /**< Client does not support seeking. */
  91037. } FLAC__StreamEncoderTellStatus;
  91038. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91039. *
  91040. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91041. * will give the string equivalent. The contents should not be modified.
  91042. */
  91043. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91044. /***********************************************************************
  91045. *
  91046. * class FLAC__StreamEncoder
  91047. *
  91048. ***********************************************************************/
  91049. struct FLAC__StreamEncoderProtected;
  91050. struct FLAC__StreamEncoderPrivate;
  91051. /** The opaque structure definition for the stream encoder type.
  91052. * See the \link flac_stream_encoder stream encoder module \endlink
  91053. * for a detailed description.
  91054. */
  91055. typedef struct {
  91056. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91057. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91058. } FLAC__StreamEncoder;
  91059. /** Signature for the read callback.
  91060. *
  91061. * A function pointer matching this signature must be passed to
  91062. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91063. * The supplied function will be called when the encoder needs to read back
  91064. * encoded data. This happens during the metadata callback, when the encoder
  91065. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91066. * while encoding. The address of the buffer to be filled is supplied, along
  91067. * with the number of bytes the buffer can hold. The callback may choose to
  91068. * supply less data and modify the byte count but must be careful not to
  91069. * overflow the buffer. The callback then returns a status code chosen from
  91070. * FLAC__StreamEncoderReadStatus.
  91071. *
  91072. * Here is an example of a read callback for stdio streams:
  91073. * \code
  91074. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91075. * {
  91076. * FILE *file = ((MyClientData*)client_data)->file;
  91077. * if(*bytes > 0) {
  91078. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91079. * if(ferror(file))
  91080. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91081. * else if(*bytes == 0)
  91082. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91083. * else
  91084. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91085. * }
  91086. * else
  91087. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91088. * }
  91089. * \endcode
  91090. *
  91091. * \note In general, FLAC__StreamEncoder functions which change the
  91092. * state should not be called on the \a encoder while in the callback.
  91093. *
  91094. * \param encoder The encoder instance calling the callback.
  91095. * \param buffer A pointer to a location for the callee to store
  91096. * data to be encoded.
  91097. * \param bytes A pointer to the size of the buffer. On entry
  91098. * to the callback, it contains the maximum number
  91099. * of bytes that may be stored in \a buffer. The
  91100. * callee must set it to the actual number of bytes
  91101. * stored (0 in case of error or end-of-stream) before
  91102. * returning.
  91103. * \param client_data The callee's client data set through
  91104. * FLAC__stream_encoder_set_client_data().
  91105. * \retval FLAC__StreamEncoderReadStatus
  91106. * The callee's return status.
  91107. */
  91108. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91109. /** Signature for the write callback.
  91110. *
  91111. * A function pointer matching this signature must be passed to
  91112. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91113. * by the encoder anytime there is raw encoded data ready to write. It may
  91114. * include metadata mixed with encoded audio frames and the data is not
  91115. * guaranteed to be aligned on frame or metadata block boundaries.
  91116. *
  91117. * The only duty of the callback is to write out the \a bytes worth of data
  91118. * in \a buffer to the current position in the output stream. The arguments
  91119. * \a samples and \a current_frame are purely informational. If \a samples
  91120. * is greater than \c 0, then \a current_frame will hold the current frame
  91121. * number that is being written; otherwise it indicates that the write
  91122. * callback is being called to write metadata.
  91123. *
  91124. * \note
  91125. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91126. * write callback will be called twice when writing each audio
  91127. * frame; once for the page header, and once for the page body.
  91128. * When writing the page header, the \a samples argument to the
  91129. * write callback will be \c 0.
  91130. *
  91131. * \note In general, FLAC__StreamEncoder functions which change the
  91132. * state should not be called on the \a encoder while in the callback.
  91133. *
  91134. * \param encoder The encoder instance calling the callback.
  91135. * \param buffer An array of encoded data of length \a bytes.
  91136. * \param bytes The byte length of \a buffer.
  91137. * \param samples The number of samples encoded by \a buffer.
  91138. * \c 0 has a special meaning; see above.
  91139. * \param current_frame The number of the current frame being encoded.
  91140. * \param client_data The callee's client data set through
  91141. * FLAC__stream_encoder_init_*().
  91142. * \retval FLAC__StreamEncoderWriteStatus
  91143. * The callee's return status.
  91144. */
  91145. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91146. /** Signature for the seek callback.
  91147. *
  91148. * A function pointer matching this signature may be passed to
  91149. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91150. * when the encoder needs to seek the output stream. The encoder will pass
  91151. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91152. *
  91153. * Here is an example of a seek callback for stdio streams:
  91154. * \code
  91155. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91156. * {
  91157. * FILE *file = ((MyClientData*)client_data)->file;
  91158. * if(file == stdin)
  91159. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91160. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91161. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91162. * else
  91163. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91164. * }
  91165. * \endcode
  91166. *
  91167. * \note In general, FLAC__StreamEncoder functions which change the
  91168. * state should not be called on the \a encoder while in the callback.
  91169. *
  91170. * \param encoder The encoder instance calling the callback.
  91171. * \param absolute_byte_offset The offset from the beginning of the stream
  91172. * to seek to.
  91173. * \param client_data The callee's client data set through
  91174. * FLAC__stream_encoder_init_*().
  91175. * \retval FLAC__StreamEncoderSeekStatus
  91176. * The callee's return status.
  91177. */
  91178. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91179. /** Signature for the tell callback.
  91180. *
  91181. * A function pointer matching this signature may be passed to
  91182. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91183. * when the encoder needs to know the current position of the output stream.
  91184. *
  91185. * \warning
  91186. * The callback must return the true current byte offset of the output to
  91187. * which the encoder is writing. If you are buffering the output, make
  91188. * sure and take this into account. If you are writing directly to a
  91189. * FILE* from your write callback, ftell() is sufficient. If you are
  91190. * writing directly to a file descriptor from your write callback, you
  91191. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91192. * these points to rewrite metadata after encoding.
  91193. *
  91194. * Here is an example of a tell callback for stdio streams:
  91195. * \code
  91196. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91197. * {
  91198. * FILE *file = ((MyClientData*)client_data)->file;
  91199. * off_t pos;
  91200. * if(file == stdin)
  91201. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91202. * else if((pos = ftello(file)) < 0)
  91203. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91204. * else {
  91205. * *absolute_byte_offset = (FLAC__uint64)pos;
  91206. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91207. * }
  91208. * }
  91209. * \endcode
  91210. *
  91211. * \note In general, FLAC__StreamEncoder functions which change the
  91212. * state should not be called on the \a encoder while in the callback.
  91213. *
  91214. * \param encoder The encoder instance calling the callback.
  91215. * \param absolute_byte_offset The address at which to store the current
  91216. * position of the output.
  91217. * \param client_data The callee's client data set through
  91218. * FLAC__stream_encoder_init_*().
  91219. * \retval FLAC__StreamEncoderTellStatus
  91220. * The callee's return status.
  91221. */
  91222. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91223. /** Signature for the metadata callback.
  91224. *
  91225. * A function pointer matching this signature may be passed to
  91226. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91227. * once at the end of encoding with the populated STREAMINFO structure. This
  91228. * is so the client can seek back to the beginning of the file and write the
  91229. * STREAMINFO block with the correct statistics after encoding (like
  91230. * minimum/maximum frame size and total samples).
  91231. *
  91232. * \note In general, FLAC__StreamEncoder functions which change the
  91233. * state should not be called on the \a encoder while in the callback.
  91234. *
  91235. * \param encoder The encoder instance calling the callback.
  91236. * \param metadata The final populated STREAMINFO block.
  91237. * \param client_data The callee's client data set through
  91238. * FLAC__stream_encoder_init_*().
  91239. */
  91240. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91241. /** Signature for the progress callback.
  91242. *
  91243. * A function pointer matching this signature may be passed to
  91244. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91245. * The supplied function will be called when the encoder has finished
  91246. * writing a frame. The \c total_frames_estimate argument to the
  91247. * callback will be based on the value from
  91248. * FLAC__stream_encoder_set_total_samples_estimate().
  91249. *
  91250. * \note In general, FLAC__StreamEncoder functions which change the
  91251. * state should not be called on the \a encoder while in the callback.
  91252. *
  91253. * \param encoder The encoder instance calling the callback.
  91254. * \param bytes_written Bytes written so far.
  91255. * \param samples_written Samples written so far.
  91256. * \param frames_written Frames written so far.
  91257. * \param total_frames_estimate The estimate of the total number of
  91258. * frames to be written.
  91259. * \param client_data The callee's client data set through
  91260. * FLAC__stream_encoder_init_*().
  91261. */
  91262. 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);
  91263. /***********************************************************************
  91264. *
  91265. * Class constructor/destructor
  91266. *
  91267. ***********************************************************************/
  91268. /** Create a new stream encoder instance. The instance is created with
  91269. * default settings; see the individual FLAC__stream_encoder_set_*()
  91270. * functions for each setting's default.
  91271. *
  91272. * \retval FLAC__StreamEncoder*
  91273. * \c NULL if there was an error allocating memory, else the new instance.
  91274. */
  91275. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91276. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91277. *
  91278. * \param encoder A pointer to an existing encoder.
  91279. * \assert
  91280. * \code encoder != NULL \endcode
  91281. */
  91282. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91283. /***********************************************************************
  91284. *
  91285. * Public class method prototypes
  91286. *
  91287. ***********************************************************************/
  91288. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91289. *
  91290. * \note
  91291. * This does not need to be set for native FLAC encoding.
  91292. *
  91293. * \note
  91294. * It is recommended to set a serial number explicitly as the default of '0'
  91295. * may collide with other streams.
  91296. *
  91297. * \default \c 0
  91298. * \param encoder An encoder instance to set.
  91299. * \param serial_number See above.
  91300. * \assert
  91301. * \code encoder != NULL \endcode
  91302. * \retval FLAC__bool
  91303. * \c false if the encoder is already initialized, else \c true.
  91304. */
  91305. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91306. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91307. * encoded output by feeding it through an internal decoder and comparing
  91308. * the original signal against the decoded signal. If a mismatch occurs,
  91309. * the process call will return \c false. Note that this will slow the
  91310. * encoding process by the extra time required for decoding and comparison.
  91311. *
  91312. * \default \c false
  91313. * \param encoder An encoder instance to set.
  91314. * \param value Flag value (see above).
  91315. * \assert
  91316. * \code encoder != NULL \endcode
  91317. * \retval FLAC__bool
  91318. * \c false if the encoder is already initialized, else \c true.
  91319. */
  91320. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91321. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91322. * the encoder will comply with the Subset and will check the
  91323. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91324. * comply. If \c false, the settings may take advantage of the full
  91325. * range that the format allows.
  91326. *
  91327. * Make sure you know what it entails before setting this to \c false.
  91328. *
  91329. * \default \c true
  91330. * \param encoder An encoder instance to set.
  91331. * \param value Flag value (see above).
  91332. * \assert
  91333. * \code encoder != NULL \endcode
  91334. * \retval FLAC__bool
  91335. * \c false if the encoder is already initialized, else \c true.
  91336. */
  91337. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91338. /** Set the number of channels to be encoded.
  91339. *
  91340. * \default \c 2
  91341. * \param encoder An encoder instance to set.
  91342. * \param value See above.
  91343. * \assert
  91344. * \code encoder != NULL \endcode
  91345. * \retval FLAC__bool
  91346. * \c false if the encoder is already initialized, else \c true.
  91347. */
  91348. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91349. /** Set the sample resolution of the input to be encoded.
  91350. *
  91351. * \warning
  91352. * Do not feed the encoder data that is wider than the value you
  91353. * set here or you will generate an invalid stream.
  91354. *
  91355. * \default \c 16
  91356. * \param encoder An encoder instance to set.
  91357. * \param value See above.
  91358. * \assert
  91359. * \code encoder != NULL \endcode
  91360. * \retval FLAC__bool
  91361. * \c false if the encoder is already initialized, else \c true.
  91362. */
  91363. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91364. /** Set the sample rate (in Hz) of the input to be encoded.
  91365. *
  91366. * \default \c 44100
  91367. * \param encoder An encoder instance to set.
  91368. * \param value See above.
  91369. * \assert
  91370. * \code encoder != NULL \endcode
  91371. * \retval FLAC__bool
  91372. * \c false if the encoder is already initialized, else \c true.
  91373. */
  91374. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91375. /** Set the compression level
  91376. *
  91377. * The compression level is roughly proportional to the amount of effort
  91378. * the encoder expends to compress the file. A higher level usually
  91379. * means more computation but higher compression. The default level is
  91380. * suitable for most applications.
  91381. *
  91382. * Currently the levels range from \c 0 (fastest, least compression) to
  91383. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91384. * treated as \c 8.
  91385. *
  91386. * This function automatically calls the following other \c _set_
  91387. * functions with appropriate values, so the client does not need to
  91388. * unless it specifically wants to override them:
  91389. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91390. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91391. * - FLAC__stream_encoder_set_apodization()
  91392. * - FLAC__stream_encoder_set_max_lpc_order()
  91393. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91394. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91395. * - FLAC__stream_encoder_set_do_escape_coding()
  91396. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91397. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91398. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91399. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91400. *
  91401. * The actual values set for each level are:
  91402. * <table>
  91403. * <tr>
  91404. * <td><b>level</b><td>
  91405. * <td>do mid-side stereo<td>
  91406. * <td>loose mid-side stereo<td>
  91407. * <td>apodization<td>
  91408. * <td>max lpc order<td>
  91409. * <td>qlp coeff precision<td>
  91410. * <td>qlp coeff prec search<td>
  91411. * <td>escape coding<td>
  91412. * <td>exhaustive model search<td>
  91413. * <td>min residual partition order<td>
  91414. * <td>max residual partition order<td>
  91415. * <td>rice parameter search dist<td>
  91416. * </tr>
  91417. * <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>
  91418. * <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>
  91419. * <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>
  91420. * <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>
  91421. * <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>
  91422. * <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>
  91423. * <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>
  91424. * <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>
  91425. * <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>
  91426. * </table>
  91427. *
  91428. * \default \c 5
  91429. * \param encoder An encoder instance to set.
  91430. * \param value See above.
  91431. * \assert
  91432. * \code encoder != NULL \endcode
  91433. * \retval FLAC__bool
  91434. * \c false if the encoder is already initialized, else \c true.
  91435. */
  91436. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91437. /** Set the blocksize to use while encoding.
  91438. *
  91439. * The number of samples to use per frame. Use \c 0 to let the encoder
  91440. * estimate a blocksize; this is usually best.
  91441. *
  91442. * \default \c 0
  91443. * \param encoder An encoder instance to set.
  91444. * \param value See above.
  91445. * \assert
  91446. * \code encoder != NULL \endcode
  91447. * \retval FLAC__bool
  91448. * \c false if the encoder is already initialized, else \c true.
  91449. */
  91450. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91451. /** Set to \c true to enable mid-side encoding on stereo input. The
  91452. * number of channels must be 2 for this to have any effect. Set to
  91453. * \c false to use only independent channel coding.
  91454. *
  91455. * \default \c false
  91456. * \param encoder An encoder instance to set.
  91457. * \param value Flag value (see above).
  91458. * \assert
  91459. * \code encoder != NULL \endcode
  91460. * \retval FLAC__bool
  91461. * \c false if the encoder is already initialized, else \c true.
  91462. */
  91463. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91464. /** Set to \c true to enable adaptive switching between mid-side and
  91465. * left-right encoding on stereo input. Set to \c false to use
  91466. * exhaustive searching. Setting this to \c true requires
  91467. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91468. * \c true in order to have any effect.
  91469. *
  91470. * \default \c false
  91471. * \param encoder An encoder instance to set.
  91472. * \param value Flag value (see above).
  91473. * \assert
  91474. * \code encoder != NULL \endcode
  91475. * \retval FLAC__bool
  91476. * \c false if the encoder is already initialized, else \c true.
  91477. */
  91478. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91479. /** Sets the apodization function(s) the encoder will use when windowing
  91480. * audio data for LPC analysis.
  91481. *
  91482. * The \a specification is a plain ASCII string which specifies exactly
  91483. * which functions to use. There may be more than one (up to 32),
  91484. * separated by \c ';' characters. Some functions take one or more
  91485. * comma-separated arguments in parentheses.
  91486. *
  91487. * The available functions are \c bartlett, \c bartlett_hann,
  91488. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91489. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91490. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91491. *
  91492. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91493. * (0<STDDEV<=0.5).
  91494. *
  91495. * For \c tukey(P), P specifies the fraction of the window that is
  91496. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91497. * corresponds to \c hann.
  91498. *
  91499. * Example specifications are \c "blackman" or
  91500. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91501. *
  91502. * Any function that is specified erroneously is silently dropped. Up
  91503. * to 32 functions are kept, the rest are dropped. If the specification
  91504. * is empty the encoder defaults to \c "tukey(0.5)".
  91505. *
  91506. * When more than one function is specified, then for every subframe the
  91507. * encoder will try each of them separately and choose the window that
  91508. * results in the smallest compressed subframe.
  91509. *
  91510. * Note that each function specified causes the encoder to occupy a
  91511. * floating point array in which to store the window.
  91512. *
  91513. * \default \c "tukey(0.5)"
  91514. * \param encoder An encoder instance to set.
  91515. * \param specification See above.
  91516. * \assert
  91517. * \code encoder != NULL \endcode
  91518. * \code specification != NULL \endcode
  91519. * \retval FLAC__bool
  91520. * \c false if the encoder is already initialized, else \c true.
  91521. */
  91522. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91523. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91524. *
  91525. * \default \c 0
  91526. * \param encoder An encoder instance to set.
  91527. * \param value See above.
  91528. * \assert
  91529. * \code encoder != NULL \endcode
  91530. * \retval FLAC__bool
  91531. * \c false if the encoder is already initialized, else \c true.
  91532. */
  91533. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91534. /** Set the precision, in bits, of the quantized linear predictor
  91535. * coefficients, or \c 0 to let the encoder select it based on the
  91536. * blocksize.
  91537. *
  91538. * \note
  91539. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91540. * be less than 32.
  91541. *
  91542. * \default \c 0
  91543. * \param encoder An encoder instance to set.
  91544. * \param value See above.
  91545. * \assert
  91546. * \code encoder != NULL \endcode
  91547. * \retval FLAC__bool
  91548. * \c false if the encoder is already initialized, else \c true.
  91549. */
  91550. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91551. /** Set to \c false to use only the specified quantized linear predictor
  91552. * coefficient precision, or \c true to search neighboring precision
  91553. * values and use the best one.
  91554. *
  91555. * \default \c false
  91556. * \param encoder An encoder instance to set.
  91557. * \param value See above.
  91558. * \assert
  91559. * \code encoder != NULL \endcode
  91560. * \retval FLAC__bool
  91561. * \c false if the encoder is already initialized, else \c true.
  91562. */
  91563. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91564. /** Deprecated. Setting this value has no effect.
  91565. *
  91566. * \default \c false
  91567. * \param encoder An encoder instance to set.
  91568. * \param value See above.
  91569. * \assert
  91570. * \code encoder != NULL \endcode
  91571. * \retval FLAC__bool
  91572. * \c false if the encoder is already initialized, else \c true.
  91573. */
  91574. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91575. /** Set to \c false to let the encoder estimate the best model order
  91576. * based on the residual signal energy, or \c true to force the
  91577. * encoder to evaluate all order models and select the best.
  91578. *
  91579. * \default \c false
  91580. * \param encoder An encoder instance to set.
  91581. * \param value 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_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91588. /** Set the minimum partition order to search when coding the residual.
  91589. * This is used in tandem with
  91590. * FLAC__stream_encoder_set_max_residual_partition_order().
  91591. *
  91592. * The partition order determines the context size in the residual.
  91593. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91594. *
  91595. * Set both min and max values to \c 0 to force a single context,
  91596. * whose Rice parameter is based on the residual signal variance.
  91597. * Otherwise, set a min and max order, and the encoder will search
  91598. * all orders, using the mean of each context for its Rice parameter,
  91599. * and use the best.
  91600. *
  91601. * \default \c 0
  91602. * \param encoder An encoder instance to set.
  91603. * \param value See above.
  91604. * \assert
  91605. * \code encoder != NULL \endcode
  91606. * \retval FLAC__bool
  91607. * \c false if the encoder is already initialized, else \c true.
  91608. */
  91609. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91610. /** Set the maximum partition order to search when coding the residual.
  91611. * This is used in tandem with
  91612. * FLAC__stream_encoder_set_min_residual_partition_order().
  91613. *
  91614. * The partition order determines the context size in the residual.
  91615. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91616. *
  91617. * Set both min and max values to \c 0 to force a single context,
  91618. * whose Rice parameter is based on the residual signal variance.
  91619. * Otherwise, set a min and max order, and the encoder will search
  91620. * all orders, using the mean of each context for its Rice parameter,
  91621. * and use the best.
  91622. *
  91623. * \default \c 0
  91624. * \param encoder An encoder instance to set.
  91625. * \param value See above.
  91626. * \assert
  91627. * \code encoder != NULL \endcode
  91628. * \retval FLAC__bool
  91629. * \c false if the encoder is already initialized, else \c true.
  91630. */
  91631. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91632. /** Deprecated. Setting this value has no effect.
  91633. *
  91634. * \default \c 0
  91635. * \param encoder An encoder instance to set.
  91636. * \param value See above.
  91637. * \assert
  91638. * \code encoder != NULL \endcode
  91639. * \retval FLAC__bool
  91640. * \c false if the encoder is already initialized, else \c true.
  91641. */
  91642. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91643. /** Set an estimate of the total samples that will be encoded.
  91644. * This is merely an estimate and may be set to \c 0 if unknown.
  91645. * This value will be written to the STREAMINFO block before encoding,
  91646. * and can remove the need for the caller to rewrite the value later
  91647. * if the value is known before encoding.
  91648. *
  91649. * \default \c 0
  91650. * \param encoder An encoder instance to set.
  91651. * \param value See above.
  91652. * \assert
  91653. * \code encoder != NULL \endcode
  91654. * \retval FLAC__bool
  91655. * \c false if the encoder is already initialized, else \c true.
  91656. */
  91657. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91658. /** Set the metadata blocks to be emitted to the stream before encoding.
  91659. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91660. * array of pointers to metadata blocks. The array is non-const since
  91661. * the encoder may need to change the \a is_last flag inside them, and
  91662. * in some cases update seek point offsets. Otherwise, the encoder will
  91663. * not modify or free the blocks. It is up to the caller to free the
  91664. * metadata blocks after encoding finishes.
  91665. *
  91666. * \note
  91667. * The encoder stores only copies of the pointers in the \a metadata array;
  91668. * the metadata blocks themselves must survive at least until after
  91669. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91670. *
  91671. * \note
  91672. * The STREAMINFO block is always written and no STREAMINFO block may
  91673. * occur in the supplied array.
  91674. *
  91675. * \note
  91676. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91677. * in the \a metadata array, but the client has specified that it does not
  91678. * support seeking, then the SEEKTABLE will be written verbatim. However
  91679. * by itself this is not very useful as the client will not know the stream
  91680. * offsets for the seekpoints ahead of time. In order to get a proper
  91681. * seektable the client must support seeking. See next note.
  91682. *
  91683. * \note
  91684. * SEEKTABLE blocks are handled specially. Since you will not know
  91685. * the values for the seek point stream offsets, you should pass in
  91686. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91687. * required sample numbers (or placeholder points), with \c 0 for the
  91688. * \a frame_samples and \a stream_offset fields for each point. If the
  91689. * client has specified that it supports seeking by providing a seek
  91690. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91691. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91692. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91693. * then while it is encoding the encoder will fill the stream offsets in
  91694. * for you and when encoding is finished, it will seek back and write the
  91695. * real values into the SEEKTABLE block in the stream. There are helper
  91696. * routines for manipulating seektable template blocks; see metadata.h:
  91697. * FLAC__metadata_object_seektable_template_*(). If the client does
  91698. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91699. * will slow down or remove the ability to seek in the FLAC stream.
  91700. *
  91701. * \note
  91702. * The encoder instance \b will modify the first \c SEEKTABLE block
  91703. * as it transforms the template to a valid seektable while encoding,
  91704. * but it is still up to the caller to free all metadata blocks after
  91705. * encoding.
  91706. *
  91707. * \note
  91708. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91709. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91710. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91711. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91712. * block is present in the \a metadata array, libFLAC will write an
  91713. * empty one, containing only the vendor string.
  91714. *
  91715. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91716. * the second metadata block of the stream. The encoder already supplies
  91717. * the STREAMINFO block automatically. If \a metadata does not contain a
  91718. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91719. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91720. * first, the init function will reorder \a metadata by moving the
  91721. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91722. * blocks will remain as they were.
  91723. *
  91724. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91725. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91726. * return \c false.
  91727. *
  91728. * \default \c NULL, 0
  91729. * \param encoder An encoder instance to set.
  91730. * \param metadata See above.
  91731. * \param num_blocks See above.
  91732. * \assert
  91733. * \code encoder != NULL \endcode
  91734. * \retval FLAC__bool
  91735. * \c false if the encoder is already initialized, else \c true.
  91736. * \c false if the encoder is already initialized, or if
  91737. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91738. */
  91739. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91740. /** Get the current encoder state.
  91741. *
  91742. * \param encoder An encoder instance to query.
  91743. * \assert
  91744. * \code encoder != NULL \endcode
  91745. * \retval FLAC__StreamEncoderState
  91746. * The current encoder state.
  91747. */
  91748. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91749. /** Get the state of the verify stream decoder.
  91750. * Useful when the stream encoder state is
  91751. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91752. *
  91753. * \param encoder An encoder instance to query.
  91754. * \assert
  91755. * \code encoder != NULL \endcode
  91756. * \retval FLAC__StreamDecoderState
  91757. * The verify stream decoder state.
  91758. */
  91759. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91760. /** Get the current encoder state as a C string.
  91761. * This version automatically resolves
  91762. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91763. * verify decoder's state.
  91764. *
  91765. * \param encoder A encoder instance to query.
  91766. * \assert
  91767. * \code encoder != NULL \endcode
  91768. * \retval const char *
  91769. * The encoder state as a C string. Do not modify the contents.
  91770. */
  91771. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91772. /** Get relevant values about the nature of a verify decoder error.
  91773. * Useful when the stream encoder state is
  91774. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91775. * be addresses in which the stats will be returned, or NULL if value
  91776. * is not desired.
  91777. *
  91778. * \param encoder An encoder instance to query.
  91779. * \param absolute_sample The absolute sample number of the mismatch.
  91780. * \param frame_number The number of the frame in which the mismatch occurred.
  91781. * \param channel The channel in which the mismatch occurred.
  91782. * \param sample The number of the sample (relative to the frame) in
  91783. * which the mismatch occurred.
  91784. * \param expected The expected value for the sample in question.
  91785. * \param got The actual value returned by the decoder.
  91786. * \assert
  91787. * \code encoder != NULL \endcode
  91788. */
  91789. 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);
  91790. /** Get the "verify" flag.
  91791. *
  91792. * \param encoder An encoder instance to query.
  91793. * \assert
  91794. * \code encoder != NULL \endcode
  91795. * \retval FLAC__bool
  91796. * See FLAC__stream_encoder_set_verify().
  91797. */
  91798. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91799. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91800. *
  91801. * \param encoder An encoder instance to query.
  91802. * \assert
  91803. * \code encoder != NULL \endcode
  91804. * \retval FLAC__bool
  91805. * See FLAC__stream_encoder_set_streamable_subset().
  91806. */
  91807. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91808. /** Get the number of input channels being processed.
  91809. *
  91810. * \param encoder An encoder instance to query.
  91811. * \assert
  91812. * \code encoder != NULL \endcode
  91813. * \retval unsigned
  91814. * See FLAC__stream_encoder_set_channels().
  91815. */
  91816. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91817. /** Get the input sample resolution setting.
  91818. *
  91819. * \param encoder An encoder instance to query.
  91820. * \assert
  91821. * \code encoder != NULL \endcode
  91822. * \retval unsigned
  91823. * See FLAC__stream_encoder_set_bits_per_sample().
  91824. */
  91825. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91826. /** Get the input sample rate setting.
  91827. *
  91828. * \param encoder An encoder instance to query.
  91829. * \assert
  91830. * \code encoder != NULL \endcode
  91831. * \retval unsigned
  91832. * See FLAC__stream_encoder_set_sample_rate().
  91833. */
  91834. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91835. /** Get the blocksize setting.
  91836. *
  91837. * \param encoder An encoder instance to query.
  91838. * \assert
  91839. * \code encoder != NULL \endcode
  91840. * \retval unsigned
  91841. * See FLAC__stream_encoder_set_blocksize().
  91842. */
  91843. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91844. /** Get the "mid/side stereo coding" flag.
  91845. *
  91846. * \param encoder An encoder instance to query.
  91847. * \assert
  91848. * \code encoder != NULL \endcode
  91849. * \retval FLAC__bool
  91850. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91851. */
  91852. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91853. /** Get the "adaptive mid/side switching" flag.
  91854. *
  91855. * \param encoder An encoder instance to query.
  91856. * \assert
  91857. * \code encoder != NULL \endcode
  91858. * \retval FLAC__bool
  91859. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91860. */
  91861. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91862. /** Get the maximum LPC order setting.
  91863. *
  91864. * \param encoder An encoder instance to query.
  91865. * \assert
  91866. * \code encoder != NULL \endcode
  91867. * \retval unsigned
  91868. * See FLAC__stream_encoder_set_max_lpc_order().
  91869. */
  91870. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91871. /** Get the quantized linear predictor coefficient precision setting.
  91872. *
  91873. * \param encoder An encoder instance to query.
  91874. * \assert
  91875. * \code encoder != NULL \endcode
  91876. * \retval unsigned
  91877. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91878. */
  91879. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91880. /** Get the qlp coefficient precision search flag.
  91881. *
  91882. * \param encoder An encoder instance to query.
  91883. * \assert
  91884. * \code encoder != NULL \endcode
  91885. * \retval FLAC__bool
  91886. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91887. */
  91888. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91889. /** Get the "escape coding" flag.
  91890. *
  91891. * \param encoder An encoder instance to query.
  91892. * \assert
  91893. * \code encoder != NULL \endcode
  91894. * \retval FLAC__bool
  91895. * See FLAC__stream_encoder_set_do_escape_coding().
  91896. */
  91897. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91898. /** Get the exhaustive model search flag.
  91899. *
  91900. * \param encoder An encoder instance to query.
  91901. * \assert
  91902. * \code encoder != NULL \endcode
  91903. * \retval FLAC__bool
  91904. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91905. */
  91906. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91907. /** Get the minimum residual partition order setting.
  91908. *
  91909. * \param encoder An encoder instance to query.
  91910. * \assert
  91911. * \code encoder != NULL \endcode
  91912. * \retval unsigned
  91913. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91914. */
  91915. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91916. /** Get maximum residual partition order setting.
  91917. *
  91918. * \param encoder An encoder instance to query.
  91919. * \assert
  91920. * \code encoder != NULL \endcode
  91921. * \retval unsigned
  91922. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91923. */
  91924. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91925. /** Get the Rice parameter search distance setting.
  91926. *
  91927. * \param encoder An encoder instance to query.
  91928. * \assert
  91929. * \code encoder != NULL \endcode
  91930. * \retval unsigned
  91931. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91932. */
  91933. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91934. /** Get the previously set estimate of the total samples to be encoded.
  91935. * The encoder merely mimics back the value given to
  91936. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91937. * other way of knowing how many samples the client will encode.
  91938. *
  91939. * \param encoder An encoder instance to set.
  91940. * \assert
  91941. * \code encoder != NULL \endcode
  91942. * \retval FLAC__uint64
  91943. * See FLAC__stream_encoder_get_total_samples_estimate().
  91944. */
  91945. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91946. /** Initialize the encoder instance to encode native FLAC streams.
  91947. *
  91948. * This flavor of initialization sets up the encoder to encode to a
  91949. * native FLAC stream. I/O is performed via callbacks to the client.
  91950. * For encoding to a plain file via filename or open \c FILE*,
  91951. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91952. * provide a simpler interface.
  91953. *
  91954. * This function should be called after FLAC__stream_encoder_new() and
  91955. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91956. * or FLAC__stream_encoder_process_interleaved().
  91957. * initialization succeeded.
  91958. *
  91959. * The call to FLAC__stream_encoder_init_stream() currently will also
  91960. * immediately call the write callback several times, once with the \c fLaC
  91961. * signature, and once for each encoded metadata block.
  91962. *
  91963. * \param encoder An uninitialized encoder instance.
  91964. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91965. * pointer must not be \c NULL.
  91966. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91967. * pointer may be \c NULL if seeking is not
  91968. * supported. The encoder uses seeking to go back
  91969. * and write some some stream statistics to the
  91970. * STREAMINFO block; this is recommended but not
  91971. * necessary to create a valid FLAC stream. If
  91972. * \a seek_callback is not \c NULL then a
  91973. * \a tell_callback must also be supplied.
  91974. * Alternatively, a dummy seek callback that just
  91975. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91976. * may also be supplied, all though this is slightly
  91977. * less efficient for the encoder.
  91978. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91979. * pointer may be \c NULL if seeking is not
  91980. * supported. If \a seek_callback is \c NULL then
  91981. * this argument will be ignored. If
  91982. * \a seek_callback is not \c NULL then a
  91983. * \a tell_callback must also be supplied.
  91984. * Alternatively, a dummy tell callback that just
  91985. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91986. * may also be supplied, all though this is slightly
  91987. * less efficient for the encoder.
  91988. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91989. * pointer may be \c NULL if the callback is not
  91990. * desired. If the client provides a seek callback,
  91991. * this function is not necessary as the encoder
  91992. * will automatically seek back and update the
  91993. * STREAMINFO block. It may also be \c NULL if the
  91994. * client does not support seeking, since it will
  91995. * have no way of going back to update the
  91996. * STREAMINFO. However the client can still supply
  91997. * a callback if it would like to know the details
  91998. * from the STREAMINFO.
  91999. * \param client_data This value will be supplied to callbacks in their
  92000. * \a client_data argument.
  92001. * \assert
  92002. * \code encoder != NULL \endcode
  92003. * \retval FLAC__StreamEncoderInitStatus
  92004. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92005. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92006. */
  92007. 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);
  92008. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92009. *
  92010. * This flavor of initialization sets up the encoder to encode to a FLAC
  92011. * stream in an Ogg container. I/O is performed via callbacks to the
  92012. * client. For encoding to a plain file via filename or open \c FILE*,
  92013. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92014. * provide a simpler interface.
  92015. *
  92016. * This function should be called after FLAC__stream_encoder_new() and
  92017. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92018. * or FLAC__stream_encoder_process_interleaved().
  92019. * initialization succeeded.
  92020. *
  92021. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92022. * immediately call the write callback several times to write the metadata
  92023. * packets.
  92024. *
  92025. * \param encoder An uninitialized encoder instance.
  92026. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92027. * pointer must not be \c NULL if \a seek_callback
  92028. * is non-NULL since they are both needed to be
  92029. * able to write data back to the Ogg FLAC stream
  92030. * in the post-encode phase.
  92031. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92032. * pointer must not be \c NULL.
  92033. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92034. * pointer may be \c NULL if seeking is not
  92035. * supported. The encoder uses seeking to go back
  92036. * and write some some stream statistics to the
  92037. * STREAMINFO block; this is recommended but not
  92038. * necessary to create a valid FLAC stream. If
  92039. * \a seek_callback is not \c NULL then a
  92040. * \a tell_callback must also be supplied.
  92041. * Alternatively, a dummy seek callback that just
  92042. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92043. * may also be supplied, all though this is slightly
  92044. * less efficient for the encoder.
  92045. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92046. * pointer may be \c NULL if seeking is not
  92047. * supported. If \a seek_callback is \c NULL then
  92048. * this argument will be ignored. If
  92049. * \a seek_callback is not \c NULL then a
  92050. * \a tell_callback must also be supplied.
  92051. * Alternatively, a dummy tell callback that just
  92052. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92053. * may also be supplied, all though this is slightly
  92054. * less efficient for the encoder.
  92055. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92056. * pointer may be \c NULL if the callback is not
  92057. * desired. If the client provides a seek callback,
  92058. * this function is not necessary as the encoder
  92059. * will automatically seek back and update the
  92060. * STREAMINFO block. It may also be \c NULL if the
  92061. * client does not support seeking, since it will
  92062. * have no way of going back to update the
  92063. * STREAMINFO. However the client can still supply
  92064. * a callback if it would like to know the details
  92065. * from the STREAMINFO.
  92066. * \param client_data This value will be supplied to callbacks in their
  92067. * \a client_data argument.
  92068. * \assert
  92069. * \code encoder != NULL \endcode
  92070. * \retval FLAC__StreamEncoderInitStatus
  92071. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92072. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92073. */
  92074. 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);
  92075. /** Initialize the encoder instance to encode native FLAC files.
  92076. *
  92077. * This flavor of initialization sets up the encoder to encode to a
  92078. * plain native FLAC file. For non-stdio streams, you must use
  92079. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92080. *
  92081. * This function should be called after FLAC__stream_encoder_new() and
  92082. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92083. * or FLAC__stream_encoder_process_interleaved().
  92084. * initialization succeeded.
  92085. *
  92086. * \param encoder An uninitialized encoder instance.
  92087. * \param file An open file. The file should have been opened
  92088. * with mode \c "w+b" and rewound. The file
  92089. * becomes owned by the encoder and should not be
  92090. * manipulated by the client while encoding.
  92091. * Unless \a file is \c stdout, it will be closed
  92092. * when FLAC__stream_encoder_finish() is called.
  92093. * Note however that a proper SEEKTABLE cannot be
  92094. * created when encoding to \c stdout since it is
  92095. * not seekable.
  92096. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92097. * pointer may be \c NULL if the callback is not
  92098. * desired.
  92099. * \param client_data This value will be supplied to callbacks in their
  92100. * \a client_data argument.
  92101. * \assert
  92102. * \code encoder != NULL \endcode
  92103. * \code file != NULL \endcode
  92104. * \retval FLAC__StreamEncoderInitStatus
  92105. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92106. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92107. */
  92108. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92109. /** Initialize the encoder instance to encode Ogg FLAC files.
  92110. *
  92111. * This flavor of initialization sets up the encoder to encode to a
  92112. * plain Ogg FLAC file. For non-stdio streams, you must use
  92113. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92114. *
  92115. * This function should be called after FLAC__stream_encoder_new() and
  92116. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92117. * or FLAC__stream_encoder_process_interleaved().
  92118. * initialization succeeded.
  92119. *
  92120. * \param encoder An uninitialized encoder instance.
  92121. * \param file An open file. The file should have been opened
  92122. * with mode \c "w+b" and rewound. The file
  92123. * becomes owned by the encoder and should not be
  92124. * manipulated by the client while encoding.
  92125. * Unless \a file is \c stdout, it will be closed
  92126. * when FLAC__stream_encoder_finish() is called.
  92127. * Note however that a proper SEEKTABLE cannot be
  92128. * created when encoding to \c stdout since it is
  92129. * not seekable.
  92130. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92131. * pointer may be \c NULL if the callback is not
  92132. * desired.
  92133. * \param client_data This value will be supplied to callbacks in their
  92134. * \a client_data argument.
  92135. * \assert
  92136. * \code encoder != NULL \endcode
  92137. * \code file != NULL \endcode
  92138. * \retval FLAC__StreamEncoderInitStatus
  92139. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92140. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92141. */
  92142. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92143. /** Initialize the encoder instance to encode native FLAC files.
  92144. *
  92145. * This flavor of initialization sets up the encoder to encode to a plain
  92146. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92147. * with Unicode filenames on Windows), you must use
  92148. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92149. * and provide callbacks for the I/O.
  92150. *
  92151. * This function should be called after FLAC__stream_encoder_new() and
  92152. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92153. * or FLAC__stream_encoder_process_interleaved().
  92154. * initialization succeeded.
  92155. *
  92156. * \param encoder An uninitialized encoder instance.
  92157. * \param filename The name of the file to encode to. The file will
  92158. * be opened with fopen(). Use \c NULL to encode to
  92159. * \c stdout. Note however that a proper SEEKTABLE
  92160. * cannot be created when encoding to \c stdout since
  92161. * it is not seekable.
  92162. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92163. * pointer may be \c NULL if the callback is not
  92164. * desired.
  92165. * \param client_data This value will be supplied to callbacks in their
  92166. * \a client_data argument.
  92167. * \assert
  92168. * \code encoder != NULL \endcode
  92169. * \retval FLAC__StreamEncoderInitStatus
  92170. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92171. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92172. */
  92173. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92174. /** Initialize the encoder instance to encode Ogg FLAC files.
  92175. *
  92176. * This flavor of initialization sets up the encoder to encode to a plain
  92177. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92178. * with Unicode filenames on Windows), you must use
  92179. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92180. * and provide callbacks for the I/O.
  92181. *
  92182. * This function should be called after FLAC__stream_encoder_new() and
  92183. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92184. * or FLAC__stream_encoder_process_interleaved().
  92185. * initialization succeeded.
  92186. *
  92187. * \param encoder An uninitialized encoder instance.
  92188. * \param filename The name of the file to encode to. The file will
  92189. * be opened with fopen(). Use \c NULL to encode to
  92190. * \c stdout. Note however that a proper SEEKTABLE
  92191. * cannot be created when encoding to \c stdout since
  92192. * it is not seekable.
  92193. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92194. * pointer may be \c NULL if the callback is not
  92195. * desired.
  92196. * \param client_data This value will be supplied to callbacks in their
  92197. * \a client_data argument.
  92198. * \assert
  92199. * \code encoder != NULL \endcode
  92200. * \retval FLAC__StreamEncoderInitStatus
  92201. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92202. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92203. */
  92204. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92205. /** Finish the encoding process.
  92206. * Flushes the encoding buffer, releases resources, resets the encoder
  92207. * settings to their defaults, and returns the encoder state to
  92208. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92209. * one or more write callbacks before returning, and will generate
  92210. * a metadata callback.
  92211. *
  92212. * Note that in the course of processing the last frame, errors can
  92213. * occur, so the caller should be sure to check the return value to
  92214. * ensure the file was encoded properly.
  92215. *
  92216. * In the event of a prematurely-terminated encode, it is not strictly
  92217. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92218. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92219. * with a FLAC__stream_encoder_finish().
  92220. *
  92221. * \param encoder An uninitialized encoder instance.
  92222. * \assert
  92223. * \code encoder != NULL \endcode
  92224. * \retval FLAC__bool
  92225. * \c false if an error occurred processing the last frame; or if verify
  92226. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92227. * verify mismatch; else \c true. If \c false, caller should check the
  92228. * state with FLAC__stream_encoder_get_state() for more information
  92229. * about the error.
  92230. */
  92231. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92232. /** Submit data for encoding.
  92233. * This version allows you to supply the input data via an array of
  92234. * pointers, each pointer pointing to an array of \a samples samples
  92235. * representing one channel. The samples need not be block-aligned,
  92236. * but each channel should have the same number of samples. Each sample
  92237. * should be a signed integer, right-justified to the resolution set by
  92238. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92239. * resolution is 16 bits per sample, the samples should all be in the
  92240. * range [-32768,32767].
  92241. *
  92242. * For applications where channel order is important, channels must
  92243. * follow the order as described in the
  92244. * <A HREF="../format.html#frame_header">frame header</A>.
  92245. *
  92246. * \param encoder An initialized encoder instance in the OK state.
  92247. * \param buffer An array of pointers to each channel's signal.
  92248. * \param samples The number of samples in one channel.
  92249. * \assert
  92250. * \code encoder != NULL \endcode
  92251. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92252. * \retval FLAC__bool
  92253. * \c true if successful, else \c false; in this case, check the
  92254. * encoder state with FLAC__stream_encoder_get_state() to see what
  92255. * went wrong.
  92256. */
  92257. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92258. /** Submit data for encoding.
  92259. * This version allows you to supply the input data where the channels
  92260. * are interleaved into a single array (i.e. channel0_sample0,
  92261. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92262. * The samples need not be block-aligned but they must be
  92263. * sample-aligned, i.e. the first value should be channel0_sample0
  92264. * and the last value channelN_sampleM. Each sample should be a signed
  92265. * integer, right-justified to the resolution set by
  92266. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92267. * resolution is 16 bits per sample, the samples should all be in the
  92268. * range [-32768,32767].
  92269. *
  92270. * For applications where channel order is important, channels must
  92271. * follow the order as described in the
  92272. * <A HREF="../format.html#frame_header">frame header</A>.
  92273. *
  92274. * \param encoder An initialized encoder instance in the OK state.
  92275. * \param buffer An array of channel-interleaved data (see above).
  92276. * \param samples The number of samples in one channel, the same as for
  92277. * FLAC__stream_encoder_process(). For example, if
  92278. * encoding two channels, \c 1000 \a samples corresponds
  92279. * to a \a buffer of 2000 values.
  92280. * \assert
  92281. * \code encoder != NULL \endcode
  92282. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92283. * \retval FLAC__bool
  92284. * \c true if successful, else \c false; in this case, check the
  92285. * encoder state with FLAC__stream_encoder_get_state() to see what
  92286. * went wrong.
  92287. */
  92288. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92289. /* \} */
  92290. #ifdef __cplusplus
  92291. }
  92292. #endif
  92293. #endif
  92294. /*** End of inlined file: stream_encoder.h ***/
  92295. #ifdef _MSC_VER
  92296. /* OPT: an MSVC built-in would be better */
  92297. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92298. {
  92299. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92300. return (x>>16) | (x<<16);
  92301. }
  92302. #endif
  92303. #if defined(_MSC_VER) && defined(_X86_)
  92304. /* OPT: an MSVC built-in would be better */
  92305. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92306. {
  92307. __asm {
  92308. mov edx, start
  92309. mov ecx, len
  92310. test ecx, ecx
  92311. loop1:
  92312. jz done1
  92313. mov eax, [edx]
  92314. bswap eax
  92315. mov [edx], eax
  92316. add edx, 4
  92317. dec ecx
  92318. jmp short loop1
  92319. done1:
  92320. }
  92321. }
  92322. #endif
  92323. /** \mainpage
  92324. *
  92325. * \section intro Introduction
  92326. *
  92327. * This is the documentation for the FLAC C and C++ APIs. It is
  92328. * highly interconnected; this introduction should give you a top
  92329. * level idea of the structure and how to find the information you
  92330. * need. As a prerequisite you should have at least a basic
  92331. * knowledge of the FLAC format, documented
  92332. * <A HREF="../format.html">here</A>.
  92333. *
  92334. * \section c_api FLAC C API
  92335. *
  92336. * The FLAC C API is the interface to libFLAC, a set of structures
  92337. * describing the components of FLAC streams, and functions for
  92338. * encoding and decoding streams, as well as manipulating FLAC
  92339. * metadata in files. The public include files will be installed
  92340. * in your include area (for example /usr/include/FLAC/...).
  92341. *
  92342. * By writing a little code and linking against libFLAC, it is
  92343. * relatively easy to add FLAC support to another program. The
  92344. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92345. * Complete source code of libFLAC as well as the command-line
  92346. * encoder and plugins is available and is a useful source of
  92347. * examples.
  92348. *
  92349. * Aside from encoders and decoders, libFLAC provides a powerful
  92350. * metadata interface for manipulating metadata in FLAC files. It
  92351. * allows the user to add, delete, and modify FLAC metadata blocks
  92352. * and it can automatically take advantage of PADDING blocks to avoid
  92353. * rewriting the entire FLAC file when changing the size of the
  92354. * metadata.
  92355. *
  92356. * libFLAC usually only requires the standard C library and C math
  92357. * library. In particular, threading is not used so there is no
  92358. * dependency on a thread library. However, libFLAC does not use
  92359. * global variables and should be thread-safe.
  92360. *
  92361. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92362. * However the metadata editing interfaces currently have limited
  92363. * read-only support for Ogg FLAC files.
  92364. *
  92365. * \section cpp_api FLAC C++ API
  92366. *
  92367. * The FLAC C++ API is a set of classes that encapsulate the
  92368. * structures and functions in libFLAC. They provide slightly more
  92369. * functionality with respect to metadata but are otherwise
  92370. * equivalent. For the most part, they share the same usage as
  92371. * their counterparts in libFLAC, and the FLAC C API documentation
  92372. * can be used as a supplement. The public include files
  92373. * for the C++ API will be installed in your include area (for
  92374. * example /usr/include/FLAC++/...).
  92375. *
  92376. * libFLAC++ is also licensed under
  92377. * <A HREF="../license.html">Xiph's BSD license</A>.
  92378. *
  92379. * \section getting_started Getting Started
  92380. *
  92381. * A good starting point for learning the API is to browse through
  92382. * the <A HREF="modules.html">modules</A>. Modules are logical
  92383. * groupings of related functions or classes, which correspond roughly
  92384. * to header files or sections of header files. Each module includes a
  92385. * detailed description of the general usage of its functions or
  92386. * classes.
  92387. *
  92388. * From there you can go on to look at the documentation of
  92389. * individual functions. You can see different views of the individual
  92390. * functions through the links in top bar across this page.
  92391. *
  92392. * If you prefer a more hands-on approach, you can jump right to some
  92393. * <A HREF="../documentation_example_code.html">example code</A>.
  92394. *
  92395. * \section porting_guide Porting Guide
  92396. *
  92397. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92398. * has been introduced which gives detailed instructions on how to
  92399. * port your code to newer versions of FLAC.
  92400. *
  92401. * \section embedded_developers Embedded Developers
  92402. *
  92403. * libFLAC has grown larger over time as more functionality has been
  92404. * included, but much of it may be unnecessary for a particular embedded
  92405. * implementation. Unused parts may be pruned by some simple editing of
  92406. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92407. * metadata interface are all independent from each other.
  92408. *
  92409. * It is easiest to just describe the dependencies:
  92410. *
  92411. * - All modules depend on the \link flac_format Format \endlink module.
  92412. * - The decoders and encoders depend on the bitbuffer.
  92413. * - The decoder is independent of the encoder. The encoder uses the
  92414. * decoder because of the verify feature, but this can be removed if
  92415. * not needed.
  92416. * - Parts of the metadata interface require the stream decoder (but not
  92417. * the encoder).
  92418. * - Ogg support is selectable through the compile time macro
  92419. * \c FLAC__HAS_OGG.
  92420. *
  92421. * For example, if your application only requires the stream decoder, no
  92422. * encoder, and no metadata interface, you can remove the stream encoder
  92423. * and the metadata interface, which will greatly reduce the size of the
  92424. * library.
  92425. *
  92426. * Also, there are several places in the libFLAC code with comments marked
  92427. * with "OPT:" where a #define can be changed to enable code that might be
  92428. * faster on a specific platform. Experimenting with these can yield faster
  92429. * binaries.
  92430. */
  92431. /** \defgroup porting Porting Guide for New Versions
  92432. *
  92433. * This module describes differences in the library interfaces from
  92434. * version to version. It assists in the porting of code that uses
  92435. * the libraries to newer versions of FLAC.
  92436. *
  92437. * One simple facility for making porting easier that has been added
  92438. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92439. * library's includes (e.g. \c include/FLAC/export.h). The
  92440. * \c #defines mirror the libraries'
  92441. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92442. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92443. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92444. * These can be used to support multiple versions of an API during the
  92445. * transition phase, e.g.
  92446. *
  92447. * \code
  92448. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92449. * legacy code
  92450. * #else
  92451. * new code
  92452. * #endif
  92453. * \endcode
  92454. *
  92455. * The the source will work for multiple versions and the legacy code can
  92456. * easily be removed when the transition is complete.
  92457. *
  92458. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92459. * include/FLAC/export.h), which can be used to determine whether or not
  92460. * the library has been compiled with support for Ogg FLAC. This is
  92461. * simpler than trying to call an Ogg init function and catching the
  92462. * error.
  92463. */
  92464. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92465. * \ingroup porting
  92466. *
  92467. * \brief
  92468. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92469. *
  92470. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92471. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92472. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92473. * decoding layers and three encoding layers have been merged into a
  92474. * single stream decoder and stream encoder. That is, the functionality
  92475. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92476. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92477. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92478. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92479. * is there is now a single API that can be used to encode or decode
  92480. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92481. * on both seekable and non-seekable streams.
  92482. *
  92483. * Instead of creating an encoder or decoder of a certain layer, now the
  92484. * client will always create a FLAC__StreamEncoder or
  92485. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92486. * initialization function. For example, for the decoder,
  92487. * FLAC__stream_decoder_init() has been replaced by
  92488. * FLAC__stream_decoder_init_stream(). This init function takes
  92489. * callbacks for the I/O, and the seeking callbacks are optional. This
  92490. * allows the client to use the same object for seekable and
  92491. * non-seekable streams. For decoding a FLAC file directly, the client
  92492. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92493. * and fewer callbacks; most of the other callbacks are supplied
  92494. * internally. For situations where fopen()ing by filename is not
  92495. * possible (e.g. Unicode filenames on Windows) the client can instead
  92496. * open the file itself and supply the FILE* to
  92497. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92498. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92499. * Since the callbacks and client data are now passed to the init
  92500. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92501. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92502. * rest of the calls to the decoder are the same as before.
  92503. *
  92504. * There are counterpart init functions for Ogg FLAC, e.g.
  92505. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92506. * and callbacks are the same as for native FLAC.
  92507. *
  92508. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92509. * been set up like so:
  92510. *
  92511. * \code
  92512. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92513. * if(decoder == NULL) do_something;
  92514. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92515. * [... other settings ...]
  92516. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92517. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92518. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92519. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92520. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92521. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92522. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92523. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92524. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92525. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92526. * \endcode
  92527. *
  92528. * In FLAC 1.1.3 it is like this:
  92529. *
  92530. * \code
  92531. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92532. * if(decoder == NULL) do_something;
  92533. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92534. * [... other settings ...]
  92535. * if(FLAC__stream_decoder_init_stream(
  92536. * decoder,
  92537. * my_read_callback,
  92538. * my_seek_callback, // or NULL
  92539. * my_tell_callback, // or NULL
  92540. * my_length_callback, // or NULL
  92541. * my_eof_callback, // or NULL
  92542. * my_write_callback,
  92543. * my_metadata_callback, // or NULL
  92544. * my_error_callback,
  92545. * my_client_data
  92546. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92547. * \endcode
  92548. *
  92549. * or you could do;
  92550. *
  92551. * \code
  92552. * [...]
  92553. * FILE *file = fopen("somefile.flac","rb");
  92554. * if(file == NULL) do_somthing;
  92555. * if(FLAC__stream_decoder_init_FILE(
  92556. * decoder,
  92557. * file,
  92558. * my_write_callback,
  92559. * my_metadata_callback, // or NULL
  92560. * my_error_callback,
  92561. * my_client_data
  92562. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92563. * \endcode
  92564. *
  92565. * or just:
  92566. *
  92567. * \code
  92568. * [...]
  92569. * if(FLAC__stream_decoder_init_file(
  92570. * decoder,
  92571. * "somefile.flac",
  92572. * my_write_callback,
  92573. * my_metadata_callback, // or NULL
  92574. * my_error_callback,
  92575. * my_client_data
  92576. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92577. * \endcode
  92578. *
  92579. * Another small change to the decoder is in how it handles unparseable
  92580. * streams. Before, when the decoder found an unparseable stream
  92581. * (reserved for when the decoder encounters a stream from a future
  92582. * encoder that it can't parse), it changed the state to
  92583. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92584. * drops sync and calls the error callback with a new error code
  92585. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92586. * more robust. If your error callback does not discriminate on the the
  92587. * error state, your code does not need to be changed.
  92588. *
  92589. * The encoder now has a new setting:
  92590. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92591. * method used to window the data before LPC analysis. You only need to
  92592. * add a call to this function if the default is not suitable. There
  92593. * are also two new convenience functions that may be useful:
  92594. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92595. * FLAC__metadata_get_cuesheet().
  92596. *
  92597. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92598. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92599. * is now \c size_t instead of \c unsigned.
  92600. */
  92601. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92602. * \ingroup porting
  92603. *
  92604. * \brief
  92605. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92606. *
  92607. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92608. * There was a slight change in the implementation of
  92609. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92610. * of the \a metadata array of pointers so the client no longer needs
  92611. * to maintain it after the call. The objects themselves that are
  92612. * pointed to by the array are still not copied though and must be
  92613. * maintained until the call to FLAC__stream_encoder_finish().
  92614. */
  92615. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92616. * \ingroup porting
  92617. *
  92618. * \brief
  92619. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92620. *
  92621. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92622. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92623. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92624. *
  92625. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92626. * has changed to reflect the conversion of one of the reserved bits
  92627. * into active use. It used to be \c 2 and now is \c 1. However the
  92628. * FLAC frame header length has not changed, so to skip the proper
  92629. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92630. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92631. */
  92632. /** \defgroup flac FLAC C API
  92633. *
  92634. * The FLAC C API is the interface to libFLAC, a set of structures
  92635. * describing the components of FLAC streams, and functions for
  92636. * encoding and decoding streams, as well as manipulating FLAC
  92637. * metadata in files.
  92638. *
  92639. * You should start with the format components as all other modules
  92640. * are dependent on it.
  92641. */
  92642. #endif
  92643. /*** End of inlined file: all.h ***/
  92644. /*** Start of inlined file: bitmath.c ***/
  92645. /*** Start of inlined file: juce_FlacHeader.h ***/
  92646. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92647. // tasks..
  92648. #define VERSION "1.2.1"
  92649. #define FLAC__NO_DLL 1
  92650. #if JUCE_MSVC
  92651. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92652. #endif
  92653. #if JUCE_MAC
  92654. #define FLAC__SYS_DARWIN 1
  92655. #endif
  92656. /*** End of inlined file: juce_FlacHeader.h ***/
  92657. #if JUCE_USE_FLAC
  92658. #if HAVE_CONFIG_H
  92659. # include <config.h>
  92660. #endif
  92661. /*** Start of inlined file: bitmath.h ***/
  92662. #ifndef FLAC__PRIVATE__BITMATH_H
  92663. #define FLAC__PRIVATE__BITMATH_H
  92664. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92665. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92666. unsigned FLAC__bitmath_silog2(int v);
  92667. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92668. #endif
  92669. /*** End of inlined file: bitmath.h ***/
  92670. /* An example of what FLAC__bitmath_ilog2() computes:
  92671. *
  92672. * ilog2( 0) = assertion failure
  92673. * ilog2( 1) = 0
  92674. * ilog2( 2) = 1
  92675. * ilog2( 3) = 1
  92676. * ilog2( 4) = 2
  92677. * ilog2( 5) = 2
  92678. * ilog2( 6) = 2
  92679. * ilog2( 7) = 2
  92680. * ilog2( 8) = 3
  92681. * ilog2( 9) = 3
  92682. * ilog2(10) = 3
  92683. * ilog2(11) = 3
  92684. * ilog2(12) = 3
  92685. * ilog2(13) = 3
  92686. * ilog2(14) = 3
  92687. * ilog2(15) = 3
  92688. * ilog2(16) = 4
  92689. * ilog2(17) = 4
  92690. * ilog2(18) = 4
  92691. */
  92692. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92693. {
  92694. unsigned l = 0;
  92695. FLAC__ASSERT(v > 0);
  92696. while(v >>= 1)
  92697. l++;
  92698. return l;
  92699. }
  92700. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92701. {
  92702. unsigned l = 0;
  92703. FLAC__ASSERT(v > 0);
  92704. while(v >>= 1)
  92705. l++;
  92706. return l;
  92707. }
  92708. /* An example of what FLAC__bitmath_silog2() computes:
  92709. *
  92710. * silog2(-10) = 5
  92711. * silog2(- 9) = 5
  92712. * silog2(- 8) = 4
  92713. * silog2(- 7) = 4
  92714. * silog2(- 6) = 4
  92715. * silog2(- 5) = 4
  92716. * silog2(- 4) = 3
  92717. * silog2(- 3) = 3
  92718. * silog2(- 2) = 2
  92719. * silog2(- 1) = 2
  92720. * silog2( 0) = 0
  92721. * silog2( 1) = 2
  92722. * silog2( 2) = 3
  92723. * silog2( 3) = 3
  92724. * silog2( 4) = 4
  92725. * silog2( 5) = 4
  92726. * silog2( 6) = 4
  92727. * silog2( 7) = 4
  92728. * silog2( 8) = 5
  92729. * silog2( 9) = 5
  92730. * silog2( 10) = 5
  92731. */
  92732. unsigned FLAC__bitmath_silog2(int v)
  92733. {
  92734. while(1) {
  92735. if(v == 0) {
  92736. return 0;
  92737. }
  92738. else if(v > 0) {
  92739. unsigned l = 0;
  92740. while(v) {
  92741. l++;
  92742. v >>= 1;
  92743. }
  92744. return l+1;
  92745. }
  92746. else if(v == -1) {
  92747. return 2;
  92748. }
  92749. else {
  92750. v++;
  92751. v = -v;
  92752. }
  92753. }
  92754. }
  92755. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92756. {
  92757. while(1) {
  92758. if(v == 0) {
  92759. return 0;
  92760. }
  92761. else if(v > 0) {
  92762. unsigned l = 0;
  92763. while(v) {
  92764. l++;
  92765. v >>= 1;
  92766. }
  92767. return l+1;
  92768. }
  92769. else if(v == -1) {
  92770. return 2;
  92771. }
  92772. else {
  92773. v++;
  92774. v = -v;
  92775. }
  92776. }
  92777. }
  92778. #endif
  92779. /*** End of inlined file: bitmath.c ***/
  92780. /*** Start of inlined file: bitreader.c ***/
  92781. /*** Start of inlined file: juce_FlacHeader.h ***/
  92782. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92783. // tasks..
  92784. #define VERSION "1.2.1"
  92785. #define FLAC__NO_DLL 1
  92786. #if JUCE_MSVC
  92787. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92788. #endif
  92789. #if JUCE_MAC
  92790. #define FLAC__SYS_DARWIN 1
  92791. #endif
  92792. /*** End of inlined file: juce_FlacHeader.h ***/
  92793. #if JUCE_USE_FLAC
  92794. #if HAVE_CONFIG_H
  92795. # include <config.h>
  92796. #endif
  92797. #include <stdlib.h> /* for malloc() */
  92798. #include <string.h> /* for memcpy(), memset() */
  92799. #ifdef _MSC_VER
  92800. #include <winsock.h> /* for ntohl() */
  92801. #elif defined FLAC__SYS_DARWIN
  92802. #include <machine/endian.h> /* for ntohl() */
  92803. #elif defined __MINGW32__
  92804. #include <winsock.h> /* for ntohl() */
  92805. #else
  92806. #include <netinet/in.h> /* for ntohl() */
  92807. #endif
  92808. /*** Start of inlined file: bitreader.h ***/
  92809. #ifndef FLAC__PRIVATE__BITREADER_H
  92810. #define FLAC__PRIVATE__BITREADER_H
  92811. #include <stdio.h> /* for FILE */
  92812. /*** Start of inlined file: cpu.h ***/
  92813. #ifndef FLAC__PRIVATE__CPU_H
  92814. #define FLAC__PRIVATE__CPU_H
  92815. #ifdef HAVE_CONFIG_H
  92816. #include <config.h>
  92817. #endif
  92818. typedef enum {
  92819. FLAC__CPUINFO_TYPE_IA32,
  92820. FLAC__CPUINFO_TYPE_PPC,
  92821. FLAC__CPUINFO_TYPE_UNKNOWN
  92822. } FLAC__CPUInfo_Type;
  92823. typedef struct {
  92824. FLAC__bool cpuid;
  92825. FLAC__bool bswap;
  92826. FLAC__bool cmov;
  92827. FLAC__bool mmx;
  92828. FLAC__bool fxsr;
  92829. FLAC__bool sse;
  92830. FLAC__bool sse2;
  92831. FLAC__bool sse3;
  92832. FLAC__bool ssse3;
  92833. FLAC__bool _3dnow;
  92834. FLAC__bool ext3dnow;
  92835. FLAC__bool extmmx;
  92836. } FLAC__CPUInfo_IA32;
  92837. typedef struct {
  92838. FLAC__bool altivec;
  92839. FLAC__bool ppc64;
  92840. } FLAC__CPUInfo_PPC;
  92841. typedef struct {
  92842. FLAC__bool use_asm;
  92843. FLAC__CPUInfo_Type type;
  92844. union {
  92845. FLAC__CPUInfo_IA32 ia32;
  92846. FLAC__CPUInfo_PPC ppc;
  92847. } data;
  92848. } FLAC__CPUInfo;
  92849. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92850. #ifndef FLAC__NO_ASM
  92851. #ifdef FLAC__CPU_IA32
  92852. #ifdef FLAC__HAS_NASM
  92853. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92854. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92855. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92856. #endif
  92857. #endif
  92858. #endif
  92859. #endif
  92860. /*** End of inlined file: cpu.h ***/
  92861. /*
  92862. * opaque structure definition
  92863. */
  92864. struct FLAC__BitReader;
  92865. typedef struct FLAC__BitReader FLAC__BitReader;
  92866. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92867. /*
  92868. * construction, deletion, initialization, etc functions
  92869. */
  92870. FLAC__BitReader *FLAC__bitreader_new(void);
  92871. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92872. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92873. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92874. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92875. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92876. /*
  92877. * CRC functions
  92878. */
  92879. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92880. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92881. /*
  92882. * info functions
  92883. */
  92884. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92885. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92886. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92887. /*
  92888. * read functions
  92889. */
  92890. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92891. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92892. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92893. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92894. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92895. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92896. 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! */
  92897. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92898. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92899. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92900. #ifndef FLAC__NO_ASM
  92901. # ifdef FLAC__CPU_IA32
  92902. # ifdef FLAC__HAS_NASM
  92903. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92904. # endif
  92905. # endif
  92906. #endif
  92907. #if 0 /* UNUSED */
  92908. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92909. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92910. #endif
  92911. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92912. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92913. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92914. #endif
  92915. /*** End of inlined file: bitreader.h ***/
  92916. /*** Start of inlined file: crc.h ***/
  92917. #ifndef FLAC__PRIVATE__CRC_H
  92918. #define FLAC__PRIVATE__CRC_H
  92919. /* 8 bit CRC generator, MSB shifted first
  92920. ** polynomial = x^8 + x^2 + x^1 + x^0
  92921. ** init = 0
  92922. */
  92923. extern FLAC__byte const FLAC__crc8_table[256];
  92924. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92925. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92926. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92927. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92928. /* 16 bit CRC generator, MSB shifted first
  92929. ** polynomial = x^16 + x^15 + x^2 + x^0
  92930. ** init = 0
  92931. */
  92932. extern unsigned FLAC__crc16_table[256];
  92933. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92934. /* this alternate may be faster on some systems/compilers */
  92935. #if 0
  92936. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92937. #endif
  92938. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92939. #endif
  92940. /*** End of inlined file: crc.h ***/
  92941. /* Things should be fastest when this matches the machine word size */
  92942. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92943. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92944. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92945. typedef FLAC__uint32 brword;
  92946. #define FLAC__BYTES_PER_WORD 4
  92947. #define FLAC__BITS_PER_WORD 32
  92948. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92949. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92950. #if WORDS_BIGENDIAN
  92951. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92952. #else
  92953. #if defined (_MSC_VER) && defined (_X86_)
  92954. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92955. #else
  92956. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92957. #endif
  92958. #endif
  92959. /* counts the # of zero MSBs in a word */
  92960. #define COUNT_ZERO_MSBS(word) ( \
  92961. (word) <= 0xffff ? \
  92962. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92963. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92964. )
  92965. /* this alternate might be slightly faster on some systems/compilers: */
  92966. #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])) )
  92967. /*
  92968. * This should be at least twice as large as the largest number of words
  92969. * required to represent any 'number' (in any encoding) you are going to
  92970. * read. With FLAC this is on the order of maybe a few hundred bits.
  92971. * If the buffer is smaller than that, the decoder won't be able to read
  92972. * in a whole number that is in a variable length encoding (e.g. Rice).
  92973. * But to be practical it should be at least 1K bytes.
  92974. *
  92975. * Increase this number to decrease the number of read callbacks, at the
  92976. * expense of using more memory. Or decrease for the reverse effect,
  92977. * keeping in mind the limit from the first paragraph. The optimal size
  92978. * also depends on the CPU cache size and other factors; some twiddling
  92979. * may be necessary to squeeze out the best performance.
  92980. */
  92981. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92982. static const unsigned char byte_to_unary_table[] = {
  92983. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92984. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92985. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92986. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92987. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92988. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92989. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92990. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92999. };
  93000. #ifdef min
  93001. #undef min
  93002. #endif
  93003. #define min(x,y) ((x)<(y)?(x):(y))
  93004. #ifdef max
  93005. #undef max
  93006. #endif
  93007. #define max(x,y) ((x)>(y)?(x):(y))
  93008. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93009. #ifdef _MSC_VER
  93010. #define FLAC__U64L(x) x
  93011. #else
  93012. #define FLAC__U64L(x) x##LLU
  93013. #endif
  93014. #ifndef FLaC__INLINE
  93015. #define FLaC__INLINE
  93016. #endif
  93017. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93018. struct FLAC__BitReader {
  93019. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93020. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93021. brword *buffer;
  93022. unsigned capacity; /* in words */
  93023. unsigned words; /* # of completed words in buffer */
  93024. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93025. unsigned consumed_words; /* #words ... */
  93026. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93027. unsigned read_crc16; /* the running frame CRC */
  93028. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93029. FLAC__BitReaderReadCallback read_callback;
  93030. void *client_data;
  93031. FLAC__CPUInfo cpu_info;
  93032. };
  93033. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93034. {
  93035. register unsigned crc = br->read_crc16;
  93036. #if FLAC__BYTES_PER_WORD == 4
  93037. switch(br->crc16_align) {
  93038. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93039. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93040. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93041. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93042. }
  93043. #elif FLAC__BYTES_PER_WORD == 8
  93044. switch(br->crc16_align) {
  93045. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93046. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93047. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93048. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93049. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93050. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93051. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93052. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93053. }
  93054. #else
  93055. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93056. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93057. br->read_crc16 = crc;
  93058. #endif
  93059. br->crc16_align = 0;
  93060. }
  93061. /* would be static except it needs to be called by asm routines */
  93062. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93063. {
  93064. unsigned start, end;
  93065. size_t bytes;
  93066. FLAC__byte *target;
  93067. /* first shift the unconsumed buffer data toward the front as much as possible */
  93068. if(br->consumed_words > 0) {
  93069. start = br->consumed_words;
  93070. end = br->words + (br->bytes? 1:0);
  93071. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93072. br->words -= start;
  93073. br->consumed_words = 0;
  93074. }
  93075. /*
  93076. * set the target for reading, taking into account word alignment and endianness
  93077. */
  93078. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93079. if(bytes == 0)
  93080. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93081. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93082. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93083. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93084. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93085. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93086. * ^^-------target, bytes=3
  93087. * on LE machines, have to byteswap the odd tail word so nothing is
  93088. * overwritten:
  93089. */
  93090. #if WORDS_BIGENDIAN
  93091. #else
  93092. if(br->bytes)
  93093. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93094. #endif
  93095. /* now it looks like:
  93096. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93097. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93098. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93099. * ^^-------target, bytes=3
  93100. */
  93101. /* read in the data; note that the callback may return a smaller number of bytes */
  93102. if(!br->read_callback(target, &bytes, br->client_data))
  93103. return false;
  93104. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93105. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93106. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93107. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93108. * now have to byteswap on LE machines:
  93109. */
  93110. #if WORDS_BIGENDIAN
  93111. #else
  93112. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93113. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93114. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93115. start = br->words;
  93116. local_swap32_block_(br->buffer + start, end - start);
  93117. }
  93118. else
  93119. # endif
  93120. for(start = br->words; start < end; start++)
  93121. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93122. #endif
  93123. /* now it looks like:
  93124. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93125. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93126. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93127. * finally we'll update the reader values:
  93128. */
  93129. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93130. br->words = end / FLAC__BYTES_PER_WORD;
  93131. br->bytes = end % FLAC__BYTES_PER_WORD;
  93132. return true;
  93133. }
  93134. /***********************************************************************
  93135. *
  93136. * Class constructor/destructor
  93137. *
  93138. ***********************************************************************/
  93139. FLAC__BitReader *FLAC__bitreader_new(void)
  93140. {
  93141. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93142. /* calloc() implies:
  93143. memset(br, 0, sizeof(FLAC__BitReader));
  93144. br->buffer = 0;
  93145. br->capacity = 0;
  93146. br->words = br->bytes = 0;
  93147. br->consumed_words = br->consumed_bits = 0;
  93148. br->read_callback = 0;
  93149. br->client_data = 0;
  93150. */
  93151. return br;
  93152. }
  93153. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93154. {
  93155. FLAC__ASSERT(0 != br);
  93156. FLAC__bitreader_free(br);
  93157. free(br);
  93158. }
  93159. /***********************************************************************
  93160. *
  93161. * Public class methods
  93162. *
  93163. ***********************************************************************/
  93164. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93165. {
  93166. FLAC__ASSERT(0 != br);
  93167. br->words = br->bytes = 0;
  93168. br->consumed_words = br->consumed_bits = 0;
  93169. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93170. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93171. if(br->buffer == 0)
  93172. return false;
  93173. br->read_callback = rcb;
  93174. br->client_data = cd;
  93175. br->cpu_info = cpu;
  93176. return true;
  93177. }
  93178. void FLAC__bitreader_free(FLAC__BitReader *br)
  93179. {
  93180. FLAC__ASSERT(0 != br);
  93181. if(0 != br->buffer)
  93182. free(br->buffer);
  93183. br->buffer = 0;
  93184. br->capacity = 0;
  93185. br->words = br->bytes = 0;
  93186. br->consumed_words = br->consumed_bits = 0;
  93187. br->read_callback = 0;
  93188. br->client_data = 0;
  93189. }
  93190. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93191. {
  93192. br->words = br->bytes = 0;
  93193. br->consumed_words = br->consumed_bits = 0;
  93194. return true;
  93195. }
  93196. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93197. {
  93198. unsigned i, j;
  93199. if(br == 0) {
  93200. fprintf(out, "bitreader is NULL\n");
  93201. }
  93202. else {
  93203. 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);
  93204. for(i = 0; i < br->words; i++) {
  93205. fprintf(out, "%08X: ", i);
  93206. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93207. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93208. fprintf(out, ".");
  93209. else
  93210. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93211. fprintf(out, "\n");
  93212. }
  93213. if(br->bytes > 0) {
  93214. fprintf(out, "%08X: ", i);
  93215. for(j = 0; j < br->bytes*8; j++)
  93216. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93217. fprintf(out, ".");
  93218. else
  93219. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93220. fprintf(out, "\n");
  93221. }
  93222. }
  93223. }
  93224. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93225. {
  93226. FLAC__ASSERT(0 != br);
  93227. FLAC__ASSERT(0 != br->buffer);
  93228. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93229. br->read_crc16 = (unsigned)seed;
  93230. br->crc16_align = br->consumed_bits;
  93231. }
  93232. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93233. {
  93234. FLAC__ASSERT(0 != br);
  93235. FLAC__ASSERT(0 != br->buffer);
  93236. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93237. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93238. /* CRC any tail bytes in a partially-consumed word */
  93239. if(br->consumed_bits) {
  93240. const brword tail = br->buffer[br->consumed_words];
  93241. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93242. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93243. }
  93244. return br->read_crc16;
  93245. }
  93246. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93247. {
  93248. return ((br->consumed_bits & 7) == 0);
  93249. }
  93250. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93251. {
  93252. return 8 - (br->consumed_bits & 7);
  93253. }
  93254. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93255. {
  93256. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93257. }
  93258. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93259. {
  93260. FLAC__ASSERT(0 != br);
  93261. FLAC__ASSERT(0 != br->buffer);
  93262. FLAC__ASSERT(bits <= 32);
  93263. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93264. FLAC__ASSERT(br->consumed_words <= br->words);
  93265. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93266. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93267. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93268. *val = 0;
  93269. return true;
  93270. }
  93271. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93272. if(!bitreader_read_from_client_(br))
  93273. return false;
  93274. }
  93275. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93276. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93277. if(br->consumed_bits) {
  93278. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93279. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93280. const brword word = br->buffer[br->consumed_words];
  93281. if(bits < n) {
  93282. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93283. br->consumed_bits += bits;
  93284. return true;
  93285. }
  93286. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93287. bits -= n;
  93288. crc16_update_word_(br, word);
  93289. br->consumed_words++;
  93290. br->consumed_bits = 0;
  93291. 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 */
  93292. *val <<= bits;
  93293. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93294. br->consumed_bits = bits;
  93295. }
  93296. return true;
  93297. }
  93298. else {
  93299. const brword word = br->buffer[br->consumed_words];
  93300. if(bits < FLAC__BITS_PER_WORD) {
  93301. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93302. br->consumed_bits = bits;
  93303. return true;
  93304. }
  93305. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93306. *val = word;
  93307. crc16_update_word_(br, word);
  93308. br->consumed_words++;
  93309. return true;
  93310. }
  93311. }
  93312. else {
  93313. /* in this case we're starting our read at a partial tail word;
  93314. * the reader has guaranteed that we have at least 'bits' bits
  93315. * available to read, which makes this case simpler.
  93316. */
  93317. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93318. if(br->consumed_bits) {
  93319. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93320. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93321. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93322. br->consumed_bits += bits;
  93323. return true;
  93324. }
  93325. else {
  93326. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93327. br->consumed_bits += bits;
  93328. return true;
  93329. }
  93330. }
  93331. }
  93332. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93333. {
  93334. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93335. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93336. return false;
  93337. /* sign-extend: */
  93338. *val <<= (32-bits);
  93339. *val >>= (32-bits);
  93340. return true;
  93341. }
  93342. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93343. {
  93344. FLAC__uint32 hi, lo;
  93345. if(bits > 32) {
  93346. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93347. return false;
  93348. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93349. return false;
  93350. *val = hi;
  93351. *val <<= 32;
  93352. *val |= lo;
  93353. }
  93354. else {
  93355. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93356. return false;
  93357. *val = lo;
  93358. }
  93359. return true;
  93360. }
  93361. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93362. {
  93363. FLAC__uint32 x8, x32 = 0;
  93364. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93365. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93366. return false;
  93367. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93368. return false;
  93369. x32 |= (x8 << 8);
  93370. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93371. return false;
  93372. x32 |= (x8 << 16);
  93373. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93374. return false;
  93375. x32 |= (x8 << 24);
  93376. *val = x32;
  93377. return true;
  93378. }
  93379. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93380. {
  93381. /*
  93382. * OPT: a faster implementation is possible but probably not that useful
  93383. * since this is only called a couple of times in the metadata readers.
  93384. */
  93385. FLAC__ASSERT(0 != br);
  93386. FLAC__ASSERT(0 != br->buffer);
  93387. if(bits > 0) {
  93388. const unsigned n = br->consumed_bits & 7;
  93389. unsigned m;
  93390. FLAC__uint32 x;
  93391. if(n != 0) {
  93392. m = min(8-n, bits);
  93393. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93394. return false;
  93395. bits -= m;
  93396. }
  93397. m = bits / 8;
  93398. if(m > 0) {
  93399. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93400. return false;
  93401. bits %= 8;
  93402. }
  93403. if(bits > 0) {
  93404. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93405. return false;
  93406. }
  93407. }
  93408. return true;
  93409. }
  93410. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93411. {
  93412. FLAC__uint32 x;
  93413. FLAC__ASSERT(0 != br);
  93414. FLAC__ASSERT(0 != br->buffer);
  93415. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93416. /* step 1: skip over partial head word to get word aligned */
  93417. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93418. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93419. return false;
  93420. nvals--;
  93421. }
  93422. if(0 == nvals)
  93423. return true;
  93424. /* step 2: skip whole words in chunks */
  93425. while(nvals >= FLAC__BYTES_PER_WORD) {
  93426. if(br->consumed_words < br->words) {
  93427. br->consumed_words++;
  93428. nvals -= FLAC__BYTES_PER_WORD;
  93429. }
  93430. else if(!bitreader_read_from_client_(br))
  93431. return false;
  93432. }
  93433. /* step 3: skip any remainder from partial tail bytes */
  93434. while(nvals) {
  93435. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93436. return false;
  93437. nvals--;
  93438. }
  93439. return true;
  93440. }
  93441. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93442. {
  93443. FLAC__uint32 x;
  93444. FLAC__ASSERT(0 != br);
  93445. FLAC__ASSERT(0 != br->buffer);
  93446. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93447. /* step 1: read from partial head word to get word aligned */
  93448. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93449. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93450. return false;
  93451. *val++ = (FLAC__byte)x;
  93452. nvals--;
  93453. }
  93454. if(0 == nvals)
  93455. return true;
  93456. /* step 2: read whole words in chunks */
  93457. while(nvals >= FLAC__BYTES_PER_WORD) {
  93458. if(br->consumed_words < br->words) {
  93459. const brword word = br->buffer[br->consumed_words++];
  93460. #if FLAC__BYTES_PER_WORD == 4
  93461. val[0] = (FLAC__byte)(word >> 24);
  93462. val[1] = (FLAC__byte)(word >> 16);
  93463. val[2] = (FLAC__byte)(word >> 8);
  93464. val[3] = (FLAC__byte)word;
  93465. #elif FLAC__BYTES_PER_WORD == 8
  93466. val[0] = (FLAC__byte)(word >> 56);
  93467. val[1] = (FLAC__byte)(word >> 48);
  93468. val[2] = (FLAC__byte)(word >> 40);
  93469. val[3] = (FLAC__byte)(word >> 32);
  93470. val[4] = (FLAC__byte)(word >> 24);
  93471. val[5] = (FLAC__byte)(word >> 16);
  93472. val[6] = (FLAC__byte)(word >> 8);
  93473. val[7] = (FLAC__byte)word;
  93474. #else
  93475. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93476. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93477. #endif
  93478. val += FLAC__BYTES_PER_WORD;
  93479. nvals -= FLAC__BYTES_PER_WORD;
  93480. }
  93481. else if(!bitreader_read_from_client_(br))
  93482. return false;
  93483. }
  93484. /* step 3: read any remainder from partial tail bytes */
  93485. while(nvals) {
  93486. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93487. return false;
  93488. *val++ = (FLAC__byte)x;
  93489. nvals--;
  93490. }
  93491. return true;
  93492. }
  93493. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93494. #if 0 /* slow but readable version */
  93495. {
  93496. unsigned bit;
  93497. FLAC__ASSERT(0 != br);
  93498. FLAC__ASSERT(0 != br->buffer);
  93499. *val = 0;
  93500. while(1) {
  93501. if(!FLAC__bitreader_read_bit(br, &bit))
  93502. return false;
  93503. if(bit)
  93504. break;
  93505. else
  93506. *val++;
  93507. }
  93508. return true;
  93509. }
  93510. #else
  93511. {
  93512. unsigned i;
  93513. FLAC__ASSERT(0 != br);
  93514. FLAC__ASSERT(0 != br->buffer);
  93515. *val = 0;
  93516. while(1) {
  93517. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93518. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93519. if(b) {
  93520. i = COUNT_ZERO_MSBS(b);
  93521. *val += i;
  93522. i++;
  93523. br->consumed_bits += i;
  93524. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93525. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93526. br->consumed_words++;
  93527. br->consumed_bits = 0;
  93528. }
  93529. return true;
  93530. }
  93531. else {
  93532. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93533. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93534. br->consumed_words++;
  93535. br->consumed_bits = 0;
  93536. /* didn't find stop bit yet, have to keep going... */
  93537. }
  93538. }
  93539. /* at this point we've eaten up all the whole words; have to try
  93540. * reading through any tail bytes before calling the read callback.
  93541. * this is a repeat of the above logic adjusted for the fact we
  93542. * don't have a whole word. note though if the client is feeding
  93543. * us data a byte at a time (unlikely), br->consumed_bits may not
  93544. * be zero.
  93545. */
  93546. if(br->bytes) {
  93547. const unsigned end = br->bytes * 8;
  93548. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93549. if(b) {
  93550. i = COUNT_ZERO_MSBS(b);
  93551. *val += i;
  93552. i++;
  93553. br->consumed_bits += i;
  93554. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93555. return true;
  93556. }
  93557. else {
  93558. *val += end - br->consumed_bits;
  93559. br->consumed_bits += end;
  93560. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93561. /* didn't find stop bit yet, have to keep going... */
  93562. }
  93563. }
  93564. if(!bitreader_read_from_client_(br))
  93565. return false;
  93566. }
  93567. }
  93568. #endif
  93569. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93570. {
  93571. FLAC__uint32 lsbs = 0, msbs = 0;
  93572. unsigned uval;
  93573. FLAC__ASSERT(0 != br);
  93574. FLAC__ASSERT(0 != br->buffer);
  93575. FLAC__ASSERT(parameter <= 31);
  93576. /* read the unary MSBs and end bit */
  93577. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93578. return false;
  93579. /* read the binary LSBs */
  93580. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93581. return false;
  93582. /* compose the value */
  93583. uval = (msbs << parameter) | lsbs;
  93584. if(uval & 1)
  93585. *val = -((int)(uval >> 1)) - 1;
  93586. else
  93587. *val = (int)(uval >> 1);
  93588. return true;
  93589. }
  93590. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93591. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93592. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93593. /* OPT: possibly faster version for use with MSVC */
  93594. #ifdef _MSC_VER
  93595. {
  93596. unsigned i;
  93597. unsigned uval = 0;
  93598. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93599. /* try and get br->consumed_words and br->consumed_bits into register;
  93600. * must remember to flush them back to *br before calling other
  93601. * bitwriter functions that use them, and before returning */
  93602. register unsigned cwords;
  93603. register unsigned cbits;
  93604. FLAC__ASSERT(0 != br);
  93605. FLAC__ASSERT(0 != br->buffer);
  93606. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93607. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93608. FLAC__ASSERT(parameter < 32);
  93609. /* 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 */
  93610. if(nvals == 0)
  93611. return true;
  93612. cbits = br->consumed_bits;
  93613. cwords = br->consumed_words;
  93614. while(1) {
  93615. /* read unary part */
  93616. while(1) {
  93617. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93618. brword b = br->buffer[cwords] << cbits;
  93619. if(b) {
  93620. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93621. __asm {
  93622. bsr eax, b
  93623. not eax
  93624. and eax, 31
  93625. mov i, eax
  93626. }
  93627. #else
  93628. i = COUNT_ZERO_MSBS(b);
  93629. #endif
  93630. uval += i;
  93631. bits = parameter;
  93632. i++;
  93633. cbits += i;
  93634. if(cbits == FLAC__BITS_PER_WORD) {
  93635. crc16_update_word_(br, br->buffer[cwords]);
  93636. cwords++;
  93637. cbits = 0;
  93638. }
  93639. goto break1;
  93640. }
  93641. else {
  93642. uval += FLAC__BITS_PER_WORD - cbits;
  93643. crc16_update_word_(br, br->buffer[cwords]);
  93644. cwords++;
  93645. cbits = 0;
  93646. /* didn't find stop bit yet, have to keep going... */
  93647. }
  93648. }
  93649. /* at this point we've eaten up all the whole words; have to try
  93650. * reading through any tail bytes before calling the read callback.
  93651. * this is a repeat of the above logic adjusted for the fact we
  93652. * don't have a whole word. note though if the client is feeding
  93653. * us data a byte at a time (unlikely), br->consumed_bits may not
  93654. * be zero.
  93655. */
  93656. if(br->bytes) {
  93657. const unsigned end = br->bytes * 8;
  93658. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93659. if(b) {
  93660. i = COUNT_ZERO_MSBS(b);
  93661. uval += i;
  93662. bits = parameter;
  93663. i++;
  93664. cbits += i;
  93665. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93666. goto break1;
  93667. }
  93668. else {
  93669. uval += end - cbits;
  93670. cbits += end;
  93671. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93672. /* didn't find stop bit yet, have to keep going... */
  93673. }
  93674. }
  93675. /* flush registers and read; bitreader_read_from_client_() does
  93676. * not touch br->consumed_bits at all but we still need to set
  93677. * it in case it fails and we have to return false.
  93678. */
  93679. br->consumed_bits = cbits;
  93680. br->consumed_words = cwords;
  93681. if(!bitreader_read_from_client_(br))
  93682. return false;
  93683. cwords = br->consumed_words;
  93684. }
  93685. break1:
  93686. /* read binary part */
  93687. FLAC__ASSERT(cwords <= br->words);
  93688. if(bits) {
  93689. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93690. /* flush registers and read; bitreader_read_from_client_() does
  93691. * not touch br->consumed_bits at all but we still need to set
  93692. * it in case it fails and we have to return false.
  93693. */
  93694. br->consumed_bits = cbits;
  93695. br->consumed_words = cwords;
  93696. if(!bitreader_read_from_client_(br))
  93697. return false;
  93698. cwords = br->consumed_words;
  93699. }
  93700. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93701. if(cbits) {
  93702. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93703. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93704. const brword word = br->buffer[cwords];
  93705. if(bits < n) {
  93706. uval <<= bits;
  93707. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93708. cbits += bits;
  93709. goto break2;
  93710. }
  93711. uval <<= n;
  93712. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93713. bits -= n;
  93714. crc16_update_word_(br, word);
  93715. cwords++;
  93716. cbits = 0;
  93717. 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 */
  93718. uval <<= bits;
  93719. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93720. cbits = bits;
  93721. }
  93722. goto break2;
  93723. }
  93724. else {
  93725. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93726. uval <<= bits;
  93727. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93728. cbits = bits;
  93729. goto break2;
  93730. }
  93731. }
  93732. else {
  93733. /* in this case we're starting our read at a partial tail word;
  93734. * the reader has guaranteed that we have at least 'bits' bits
  93735. * available to read, which makes this case simpler.
  93736. */
  93737. uval <<= bits;
  93738. if(cbits) {
  93739. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93740. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93741. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93742. cbits += bits;
  93743. goto break2;
  93744. }
  93745. else {
  93746. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93747. cbits += bits;
  93748. goto break2;
  93749. }
  93750. }
  93751. }
  93752. break2:
  93753. /* compose the value */
  93754. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93755. /* are we done? */
  93756. --nvals;
  93757. if(nvals == 0) {
  93758. br->consumed_bits = cbits;
  93759. br->consumed_words = cwords;
  93760. return true;
  93761. }
  93762. uval = 0;
  93763. ++vals;
  93764. }
  93765. }
  93766. #else
  93767. {
  93768. unsigned i;
  93769. unsigned uval = 0;
  93770. /* try and get br->consumed_words and br->consumed_bits into register;
  93771. * must remember to flush them back to *br before calling other
  93772. * bitwriter functions that use them, and before returning */
  93773. register unsigned cwords;
  93774. register unsigned cbits;
  93775. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93776. FLAC__ASSERT(0 != br);
  93777. FLAC__ASSERT(0 != br->buffer);
  93778. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93779. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93780. FLAC__ASSERT(parameter < 32);
  93781. /* 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 */
  93782. if(nvals == 0)
  93783. return true;
  93784. cbits = br->consumed_bits;
  93785. cwords = br->consumed_words;
  93786. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93787. while(1) {
  93788. /* read unary part */
  93789. while(1) {
  93790. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93791. brword b = br->buffer[cwords] << cbits;
  93792. if(b) {
  93793. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93794. asm volatile (
  93795. "bsrl %1, %0;"
  93796. "notl %0;"
  93797. "andl $31, %0;"
  93798. : "=r"(i)
  93799. : "r"(b)
  93800. );
  93801. #else
  93802. i = COUNT_ZERO_MSBS(b);
  93803. #endif
  93804. uval += i;
  93805. cbits += i;
  93806. cbits++; /* skip over stop bit */
  93807. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93808. crc16_update_word_(br, br->buffer[cwords]);
  93809. cwords++;
  93810. cbits = 0;
  93811. }
  93812. goto break1;
  93813. }
  93814. else {
  93815. uval += FLAC__BITS_PER_WORD - cbits;
  93816. crc16_update_word_(br, br->buffer[cwords]);
  93817. cwords++;
  93818. cbits = 0;
  93819. /* didn't find stop bit yet, have to keep going... */
  93820. }
  93821. }
  93822. /* at this point we've eaten up all the whole words; have to try
  93823. * reading through any tail bytes before calling the read callback.
  93824. * this is a repeat of the above logic adjusted for the fact we
  93825. * don't have a whole word. note though if the client is feeding
  93826. * us data a byte at a time (unlikely), br->consumed_bits may not
  93827. * be zero.
  93828. */
  93829. if(br->bytes) {
  93830. const unsigned end = br->bytes * 8;
  93831. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93832. if(b) {
  93833. i = COUNT_ZERO_MSBS(b);
  93834. uval += i;
  93835. cbits += i;
  93836. cbits++; /* skip over stop bit */
  93837. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93838. goto break1;
  93839. }
  93840. else {
  93841. uval += end - cbits;
  93842. cbits += end;
  93843. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93844. /* didn't find stop bit yet, have to keep going... */
  93845. }
  93846. }
  93847. /* flush registers and read; bitreader_read_from_client_() does
  93848. * not touch br->consumed_bits at all but we still need to set
  93849. * it in case it fails and we have to return false.
  93850. */
  93851. br->consumed_bits = cbits;
  93852. br->consumed_words = cwords;
  93853. if(!bitreader_read_from_client_(br))
  93854. return false;
  93855. cwords = br->consumed_words;
  93856. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93857. /* + uval to offset our count by the # of unary bits already
  93858. * consumed before the read, because we will add these back
  93859. * in all at once at break1
  93860. */
  93861. }
  93862. break1:
  93863. ucbits -= uval;
  93864. ucbits--; /* account for stop bit */
  93865. /* read binary part */
  93866. FLAC__ASSERT(cwords <= br->words);
  93867. if(parameter) {
  93868. while(ucbits < parameter) {
  93869. /* flush registers and read; bitreader_read_from_client_() does
  93870. * not touch br->consumed_bits at all but we still need to set
  93871. * it in case it fails and we have to return false.
  93872. */
  93873. br->consumed_bits = cbits;
  93874. br->consumed_words = cwords;
  93875. if(!bitreader_read_from_client_(br))
  93876. return false;
  93877. cwords = br->consumed_words;
  93878. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93879. }
  93880. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93881. if(cbits) {
  93882. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93883. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93884. const brword word = br->buffer[cwords];
  93885. if(parameter < n) {
  93886. uval <<= parameter;
  93887. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93888. cbits += parameter;
  93889. }
  93890. else {
  93891. uval <<= n;
  93892. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93893. crc16_update_word_(br, word);
  93894. cwords++;
  93895. cbits = parameter - n;
  93896. 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 */
  93897. uval <<= cbits;
  93898. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93899. }
  93900. }
  93901. }
  93902. else {
  93903. cbits = parameter;
  93904. uval <<= parameter;
  93905. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93906. }
  93907. }
  93908. else {
  93909. /* in this case we're starting our read at a partial tail word;
  93910. * the reader has guaranteed that we have at least 'parameter'
  93911. * bits available to read, which makes this case simpler.
  93912. */
  93913. uval <<= parameter;
  93914. if(cbits) {
  93915. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93916. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93917. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93918. cbits += parameter;
  93919. }
  93920. else {
  93921. cbits = parameter;
  93922. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93923. }
  93924. }
  93925. }
  93926. ucbits -= parameter;
  93927. /* compose the value */
  93928. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93929. /* are we done? */
  93930. --nvals;
  93931. if(nvals == 0) {
  93932. br->consumed_bits = cbits;
  93933. br->consumed_words = cwords;
  93934. return true;
  93935. }
  93936. uval = 0;
  93937. ++vals;
  93938. }
  93939. }
  93940. #endif
  93941. #if 0 /* UNUSED */
  93942. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93943. {
  93944. FLAC__uint32 lsbs = 0, msbs = 0;
  93945. unsigned bit, uval, k;
  93946. FLAC__ASSERT(0 != br);
  93947. FLAC__ASSERT(0 != br->buffer);
  93948. k = FLAC__bitmath_ilog2(parameter);
  93949. /* read the unary MSBs and end bit */
  93950. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93951. return false;
  93952. /* read the binary LSBs */
  93953. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93954. return false;
  93955. if(parameter == 1u<<k) {
  93956. /* compose the value */
  93957. uval = (msbs << k) | lsbs;
  93958. }
  93959. else {
  93960. unsigned d = (1 << (k+1)) - parameter;
  93961. if(lsbs >= d) {
  93962. if(!FLAC__bitreader_read_bit(br, &bit))
  93963. return false;
  93964. lsbs <<= 1;
  93965. lsbs |= bit;
  93966. lsbs -= d;
  93967. }
  93968. /* compose the value */
  93969. uval = msbs * parameter + lsbs;
  93970. }
  93971. /* unfold unsigned to signed */
  93972. if(uval & 1)
  93973. *val = -((int)(uval >> 1)) - 1;
  93974. else
  93975. *val = (int)(uval >> 1);
  93976. return true;
  93977. }
  93978. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93979. {
  93980. FLAC__uint32 lsbs, msbs = 0;
  93981. unsigned bit, k;
  93982. FLAC__ASSERT(0 != br);
  93983. FLAC__ASSERT(0 != br->buffer);
  93984. k = FLAC__bitmath_ilog2(parameter);
  93985. /* read the unary MSBs and end bit */
  93986. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93987. return false;
  93988. /* read the binary LSBs */
  93989. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93990. return false;
  93991. if(parameter == 1u<<k) {
  93992. /* compose the value */
  93993. *val = (msbs << k) | lsbs;
  93994. }
  93995. else {
  93996. unsigned d = (1 << (k+1)) - parameter;
  93997. if(lsbs >= d) {
  93998. if(!FLAC__bitreader_read_bit(br, &bit))
  93999. return false;
  94000. lsbs <<= 1;
  94001. lsbs |= bit;
  94002. lsbs -= d;
  94003. }
  94004. /* compose the value */
  94005. *val = msbs * parameter + lsbs;
  94006. }
  94007. return true;
  94008. }
  94009. #endif /* UNUSED */
  94010. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94011. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94012. {
  94013. FLAC__uint32 v = 0;
  94014. FLAC__uint32 x;
  94015. unsigned i;
  94016. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94017. return false;
  94018. if(raw)
  94019. raw[(*rawlen)++] = (FLAC__byte)x;
  94020. if(!(x & 0x80)) { /* 0xxxxxxx */
  94021. v = x;
  94022. i = 0;
  94023. }
  94024. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94025. v = x & 0x1F;
  94026. i = 1;
  94027. }
  94028. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94029. v = x & 0x0F;
  94030. i = 2;
  94031. }
  94032. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94033. v = x & 0x07;
  94034. i = 3;
  94035. }
  94036. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94037. v = x & 0x03;
  94038. i = 4;
  94039. }
  94040. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94041. v = x & 0x01;
  94042. i = 5;
  94043. }
  94044. else {
  94045. *val = 0xffffffff;
  94046. return true;
  94047. }
  94048. for( ; i; i--) {
  94049. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94050. return false;
  94051. if(raw)
  94052. raw[(*rawlen)++] = (FLAC__byte)x;
  94053. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94054. *val = 0xffffffff;
  94055. return true;
  94056. }
  94057. v <<= 6;
  94058. v |= (x & 0x3F);
  94059. }
  94060. *val = v;
  94061. return true;
  94062. }
  94063. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94064. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94065. {
  94066. FLAC__uint64 v = 0;
  94067. FLAC__uint32 x;
  94068. unsigned i;
  94069. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94070. return false;
  94071. if(raw)
  94072. raw[(*rawlen)++] = (FLAC__byte)x;
  94073. if(!(x & 0x80)) { /* 0xxxxxxx */
  94074. v = x;
  94075. i = 0;
  94076. }
  94077. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94078. v = x & 0x1F;
  94079. i = 1;
  94080. }
  94081. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94082. v = x & 0x0F;
  94083. i = 2;
  94084. }
  94085. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94086. v = x & 0x07;
  94087. i = 3;
  94088. }
  94089. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94090. v = x & 0x03;
  94091. i = 4;
  94092. }
  94093. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94094. v = x & 0x01;
  94095. i = 5;
  94096. }
  94097. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94098. v = 0;
  94099. i = 6;
  94100. }
  94101. else {
  94102. *val = FLAC__U64L(0xffffffffffffffff);
  94103. return true;
  94104. }
  94105. for( ; i; i--) {
  94106. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94107. return false;
  94108. if(raw)
  94109. raw[(*rawlen)++] = (FLAC__byte)x;
  94110. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94111. *val = FLAC__U64L(0xffffffffffffffff);
  94112. return true;
  94113. }
  94114. v <<= 6;
  94115. v |= (x & 0x3F);
  94116. }
  94117. *val = v;
  94118. return true;
  94119. }
  94120. #endif
  94121. /*** End of inlined file: bitreader.c ***/
  94122. /*** Start of inlined file: bitwriter.c ***/
  94123. /*** Start of inlined file: juce_FlacHeader.h ***/
  94124. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94125. // tasks..
  94126. #define VERSION "1.2.1"
  94127. #define FLAC__NO_DLL 1
  94128. #if JUCE_MSVC
  94129. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94130. #endif
  94131. #if JUCE_MAC
  94132. #define FLAC__SYS_DARWIN 1
  94133. #endif
  94134. /*** End of inlined file: juce_FlacHeader.h ***/
  94135. #if JUCE_USE_FLAC
  94136. #if HAVE_CONFIG_H
  94137. # include <config.h>
  94138. #endif
  94139. #include <stdlib.h> /* for malloc() */
  94140. #include <string.h> /* for memcpy(), memset() */
  94141. #ifdef _MSC_VER
  94142. #include <winsock.h> /* for ntohl() */
  94143. #elif defined FLAC__SYS_DARWIN
  94144. #include <machine/endian.h> /* for ntohl() */
  94145. #elif defined __MINGW32__
  94146. #include <winsock.h> /* for ntohl() */
  94147. #else
  94148. #include <netinet/in.h> /* for ntohl() */
  94149. #endif
  94150. #if 0 /* UNUSED */
  94151. #endif
  94152. /*** Start of inlined file: bitwriter.h ***/
  94153. #ifndef FLAC__PRIVATE__BITWRITER_H
  94154. #define FLAC__PRIVATE__BITWRITER_H
  94155. #include <stdio.h> /* for FILE */
  94156. /*
  94157. * opaque structure definition
  94158. */
  94159. struct FLAC__BitWriter;
  94160. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94161. /*
  94162. * construction, deletion, initialization, etc functions
  94163. */
  94164. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94165. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94166. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94167. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94168. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94169. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94170. /*
  94171. * CRC functions
  94172. *
  94173. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94174. */
  94175. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94176. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94177. /*
  94178. * info functions
  94179. */
  94180. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94181. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94182. /*
  94183. * direct buffer access
  94184. *
  94185. * there may be no calls on the bitwriter between get and release.
  94186. * the bitwriter continues to own the returned buffer.
  94187. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94188. */
  94189. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94190. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94191. /*
  94192. * write functions
  94193. */
  94194. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94195. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94196. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94197. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94198. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94199. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94200. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94201. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94202. #if 0 /* UNUSED */
  94203. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94204. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94205. #endif
  94206. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94207. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94208. #if 0 /* UNUSED */
  94209. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94210. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94211. #endif
  94212. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94213. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94214. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94215. #endif
  94216. /*** End of inlined file: bitwriter.h ***/
  94217. /*** Start of inlined file: alloc.h ***/
  94218. #ifndef FLAC__SHARE__ALLOC_H
  94219. #define FLAC__SHARE__ALLOC_H
  94220. #if HAVE_CONFIG_H
  94221. # include <config.h>
  94222. #endif
  94223. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94224. * before #including this file, otherwise SIZE_MAX might not be defined
  94225. */
  94226. #include <limits.h> /* for SIZE_MAX */
  94227. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94228. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94229. #endif
  94230. #include <stdlib.h> /* for size_t, malloc(), etc */
  94231. #ifndef SIZE_MAX
  94232. # ifndef SIZE_T_MAX
  94233. # ifdef _MSC_VER
  94234. # define SIZE_T_MAX UINT_MAX
  94235. # else
  94236. # error
  94237. # endif
  94238. # endif
  94239. # define SIZE_MAX SIZE_T_MAX
  94240. #endif
  94241. #ifndef FLaC__INLINE
  94242. #define FLaC__INLINE
  94243. #endif
  94244. /* avoid malloc()ing 0 bytes, see:
  94245. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94246. */
  94247. static FLaC__INLINE void *safe_malloc_(size_t size)
  94248. {
  94249. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94250. if(!size)
  94251. size++;
  94252. return malloc(size);
  94253. }
  94254. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94255. {
  94256. if(!nmemb || !size)
  94257. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94258. return calloc(nmemb, size);
  94259. }
  94260. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94261. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94262. {
  94263. size2 += size1;
  94264. if(size2 < size1)
  94265. return 0;
  94266. return safe_malloc_(size2);
  94267. }
  94268. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94269. {
  94270. size2 += size1;
  94271. if(size2 < size1)
  94272. return 0;
  94273. size3 += size2;
  94274. if(size3 < size2)
  94275. return 0;
  94276. return safe_malloc_(size3);
  94277. }
  94278. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94279. {
  94280. size2 += size1;
  94281. if(size2 < size1)
  94282. return 0;
  94283. size3 += size2;
  94284. if(size3 < size2)
  94285. return 0;
  94286. size4 += size3;
  94287. if(size4 < size3)
  94288. return 0;
  94289. return safe_malloc_(size4);
  94290. }
  94291. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94292. #if 0
  94293. needs support for cases where sizeof(size_t) != 4
  94294. {
  94295. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94296. if(sizeof(size_t) == 4) {
  94297. if ((double)size1 * (double)size2 < 4294967296.0)
  94298. return malloc(size1*size2);
  94299. }
  94300. return 0;
  94301. }
  94302. #else
  94303. /* better? */
  94304. {
  94305. if(!size1 || !size2)
  94306. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94307. if(size1 > SIZE_MAX / size2)
  94308. return 0;
  94309. return malloc(size1*size2);
  94310. }
  94311. #endif
  94312. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94313. {
  94314. if(!size1 || !size2 || !size3)
  94315. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94316. if(size1 > SIZE_MAX / size2)
  94317. return 0;
  94318. size1 *= size2;
  94319. if(size1 > SIZE_MAX / size3)
  94320. return 0;
  94321. return malloc(size1*size3);
  94322. }
  94323. /* size1*size2 + size3 */
  94324. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94325. {
  94326. if(!size1 || !size2)
  94327. return safe_malloc_(size3);
  94328. if(size1 > SIZE_MAX / size2)
  94329. return 0;
  94330. return safe_malloc_add_2op_(size1*size2, size3);
  94331. }
  94332. /* size1 * (size2 + size3) */
  94333. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94334. {
  94335. if(!size1 || (!size2 && !size3))
  94336. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94337. size2 += size3;
  94338. if(size2 < size3)
  94339. return 0;
  94340. return safe_malloc_mul_2op_(size1, size2);
  94341. }
  94342. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94343. {
  94344. size2 += size1;
  94345. if(size2 < size1)
  94346. return 0;
  94347. return realloc(ptr, size2);
  94348. }
  94349. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94350. {
  94351. size2 += size1;
  94352. if(size2 < size1)
  94353. return 0;
  94354. size3 += size2;
  94355. if(size3 < size2)
  94356. return 0;
  94357. return realloc(ptr, size3);
  94358. }
  94359. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94360. {
  94361. size2 += size1;
  94362. if(size2 < size1)
  94363. return 0;
  94364. size3 += size2;
  94365. if(size3 < size2)
  94366. return 0;
  94367. size4 += size3;
  94368. if(size4 < size3)
  94369. return 0;
  94370. return realloc(ptr, size4);
  94371. }
  94372. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94373. {
  94374. if(!size1 || !size2)
  94375. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94376. if(size1 > SIZE_MAX / size2)
  94377. return 0;
  94378. return realloc(ptr, size1*size2);
  94379. }
  94380. /* size1 * (size2 + size3) */
  94381. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94382. {
  94383. if(!size1 || (!size2 && !size3))
  94384. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94385. size2 += size3;
  94386. if(size2 < size3)
  94387. return 0;
  94388. return safe_realloc_mul_2op_(ptr, size1, size2);
  94389. }
  94390. #endif
  94391. /*** End of inlined file: alloc.h ***/
  94392. /* Things should be fastest when this matches the machine word size */
  94393. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94394. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94395. typedef FLAC__uint32 bwword;
  94396. #define FLAC__BYTES_PER_WORD 4
  94397. #define FLAC__BITS_PER_WORD 32
  94398. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94399. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94400. #if WORDS_BIGENDIAN
  94401. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94402. #else
  94403. #ifdef _MSC_VER
  94404. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94405. #else
  94406. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94407. #endif
  94408. #endif
  94409. /*
  94410. * The default capacity here doesn't matter too much. The buffer always grows
  94411. * to hold whatever is written to it. Usually the encoder will stop adding at
  94412. * a frame or metadata block, then write that out and clear the buffer for the
  94413. * next one.
  94414. */
  94415. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94416. /* When growing, increment 4K at a time */
  94417. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94418. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94419. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94420. #ifdef min
  94421. #undef min
  94422. #endif
  94423. #define min(x,y) ((x)<(y)?(x):(y))
  94424. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94425. #ifdef _MSC_VER
  94426. #define FLAC__U64L(x) x
  94427. #else
  94428. #define FLAC__U64L(x) x##LLU
  94429. #endif
  94430. #ifndef FLaC__INLINE
  94431. #define FLaC__INLINE
  94432. #endif
  94433. struct FLAC__BitWriter {
  94434. bwword *buffer;
  94435. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94436. unsigned capacity; /* capacity of buffer in words */
  94437. unsigned words; /* # of complete words in buffer */
  94438. unsigned bits; /* # of used bits in accum */
  94439. };
  94440. /* * WATCHOUT: The current implementation only grows the buffer. */
  94441. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94442. {
  94443. unsigned new_capacity;
  94444. bwword *new_buffer;
  94445. FLAC__ASSERT(0 != bw);
  94446. FLAC__ASSERT(0 != bw->buffer);
  94447. /* calculate total words needed to store 'bits_to_add' additional bits */
  94448. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94449. /* it's possible (due to pessimism in the growth estimation that
  94450. * leads to this call) that we don't actually need to grow
  94451. */
  94452. if(bw->capacity >= new_capacity)
  94453. return true;
  94454. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94455. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94456. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94457. /* make sure we got everything right */
  94458. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94459. FLAC__ASSERT(new_capacity > bw->capacity);
  94460. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94461. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94462. if(new_buffer == 0)
  94463. return false;
  94464. bw->buffer = new_buffer;
  94465. bw->capacity = new_capacity;
  94466. return true;
  94467. }
  94468. /***********************************************************************
  94469. *
  94470. * Class constructor/destructor
  94471. *
  94472. ***********************************************************************/
  94473. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94474. {
  94475. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94476. /* note that calloc() sets all members to 0 for us */
  94477. return bw;
  94478. }
  94479. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94480. {
  94481. FLAC__ASSERT(0 != bw);
  94482. FLAC__bitwriter_free(bw);
  94483. free(bw);
  94484. }
  94485. /***********************************************************************
  94486. *
  94487. * Public class methods
  94488. *
  94489. ***********************************************************************/
  94490. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94491. {
  94492. FLAC__ASSERT(0 != bw);
  94493. bw->words = bw->bits = 0;
  94494. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94495. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94496. if(bw->buffer == 0)
  94497. return false;
  94498. return true;
  94499. }
  94500. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94501. {
  94502. FLAC__ASSERT(0 != bw);
  94503. if(0 != bw->buffer)
  94504. free(bw->buffer);
  94505. bw->buffer = 0;
  94506. bw->capacity = 0;
  94507. bw->words = bw->bits = 0;
  94508. }
  94509. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94510. {
  94511. bw->words = bw->bits = 0;
  94512. }
  94513. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94514. {
  94515. unsigned i, j;
  94516. if(bw == 0) {
  94517. fprintf(out, "bitwriter is NULL\n");
  94518. }
  94519. else {
  94520. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94521. for(i = 0; i < bw->words; i++) {
  94522. fprintf(out, "%08X: ", i);
  94523. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94524. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94525. fprintf(out, "\n");
  94526. }
  94527. if(bw->bits > 0) {
  94528. fprintf(out, "%08X: ", i);
  94529. for(j = 0; j < bw->bits; j++)
  94530. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94531. fprintf(out, "\n");
  94532. }
  94533. }
  94534. }
  94535. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94536. {
  94537. const FLAC__byte *buffer;
  94538. size_t bytes;
  94539. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94540. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94541. return false;
  94542. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94543. FLAC__bitwriter_release_buffer(bw);
  94544. return true;
  94545. }
  94546. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94547. {
  94548. const FLAC__byte *buffer;
  94549. size_t bytes;
  94550. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94551. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94552. return false;
  94553. *crc = FLAC__crc8(buffer, bytes);
  94554. FLAC__bitwriter_release_buffer(bw);
  94555. return true;
  94556. }
  94557. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94558. {
  94559. return ((bw->bits & 7) == 0);
  94560. }
  94561. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94562. {
  94563. return FLAC__TOTAL_BITS(bw);
  94564. }
  94565. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94566. {
  94567. FLAC__ASSERT((bw->bits & 7) == 0);
  94568. /* double protection */
  94569. if(bw->bits & 7)
  94570. return false;
  94571. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94572. if(bw->bits) {
  94573. FLAC__ASSERT(bw->words <= bw->capacity);
  94574. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94575. return false;
  94576. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94577. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94578. }
  94579. /* now we can just return what we have */
  94580. *buffer = (FLAC__byte*)bw->buffer;
  94581. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94582. return true;
  94583. }
  94584. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94585. {
  94586. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94587. * get-mode' flag could be added everywhere and then cleared here
  94588. */
  94589. (void)bw;
  94590. }
  94591. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94592. {
  94593. unsigned n;
  94594. FLAC__ASSERT(0 != bw);
  94595. FLAC__ASSERT(0 != bw->buffer);
  94596. if(bits == 0)
  94597. return true;
  94598. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94599. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94600. return false;
  94601. /* first part gets to word alignment */
  94602. if(bw->bits) {
  94603. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94604. bw->accum <<= n;
  94605. bits -= n;
  94606. bw->bits += n;
  94607. if(bw->bits == FLAC__BITS_PER_WORD) {
  94608. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94609. bw->bits = 0;
  94610. }
  94611. else
  94612. return true;
  94613. }
  94614. /* do whole words */
  94615. while(bits >= FLAC__BITS_PER_WORD) {
  94616. bw->buffer[bw->words++] = 0;
  94617. bits -= FLAC__BITS_PER_WORD;
  94618. }
  94619. /* do any leftovers */
  94620. if(bits > 0) {
  94621. bw->accum = 0;
  94622. bw->bits = bits;
  94623. }
  94624. return true;
  94625. }
  94626. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94627. {
  94628. register unsigned left;
  94629. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94630. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94631. FLAC__ASSERT(0 != bw);
  94632. FLAC__ASSERT(0 != bw->buffer);
  94633. FLAC__ASSERT(bits <= 32);
  94634. if(bits == 0)
  94635. return true;
  94636. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94637. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94638. return false;
  94639. left = FLAC__BITS_PER_WORD - bw->bits;
  94640. if(bits < left) {
  94641. bw->accum <<= bits;
  94642. bw->accum |= val;
  94643. bw->bits += bits;
  94644. }
  94645. 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 */
  94646. bw->accum <<= left;
  94647. bw->accum |= val >> (bw->bits = bits - left);
  94648. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94649. bw->accum = val;
  94650. }
  94651. else {
  94652. bw->accum = val;
  94653. bw->bits = 0;
  94654. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94655. }
  94656. return true;
  94657. }
  94658. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94659. {
  94660. /* zero-out unused bits */
  94661. if(bits < 32)
  94662. val &= (~(0xffffffff << bits));
  94663. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94664. }
  94665. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94666. {
  94667. /* this could be a little faster but it's not used for much */
  94668. if(bits > 32) {
  94669. return
  94670. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94671. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94672. }
  94673. else
  94674. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94675. }
  94676. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94677. {
  94678. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94679. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94680. return false;
  94681. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94682. return false;
  94683. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94684. return false;
  94685. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94686. return false;
  94687. return true;
  94688. }
  94689. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94690. {
  94691. unsigned i;
  94692. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94693. for(i = 0; i < nvals; i++) {
  94694. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94695. return false;
  94696. }
  94697. return true;
  94698. }
  94699. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94700. {
  94701. if(val < 32)
  94702. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94703. else
  94704. return
  94705. FLAC__bitwriter_write_zeroes(bw, val) &&
  94706. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94707. }
  94708. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94709. {
  94710. FLAC__uint32 uval;
  94711. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94712. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94713. uval = (val<<1) ^ (val>>31);
  94714. return 1 + parameter + (uval >> parameter);
  94715. }
  94716. #if 0 /* UNUSED */
  94717. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94718. {
  94719. unsigned bits, msbs, uval;
  94720. unsigned k;
  94721. FLAC__ASSERT(parameter > 0);
  94722. /* fold signed to unsigned */
  94723. if(val < 0)
  94724. uval = (unsigned)(((-(++val)) << 1) + 1);
  94725. else
  94726. uval = (unsigned)(val << 1);
  94727. k = FLAC__bitmath_ilog2(parameter);
  94728. if(parameter == 1u<<k) {
  94729. FLAC__ASSERT(k <= 30);
  94730. msbs = uval >> k;
  94731. bits = 1 + k + msbs;
  94732. }
  94733. else {
  94734. unsigned q, r, d;
  94735. d = (1 << (k+1)) - parameter;
  94736. q = uval / parameter;
  94737. r = uval - (q * parameter);
  94738. bits = 1 + q + k;
  94739. if(r >= d)
  94740. bits++;
  94741. }
  94742. return bits;
  94743. }
  94744. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94745. {
  94746. unsigned bits, msbs;
  94747. unsigned k;
  94748. FLAC__ASSERT(parameter > 0);
  94749. k = FLAC__bitmath_ilog2(parameter);
  94750. if(parameter == 1u<<k) {
  94751. FLAC__ASSERT(k <= 30);
  94752. msbs = uval >> k;
  94753. bits = 1 + k + msbs;
  94754. }
  94755. else {
  94756. unsigned q, r, d;
  94757. d = (1 << (k+1)) - parameter;
  94758. q = uval / parameter;
  94759. r = uval - (q * parameter);
  94760. bits = 1 + q + k;
  94761. if(r >= d)
  94762. bits++;
  94763. }
  94764. return bits;
  94765. }
  94766. #endif /* UNUSED */
  94767. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94768. {
  94769. unsigned total_bits, interesting_bits, msbs;
  94770. FLAC__uint32 uval, pattern;
  94771. FLAC__ASSERT(0 != bw);
  94772. FLAC__ASSERT(0 != bw->buffer);
  94773. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94774. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94775. uval = (val<<1) ^ (val>>31);
  94776. msbs = uval >> parameter;
  94777. interesting_bits = 1 + parameter;
  94778. total_bits = interesting_bits + msbs;
  94779. pattern = 1 << parameter; /* the unary end bit */
  94780. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94781. if(total_bits <= 32)
  94782. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94783. else
  94784. return
  94785. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94786. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94787. }
  94788. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94789. {
  94790. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94791. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94792. FLAC__uint32 uval;
  94793. unsigned left;
  94794. const unsigned lsbits = 1 + parameter;
  94795. unsigned msbits;
  94796. FLAC__ASSERT(0 != bw);
  94797. FLAC__ASSERT(0 != bw->buffer);
  94798. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94799. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94800. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94801. while(nvals) {
  94802. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94803. uval = (*vals<<1) ^ (*vals>>31);
  94804. msbits = uval >> parameter;
  94805. #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) */
  94806. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94807. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94808. bw->bits = bw->bits + msbits + lsbits;
  94809. uval |= mask1; /* set stop bit */
  94810. uval &= mask2; /* mask off unused top bits */
  94811. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94812. bw->accum <<= msbits;
  94813. bw->accum <<= lsbits;
  94814. bw->accum |= uval;
  94815. if(bw->bits == FLAC__BITS_PER_WORD) {
  94816. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94817. bw->bits = 0;
  94818. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94819. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94820. FLAC__ASSERT(bw->capacity == bw->words);
  94821. return false;
  94822. }
  94823. }
  94824. }
  94825. else {
  94826. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94827. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94828. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94829. bw->bits = bw->bits + msbits + lsbits;
  94830. uval |= mask1; /* set stop bit */
  94831. uval &= mask2; /* mask off unused top bits */
  94832. bw->accum <<= msbits + lsbits;
  94833. bw->accum |= uval;
  94834. }
  94835. else {
  94836. #endif
  94837. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94838. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94839. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94840. return false;
  94841. if(msbits) {
  94842. /* first part gets to word alignment */
  94843. if(bw->bits) {
  94844. left = FLAC__BITS_PER_WORD - bw->bits;
  94845. if(msbits < left) {
  94846. bw->accum <<= msbits;
  94847. bw->bits += msbits;
  94848. goto break1;
  94849. }
  94850. else {
  94851. bw->accum <<= left;
  94852. msbits -= left;
  94853. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94854. bw->bits = 0;
  94855. }
  94856. }
  94857. /* do whole words */
  94858. while(msbits >= FLAC__BITS_PER_WORD) {
  94859. bw->buffer[bw->words++] = 0;
  94860. msbits -= FLAC__BITS_PER_WORD;
  94861. }
  94862. /* do any leftovers */
  94863. if(msbits > 0) {
  94864. bw->accum = 0;
  94865. bw->bits = msbits;
  94866. }
  94867. }
  94868. break1:
  94869. uval |= mask1; /* set stop bit */
  94870. uval &= mask2; /* mask off unused top bits */
  94871. left = FLAC__BITS_PER_WORD - bw->bits;
  94872. if(lsbits < left) {
  94873. bw->accum <<= lsbits;
  94874. bw->accum |= uval;
  94875. bw->bits += lsbits;
  94876. }
  94877. else {
  94878. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94879. * be > lsbits (because of previous assertions) so it would have
  94880. * triggered the (lsbits<left) case above.
  94881. */
  94882. FLAC__ASSERT(bw->bits);
  94883. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94884. bw->accum <<= left;
  94885. bw->accum |= uval >> (bw->bits = lsbits - left);
  94886. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94887. bw->accum = uval;
  94888. }
  94889. #if 1
  94890. }
  94891. #endif
  94892. vals++;
  94893. nvals--;
  94894. }
  94895. return true;
  94896. }
  94897. #if 0 /* UNUSED */
  94898. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94899. {
  94900. unsigned total_bits, msbs, uval;
  94901. unsigned k;
  94902. FLAC__ASSERT(0 != bw);
  94903. FLAC__ASSERT(0 != bw->buffer);
  94904. FLAC__ASSERT(parameter > 0);
  94905. /* fold signed to unsigned */
  94906. if(val < 0)
  94907. uval = (unsigned)(((-(++val)) << 1) + 1);
  94908. else
  94909. uval = (unsigned)(val << 1);
  94910. k = FLAC__bitmath_ilog2(parameter);
  94911. if(parameter == 1u<<k) {
  94912. unsigned pattern;
  94913. FLAC__ASSERT(k <= 30);
  94914. msbs = uval >> k;
  94915. total_bits = 1 + k + msbs;
  94916. pattern = 1 << k; /* the unary end bit */
  94917. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94918. if(total_bits <= 32) {
  94919. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94920. return false;
  94921. }
  94922. else {
  94923. /* write the unary MSBs */
  94924. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94925. return false;
  94926. /* write the unary end bit and binary LSBs */
  94927. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94928. return false;
  94929. }
  94930. }
  94931. else {
  94932. unsigned q, r, d;
  94933. d = (1 << (k+1)) - parameter;
  94934. q = uval / parameter;
  94935. r = uval - (q * parameter);
  94936. /* write the unary MSBs */
  94937. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94938. return false;
  94939. /* write the unary end bit */
  94940. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94941. return false;
  94942. /* write the binary LSBs */
  94943. if(r >= d) {
  94944. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94945. return false;
  94946. }
  94947. else {
  94948. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94949. return false;
  94950. }
  94951. }
  94952. return true;
  94953. }
  94954. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94955. {
  94956. unsigned total_bits, msbs;
  94957. unsigned k;
  94958. FLAC__ASSERT(0 != bw);
  94959. FLAC__ASSERT(0 != bw->buffer);
  94960. FLAC__ASSERT(parameter > 0);
  94961. k = FLAC__bitmath_ilog2(parameter);
  94962. if(parameter == 1u<<k) {
  94963. unsigned pattern;
  94964. FLAC__ASSERT(k <= 30);
  94965. msbs = uval >> k;
  94966. total_bits = 1 + k + msbs;
  94967. pattern = 1 << k; /* the unary end bit */
  94968. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94969. if(total_bits <= 32) {
  94970. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94971. return false;
  94972. }
  94973. else {
  94974. /* write the unary MSBs */
  94975. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94976. return false;
  94977. /* write the unary end bit and binary LSBs */
  94978. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94979. return false;
  94980. }
  94981. }
  94982. else {
  94983. unsigned q, r, d;
  94984. d = (1 << (k+1)) - parameter;
  94985. q = uval / parameter;
  94986. r = uval - (q * parameter);
  94987. /* write the unary MSBs */
  94988. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94989. return false;
  94990. /* write the unary end bit */
  94991. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94992. return false;
  94993. /* write the binary LSBs */
  94994. if(r >= d) {
  94995. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94996. return false;
  94997. }
  94998. else {
  94999. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95000. return false;
  95001. }
  95002. }
  95003. return true;
  95004. }
  95005. #endif /* UNUSED */
  95006. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95007. {
  95008. FLAC__bool ok = 1;
  95009. FLAC__ASSERT(0 != bw);
  95010. FLAC__ASSERT(0 != bw->buffer);
  95011. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95012. if(val < 0x80) {
  95013. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95014. }
  95015. else if(val < 0x800) {
  95016. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95017. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95018. }
  95019. else if(val < 0x10000) {
  95020. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95021. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95022. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95023. }
  95024. else if(val < 0x200000) {
  95025. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95026. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95027. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95028. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95029. }
  95030. else if(val < 0x4000000) {
  95031. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95032. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95033. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95034. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95035. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95036. }
  95037. else {
  95038. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95039. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95040. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95041. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95042. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95043. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95044. }
  95045. return ok;
  95046. }
  95047. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95048. {
  95049. FLAC__bool ok = 1;
  95050. FLAC__ASSERT(0 != bw);
  95051. FLAC__ASSERT(0 != bw->buffer);
  95052. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95053. if(val < 0x80) {
  95054. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95055. }
  95056. else if(val < 0x800) {
  95057. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95058. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95059. }
  95060. else if(val < 0x10000) {
  95061. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95062. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95063. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95064. }
  95065. else if(val < 0x200000) {
  95066. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95067. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95068. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95069. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95070. }
  95071. else if(val < 0x4000000) {
  95072. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95073. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95074. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95075. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95076. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95077. }
  95078. else if(val < 0x80000000) {
  95079. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95080. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95081. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95082. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95083. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95084. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95085. }
  95086. else {
  95087. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95088. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95089. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95090. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95091. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95092. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95093. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95094. }
  95095. return ok;
  95096. }
  95097. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95098. {
  95099. /* 0-pad to byte boundary */
  95100. if(bw->bits & 7u)
  95101. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95102. else
  95103. return true;
  95104. }
  95105. #endif
  95106. /*** End of inlined file: bitwriter.c ***/
  95107. /*** Start of inlined file: cpu.c ***/
  95108. /*** Start of inlined file: juce_FlacHeader.h ***/
  95109. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95110. // tasks..
  95111. #define VERSION "1.2.1"
  95112. #define FLAC__NO_DLL 1
  95113. #if JUCE_MSVC
  95114. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95115. #endif
  95116. #if JUCE_MAC
  95117. #define FLAC__SYS_DARWIN 1
  95118. #endif
  95119. /*** End of inlined file: juce_FlacHeader.h ***/
  95120. #if JUCE_USE_FLAC
  95121. #if HAVE_CONFIG_H
  95122. # include <config.h>
  95123. #endif
  95124. #include <stdlib.h>
  95125. #include <stdio.h>
  95126. #if defined FLAC__CPU_IA32
  95127. # include <signal.h>
  95128. #elif defined FLAC__CPU_PPC
  95129. # if !defined FLAC__NO_ASM
  95130. # if defined FLAC__SYS_DARWIN
  95131. # include <sys/sysctl.h>
  95132. # include <mach/mach.h>
  95133. # include <mach/mach_host.h>
  95134. # include <mach/host_info.h>
  95135. # include <mach/machine.h>
  95136. # ifndef CPU_SUBTYPE_POWERPC_970
  95137. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95138. # endif
  95139. # else /* FLAC__SYS_DARWIN */
  95140. # include <signal.h>
  95141. # include <setjmp.h>
  95142. static sigjmp_buf jmpbuf;
  95143. static volatile sig_atomic_t canjump = 0;
  95144. static void sigill_handler (int sig)
  95145. {
  95146. if (!canjump) {
  95147. signal (sig, SIG_DFL);
  95148. raise (sig);
  95149. }
  95150. canjump = 0;
  95151. siglongjmp (jmpbuf, 1);
  95152. }
  95153. # endif /* FLAC__SYS_DARWIN */
  95154. # endif /* FLAC__NO_ASM */
  95155. #endif /* FLAC__CPU_PPC */
  95156. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95157. #include <sys/param.h>
  95158. #include <sys/sysctl.h>
  95159. #include <machine/cpu.h>
  95160. #endif
  95161. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95162. #include <sys/types.h>
  95163. #include <sys/sysctl.h>
  95164. #endif
  95165. #if defined(__APPLE__)
  95166. /* how to get sysctlbyname()? */
  95167. #endif
  95168. /* these are flags in EDX of CPUID AX=00000001 */
  95169. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95170. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95171. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95172. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95173. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95174. /* these are flags in ECX of CPUID AX=00000001 */
  95175. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95176. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95177. /* these are flags in EDX of CPUID AX=80000001 */
  95178. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95179. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95180. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95181. /*
  95182. * Extra stuff needed for detection of OS support for SSE on IA-32
  95183. */
  95184. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95185. # if defined(__linux__)
  95186. /*
  95187. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95188. * modify the return address to jump over the offending SSE instruction
  95189. * and also the operation following it that indicates the instruction
  95190. * executed successfully. In this way we use no global variables and
  95191. * stay thread-safe.
  95192. *
  95193. * 3 + 3 + 6:
  95194. * 3 bytes for "xorps xmm0,xmm0"
  95195. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95196. * 6 bytes extra in case our estimate is wrong
  95197. * 12 bytes puts us in the NOP "landing zone"
  95198. */
  95199. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95200. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95201. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95202. {
  95203. (void)signal;
  95204. sc.eip += 3 + 3 + 6;
  95205. }
  95206. # else
  95207. # include <sys/ucontext.h>
  95208. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95209. {
  95210. (void)signal, (void)si;
  95211. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95212. }
  95213. # endif
  95214. # elif defined(_MSC_VER)
  95215. # include <windows.h>
  95216. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95217. # ifdef USE_TRY_CATCH_FLAVOR
  95218. # else
  95219. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95220. {
  95221. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95222. ep->ContextRecord->Eip += 3 + 3 + 6;
  95223. return EXCEPTION_CONTINUE_EXECUTION;
  95224. }
  95225. return EXCEPTION_CONTINUE_SEARCH;
  95226. }
  95227. # endif
  95228. # endif
  95229. #endif
  95230. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95231. {
  95232. /*
  95233. * IA32-specific
  95234. */
  95235. #ifdef FLAC__CPU_IA32
  95236. info->type = FLAC__CPUINFO_TYPE_IA32;
  95237. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95238. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95239. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95240. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95241. info->data.ia32.cmov = false;
  95242. info->data.ia32.mmx = false;
  95243. info->data.ia32.fxsr = false;
  95244. info->data.ia32.sse = false;
  95245. info->data.ia32.sse2 = false;
  95246. info->data.ia32.sse3 = false;
  95247. info->data.ia32.ssse3 = false;
  95248. info->data.ia32._3dnow = false;
  95249. info->data.ia32.ext3dnow = false;
  95250. info->data.ia32.extmmx = false;
  95251. if(info->data.ia32.cpuid) {
  95252. /* http://www.sandpile.org/ia32/cpuid.htm */
  95253. FLAC__uint32 flags_edx, flags_ecx;
  95254. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95255. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95256. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95257. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95258. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95259. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95260. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95261. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95262. #ifdef FLAC__USE_3DNOW
  95263. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95264. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95265. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95266. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95267. #else
  95268. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95269. #endif
  95270. #ifdef DEBUG
  95271. fprintf(stderr, "CPU info (IA-32):\n");
  95272. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95273. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95274. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95275. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95276. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95277. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95278. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95279. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95280. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95281. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95282. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95283. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95284. #endif
  95285. /*
  95286. * now have to check for OS support of SSE/SSE2
  95287. */
  95288. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95289. #if defined FLAC__NO_SSE_OS
  95290. /* assume user knows better than us; turn it off */
  95291. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95292. #elif defined FLAC__SSE_OS
  95293. /* assume user knows better than us; leave as detected above */
  95294. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95295. int sse = 0;
  95296. size_t len;
  95297. /* at least one of these must work: */
  95298. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95299. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95300. if(!sse)
  95301. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95302. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95303. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95304. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95305. size_t len = sizeof(val);
  95306. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95307. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95308. else { /* double-check SSE2 */
  95309. mib[1] = CPU_SSE2;
  95310. len = sizeof(val);
  95311. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95312. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95313. }
  95314. # else
  95315. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95316. # endif
  95317. #elif defined(__linux__)
  95318. int sse = 0;
  95319. struct sigaction sigill_save;
  95320. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95321. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95322. #else
  95323. struct sigaction sigill_sse;
  95324. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95325. __sigemptyset(&sigill_sse.sa_mask);
  95326. 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 */
  95327. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95328. #endif
  95329. {
  95330. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95331. /* see sigill_handler_sse_os() for an explanation of the following: */
  95332. asm volatile (
  95333. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95334. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95335. "incl %0\n\t" /* SIGILL handler will jump over this */
  95336. /* landing zone */
  95337. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95338. "nop\n\t"
  95339. "nop\n\t"
  95340. "nop\n\t"
  95341. "nop\n\t"
  95342. "nop\n\t"
  95343. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95344. "nop\n\t"
  95345. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95346. : "=r"(sse)
  95347. : "r"(sse)
  95348. );
  95349. sigaction(SIGILL, &sigill_save, NULL);
  95350. }
  95351. if(!sse)
  95352. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95353. #elif defined(_MSC_VER)
  95354. # ifdef USE_TRY_CATCH_FLAVOR
  95355. _try {
  95356. __asm {
  95357. # if _MSC_VER <= 1200
  95358. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95359. _emit 0x0F
  95360. _emit 0x57
  95361. _emit 0xC0
  95362. # else
  95363. xorps xmm0,xmm0
  95364. # endif
  95365. }
  95366. }
  95367. _except(EXCEPTION_EXECUTE_HANDLER) {
  95368. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95369. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95370. }
  95371. # else
  95372. int sse = 0;
  95373. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95374. /* see GCC version above for explanation */
  95375. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95376. /* http://www.codeproject.com/cpp/gccasm.asp */
  95377. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95378. __asm {
  95379. # if _MSC_VER <= 1200
  95380. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95381. _emit 0x0F
  95382. _emit 0x57
  95383. _emit 0xC0
  95384. # else
  95385. xorps xmm0,xmm0
  95386. # endif
  95387. inc sse
  95388. nop
  95389. nop
  95390. nop
  95391. nop
  95392. nop
  95393. nop
  95394. nop
  95395. nop
  95396. nop
  95397. }
  95398. SetUnhandledExceptionFilter(save);
  95399. if(!sse)
  95400. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95401. # endif
  95402. #else
  95403. /* no way to test, disable to be safe */
  95404. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95405. #endif
  95406. #ifdef DEBUG
  95407. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95408. #endif
  95409. }
  95410. }
  95411. #else
  95412. info->use_asm = false;
  95413. #endif
  95414. /*
  95415. * PPC-specific
  95416. */
  95417. #elif defined FLAC__CPU_PPC
  95418. info->type = FLAC__CPUINFO_TYPE_PPC;
  95419. # if !defined FLAC__NO_ASM
  95420. info->use_asm = true;
  95421. # ifdef FLAC__USE_ALTIVEC
  95422. # if defined FLAC__SYS_DARWIN
  95423. {
  95424. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95425. size_t len = sizeof(val);
  95426. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95427. }
  95428. {
  95429. host_basic_info_data_t hostInfo;
  95430. mach_msg_type_number_t infoCount;
  95431. infoCount = HOST_BASIC_INFO_COUNT;
  95432. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95433. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95434. }
  95435. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95436. {
  95437. /* no Darwin, do it the brute-force way */
  95438. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95439. info->data.ppc.altivec = 0;
  95440. info->data.ppc.ppc64 = 0;
  95441. signal (SIGILL, sigill_handler);
  95442. canjump = 0;
  95443. if (!sigsetjmp (jmpbuf, 1)) {
  95444. canjump = 1;
  95445. asm volatile (
  95446. "mtspr 256, %0\n\t"
  95447. "vand %%v0, %%v0, %%v0"
  95448. :
  95449. : "r" (-1)
  95450. );
  95451. info->data.ppc.altivec = 1;
  95452. }
  95453. canjump = 0;
  95454. if (!sigsetjmp (jmpbuf, 1)) {
  95455. int x = 0;
  95456. canjump = 1;
  95457. /* PPC64 hardware implements the cntlzd instruction */
  95458. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95459. info->data.ppc.ppc64 = 1;
  95460. }
  95461. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95462. }
  95463. # endif
  95464. # else /* !FLAC__USE_ALTIVEC */
  95465. info->data.ppc.altivec = 0;
  95466. info->data.ppc.ppc64 = 0;
  95467. # endif
  95468. # else
  95469. info->use_asm = false;
  95470. # endif
  95471. /*
  95472. * unknown CPI
  95473. */
  95474. #else
  95475. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95476. info->use_asm = false;
  95477. #endif
  95478. }
  95479. #endif
  95480. /*** End of inlined file: cpu.c ***/
  95481. /*** Start of inlined file: crc.c ***/
  95482. /*** Start of inlined file: juce_FlacHeader.h ***/
  95483. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95484. // tasks..
  95485. #define VERSION "1.2.1"
  95486. #define FLAC__NO_DLL 1
  95487. #if JUCE_MSVC
  95488. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95489. #endif
  95490. #if JUCE_MAC
  95491. #define FLAC__SYS_DARWIN 1
  95492. #endif
  95493. /*** End of inlined file: juce_FlacHeader.h ***/
  95494. #if JUCE_USE_FLAC
  95495. #if HAVE_CONFIG_H
  95496. # include <config.h>
  95497. #endif
  95498. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95499. FLAC__byte const FLAC__crc8_table[256] = {
  95500. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95501. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95502. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95503. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95504. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95505. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95506. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95507. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95508. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95509. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95510. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95511. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95512. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95513. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95514. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95515. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95516. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95517. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95518. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95519. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95520. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95521. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95522. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95523. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95524. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95525. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95526. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95527. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95528. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95529. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95530. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95531. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95532. };
  95533. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95534. unsigned FLAC__crc16_table[256] = {
  95535. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95536. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95537. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95538. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95539. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95540. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95541. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95542. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95543. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95544. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95545. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95546. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95547. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95548. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95549. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95550. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95551. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95552. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95553. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95554. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95555. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95556. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95557. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95558. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95559. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95560. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95561. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95562. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95563. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95564. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95565. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95566. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95567. };
  95568. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95569. {
  95570. *crc = FLAC__crc8_table[*crc ^ data];
  95571. }
  95572. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95573. {
  95574. while(len--)
  95575. *crc = FLAC__crc8_table[*crc ^ *data++];
  95576. }
  95577. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95578. {
  95579. FLAC__uint8 crc = 0;
  95580. while(len--)
  95581. crc = FLAC__crc8_table[crc ^ *data++];
  95582. return crc;
  95583. }
  95584. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95585. {
  95586. unsigned crc = 0;
  95587. while(len--)
  95588. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95589. return crc;
  95590. }
  95591. #endif
  95592. /*** End of inlined file: crc.c ***/
  95593. /*** Start of inlined file: fixed.c ***/
  95594. /*** Start of inlined file: juce_FlacHeader.h ***/
  95595. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95596. // tasks..
  95597. #define VERSION "1.2.1"
  95598. #define FLAC__NO_DLL 1
  95599. #if JUCE_MSVC
  95600. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95601. #endif
  95602. #if JUCE_MAC
  95603. #define FLAC__SYS_DARWIN 1
  95604. #endif
  95605. /*** End of inlined file: juce_FlacHeader.h ***/
  95606. #if JUCE_USE_FLAC
  95607. #if HAVE_CONFIG_H
  95608. # include <config.h>
  95609. #endif
  95610. #include <math.h>
  95611. #include <string.h>
  95612. /*** Start of inlined file: fixed.h ***/
  95613. #ifndef FLAC__PRIVATE__FIXED_H
  95614. #define FLAC__PRIVATE__FIXED_H
  95615. #ifdef HAVE_CONFIG_H
  95616. #include <config.h>
  95617. #endif
  95618. /*** Start of inlined file: float.h ***/
  95619. #ifndef FLAC__PRIVATE__FLOAT_H
  95620. #define FLAC__PRIVATE__FLOAT_H
  95621. #ifdef HAVE_CONFIG_H
  95622. #include <config.h>
  95623. #endif
  95624. /*
  95625. * These typedefs make it easier to ensure that integer versions of
  95626. * the library really only contain integer operations. All the code
  95627. * in libFLAC should use FLAC__float and FLAC__double in place of
  95628. * float and double, and be protected by checks of the macro
  95629. * FLAC__INTEGER_ONLY_LIBRARY.
  95630. *
  95631. * FLAC__real is the basic floating point type used in LPC analysis.
  95632. */
  95633. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95634. typedef double FLAC__double;
  95635. typedef float FLAC__float;
  95636. /*
  95637. * WATCHOUT: changing FLAC__real will change the signatures of many
  95638. * functions that have assembly language equivalents and break them.
  95639. */
  95640. typedef float FLAC__real;
  95641. #else
  95642. /*
  95643. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95644. * for the integer part and lower 16 bits for the fractional part.
  95645. */
  95646. typedef FLAC__int32 FLAC__fixedpoint;
  95647. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95648. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95649. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95650. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95651. extern const FLAC__fixedpoint FLAC__FP_E;
  95652. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95653. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95654. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95655. /*
  95656. * FLAC__fixedpoint_log2()
  95657. * --------------------------------------------------------------------
  95658. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95659. * algorithm by Knuth for x >= 1.0
  95660. *
  95661. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95662. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95663. *
  95664. * 'precision' roughly limits the number of iterations that are done;
  95665. * use (unsigned)(-1) for maximum precision.
  95666. *
  95667. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95668. * function will punt and return 0.
  95669. *
  95670. * The return value will also have 'fracbits' fractional bits.
  95671. */
  95672. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95673. #endif
  95674. #endif
  95675. /*** End of inlined file: float.h ***/
  95676. /*** Start of inlined file: format.h ***/
  95677. #ifndef FLAC__PRIVATE__FORMAT_H
  95678. #define FLAC__PRIVATE__FORMAT_H
  95679. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95680. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95681. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95682. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95683. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95684. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95685. #endif
  95686. /*** End of inlined file: format.h ***/
  95687. /*
  95688. * FLAC__fixed_compute_best_predictor()
  95689. * --------------------------------------------------------------------
  95690. * Compute the best fixed predictor and the expected bits-per-sample
  95691. * of the residual signal for each order. The _wide() version uses
  95692. * 64-bit integers which is statistically necessary when bits-per-
  95693. * sample + log2(blocksize) > 30
  95694. *
  95695. * IN data[0,data_len-1]
  95696. * IN data_len
  95697. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95698. */
  95699. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95700. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95701. # ifndef FLAC__NO_ASM
  95702. # ifdef FLAC__CPU_IA32
  95703. # ifdef FLAC__HAS_NASM
  95704. 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]);
  95705. # endif
  95706. # endif
  95707. # endif
  95708. 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]);
  95709. #else
  95710. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95711. 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]);
  95712. #endif
  95713. /*
  95714. * FLAC__fixed_compute_residual()
  95715. * --------------------------------------------------------------------
  95716. * Compute the residual signal obtained from sutracting the predicted
  95717. * signal from the original.
  95718. *
  95719. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95720. * IN data_len length of original signal
  95721. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95722. * OUT residual[0,data_len-1] residual signal
  95723. */
  95724. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95725. /*
  95726. * FLAC__fixed_restore_signal()
  95727. * --------------------------------------------------------------------
  95728. * Restore the original signal by summing the residual and the
  95729. * predictor.
  95730. *
  95731. * IN residual[0,data_len-1] residual signal
  95732. * IN data_len length of original signal
  95733. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95734. * *** IMPORTANT: the caller must pass in the historical samples:
  95735. * IN data[-order,-1] previously-reconstructed historical samples
  95736. * OUT data[0,data_len-1] original signal
  95737. */
  95738. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95739. #endif
  95740. /*** End of inlined file: fixed.h ***/
  95741. #ifndef M_LN2
  95742. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95743. #define M_LN2 0.69314718055994530942
  95744. #endif
  95745. #ifdef min
  95746. #undef min
  95747. #endif
  95748. #define min(x,y) ((x) < (y)? (x) : (y))
  95749. #ifdef local_abs
  95750. #undef local_abs
  95751. #endif
  95752. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95753. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95754. /* rbps stands for residual bits per sample
  95755. *
  95756. * (ln(2) * err)
  95757. * rbps = log (-----------)
  95758. * 2 ( n )
  95759. */
  95760. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95761. {
  95762. FLAC__uint32 rbps;
  95763. unsigned bits; /* the number of bits required to represent a number */
  95764. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95765. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95766. FLAC__ASSERT(err > 0);
  95767. FLAC__ASSERT(n > 0);
  95768. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95769. if(err <= n)
  95770. return 0;
  95771. /*
  95772. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95773. * These allow us later to know we won't lose too much precision in the
  95774. * fixed-point division (err<<fracbits)/n.
  95775. */
  95776. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95777. err <<= fracbits;
  95778. err /= n;
  95779. /* err now holds err/n with fracbits fractional bits */
  95780. /*
  95781. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95782. * our purposes.
  95783. */
  95784. FLAC__ASSERT(err > 0);
  95785. bits = FLAC__bitmath_ilog2(err)+1;
  95786. if(bits > 16) {
  95787. err >>= (bits-16);
  95788. fracbits -= (bits-16);
  95789. }
  95790. rbps = (FLAC__uint32)err;
  95791. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95792. rbps *= FLAC__FP_LN2;
  95793. fracbits += 16;
  95794. FLAC__ASSERT(fracbits >= 0);
  95795. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95796. {
  95797. const int f = fracbits & 3;
  95798. if(f) {
  95799. rbps >>= f;
  95800. fracbits -= f;
  95801. }
  95802. }
  95803. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95804. if(rbps == 0)
  95805. return 0;
  95806. /*
  95807. * The return value must have 16 fractional bits. Since the whole part
  95808. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95809. * must be >= -3, these assertion allows us to be able to shift rbps
  95810. * left if necessary to get 16 fracbits without losing any bits of the
  95811. * whole part of rbps.
  95812. *
  95813. * There is a slight chance due to accumulated error that the whole part
  95814. * will require 6 bits, so we use 6 in the assertion. Really though as
  95815. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95816. */
  95817. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95818. FLAC__ASSERT(fracbits >= -3);
  95819. /* now shift the decimal point into place */
  95820. if(fracbits < 16)
  95821. return rbps << (16-fracbits);
  95822. else if(fracbits > 16)
  95823. return rbps >> (fracbits-16);
  95824. else
  95825. return rbps;
  95826. }
  95827. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95828. {
  95829. FLAC__uint32 rbps;
  95830. unsigned bits; /* the number of bits required to represent a number */
  95831. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95832. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95833. FLAC__ASSERT(err > 0);
  95834. FLAC__ASSERT(n > 0);
  95835. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95836. if(err <= n)
  95837. return 0;
  95838. /*
  95839. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95840. * These allow us later to know we won't lose too much precision in the
  95841. * fixed-point division (err<<fracbits)/n.
  95842. */
  95843. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95844. err <<= fracbits;
  95845. err /= n;
  95846. /* err now holds err/n with fracbits fractional bits */
  95847. /*
  95848. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95849. * our purposes.
  95850. */
  95851. FLAC__ASSERT(err > 0);
  95852. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95853. if(bits > 16) {
  95854. err >>= (bits-16);
  95855. fracbits -= (bits-16);
  95856. }
  95857. rbps = (FLAC__uint32)err;
  95858. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95859. rbps *= FLAC__FP_LN2;
  95860. fracbits += 16;
  95861. FLAC__ASSERT(fracbits >= 0);
  95862. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95863. {
  95864. const int f = fracbits & 3;
  95865. if(f) {
  95866. rbps >>= f;
  95867. fracbits -= f;
  95868. }
  95869. }
  95870. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95871. if(rbps == 0)
  95872. return 0;
  95873. /*
  95874. * The return value must have 16 fractional bits. Since the whole part
  95875. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95876. * must be >= -3, these assertion allows us to be able to shift rbps
  95877. * left if necessary to get 16 fracbits without losing any bits of the
  95878. * whole part of rbps.
  95879. *
  95880. * There is a slight chance due to accumulated error that the whole part
  95881. * will require 6 bits, so we use 6 in the assertion. Really though as
  95882. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95883. */
  95884. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95885. FLAC__ASSERT(fracbits >= -3);
  95886. /* now shift the decimal point into place */
  95887. if(fracbits < 16)
  95888. return rbps << (16-fracbits);
  95889. else if(fracbits > 16)
  95890. return rbps >> (fracbits-16);
  95891. else
  95892. return rbps;
  95893. }
  95894. #endif
  95895. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95896. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95897. #else
  95898. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95899. #endif
  95900. {
  95901. FLAC__int32 last_error_0 = data[-1];
  95902. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95903. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95904. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95905. FLAC__int32 error, save;
  95906. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95907. unsigned i, order;
  95908. for(i = 0; i < data_len; i++) {
  95909. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95910. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95911. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95912. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95913. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95914. }
  95915. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95916. order = 0;
  95917. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95918. order = 1;
  95919. else if(total_error_2 < min(total_error_3, total_error_4))
  95920. order = 2;
  95921. else if(total_error_3 < total_error_4)
  95922. order = 3;
  95923. else
  95924. order = 4;
  95925. /* Estimate the expected number of bits per residual signal sample. */
  95926. /* 'total_error*' is linearly related to the variance of the residual */
  95927. /* signal, so we use it directly to compute E(|x|) */
  95928. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95929. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95930. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95931. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95932. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95933. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95934. 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);
  95935. 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);
  95936. 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);
  95937. 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);
  95938. 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);
  95939. #else
  95940. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95941. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95942. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95943. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95944. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95945. #endif
  95946. return order;
  95947. }
  95948. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95949. 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])
  95950. #else
  95951. 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])
  95952. #endif
  95953. {
  95954. FLAC__int32 last_error_0 = data[-1];
  95955. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95956. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95957. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95958. FLAC__int32 error, save;
  95959. /* total_error_* are 64-bits to avoid overflow when encoding
  95960. * erratic signals when the bits-per-sample and blocksize are
  95961. * large.
  95962. */
  95963. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95964. unsigned i, order;
  95965. for(i = 0; i < data_len; i++) {
  95966. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95967. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95968. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95969. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95970. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95971. }
  95972. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95973. order = 0;
  95974. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95975. order = 1;
  95976. else if(total_error_2 < min(total_error_3, total_error_4))
  95977. order = 2;
  95978. else if(total_error_3 < total_error_4)
  95979. order = 3;
  95980. else
  95981. order = 4;
  95982. /* Estimate the expected number of bits per residual signal sample. */
  95983. /* 'total_error*' is linearly related to the variance of the residual */
  95984. /* signal, so we use it directly to compute E(|x|) */
  95985. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95986. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95987. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95988. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95989. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95990. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95991. #if defined _MSC_VER || defined __MINGW32__
  95992. /* with MSVC you have to spoon feed it the casting */
  95993. 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);
  95994. 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);
  95995. 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);
  95996. 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);
  95997. 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);
  95998. #else
  95999. 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);
  96000. 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);
  96001. 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);
  96002. 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);
  96003. 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);
  96004. #endif
  96005. #else
  96006. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96007. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96008. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96009. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96010. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96011. #endif
  96012. return order;
  96013. }
  96014. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96015. {
  96016. const int idata_len = (int)data_len;
  96017. int i;
  96018. switch(order) {
  96019. case 0:
  96020. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96021. memcpy(residual, data, sizeof(residual[0])*data_len);
  96022. break;
  96023. case 1:
  96024. for(i = 0; i < idata_len; i++)
  96025. residual[i] = data[i] - data[i-1];
  96026. break;
  96027. case 2:
  96028. for(i = 0; i < idata_len; i++)
  96029. #if 1 /* OPT: may be faster with some compilers on some systems */
  96030. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96031. #else
  96032. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96033. #endif
  96034. break;
  96035. case 3:
  96036. for(i = 0; i < idata_len; i++)
  96037. #if 1 /* OPT: may be faster with some compilers on some systems */
  96038. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96039. #else
  96040. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96041. #endif
  96042. break;
  96043. case 4:
  96044. for(i = 0; i < idata_len; i++)
  96045. #if 1 /* OPT: may be faster with some compilers on some systems */
  96046. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96047. #else
  96048. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96049. #endif
  96050. break;
  96051. default:
  96052. FLAC__ASSERT(0);
  96053. }
  96054. }
  96055. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96056. {
  96057. int i, idata_len = (int)data_len;
  96058. switch(order) {
  96059. case 0:
  96060. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96061. memcpy(data, residual, sizeof(residual[0])*data_len);
  96062. break;
  96063. case 1:
  96064. for(i = 0; i < idata_len; i++)
  96065. data[i] = residual[i] + data[i-1];
  96066. break;
  96067. case 2:
  96068. for(i = 0; i < idata_len; i++)
  96069. #if 1 /* OPT: may be faster with some compilers on some systems */
  96070. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96071. #else
  96072. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96073. #endif
  96074. break;
  96075. case 3:
  96076. for(i = 0; i < idata_len; i++)
  96077. #if 1 /* OPT: may be faster with some compilers on some systems */
  96078. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96079. #else
  96080. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96081. #endif
  96082. break;
  96083. case 4:
  96084. for(i = 0; i < idata_len; i++)
  96085. #if 1 /* OPT: may be faster with some compilers on some systems */
  96086. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96087. #else
  96088. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96089. #endif
  96090. break;
  96091. default:
  96092. FLAC__ASSERT(0);
  96093. }
  96094. }
  96095. #endif
  96096. /*** End of inlined file: fixed.c ***/
  96097. /*** Start of inlined file: float.c ***/
  96098. /*** Start of inlined file: juce_FlacHeader.h ***/
  96099. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96100. // tasks..
  96101. #define VERSION "1.2.1"
  96102. #define FLAC__NO_DLL 1
  96103. #if JUCE_MSVC
  96104. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96105. #endif
  96106. #if JUCE_MAC
  96107. #define FLAC__SYS_DARWIN 1
  96108. #endif
  96109. /*** End of inlined file: juce_FlacHeader.h ***/
  96110. #if JUCE_USE_FLAC
  96111. #if HAVE_CONFIG_H
  96112. # include <config.h>
  96113. #endif
  96114. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96115. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96116. #ifdef _MSC_VER
  96117. #define FLAC__U64L(x) x
  96118. #else
  96119. #define FLAC__U64L(x) x##LLU
  96120. #endif
  96121. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96122. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96123. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96124. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96125. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96126. /* Lookup tables for Knuth's logarithm algorithm */
  96127. #define LOG2_LOOKUP_PRECISION 16
  96128. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96129. {
  96130. /*
  96131. * 0 fraction bits
  96132. */
  96133. /* undefined */ 0x00000000,
  96134. /* lg(2/1) = */ 0x00000001,
  96135. /* lg(4/3) = */ 0x00000000,
  96136. /* lg(8/7) = */ 0x00000000,
  96137. /* lg(16/15) = */ 0x00000000,
  96138. /* lg(32/31) = */ 0x00000000,
  96139. /* lg(64/63) = */ 0x00000000,
  96140. /* lg(128/127) = */ 0x00000000,
  96141. /* lg(256/255) = */ 0x00000000,
  96142. /* lg(512/511) = */ 0x00000000,
  96143. /* lg(1024/1023) = */ 0x00000000,
  96144. /* lg(2048/2047) = */ 0x00000000,
  96145. /* lg(4096/4095) = */ 0x00000000,
  96146. /* lg(8192/8191) = */ 0x00000000,
  96147. /* lg(16384/16383) = */ 0x00000000,
  96148. /* lg(32768/32767) = */ 0x00000000
  96149. },
  96150. {
  96151. /*
  96152. * 4 fraction bits
  96153. */
  96154. /* undefined */ 0x00000000,
  96155. /* lg(2/1) = */ 0x00000010,
  96156. /* lg(4/3) = */ 0x00000007,
  96157. /* lg(8/7) = */ 0x00000003,
  96158. /* lg(16/15) = */ 0x00000001,
  96159. /* lg(32/31) = */ 0x00000001,
  96160. /* lg(64/63) = */ 0x00000000,
  96161. /* lg(128/127) = */ 0x00000000,
  96162. /* lg(256/255) = */ 0x00000000,
  96163. /* lg(512/511) = */ 0x00000000,
  96164. /* lg(1024/1023) = */ 0x00000000,
  96165. /* lg(2048/2047) = */ 0x00000000,
  96166. /* lg(4096/4095) = */ 0x00000000,
  96167. /* lg(8192/8191) = */ 0x00000000,
  96168. /* lg(16384/16383) = */ 0x00000000,
  96169. /* lg(32768/32767) = */ 0x00000000
  96170. },
  96171. {
  96172. /*
  96173. * 8 fraction bits
  96174. */
  96175. /* undefined */ 0x00000000,
  96176. /* lg(2/1) = */ 0x00000100,
  96177. /* lg(4/3) = */ 0x0000006a,
  96178. /* lg(8/7) = */ 0x00000031,
  96179. /* lg(16/15) = */ 0x00000018,
  96180. /* lg(32/31) = */ 0x0000000c,
  96181. /* lg(64/63) = */ 0x00000006,
  96182. /* lg(128/127) = */ 0x00000003,
  96183. /* lg(256/255) = */ 0x00000001,
  96184. /* lg(512/511) = */ 0x00000001,
  96185. /* lg(1024/1023) = */ 0x00000000,
  96186. /* lg(2048/2047) = */ 0x00000000,
  96187. /* lg(4096/4095) = */ 0x00000000,
  96188. /* lg(8192/8191) = */ 0x00000000,
  96189. /* lg(16384/16383) = */ 0x00000000,
  96190. /* lg(32768/32767) = */ 0x00000000
  96191. },
  96192. {
  96193. /*
  96194. * 12 fraction bits
  96195. */
  96196. /* undefined */ 0x00000000,
  96197. /* lg(2/1) = */ 0x00001000,
  96198. /* lg(4/3) = */ 0x000006a4,
  96199. /* lg(8/7) = */ 0x00000315,
  96200. /* lg(16/15) = */ 0x0000017d,
  96201. /* lg(32/31) = */ 0x000000bc,
  96202. /* lg(64/63) = */ 0x0000005d,
  96203. /* lg(128/127) = */ 0x0000002e,
  96204. /* lg(256/255) = */ 0x00000017,
  96205. /* lg(512/511) = */ 0x0000000c,
  96206. /* lg(1024/1023) = */ 0x00000006,
  96207. /* lg(2048/2047) = */ 0x00000003,
  96208. /* lg(4096/4095) = */ 0x00000001,
  96209. /* lg(8192/8191) = */ 0x00000001,
  96210. /* lg(16384/16383) = */ 0x00000000,
  96211. /* lg(32768/32767) = */ 0x00000000
  96212. },
  96213. {
  96214. /*
  96215. * 16 fraction bits
  96216. */
  96217. /* undefined */ 0x00000000,
  96218. /* lg(2/1) = */ 0x00010000,
  96219. /* lg(4/3) = */ 0x00006a40,
  96220. /* lg(8/7) = */ 0x00003151,
  96221. /* lg(16/15) = */ 0x000017d6,
  96222. /* lg(32/31) = */ 0x00000bba,
  96223. /* lg(64/63) = */ 0x000005d1,
  96224. /* lg(128/127) = */ 0x000002e6,
  96225. /* lg(256/255) = */ 0x00000172,
  96226. /* lg(512/511) = */ 0x000000b9,
  96227. /* lg(1024/1023) = */ 0x0000005c,
  96228. /* lg(2048/2047) = */ 0x0000002e,
  96229. /* lg(4096/4095) = */ 0x00000017,
  96230. /* lg(8192/8191) = */ 0x0000000c,
  96231. /* lg(16384/16383) = */ 0x00000006,
  96232. /* lg(32768/32767) = */ 0x00000003
  96233. },
  96234. {
  96235. /*
  96236. * 20 fraction bits
  96237. */
  96238. /* undefined */ 0x00000000,
  96239. /* lg(2/1) = */ 0x00100000,
  96240. /* lg(4/3) = */ 0x0006a3fe,
  96241. /* lg(8/7) = */ 0x00031513,
  96242. /* lg(16/15) = */ 0x00017d60,
  96243. /* lg(32/31) = */ 0x0000bb9d,
  96244. /* lg(64/63) = */ 0x00005d10,
  96245. /* lg(128/127) = */ 0x00002e59,
  96246. /* lg(256/255) = */ 0x00001721,
  96247. /* lg(512/511) = */ 0x00000b8e,
  96248. /* lg(1024/1023) = */ 0x000005c6,
  96249. /* lg(2048/2047) = */ 0x000002e3,
  96250. /* lg(4096/4095) = */ 0x00000171,
  96251. /* lg(8192/8191) = */ 0x000000b9,
  96252. /* lg(16384/16383) = */ 0x0000005c,
  96253. /* lg(32768/32767) = */ 0x0000002e
  96254. },
  96255. {
  96256. /*
  96257. * 24 fraction bits
  96258. */
  96259. /* undefined */ 0x00000000,
  96260. /* lg(2/1) = */ 0x01000000,
  96261. /* lg(4/3) = */ 0x006a3fe6,
  96262. /* lg(8/7) = */ 0x00315130,
  96263. /* lg(16/15) = */ 0x0017d605,
  96264. /* lg(32/31) = */ 0x000bb9ca,
  96265. /* lg(64/63) = */ 0x0005d0fc,
  96266. /* lg(128/127) = */ 0x0002e58f,
  96267. /* lg(256/255) = */ 0x0001720e,
  96268. /* lg(512/511) = */ 0x0000b8d8,
  96269. /* lg(1024/1023) = */ 0x00005c61,
  96270. /* lg(2048/2047) = */ 0x00002e2d,
  96271. /* lg(4096/4095) = */ 0x00001716,
  96272. /* lg(8192/8191) = */ 0x00000b8b,
  96273. /* lg(16384/16383) = */ 0x000005c5,
  96274. /* lg(32768/32767) = */ 0x000002e3
  96275. },
  96276. {
  96277. /*
  96278. * 28 fraction bits
  96279. */
  96280. /* undefined */ 0x00000000,
  96281. /* lg(2/1) = */ 0x10000000,
  96282. /* lg(4/3) = */ 0x06a3fe5c,
  96283. /* lg(8/7) = */ 0x03151301,
  96284. /* lg(16/15) = */ 0x017d6049,
  96285. /* lg(32/31) = */ 0x00bb9ca6,
  96286. /* lg(64/63) = */ 0x005d0fba,
  96287. /* lg(128/127) = */ 0x002e58f7,
  96288. /* lg(256/255) = */ 0x001720da,
  96289. /* lg(512/511) = */ 0x000b8d87,
  96290. /* lg(1024/1023) = */ 0x0005c60b,
  96291. /* lg(2048/2047) = */ 0x0002e2d7,
  96292. /* lg(4096/4095) = */ 0x00017160,
  96293. /* lg(8192/8191) = */ 0x0000b8ad,
  96294. /* lg(16384/16383) = */ 0x00005c56,
  96295. /* lg(32768/32767) = */ 0x00002e2b
  96296. }
  96297. };
  96298. #if 0
  96299. static const FLAC__uint64 log2_lookup_wide[] = {
  96300. {
  96301. /*
  96302. * 32 fraction bits
  96303. */
  96304. /* undefined */ 0x00000000,
  96305. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96306. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96307. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96308. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96309. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96310. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96311. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96312. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96313. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96314. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96315. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96316. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96317. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96318. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96319. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96320. },
  96321. {
  96322. /*
  96323. * 48 fraction bits
  96324. */
  96325. /* undefined */ 0x00000000,
  96326. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96327. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96328. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96329. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96330. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96331. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96332. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96333. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96334. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96335. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96336. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96337. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96338. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96339. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96340. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96341. }
  96342. };
  96343. #endif
  96344. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96345. {
  96346. const FLAC__uint32 ONE = (1u << fracbits);
  96347. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96348. FLAC__ASSERT(fracbits < 32);
  96349. FLAC__ASSERT((fracbits & 0x3) == 0);
  96350. if(x < ONE)
  96351. return 0;
  96352. if(precision > LOG2_LOOKUP_PRECISION)
  96353. precision = LOG2_LOOKUP_PRECISION;
  96354. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96355. {
  96356. FLAC__uint32 y = 0;
  96357. FLAC__uint32 z = x >> 1, k = 1;
  96358. while (x > ONE && k < precision) {
  96359. if (x - z >= ONE) {
  96360. x -= z;
  96361. z = x >> k;
  96362. y += table[k];
  96363. }
  96364. else {
  96365. z >>= 1;
  96366. k++;
  96367. }
  96368. }
  96369. return y;
  96370. }
  96371. }
  96372. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96373. #endif
  96374. /*** End of inlined file: float.c ***/
  96375. /*** Start of inlined file: format.c ***/
  96376. /*** Start of inlined file: juce_FlacHeader.h ***/
  96377. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96378. // tasks..
  96379. #define VERSION "1.2.1"
  96380. #define FLAC__NO_DLL 1
  96381. #if JUCE_MSVC
  96382. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96383. #endif
  96384. #if JUCE_MAC
  96385. #define FLAC__SYS_DARWIN 1
  96386. #endif
  96387. /*** End of inlined file: juce_FlacHeader.h ***/
  96388. #if JUCE_USE_FLAC
  96389. #if HAVE_CONFIG_H
  96390. # include <config.h>
  96391. #endif
  96392. #include <stdio.h>
  96393. #include <stdlib.h> /* for qsort() */
  96394. #include <string.h> /* for memset() */
  96395. #ifndef FLaC__INLINE
  96396. #define FLaC__INLINE
  96397. #endif
  96398. #ifdef min
  96399. #undef min
  96400. #endif
  96401. #define min(a,b) ((a)<(b)?(a):(b))
  96402. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96403. #ifdef _MSC_VER
  96404. #define FLAC__U64L(x) x
  96405. #else
  96406. #define FLAC__U64L(x) x##LLU
  96407. #endif
  96408. /* VERSION should come from configure */
  96409. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96410. ;
  96411. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96412. /* yet one more hack because of MSVC6: */
  96413. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96414. #else
  96415. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96416. #endif
  96417. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96418. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96419. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96420. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96421. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96422. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96423. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96424. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96425. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96426. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96427. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96428. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96429. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96430. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96431. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96432. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96433. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96434. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96435. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96436. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96437. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96438. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96439. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96440. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96441. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96442. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96443. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96444. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96445. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96446. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96447. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96448. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96449. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96450. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96451. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96452. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96453. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96454. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96455. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96456. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96457. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96458. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96459. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96460. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96461. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96462. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96463. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96464. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96465. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96466. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96467. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96468. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96469. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96470. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96471. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96472. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96473. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96474. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96475. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96476. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96477. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96478. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96479. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96480. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96481. "PARTITIONED_RICE",
  96482. "PARTITIONED_RICE2"
  96483. };
  96484. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96485. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96486. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96487. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96488. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96489. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96490. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96491. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96492. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96493. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96494. "CONSTANT",
  96495. "VERBATIM",
  96496. "FIXED",
  96497. "LPC"
  96498. };
  96499. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96500. "INDEPENDENT",
  96501. "LEFT_SIDE",
  96502. "RIGHT_SIDE",
  96503. "MID_SIDE"
  96504. };
  96505. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96506. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96507. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96508. };
  96509. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96510. "STREAMINFO",
  96511. "PADDING",
  96512. "APPLICATION",
  96513. "SEEKTABLE",
  96514. "VORBIS_COMMENT",
  96515. "CUESHEET",
  96516. "PICTURE"
  96517. };
  96518. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96519. "Other",
  96520. "32x32 pixels 'file icon' (PNG only)",
  96521. "Other file icon",
  96522. "Cover (front)",
  96523. "Cover (back)",
  96524. "Leaflet page",
  96525. "Media (e.g. label side of CD)",
  96526. "Lead artist/lead performer/soloist",
  96527. "Artist/performer",
  96528. "Conductor",
  96529. "Band/Orchestra",
  96530. "Composer",
  96531. "Lyricist/text writer",
  96532. "Recording Location",
  96533. "During recording",
  96534. "During performance",
  96535. "Movie/video screen capture",
  96536. "A bright coloured fish",
  96537. "Illustration",
  96538. "Band/artist logotype",
  96539. "Publisher/Studio logotype"
  96540. };
  96541. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96542. {
  96543. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96544. return false;
  96545. }
  96546. else
  96547. return true;
  96548. }
  96549. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96550. {
  96551. if(
  96552. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96553. (
  96554. sample_rate >= (1u << 16) &&
  96555. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96556. )
  96557. ) {
  96558. return false;
  96559. }
  96560. else
  96561. return true;
  96562. }
  96563. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96564. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96565. {
  96566. unsigned i;
  96567. FLAC__uint64 prev_sample_number = 0;
  96568. FLAC__bool got_prev = false;
  96569. FLAC__ASSERT(0 != seek_table);
  96570. for(i = 0; i < seek_table->num_points; i++) {
  96571. if(got_prev) {
  96572. if(
  96573. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96574. seek_table->points[i].sample_number <= prev_sample_number
  96575. )
  96576. return false;
  96577. }
  96578. prev_sample_number = seek_table->points[i].sample_number;
  96579. got_prev = true;
  96580. }
  96581. return true;
  96582. }
  96583. /* used as the sort predicate for qsort() */
  96584. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96585. {
  96586. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96587. if(l->sample_number == r->sample_number)
  96588. return 0;
  96589. else if(l->sample_number < r->sample_number)
  96590. return -1;
  96591. else
  96592. return 1;
  96593. }
  96594. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96595. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96596. {
  96597. unsigned i, j;
  96598. FLAC__bool first;
  96599. FLAC__ASSERT(0 != seek_table);
  96600. /* sort the seekpoints */
  96601. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96602. /* uniquify the seekpoints */
  96603. first = true;
  96604. for(i = j = 0; i < seek_table->num_points; i++) {
  96605. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96606. if(!first) {
  96607. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96608. continue;
  96609. }
  96610. }
  96611. first = false;
  96612. seek_table->points[j++] = seek_table->points[i];
  96613. }
  96614. for(i = j; i < seek_table->num_points; i++) {
  96615. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96616. seek_table->points[i].stream_offset = 0;
  96617. seek_table->points[i].frame_samples = 0;
  96618. }
  96619. return j;
  96620. }
  96621. /*
  96622. * also disallows non-shortest-form encodings, c.f.
  96623. * http://www.unicode.org/versions/corrigendum1.html
  96624. * and a more clear explanation at the end of this section:
  96625. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96626. */
  96627. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96628. {
  96629. FLAC__ASSERT(0 != utf8);
  96630. if ((utf8[0] & 0x80) == 0) {
  96631. return 1;
  96632. }
  96633. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96634. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96635. return 0;
  96636. return 2;
  96637. }
  96638. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96639. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96640. return 0;
  96641. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96642. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96643. return 0;
  96644. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96645. return 0;
  96646. return 3;
  96647. }
  96648. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96649. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96650. return 0;
  96651. return 4;
  96652. }
  96653. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96654. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96655. return 0;
  96656. return 5;
  96657. }
  96658. 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) {
  96659. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96660. return 0;
  96661. return 6;
  96662. }
  96663. else {
  96664. return 0;
  96665. }
  96666. }
  96667. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96668. {
  96669. char c;
  96670. for(c = *name; c; c = *(++name))
  96671. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96672. return false;
  96673. return true;
  96674. }
  96675. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96676. {
  96677. if(length == (unsigned)(-1)) {
  96678. while(*value) {
  96679. unsigned n = utf8len_(value);
  96680. if(n == 0)
  96681. return false;
  96682. value += n;
  96683. }
  96684. }
  96685. else {
  96686. const FLAC__byte *end = value + length;
  96687. while(value < end) {
  96688. unsigned n = utf8len_(value);
  96689. if(n == 0)
  96690. return false;
  96691. value += n;
  96692. }
  96693. if(value != end)
  96694. return false;
  96695. }
  96696. return true;
  96697. }
  96698. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96699. {
  96700. const FLAC__byte *s, *end;
  96701. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96702. if(*s < 0x20 || *s > 0x7D)
  96703. return false;
  96704. }
  96705. if(s == end)
  96706. return false;
  96707. s++; /* skip '=' */
  96708. while(s < end) {
  96709. unsigned n = utf8len_(s);
  96710. if(n == 0)
  96711. return false;
  96712. s += n;
  96713. }
  96714. if(s != end)
  96715. return false;
  96716. return true;
  96717. }
  96718. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96719. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96720. {
  96721. unsigned i, j;
  96722. if(check_cd_da_subset) {
  96723. if(cue_sheet->lead_in < 2 * 44100) {
  96724. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96725. return false;
  96726. }
  96727. if(cue_sheet->lead_in % 588 != 0) {
  96728. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96729. return false;
  96730. }
  96731. }
  96732. if(cue_sheet->num_tracks == 0) {
  96733. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96734. return false;
  96735. }
  96736. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96737. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96738. return false;
  96739. }
  96740. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96741. if(cue_sheet->tracks[i].number == 0) {
  96742. if(violation) *violation = "cue sheet may not have a track number 0";
  96743. return false;
  96744. }
  96745. if(check_cd_da_subset) {
  96746. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96747. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96748. return false;
  96749. }
  96750. }
  96751. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96752. if(violation) {
  96753. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96754. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96755. else
  96756. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96757. }
  96758. return false;
  96759. }
  96760. if(i < cue_sheet->num_tracks - 1) {
  96761. if(cue_sheet->tracks[i].num_indices == 0) {
  96762. if(violation) *violation = "cue sheet track must have at least one index point";
  96763. return false;
  96764. }
  96765. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96766. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96767. return false;
  96768. }
  96769. }
  96770. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96771. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96772. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96773. return false;
  96774. }
  96775. if(j > 0) {
  96776. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96777. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96778. return false;
  96779. }
  96780. }
  96781. }
  96782. }
  96783. return true;
  96784. }
  96785. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96786. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96787. {
  96788. char *p;
  96789. FLAC__byte *b;
  96790. for(p = picture->mime_type; *p; p++) {
  96791. if(*p < 0x20 || *p > 0x7e) {
  96792. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96793. return false;
  96794. }
  96795. }
  96796. for(b = picture->description; *b; ) {
  96797. unsigned n = utf8len_(b);
  96798. if(n == 0) {
  96799. if(violation) *violation = "description string must be valid UTF-8";
  96800. return false;
  96801. }
  96802. b += n;
  96803. }
  96804. return true;
  96805. }
  96806. /*
  96807. * These routines are private to libFLAC
  96808. */
  96809. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96810. {
  96811. return
  96812. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96813. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96814. blocksize,
  96815. predictor_order
  96816. );
  96817. }
  96818. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96819. {
  96820. unsigned max_rice_partition_order = 0;
  96821. while(!(blocksize & 1)) {
  96822. max_rice_partition_order++;
  96823. blocksize >>= 1;
  96824. }
  96825. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96826. }
  96827. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96828. {
  96829. unsigned max_rice_partition_order = limit;
  96830. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96831. max_rice_partition_order--;
  96832. FLAC__ASSERT(
  96833. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96834. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96835. );
  96836. return max_rice_partition_order;
  96837. }
  96838. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96839. {
  96840. FLAC__ASSERT(0 != object);
  96841. object->parameters = 0;
  96842. object->raw_bits = 0;
  96843. object->capacity_by_order = 0;
  96844. }
  96845. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96846. {
  96847. FLAC__ASSERT(0 != object);
  96848. if(0 != object->parameters)
  96849. free(object->parameters);
  96850. if(0 != object->raw_bits)
  96851. free(object->raw_bits);
  96852. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96853. }
  96854. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96855. {
  96856. FLAC__ASSERT(0 != object);
  96857. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96858. if(object->capacity_by_order < max_partition_order) {
  96859. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96860. return false;
  96861. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96862. return false;
  96863. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96864. object->capacity_by_order = max_partition_order;
  96865. }
  96866. return true;
  96867. }
  96868. #endif
  96869. /*** End of inlined file: format.c ***/
  96870. /*** Start of inlined file: lpc_flac.c ***/
  96871. /*** Start of inlined file: juce_FlacHeader.h ***/
  96872. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96873. // tasks..
  96874. #define VERSION "1.2.1"
  96875. #define FLAC__NO_DLL 1
  96876. #if JUCE_MSVC
  96877. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96878. #endif
  96879. #if JUCE_MAC
  96880. #define FLAC__SYS_DARWIN 1
  96881. #endif
  96882. /*** End of inlined file: juce_FlacHeader.h ***/
  96883. #if JUCE_USE_FLAC
  96884. #if HAVE_CONFIG_H
  96885. # include <config.h>
  96886. #endif
  96887. #include <math.h>
  96888. /*** Start of inlined file: lpc.h ***/
  96889. #ifndef FLAC__PRIVATE__LPC_H
  96890. #define FLAC__PRIVATE__LPC_H
  96891. #ifdef HAVE_CONFIG_H
  96892. #include <config.h>
  96893. #endif
  96894. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96895. /*
  96896. * FLAC__lpc_window_data()
  96897. * --------------------------------------------------------------------
  96898. * Applies the given window to the data.
  96899. * OPT: asm implementation
  96900. *
  96901. * IN in[0,data_len-1]
  96902. * IN window[0,data_len-1]
  96903. * OUT out[0,lag-1]
  96904. * IN data_len
  96905. */
  96906. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96907. /*
  96908. * FLAC__lpc_compute_autocorrelation()
  96909. * --------------------------------------------------------------------
  96910. * Compute the autocorrelation for lags between 0 and lag-1.
  96911. * Assumes data[] outside of [0,data_len-1] == 0.
  96912. * Asserts that lag > 0.
  96913. *
  96914. * IN data[0,data_len-1]
  96915. * IN data_len
  96916. * IN 0 < lag <= data_len
  96917. * OUT autoc[0,lag-1]
  96918. */
  96919. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96920. #ifndef FLAC__NO_ASM
  96921. # ifdef FLAC__CPU_IA32
  96922. # ifdef FLAC__HAS_NASM
  96923. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96924. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96925. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96926. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96927. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96928. # endif
  96929. # endif
  96930. #endif
  96931. /*
  96932. * FLAC__lpc_compute_lp_coefficients()
  96933. * --------------------------------------------------------------------
  96934. * Computes LP coefficients for orders 1..max_order.
  96935. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96936. * and there is no point in calculating a predictor.
  96937. *
  96938. * IN autoc[0,max_order] autocorrelation values
  96939. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96940. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96941. * *** IMPORTANT:
  96942. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96943. * OUT error[0,max_order-1] error for each order (more
  96944. * specifically, the variance of
  96945. * the error signal times # of
  96946. * samples in the signal)
  96947. *
  96948. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96949. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96950. * in lp_coeff[7][0,7], etc.
  96951. */
  96952. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96953. /*
  96954. * FLAC__lpc_quantize_coefficients()
  96955. * --------------------------------------------------------------------
  96956. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96957. * must be less than 32 (sizeof(FLAC__int32)*8).
  96958. *
  96959. * IN lp_coeff[0,order-1] LP coefficients
  96960. * IN order LP order
  96961. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96962. * desired precision (in bits, including sign
  96963. * bit) of largest coefficient
  96964. * OUT qlp_coeff[0,order-1] quantized coefficients
  96965. * OUT shift # of bits to shift right to get approximated
  96966. * LP coefficients. NOTE: could be negative.
  96967. * RETURN 0 => quantization OK
  96968. * 1 => coefficients require too much shifting for *shift to
  96969. * fit in the LPC subframe header. 'shift' is unset.
  96970. * 2 => coefficients are all zero, which is bad. 'shift' is
  96971. * unset.
  96972. */
  96973. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96974. /*
  96975. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96976. * --------------------------------------------------------------------
  96977. * Compute the residual signal obtained from sutracting the predicted
  96978. * signal from the original.
  96979. *
  96980. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96981. * IN data_len length of original signal
  96982. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96983. * IN order > 0 LP order
  96984. * IN lp_quantization quantization of LP coefficients in bits
  96985. * OUT residual[0,data_len-1] residual signal
  96986. */
  96987. 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[]);
  96988. 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[]);
  96989. #ifndef FLAC__NO_ASM
  96990. # ifdef FLAC__CPU_IA32
  96991. # ifdef FLAC__HAS_NASM
  96992. 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[]);
  96993. 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[]);
  96994. # endif
  96995. # endif
  96996. #endif
  96997. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96998. /*
  96999. * FLAC__lpc_restore_signal()
  97000. * --------------------------------------------------------------------
  97001. * Restore the original signal by summing the residual and the
  97002. * predictor.
  97003. *
  97004. * IN residual[0,data_len-1] residual signal
  97005. * IN data_len length of original signal
  97006. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97007. * IN order > 0 LP order
  97008. * IN lp_quantization quantization of LP coefficients in bits
  97009. * *** IMPORTANT: the caller must pass in the historical samples:
  97010. * IN data[-order,-1] previously-reconstructed historical samples
  97011. * OUT data[0,data_len-1] original signal
  97012. */
  97013. 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[]);
  97014. 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[]);
  97015. #ifndef FLAC__NO_ASM
  97016. # ifdef FLAC__CPU_IA32
  97017. # ifdef FLAC__HAS_NASM
  97018. 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[]);
  97019. 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[]);
  97020. # endif /* FLAC__HAS_NASM */
  97021. # elif defined FLAC__CPU_PPC
  97022. 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[]);
  97023. 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[]);
  97024. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97025. #endif /* FLAC__NO_ASM */
  97026. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97027. /*
  97028. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97029. * --------------------------------------------------------------------
  97030. * Compute the expected number of bits per residual signal sample
  97031. * based on the LP error (which is related to the residual variance).
  97032. *
  97033. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97034. * IN total_samples > 0 # of samples in residual signal
  97035. * RETURN expected bits per sample
  97036. */
  97037. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97038. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97039. /*
  97040. * FLAC__lpc_compute_best_order()
  97041. * --------------------------------------------------------------------
  97042. * Compute the best order from the array of signal errors returned
  97043. * during coefficient computation.
  97044. *
  97045. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97046. * IN max_order > 0 max LP order
  97047. * IN total_samples > 0 # of samples in residual signal
  97048. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97049. * (includes warmup sample size and quantized LP coefficient)
  97050. * RETURN [1,max_order] best order
  97051. */
  97052. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97053. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97054. #endif
  97055. /*** End of inlined file: lpc.h ***/
  97056. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97057. #include <stdio.h>
  97058. #endif
  97059. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97060. #ifndef M_LN2
  97061. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97062. #define M_LN2 0.69314718055994530942
  97063. #endif
  97064. /* OPT: #undef'ing this may improve the speed on some architectures */
  97065. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97066. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97067. {
  97068. unsigned i;
  97069. for(i = 0; i < data_len; i++)
  97070. out[i] = in[i] * window[i];
  97071. }
  97072. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97073. {
  97074. /* a readable, but slower, version */
  97075. #if 0
  97076. FLAC__real d;
  97077. unsigned i;
  97078. FLAC__ASSERT(lag > 0);
  97079. FLAC__ASSERT(lag <= data_len);
  97080. /*
  97081. * Technically we should subtract the mean first like so:
  97082. * for(i = 0; i < data_len; i++)
  97083. * data[i] -= mean;
  97084. * but it appears not to make enough of a difference to matter, and
  97085. * most signals are already closely centered around zero
  97086. */
  97087. while(lag--) {
  97088. for(i = lag, d = 0.0; i < data_len; i++)
  97089. d += data[i] * data[i - lag];
  97090. autoc[lag] = d;
  97091. }
  97092. #endif
  97093. /*
  97094. * this version tends to run faster because of better data locality
  97095. * ('data_len' is usually much larger than 'lag')
  97096. */
  97097. FLAC__real d;
  97098. unsigned sample, coeff;
  97099. const unsigned limit = data_len - lag;
  97100. FLAC__ASSERT(lag > 0);
  97101. FLAC__ASSERT(lag <= data_len);
  97102. for(coeff = 0; coeff < lag; coeff++)
  97103. autoc[coeff] = 0.0;
  97104. for(sample = 0; sample <= limit; sample++) {
  97105. d = data[sample];
  97106. for(coeff = 0; coeff < lag; coeff++)
  97107. autoc[coeff] += d * data[sample+coeff];
  97108. }
  97109. for(; sample < data_len; sample++) {
  97110. d = data[sample];
  97111. for(coeff = 0; coeff < data_len - sample; coeff++)
  97112. autoc[coeff] += d * data[sample+coeff];
  97113. }
  97114. }
  97115. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97116. {
  97117. unsigned i, j;
  97118. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97119. FLAC__ASSERT(0 != max_order);
  97120. FLAC__ASSERT(0 < *max_order);
  97121. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97122. FLAC__ASSERT(autoc[0] != 0.0);
  97123. err = autoc[0];
  97124. for(i = 0; i < *max_order; i++) {
  97125. /* Sum up this iteration's reflection coefficient. */
  97126. r = -autoc[i+1];
  97127. for(j = 0; j < i; j++)
  97128. r -= lpc[j] * autoc[i-j];
  97129. ref[i] = (r/=err);
  97130. /* Update LPC coefficients and total error. */
  97131. lpc[i]=r;
  97132. for(j = 0; j < (i>>1); j++) {
  97133. FLAC__double tmp = lpc[j];
  97134. lpc[j] += r * lpc[i-1-j];
  97135. lpc[i-1-j] += r * tmp;
  97136. }
  97137. if(i & 1)
  97138. lpc[j] += lpc[j] * r;
  97139. err *= (1.0 - r * r);
  97140. /* save this order */
  97141. for(j = 0; j <= i; j++)
  97142. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97143. error[i] = err;
  97144. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97145. if(err == 0.0) {
  97146. *max_order = i+1;
  97147. return;
  97148. }
  97149. }
  97150. }
  97151. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97152. {
  97153. unsigned i;
  97154. FLAC__double cmax;
  97155. FLAC__int32 qmax, qmin;
  97156. FLAC__ASSERT(precision > 0);
  97157. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97158. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97159. precision--;
  97160. qmax = 1 << precision;
  97161. qmin = -qmax;
  97162. qmax--;
  97163. /* calc cmax = max( |lp_coeff[i]| ) */
  97164. cmax = 0.0;
  97165. for(i = 0; i < order; i++) {
  97166. const FLAC__double d = fabs(lp_coeff[i]);
  97167. if(d > cmax)
  97168. cmax = d;
  97169. }
  97170. if(cmax <= 0.0) {
  97171. /* => coefficients are all 0, which means our constant-detect didn't work */
  97172. return 2;
  97173. }
  97174. else {
  97175. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97176. const int min_shiftlimit = -max_shiftlimit - 1;
  97177. int log2cmax;
  97178. (void)frexp(cmax, &log2cmax);
  97179. log2cmax--;
  97180. *shift = (int)precision - log2cmax - 1;
  97181. if(*shift > max_shiftlimit)
  97182. *shift = max_shiftlimit;
  97183. else if(*shift < min_shiftlimit)
  97184. return 1;
  97185. }
  97186. if(*shift >= 0) {
  97187. FLAC__double error = 0.0;
  97188. FLAC__int32 q;
  97189. for(i = 0; i < order; i++) {
  97190. error += lp_coeff[i] * (1 << *shift);
  97191. #if 1 /* unfortunately lround() is C99 */
  97192. if(error >= 0.0)
  97193. q = (FLAC__int32)(error + 0.5);
  97194. else
  97195. q = (FLAC__int32)(error - 0.5);
  97196. #else
  97197. q = lround(error);
  97198. #endif
  97199. #ifdef FLAC__OVERFLOW_DETECT
  97200. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97201. 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]);
  97202. else if(q < qmin)
  97203. 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]);
  97204. #endif
  97205. if(q > qmax)
  97206. q = qmax;
  97207. else if(q < qmin)
  97208. q = qmin;
  97209. error -= q;
  97210. qlp_coeff[i] = q;
  97211. }
  97212. }
  97213. /* negative shift is very rare but due to design flaw, negative shift is
  97214. * a NOP in the decoder, so it must be handled specially by scaling down
  97215. * coeffs
  97216. */
  97217. else {
  97218. const int nshift = -(*shift);
  97219. FLAC__double error = 0.0;
  97220. FLAC__int32 q;
  97221. #ifdef DEBUG
  97222. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97223. #endif
  97224. for(i = 0; i < order; i++) {
  97225. error += lp_coeff[i] / (1 << nshift);
  97226. #if 1 /* unfortunately lround() is C99 */
  97227. if(error >= 0.0)
  97228. q = (FLAC__int32)(error + 0.5);
  97229. else
  97230. q = (FLAC__int32)(error - 0.5);
  97231. #else
  97232. q = lround(error);
  97233. #endif
  97234. #ifdef FLAC__OVERFLOW_DETECT
  97235. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97236. 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]);
  97237. else if(q < qmin)
  97238. 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]);
  97239. #endif
  97240. if(q > qmax)
  97241. q = qmax;
  97242. else if(q < qmin)
  97243. q = qmin;
  97244. error -= q;
  97245. qlp_coeff[i] = q;
  97246. }
  97247. *shift = 0;
  97248. }
  97249. return 0;
  97250. }
  97251. 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[])
  97252. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97253. {
  97254. FLAC__int64 sumo;
  97255. unsigned i, j;
  97256. FLAC__int32 sum;
  97257. const FLAC__int32 *history;
  97258. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97259. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97260. for(i=0;i<order;i++)
  97261. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97262. fprintf(stderr,"\n");
  97263. #endif
  97264. FLAC__ASSERT(order > 0);
  97265. for(i = 0; i < data_len; i++) {
  97266. sumo = 0;
  97267. sum = 0;
  97268. history = data;
  97269. for(j = 0; j < order; j++) {
  97270. sum += qlp_coeff[j] * (*(--history));
  97271. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97272. #if defined _MSC_VER
  97273. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97274. 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);
  97275. #else
  97276. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97277. 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);
  97278. #endif
  97279. }
  97280. *(residual++) = *(data++) - (sum >> lp_quantization);
  97281. }
  97282. /* Here's a slower but clearer version:
  97283. for(i = 0; i < data_len; i++) {
  97284. sum = 0;
  97285. for(j = 0; j < order; j++)
  97286. sum += qlp_coeff[j] * data[i-j-1];
  97287. residual[i] = data[i] - (sum >> lp_quantization);
  97288. }
  97289. */
  97290. }
  97291. #else /* fully unrolled version for normal use */
  97292. {
  97293. int i;
  97294. FLAC__int32 sum;
  97295. FLAC__ASSERT(order > 0);
  97296. FLAC__ASSERT(order <= 32);
  97297. /*
  97298. * We do unique versions up to 12th order since that's the subset limit.
  97299. * Also they are roughly ordered to match frequency of occurrence to
  97300. * minimize branching.
  97301. */
  97302. if(order <= 12) {
  97303. if(order > 8) {
  97304. if(order > 10) {
  97305. if(order == 12) {
  97306. for(i = 0; i < (int)data_len; i++) {
  97307. sum = 0;
  97308. sum += qlp_coeff[11] * data[i-12];
  97309. sum += qlp_coeff[10] * data[i-11];
  97310. sum += qlp_coeff[9] * data[i-10];
  97311. sum += qlp_coeff[8] * data[i-9];
  97312. sum += qlp_coeff[7] * data[i-8];
  97313. sum += qlp_coeff[6] * data[i-7];
  97314. sum += qlp_coeff[5] * data[i-6];
  97315. sum += qlp_coeff[4] * data[i-5];
  97316. sum += qlp_coeff[3] * data[i-4];
  97317. sum += qlp_coeff[2] * data[i-3];
  97318. sum += qlp_coeff[1] * data[i-2];
  97319. sum += qlp_coeff[0] * data[i-1];
  97320. residual[i] = data[i] - (sum >> lp_quantization);
  97321. }
  97322. }
  97323. else { /* order == 11 */
  97324. for(i = 0; i < (int)data_len; i++) {
  97325. sum = 0;
  97326. sum += qlp_coeff[10] * data[i-11];
  97327. sum += qlp_coeff[9] * data[i-10];
  97328. sum += qlp_coeff[8] * data[i-9];
  97329. sum += qlp_coeff[7] * data[i-8];
  97330. sum += qlp_coeff[6] * data[i-7];
  97331. sum += qlp_coeff[5] * data[i-6];
  97332. sum += qlp_coeff[4] * data[i-5];
  97333. sum += qlp_coeff[3] * data[i-4];
  97334. sum += qlp_coeff[2] * data[i-3];
  97335. sum += qlp_coeff[1] * data[i-2];
  97336. sum += qlp_coeff[0] * data[i-1];
  97337. residual[i] = data[i] - (sum >> lp_quantization);
  97338. }
  97339. }
  97340. }
  97341. else {
  97342. if(order == 10) {
  97343. for(i = 0; i < (int)data_len; i++) {
  97344. sum = 0;
  97345. sum += qlp_coeff[9] * data[i-10];
  97346. sum += qlp_coeff[8] * data[i-9];
  97347. sum += qlp_coeff[7] * data[i-8];
  97348. sum += qlp_coeff[6] * data[i-7];
  97349. sum += qlp_coeff[5] * data[i-6];
  97350. sum += qlp_coeff[4] * data[i-5];
  97351. sum += qlp_coeff[3] * data[i-4];
  97352. sum += qlp_coeff[2] * data[i-3];
  97353. sum += qlp_coeff[1] * data[i-2];
  97354. sum += qlp_coeff[0] * data[i-1];
  97355. residual[i] = data[i] - (sum >> lp_quantization);
  97356. }
  97357. }
  97358. else { /* order == 9 */
  97359. for(i = 0; i < (int)data_len; i++) {
  97360. sum = 0;
  97361. sum += qlp_coeff[8] * data[i-9];
  97362. sum += qlp_coeff[7] * data[i-8];
  97363. sum += qlp_coeff[6] * data[i-7];
  97364. sum += qlp_coeff[5] * data[i-6];
  97365. sum += qlp_coeff[4] * data[i-5];
  97366. sum += qlp_coeff[3] * data[i-4];
  97367. sum += qlp_coeff[2] * data[i-3];
  97368. sum += qlp_coeff[1] * data[i-2];
  97369. sum += qlp_coeff[0] * data[i-1];
  97370. residual[i] = data[i] - (sum >> lp_quantization);
  97371. }
  97372. }
  97373. }
  97374. }
  97375. else if(order > 4) {
  97376. if(order > 6) {
  97377. if(order == 8) {
  97378. for(i = 0; i < (int)data_len; i++) {
  97379. sum = 0;
  97380. sum += qlp_coeff[7] * data[i-8];
  97381. sum += qlp_coeff[6] * data[i-7];
  97382. sum += qlp_coeff[5] * data[i-6];
  97383. sum += qlp_coeff[4] * data[i-5];
  97384. sum += qlp_coeff[3] * data[i-4];
  97385. sum += qlp_coeff[2] * data[i-3];
  97386. sum += qlp_coeff[1] * data[i-2];
  97387. sum += qlp_coeff[0] * data[i-1];
  97388. residual[i] = data[i] - (sum >> lp_quantization);
  97389. }
  97390. }
  97391. else { /* order == 7 */
  97392. for(i = 0; i < (int)data_len; i++) {
  97393. sum = 0;
  97394. sum += qlp_coeff[6] * data[i-7];
  97395. sum += qlp_coeff[5] * data[i-6];
  97396. sum += qlp_coeff[4] * data[i-5];
  97397. sum += qlp_coeff[3] * data[i-4];
  97398. sum += qlp_coeff[2] * data[i-3];
  97399. sum += qlp_coeff[1] * data[i-2];
  97400. sum += qlp_coeff[0] * data[i-1];
  97401. residual[i] = data[i] - (sum >> lp_quantization);
  97402. }
  97403. }
  97404. }
  97405. else {
  97406. if(order == 6) {
  97407. for(i = 0; i < (int)data_len; i++) {
  97408. sum = 0;
  97409. sum += qlp_coeff[5] * data[i-6];
  97410. sum += qlp_coeff[4] * data[i-5];
  97411. sum += qlp_coeff[3] * data[i-4];
  97412. sum += qlp_coeff[2] * data[i-3];
  97413. sum += qlp_coeff[1] * data[i-2];
  97414. sum += qlp_coeff[0] * data[i-1];
  97415. residual[i] = data[i] - (sum >> lp_quantization);
  97416. }
  97417. }
  97418. else { /* order == 5 */
  97419. for(i = 0; i < (int)data_len; i++) {
  97420. sum = 0;
  97421. sum += qlp_coeff[4] * data[i-5];
  97422. sum += qlp_coeff[3] * data[i-4];
  97423. sum += qlp_coeff[2] * data[i-3];
  97424. sum += qlp_coeff[1] * data[i-2];
  97425. sum += qlp_coeff[0] * data[i-1];
  97426. residual[i] = data[i] - (sum >> lp_quantization);
  97427. }
  97428. }
  97429. }
  97430. }
  97431. else {
  97432. if(order > 2) {
  97433. if(order == 4) {
  97434. for(i = 0; i < (int)data_len; i++) {
  97435. sum = 0;
  97436. sum += qlp_coeff[3] * data[i-4];
  97437. sum += qlp_coeff[2] * data[i-3];
  97438. sum += qlp_coeff[1] * data[i-2];
  97439. sum += qlp_coeff[0] * data[i-1];
  97440. residual[i] = data[i] - (sum >> lp_quantization);
  97441. }
  97442. }
  97443. else { /* order == 3 */
  97444. for(i = 0; i < (int)data_len; i++) {
  97445. sum = 0;
  97446. sum += qlp_coeff[2] * data[i-3];
  97447. sum += qlp_coeff[1] * data[i-2];
  97448. sum += qlp_coeff[0] * data[i-1];
  97449. residual[i] = data[i] - (sum >> lp_quantization);
  97450. }
  97451. }
  97452. }
  97453. else {
  97454. if(order == 2) {
  97455. for(i = 0; i < (int)data_len; i++) {
  97456. sum = 0;
  97457. sum += qlp_coeff[1] * data[i-2];
  97458. sum += qlp_coeff[0] * data[i-1];
  97459. residual[i] = data[i] - (sum >> lp_quantization);
  97460. }
  97461. }
  97462. else { /* order == 1 */
  97463. for(i = 0; i < (int)data_len; i++)
  97464. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97465. }
  97466. }
  97467. }
  97468. }
  97469. else { /* order > 12 */
  97470. for(i = 0; i < (int)data_len; i++) {
  97471. sum = 0;
  97472. switch(order) {
  97473. case 32: sum += qlp_coeff[31] * data[i-32];
  97474. case 31: sum += qlp_coeff[30] * data[i-31];
  97475. case 30: sum += qlp_coeff[29] * data[i-30];
  97476. case 29: sum += qlp_coeff[28] * data[i-29];
  97477. case 28: sum += qlp_coeff[27] * data[i-28];
  97478. case 27: sum += qlp_coeff[26] * data[i-27];
  97479. case 26: sum += qlp_coeff[25] * data[i-26];
  97480. case 25: sum += qlp_coeff[24] * data[i-25];
  97481. case 24: sum += qlp_coeff[23] * data[i-24];
  97482. case 23: sum += qlp_coeff[22] * data[i-23];
  97483. case 22: sum += qlp_coeff[21] * data[i-22];
  97484. case 21: sum += qlp_coeff[20] * data[i-21];
  97485. case 20: sum += qlp_coeff[19] * data[i-20];
  97486. case 19: sum += qlp_coeff[18] * data[i-19];
  97487. case 18: sum += qlp_coeff[17] * data[i-18];
  97488. case 17: sum += qlp_coeff[16] * data[i-17];
  97489. case 16: sum += qlp_coeff[15] * data[i-16];
  97490. case 15: sum += qlp_coeff[14] * data[i-15];
  97491. case 14: sum += qlp_coeff[13] * data[i-14];
  97492. case 13: sum += qlp_coeff[12] * data[i-13];
  97493. sum += qlp_coeff[11] * data[i-12];
  97494. sum += qlp_coeff[10] * data[i-11];
  97495. sum += qlp_coeff[ 9] * data[i-10];
  97496. sum += qlp_coeff[ 8] * data[i- 9];
  97497. sum += qlp_coeff[ 7] * data[i- 8];
  97498. sum += qlp_coeff[ 6] * data[i- 7];
  97499. sum += qlp_coeff[ 5] * data[i- 6];
  97500. sum += qlp_coeff[ 4] * data[i- 5];
  97501. sum += qlp_coeff[ 3] * data[i- 4];
  97502. sum += qlp_coeff[ 2] * data[i- 3];
  97503. sum += qlp_coeff[ 1] * data[i- 2];
  97504. sum += qlp_coeff[ 0] * data[i- 1];
  97505. }
  97506. residual[i] = data[i] - (sum >> lp_quantization);
  97507. }
  97508. }
  97509. }
  97510. #endif
  97511. 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[])
  97512. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97513. {
  97514. unsigned i, j;
  97515. FLAC__int64 sum;
  97516. const FLAC__int32 *history;
  97517. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97518. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97519. for(i=0;i<order;i++)
  97520. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97521. fprintf(stderr,"\n");
  97522. #endif
  97523. FLAC__ASSERT(order > 0);
  97524. for(i = 0; i < data_len; i++) {
  97525. sum = 0;
  97526. history = data;
  97527. for(j = 0; j < order; j++)
  97528. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97529. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97530. #if defined _MSC_VER
  97531. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97532. #else
  97533. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97534. #endif
  97535. break;
  97536. }
  97537. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97538. #if defined _MSC_VER
  97539. 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));
  97540. #else
  97541. 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)));
  97542. #endif
  97543. break;
  97544. }
  97545. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97546. }
  97547. }
  97548. #else /* fully unrolled version for normal use */
  97549. {
  97550. int i;
  97551. FLAC__int64 sum;
  97552. FLAC__ASSERT(order > 0);
  97553. FLAC__ASSERT(order <= 32);
  97554. /*
  97555. * We do unique versions up to 12th order since that's the subset limit.
  97556. * Also they are roughly ordered to match frequency of occurrence to
  97557. * minimize branching.
  97558. */
  97559. if(order <= 12) {
  97560. if(order > 8) {
  97561. if(order > 10) {
  97562. if(order == 12) {
  97563. for(i = 0; i < (int)data_len; i++) {
  97564. sum = 0;
  97565. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97566. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97567. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97568. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97569. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97570. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97571. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97572. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97573. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97574. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97575. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97576. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97577. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97578. }
  97579. }
  97580. else { /* order == 11 */
  97581. for(i = 0; i < (int)data_len; i++) {
  97582. sum = 0;
  97583. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97584. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97585. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97586. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97587. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97588. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97589. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97590. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97591. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97592. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97593. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97594. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97595. }
  97596. }
  97597. }
  97598. else {
  97599. if(order == 10) {
  97600. for(i = 0; i < (int)data_len; i++) {
  97601. sum = 0;
  97602. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97603. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97604. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97605. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97606. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97607. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97608. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97609. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97610. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97611. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97612. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97613. }
  97614. }
  97615. else { /* order == 9 */
  97616. for(i = 0; i < (int)data_len; i++) {
  97617. sum = 0;
  97618. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97619. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97620. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97621. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97622. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97623. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97624. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97625. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97626. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97627. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97628. }
  97629. }
  97630. }
  97631. }
  97632. else if(order > 4) {
  97633. if(order > 6) {
  97634. if(order == 8) {
  97635. for(i = 0; i < (int)data_len; i++) {
  97636. sum = 0;
  97637. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97638. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97639. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97640. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97641. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97642. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97643. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97644. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97645. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97646. }
  97647. }
  97648. else { /* order == 7 */
  97649. for(i = 0; i < (int)data_len; i++) {
  97650. sum = 0;
  97651. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97652. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97653. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97654. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97655. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97656. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97657. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97658. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97659. }
  97660. }
  97661. }
  97662. else {
  97663. if(order == 6) {
  97664. for(i = 0; i < (int)data_len; i++) {
  97665. sum = 0;
  97666. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97667. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97668. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97669. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97670. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97671. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97672. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97673. }
  97674. }
  97675. else { /* order == 5 */
  97676. for(i = 0; i < (int)data_len; i++) {
  97677. sum = 0;
  97678. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97679. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97680. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97681. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97682. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97683. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97684. }
  97685. }
  97686. }
  97687. }
  97688. else {
  97689. if(order > 2) {
  97690. if(order == 4) {
  97691. for(i = 0; i < (int)data_len; i++) {
  97692. sum = 0;
  97693. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97694. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97695. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97696. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97697. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97698. }
  97699. }
  97700. else { /* order == 3 */
  97701. for(i = 0; i < (int)data_len; i++) {
  97702. sum = 0;
  97703. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97704. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97705. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97706. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97707. }
  97708. }
  97709. }
  97710. else {
  97711. if(order == 2) {
  97712. for(i = 0; i < (int)data_len; i++) {
  97713. sum = 0;
  97714. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97715. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97716. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97717. }
  97718. }
  97719. else { /* order == 1 */
  97720. for(i = 0; i < (int)data_len; i++)
  97721. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97722. }
  97723. }
  97724. }
  97725. }
  97726. else { /* order > 12 */
  97727. for(i = 0; i < (int)data_len; i++) {
  97728. sum = 0;
  97729. switch(order) {
  97730. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97731. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97732. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97733. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97734. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97735. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97736. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97737. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97738. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97739. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97740. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97741. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97742. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97743. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97744. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97745. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97746. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97747. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97748. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97749. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97750. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97751. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97752. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97753. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97754. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97755. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97756. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97757. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97758. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97759. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97760. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97761. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97762. }
  97763. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97764. }
  97765. }
  97766. }
  97767. #endif
  97768. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97769. 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[])
  97770. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97771. {
  97772. FLAC__int64 sumo;
  97773. unsigned i, j;
  97774. FLAC__int32 sum;
  97775. const FLAC__int32 *r = residual, *history;
  97776. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97777. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97778. for(i=0;i<order;i++)
  97779. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97780. fprintf(stderr,"\n");
  97781. #endif
  97782. FLAC__ASSERT(order > 0);
  97783. for(i = 0; i < data_len; i++) {
  97784. sumo = 0;
  97785. sum = 0;
  97786. history = data;
  97787. for(j = 0; j < order; j++) {
  97788. sum += qlp_coeff[j] * (*(--history));
  97789. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97790. #if defined _MSC_VER
  97791. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97792. 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);
  97793. #else
  97794. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97795. 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);
  97796. #endif
  97797. }
  97798. *(data++) = *(r++) + (sum >> lp_quantization);
  97799. }
  97800. /* Here's a slower but clearer version:
  97801. for(i = 0; i < data_len; i++) {
  97802. sum = 0;
  97803. for(j = 0; j < order; j++)
  97804. sum += qlp_coeff[j] * data[i-j-1];
  97805. data[i] = residual[i] + (sum >> lp_quantization);
  97806. }
  97807. */
  97808. }
  97809. #else /* fully unrolled version for normal use */
  97810. {
  97811. int i;
  97812. FLAC__int32 sum;
  97813. FLAC__ASSERT(order > 0);
  97814. FLAC__ASSERT(order <= 32);
  97815. /*
  97816. * We do unique versions up to 12th order since that's the subset limit.
  97817. * Also they are roughly ordered to match frequency of occurrence to
  97818. * minimize branching.
  97819. */
  97820. if(order <= 12) {
  97821. if(order > 8) {
  97822. if(order > 10) {
  97823. if(order == 12) {
  97824. for(i = 0; i < (int)data_len; i++) {
  97825. sum = 0;
  97826. sum += qlp_coeff[11] * data[i-12];
  97827. sum += qlp_coeff[10] * data[i-11];
  97828. sum += qlp_coeff[9] * data[i-10];
  97829. sum += qlp_coeff[8] * data[i-9];
  97830. sum += qlp_coeff[7] * data[i-8];
  97831. sum += qlp_coeff[6] * data[i-7];
  97832. sum += qlp_coeff[5] * data[i-6];
  97833. sum += qlp_coeff[4] * data[i-5];
  97834. sum += qlp_coeff[3] * data[i-4];
  97835. sum += qlp_coeff[2] * data[i-3];
  97836. sum += qlp_coeff[1] * data[i-2];
  97837. sum += qlp_coeff[0] * data[i-1];
  97838. data[i] = residual[i] + (sum >> lp_quantization);
  97839. }
  97840. }
  97841. else { /* order == 11 */
  97842. for(i = 0; i < (int)data_len; i++) {
  97843. sum = 0;
  97844. sum += qlp_coeff[10] * data[i-11];
  97845. sum += qlp_coeff[9] * data[i-10];
  97846. sum += qlp_coeff[8] * data[i-9];
  97847. sum += qlp_coeff[7] * data[i-8];
  97848. sum += qlp_coeff[6] * data[i-7];
  97849. sum += qlp_coeff[5] * data[i-6];
  97850. sum += qlp_coeff[4] * data[i-5];
  97851. sum += qlp_coeff[3] * data[i-4];
  97852. sum += qlp_coeff[2] * data[i-3];
  97853. sum += qlp_coeff[1] * data[i-2];
  97854. sum += qlp_coeff[0] * data[i-1];
  97855. data[i] = residual[i] + (sum >> lp_quantization);
  97856. }
  97857. }
  97858. }
  97859. else {
  97860. if(order == 10) {
  97861. for(i = 0; i < (int)data_len; i++) {
  97862. sum = 0;
  97863. sum += qlp_coeff[9] * data[i-10];
  97864. sum += qlp_coeff[8] * data[i-9];
  97865. sum += qlp_coeff[7] * data[i-8];
  97866. sum += qlp_coeff[6] * data[i-7];
  97867. sum += qlp_coeff[5] * data[i-6];
  97868. sum += qlp_coeff[4] * data[i-5];
  97869. sum += qlp_coeff[3] * data[i-4];
  97870. sum += qlp_coeff[2] * data[i-3];
  97871. sum += qlp_coeff[1] * data[i-2];
  97872. sum += qlp_coeff[0] * data[i-1];
  97873. data[i] = residual[i] + (sum >> lp_quantization);
  97874. }
  97875. }
  97876. else { /* order == 9 */
  97877. for(i = 0; i < (int)data_len; i++) {
  97878. sum = 0;
  97879. sum += qlp_coeff[8] * data[i-9];
  97880. sum += qlp_coeff[7] * data[i-8];
  97881. sum += qlp_coeff[6] * data[i-7];
  97882. sum += qlp_coeff[5] * data[i-6];
  97883. sum += qlp_coeff[4] * data[i-5];
  97884. sum += qlp_coeff[3] * data[i-4];
  97885. sum += qlp_coeff[2] * data[i-3];
  97886. sum += qlp_coeff[1] * data[i-2];
  97887. sum += qlp_coeff[0] * data[i-1];
  97888. data[i] = residual[i] + (sum >> lp_quantization);
  97889. }
  97890. }
  97891. }
  97892. }
  97893. else if(order > 4) {
  97894. if(order > 6) {
  97895. if(order == 8) {
  97896. for(i = 0; i < (int)data_len; i++) {
  97897. sum = 0;
  97898. sum += qlp_coeff[7] * data[i-8];
  97899. sum += qlp_coeff[6] * data[i-7];
  97900. sum += qlp_coeff[5] * data[i-6];
  97901. sum += qlp_coeff[4] * data[i-5];
  97902. sum += qlp_coeff[3] * data[i-4];
  97903. sum += qlp_coeff[2] * data[i-3];
  97904. sum += qlp_coeff[1] * data[i-2];
  97905. sum += qlp_coeff[0] * data[i-1];
  97906. data[i] = residual[i] + (sum >> lp_quantization);
  97907. }
  97908. }
  97909. else { /* order == 7 */
  97910. for(i = 0; i < (int)data_len; i++) {
  97911. sum = 0;
  97912. sum += qlp_coeff[6] * data[i-7];
  97913. sum += qlp_coeff[5] * data[i-6];
  97914. sum += qlp_coeff[4] * data[i-5];
  97915. sum += qlp_coeff[3] * data[i-4];
  97916. sum += qlp_coeff[2] * data[i-3];
  97917. sum += qlp_coeff[1] * data[i-2];
  97918. sum += qlp_coeff[0] * data[i-1];
  97919. data[i] = residual[i] + (sum >> lp_quantization);
  97920. }
  97921. }
  97922. }
  97923. else {
  97924. if(order == 6) {
  97925. for(i = 0; i < (int)data_len; i++) {
  97926. sum = 0;
  97927. sum += qlp_coeff[5] * data[i-6];
  97928. sum += qlp_coeff[4] * data[i-5];
  97929. sum += qlp_coeff[3] * data[i-4];
  97930. sum += qlp_coeff[2] * data[i-3];
  97931. sum += qlp_coeff[1] * data[i-2];
  97932. sum += qlp_coeff[0] * data[i-1];
  97933. data[i] = residual[i] + (sum >> lp_quantization);
  97934. }
  97935. }
  97936. else { /* order == 5 */
  97937. for(i = 0; i < (int)data_len; i++) {
  97938. sum = 0;
  97939. sum += qlp_coeff[4] * data[i-5];
  97940. sum += qlp_coeff[3] * data[i-4];
  97941. sum += qlp_coeff[2] * data[i-3];
  97942. sum += qlp_coeff[1] * data[i-2];
  97943. sum += qlp_coeff[0] * data[i-1];
  97944. data[i] = residual[i] + (sum >> lp_quantization);
  97945. }
  97946. }
  97947. }
  97948. }
  97949. else {
  97950. if(order > 2) {
  97951. if(order == 4) {
  97952. for(i = 0; i < (int)data_len; i++) {
  97953. sum = 0;
  97954. sum += qlp_coeff[3] * data[i-4];
  97955. sum += qlp_coeff[2] * data[i-3];
  97956. sum += qlp_coeff[1] * data[i-2];
  97957. sum += qlp_coeff[0] * data[i-1];
  97958. data[i] = residual[i] + (sum >> lp_quantization);
  97959. }
  97960. }
  97961. else { /* order == 3 */
  97962. for(i = 0; i < (int)data_len; i++) {
  97963. sum = 0;
  97964. sum += qlp_coeff[2] * data[i-3];
  97965. sum += qlp_coeff[1] * data[i-2];
  97966. sum += qlp_coeff[0] * data[i-1];
  97967. data[i] = residual[i] + (sum >> lp_quantization);
  97968. }
  97969. }
  97970. }
  97971. else {
  97972. if(order == 2) {
  97973. for(i = 0; i < (int)data_len; i++) {
  97974. sum = 0;
  97975. sum += qlp_coeff[1] * data[i-2];
  97976. sum += qlp_coeff[0] * data[i-1];
  97977. data[i] = residual[i] + (sum >> lp_quantization);
  97978. }
  97979. }
  97980. else { /* order == 1 */
  97981. for(i = 0; i < (int)data_len; i++)
  97982. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97983. }
  97984. }
  97985. }
  97986. }
  97987. else { /* order > 12 */
  97988. for(i = 0; i < (int)data_len; i++) {
  97989. sum = 0;
  97990. switch(order) {
  97991. case 32: sum += qlp_coeff[31] * data[i-32];
  97992. case 31: sum += qlp_coeff[30] * data[i-31];
  97993. case 30: sum += qlp_coeff[29] * data[i-30];
  97994. case 29: sum += qlp_coeff[28] * data[i-29];
  97995. case 28: sum += qlp_coeff[27] * data[i-28];
  97996. case 27: sum += qlp_coeff[26] * data[i-27];
  97997. case 26: sum += qlp_coeff[25] * data[i-26];
  97998. case 25: sum += qlp_coeff[24] * data[i-25];
  97999. case 24: sum += qlp_coeff[23] * data[i-24];
  98000. case 23: sum += qlp_coeff[22] * data[i-23];
  98001. case 22: sum += qlp_coeff[21] * data[i-22];
  98002. case 21: sum += qlp_coeff[20] * data[i-21];
  98003. case 20: sum += qlp_coeff[19] * data[i-20];
  98004. case 19: sum += qlp_coeff[18] * data[i-19];
  98005. case 18: sum += qlp_coeff[17] * data[i-18];
  98006. case 17: sum += qlp_coeff[16] * data[i-17];
  98007. case 16: sum += qlp_coeff[15] * data[i-16];
  98008. case 15: sum += qlp_coeff[14] * data[i-15];
  98009. case 14: sum += qlp_coeff[13] * data[i-14];
  98010. case 13: sum += qlp_coeff[12] * data[i-13];
  98011. sum += qlp_coeff[11] * data[i-12];
  98012. sum += qlp_coeff[10] * data[i-11];
  98013. sum += qlp_coeff[ 9] * data[i-10];
  98014. sum += qlp_coeff[ 8] * data[i- 9];
  98015. sum += qlp_coeff[ 7] * data[i- 8];
  98016. sum += qlp_coeff[ 6] * data[i- 7];
  98017. sum += qlp_coeff[ 5] * data[i- 6];
  98018. sum += qlp_coeff[ 4] * data[i- 5];
  98019. sum += qlp_coeff[ 3] * data[i- 4];
  98020. sum += qlp_coeff[ 2] * data[i- 3];
  98021. sum += qlp_coeff[ 1] * data[i- 2];
  98022. sum += qlp_coeff[ 0] * data[i- 1];
  98023. }
  98024. data[i] = residual[i] + (sum >> lp_quantization);
  98025. }
  98026. }
  98027. }
  98028. #endif
  98029. 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[])
  98030. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98031. {
  98032. unsigned i, j;
  98033. FLAC__int64 sum;
  98034. const FLAC__int32 *r = residual, *history;
  98035. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98036. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98037. for(i=0;i<order;i++)
  98038. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98039. fprintf(stderr,"\n");
  98040. #endif
  98041. FLAC__ASSERT(order > 0);
  98042. for(i = 0; i < data_len; i++) {
  98043. sum = 0;
  98044. history = data;
  98045. for(j = 0; j < order; j++)
  98046. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98047. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98048. #ifdef _MSC_VER
  98049. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98050. #else
  98051. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98052. #endif
  98053. break;
  98054. }
  98055. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98056. #ifdef _MSC_VER
  98057. 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));
  98058. #else
  98059. 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)));
  98060. #endif
  98061. break;
  98062. }
  98063. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98064. }
  98065. }
  98066. #else /* fully unrolled version for normal use */
  98067. {
  98068. int i;
  98069. FLAC__int64 sum;
  98070. FLAC__ASSERT(order > 0);
  98071. FLAC__ASSERT(order <= 32);
  98072. /*
  98073. * We do unique versions up to 12th order since that's the subset limit.
  98074. * Also they are roughly ordered to match frequency of occurrence to
  98075. * minimize branching.
  98076. */
  98077. if(order <= 12) {
  98078. if(order > 8) {
  98079. if(order > 10) {
  98080. if(order == 12) {
  98081. for(i = 0; i < (int)data_len; i++) {
  98082. sum = 0;
  98083. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98084. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98085. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98086. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98087. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98088. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98089. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98090. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98091. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98092. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98093. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98094. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98095. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98096. }
  98097. }
  98098. else { /* order == 11 */
  98099. for(i = 0; i < (int)data_len; i++) {
  98100. sum = 0;
  98101. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98102. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98103. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98104. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98105. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98106. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98107. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98108. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98109. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98110. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98111. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98112. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98113. }
  98114. }
  98115. }
  98116. else {
  98117. if(order == 10) {
  98118. for(i = 0; i < (int)data_len; i++) {
  98119. sum = 0;
  98120. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98121. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98122. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98123. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98124. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98125. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98126. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98127. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98128. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98129. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98130. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98131. }
  98132. }
  98133. else { /* order == 9 */
  98134. for(i = 0; i < (int)data_len; i++) {
  98135. sum = 0;
  98136. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98137. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98138. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98139. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98140. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98141. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98142. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98143. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98144. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98145. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98146. }
  98147. }
  98148. }
  98149. }
  98150. else if(order > 4) {
  98151. if(order > 6) {
  98152. if(order == 8) {
  98153. for(i = 0; i < (int)data_len; i++) {
  98154. sum = 0;
  98155. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98156. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98157. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98158. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98159. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98160. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98161. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98162. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98163. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98164. }
  98165. }
  98166. else { /* order == 7 */
  98167. for(i = 0; i < (int)data_len; i++) {
  98168. sum = 0;
  98169. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98170. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98171. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98172. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98173. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98174. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98175. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98176. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98177. }
  98178. }
  98179. }
  98180. else {
  98181. if(order == 6) {
  98182. for(i = 0; i < (int)data_len; i++) {
  98183. sum = 0;
  98184. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98185. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98186. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98187. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98188. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98189. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98190. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98191. }
  98192. }
  98193. else { /* order == 5 */
  98194. for(i = 0; i < (int)data_len; i++) {
  98195. sum = 0;
  98196. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98197. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98198. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98199. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98200. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98201. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98202. }
  98203. }
  98204. }
  98205. }
  98206. else {
  98207. if(order > 2) {
  98208. if(order == 4) {
  98209. for(i = 0; i < (int)data_len; i++) {
  98210. sum = 0;
  98211. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98212. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98213. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98214. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98215. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98216. }
  98217. }
  98218. else { /* order == 3 */
  98219. for(i = 0; i < (int)data_len; i++) {
  98220. sum = 0;
  98221. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98222. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98223. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98224. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98225. }
  98226. }
  98227. }
  98228. else {
  98229. if(order == 2) {
  98230. for(i = 0; i < (int)data_len; i++) {
  98231. sum = 0;
  98232. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98233. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98234. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98235. }
  98236. }
  98237. else { /* order == 1 */
  98238. for(i = 0; i < (int)data_len; i++)
  98239. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98240. }
  98241. }
  98242. }
  98243. }
  98244. else { /* order > 12 */
  98245. for(i = 0; i < (int)data_len; i++) {
  98246. sum = 0;
  98247. switch(order) {
  98248. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98249. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98250. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98251. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98252. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98253. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98254. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98255. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98256. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98257. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98258. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98259. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98260. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98261. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98262. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98263. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98264. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98265. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98266. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98267. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98268. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98269. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98270. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98271. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98272. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98273. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98274. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98275. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98276. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98277. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98278. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98279. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98280. }
  98281. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98282. }
  98283. }
  98284. }
  98285. #endif
  98286. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98287. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98288. {
  98289. FLAC__double error_scale;
  98290. FLAC__ASSERT(total_samples > 0);
  98291. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98292. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98293. }
  98294. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98295. {
  98296. if(lpc_error > 0.0) {
  98297. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98298. if(bps >= 0.0)
  98299. return bps;
  98300. else
  98301. return 0.0;
  98302. }
  98303. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98304. return 1e32;
  98305. }
  98306. else {
  98307. return 0.0;
  98308. }
  98309. }
  98310. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98311. {
  98312. 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 */
  98313. FLAC__double bits, best_bits, error_scale;
  98314. FLAC__ASSERT(max_order > 0);
  98315. FLAC__ASSERT(total_samples > 0);
  98316. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98317. best_index = 0;
  98318. best_bits = (unsigned)(-1);
  98319. for(index = 0, order = 1; index < max_order; index++, order++) {
  98320. 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);
  98321. if(bits < best_bits) {
  98322. best_index = index;
  98323. best_bits = bits;
  98324. }
  98325. }
  98326. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98327. }
  98328. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98329. #endif
  98330. /*** End of inlined file: lpc_flac.c ***/
  98331. /*** Start of inlined file: md5.c ***/
  98332. /*** Start of inlined file: juce_FlacHeader.h ***/
  98333. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98334. // tasks..
  98335. #define VERSION "1.2.1"
  98336. #define FLAC__NO_DLL 1
  98337. #if JUCE_MSVC
  98338. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98339. #endif
  98340. #if JUCE_MAC
  98341. #define FLAC__SYS_DARWIN 1
  98342. #endif
  98343. /*** End of inlined file: juce_FlacHeader.h ***/
  98344. #if JUCE_USE_FLAC
  98345. #if HAVE_CONFIG_H
  98346. # include <config.h>
  98347. #endif
  98348. #include <stdlib.h> /* for malloc() */
  98349. #include <string.h> /* for memcpy() */
  98350. /*** Start of inlined file: md5.h ***/
  98351. #ifndef FLAC__PRIVATE__MD5_H
  98352. #define FLAC__PRIVATE__MD5_H
  98353. /*
  98354. * This is the header file for the MD5 message-digest algorithm.
  98355. * The algorithm is due to Ron Rivest. This code was
  98356. * written by Colin Plumb in 1993, no copyright is claimed.
  98357. * This code is in the public domain; do with it what you wish.
  98358. *
  98359. * Equivalent code is available from RSA Data Security, Inc.
  98360. * This code has been tested against that, and is equivalent,
  98361. * except that you don't need to include two pages of legalese
  98362. * with every copy.
  98363. *
  98364. * To compute the message digest of a chunk of bytes, declare an
  98365. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98366. * needed on buffers full of bytes, and then call MD5Final, which
  98367. * will fill a supplied 16-byte array with the digest.
  98368. *
  98369. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98370. * header definitions; now uses stuff from dpkg's config.h
  98371. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98372. * Still in the public domain.
  98373. *
  98374. * Josh Coalson: made some changes to integrate with libFLAC.
  98375. * Still in the public domain, with no warranty.
  98376. */
  98377. typedef struct {
  98378. FLAC__uint32 in[16];
  98379. FLAC__uint32 buf[4];
  98380. FLAC__uint32 bytes[2];
  98381. FLAC__byte *internal_buf;
  98382. size_t capacity;
  98383. } FLAC__MD5Context;
  98384. void FLAC__MD5Init(FLAC__MD5Context *context);
  98385. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98386. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98387. #endif
  98388. /*** End of inlined file: md5.h ***/
  98389. #ifndef FLaC__INLINE
  98390. #define FLaC__INLINE
  98391. #endif
  98392. /*
  98393. * This code implements the MD5 message-digest algorithm.
  98394. * The algorithm is due to Ron Rivest. This code was
  98395. * written by Colin Plumb in 1993, no copyright is claimed.
  98396. * This code is in the public domain; do with it what you wish.
  98397. *
  98398. * Equivalent code is available from RSA Data Security, Inc.
  98399. * This code has been tested against that, and is equivalent,
  98400. * except that you don't need to include two pages of legalese
  98401. * with every copy.
  98402. *
  98403. * To compute the message digest of a chunk of bytes, declare an
  98404. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98405. * needed on buffers full of bytes, and then call MD5Final, which
  98406. * will fill a supplied 16-byte array with the digest.
  98407. *
  98408. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98409. * definitions; now uses stuff from dpkg's config.h.
  98410. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98411. * Still in the public domain.
  98412. *
  98413. * Josh Coalson: made some changes to integrate with libFLAC.
  98414. * Still in the public domain.
  98415. */
  98416. /* The four core functions - F1 is optimized somewhat */
  98417. /* #define F1(x, y, z) (x & y | ~x & z) */
  98418. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98419. #define F2(x, y, z) F1(z, x, y)
  98420. #define F3(x, y, z) (x ^ y ^ z)
  98421. #define F4(x, y, z) (y ^ (x | ~z))
  98422. /* This is the central step in the MD5 algorithm. */
  98423. #define MD5STEP(f,w,x,y,z,in,s) \
  98424. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98425. /*
  98426. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98427. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98428. * the data and converts bytes into longwords for this routine.
  98429. */
  98430. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98431. {
  98432. register FLAC__uint32 a, b, c, d;
  98433. a = buf[0];
  98434. b = buf[1];
  98435. c = buf[2];
  98436. d = buf[3];
  98437. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98438. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98439. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98440. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98441. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98442. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98443. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98444. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98445. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98446. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98447. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98448. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98449. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98450. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98451. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98452. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98453. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98454. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98455. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98456. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98457. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98458. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98459. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98460. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98461. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98462. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98463. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98464. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98465. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98466. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98467. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98468. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98469. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98470. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98471. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98472. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98473. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98474. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98475. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98476. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98477. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98478. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98479. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98480. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98481. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98482. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98483. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98484. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98485. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98486. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98487. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98488. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98489. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98490. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98491. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98492. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98493. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98494. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98495. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98496. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98497. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98498. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98499. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98500. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98501. buf[0] += a;
  98502. buf[1] += b;
  98503. buf[2] += c;
  98504. buf[3] += d;
  98505. }
  98506. #if WORDS_BIGENDIAN
  98507. //@@@@@@ OPT: use bswap/intrinsics
  98508. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98509. {
  98510. register FLAC__uint32 x;
  98511. do {
  98512. x = *buf;
  98513. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98514. *buf++ = (x >> 16) | (x << 16);
  98515. } while (--words);
  98516. }
  98517. static void byteSwapX16(FLAC__uint32 *buf)
  98518. {
  98519. register FLAC__uint32 x;
  98520. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98521. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98522. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98523. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98524. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98525. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98526. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98527. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98528. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98529. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98530. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98531. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98532. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98533. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98534. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98535. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98536. }
  98537. #else
  98538. #define byteSwap(buf, words)
  98539. #define byteSwapX16(buf)
  98540. #endif
  98541. /*
  98542. * Update context to reflect the concatenation of another buffer full
  98543. * of bytes.
  98544. */
  98545. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98546. {
  98547. FLAC__uint32 t;
  98548. /* Update byte count */
  98549. t = ctx->bytes[0];
  98550. if ((ctx->bytes[0] = t + len) < t)
  98551. ctx->bytes[1]++; /* Carry from low to high */
  98552. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98553. if (t > len) {
  98554. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98555. return;
  98556. }
  98557. /* First chunk is an odd size */
  98558. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98559. byteSwapX16(ctx->in);
  98560. FLAC__MD5Transform(ctx->buf, ctx->in);
  98561. buf += t;
  98562. len -= t;
  98563. /* Process data in 64-byte chunks */
  98564. while (len >= 64) {
  98565. memcpy(ctx->in, buf, 64);
  98566. byteSwapX16(ctx->in);
  98567. FLAC__MD5Transform(ctx->buf, ctx->in);
  98568. buf += 64;
  98569. len -= 64;
  98570. }
  98571. /* Handle any remaining bytes of data. */
  98572. memcpy(ctx->in, buf, len);
  98573. }
  98574. /*
  98575. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98576. * initialization constants.
  98577. */
  98578. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98579. {
  98580. ctx->buf[0] = 0x67452301;
  98581. ctx->buf[1] = 0xefcdab89;
  98582. ctx->buf[2] = 0x98badcfe;
  98583. ctx->buf[3] = 0x10325476;
  98584. ctx->bytes[0] = 0;
  98585. ctx->bytes[1] = 0;
  98586. ctx->internal_buf = 0;
  98587. ctx->capacity = 0;
  98588. }
  98589. /*
  98590. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98591. * 1 0* (64-bit count of bits processed, MSB-first)
  98592. */
  98593. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98594. {
  98595. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98596. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98597. /* Set the first char of padding to 0x80. There is always room. */
  98598. *p++ = 0x80;
  98599. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98600. count = 56 - 1 - count;
  98601. if (count < 0) { /* Padding forces an extra block */
  98602. memset(p, 0, count + 8);
  98603. byteSwapX16(ctx->in);
  98604. FLAC__MD5Transform(ctx->buf, ctx->in);
  98605. p = (FLAC__byte *)ctx->in;
  98606. count = 56;
  98607. }
  98608. memset(p, 0, count);
  98609. byteSwap(ctx->in, 14);
  98610. /* Append length in bits and transform */
  98611. ctx->in[14] = ctx->bytes[0] << 3;
  98612. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98613. FLAC__MD5Transform(ctx->buf, ctx->in);
  98614. byteSwap(ctx->buf, 4);
  98615. memcpy(digest, ctx->buf, 16);
  98616. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98617. if(0 != ctx->internal_buf) {
  98618. free(ctx->internal_buf);
  98619. ctx->internal_buf = 0;
  98620. ctx->capacity = 0;
  98621. }
  98622. }
  98623. /*
  98624. * Convert the incoming audio signal to a byte stream
  98625. */
  98626. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98627. {
  98628. unsigned channel, sample;
  98629. register FLAC__int32 a_word;
  98630. register FLAC__byte *buf_ = buf;
  98631. #if WORDS_BIGENDIAN
  98632. #else
  98633. if(channels == 2 && bytes_per_sample == 2) {
  98634. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98635. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98636. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98637. *buf1_ = (FLAC__int16)signal[1][sample];
  98638. }
  98639. else if(channels == 1 && bytes_per_sample == 2) {
  98640. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98641. for(sample = 0; sample < samples; sample++)
  98642. *buf1_++ = (FLAC__int16)signal[0][sample];
  98643. }
  98644. else
  98645. #endif
  98646. if(bytes_per_sample == 2) {
  98647. if(channels == 2) {
  98648. for(sample = 0; sample < samples; sample++) {
  98649. a_word = signal[0][sample];
  98650. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98651. *buf_++ = (FLAC__byte)a_word;
  98652. a_word = signal[1][sample];
  98653. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98654. *buf_++ = (FLAC__byte)a_word;
  98655. }
  98656. }
  98657. else if(channels == 1) {
  98658. for(sample = 0; sample < samples; sample++) {
  98659. a_word = signal[0][sample];
  98660. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98661. *buf_++ = (FLAC__byte)a_word;
  98662. }
  98663. }
  98664. else {
  98665. for(sample = 0; sample < samples; sample++) {
  98666. for(channel = 0; channel < channels; channel++) {
  98667. a_word = signal[channel][sample];
  98668. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98669. *buf_++ = (FLAC__byte)a_word;
  98670. }
  98671. }
  98672. }
  98673. }
  98674. else if(bytes_per_sample == 3) {
  98675. if(channels == 2) {
  98676. for(sample = 0; sample < samples; sample++) {
  98677. a_word = signal[0][sample];
  98678. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98679. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98680. *buf_++ = (FLAC__byte)a_word;
  98681. a_word = signal[1][sample];
  98682. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98683. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98684. *buf_++ = (FLAC__byte)a_word;
  98685. }
  98686. }
  98687. else if(channels == 1) {
  98688. for(sample = 0; sample < samples; sample++) {
  98689. a_word = signal[0][sample];
  98690. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98691. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98692. *buf_++ = (FLAC__byte)a_word;
  98693. }
  98694. }
  98695. else {
  98696. for(sample = 0; sample < samples; sample++) {
  98697. for(channel = 0; channel < channels; channel++) {
  98698. a_word = signal[channel][sample];
  98699. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98700. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98701. *buf_++ = (FLAC__byte)a_word;
  98702. }
  98703. }
  98704. }
  98705. }
  98706. else if(bytes_per_sample == 1) {
  98707. if(channels == 2) {
  98708. for(sample = 0; sample < samples; sample++) {
  98709. a_word = signal[0][sample];
  98710. *buf_++ = (FLAC__byte)a_word;
  98711. a_word = signal[1][sample];
  98712. *buf_++ = (FLAC__byte)a_word;
  98713. }
  98714. }
  98715. else if(channels == 1) {
  98716. for(sample = 0; sample < samples; sample++) {
  98717. a_word = signal[0][sample];
  98718. *buf_++ = (FLAC__byte)a_word;
  98719. }
  98720. }
  98721. else {
  98722. for(sample = 0; sample < samples; sample++) {
  98723. for(channel = 0; channel < channels; channel++) {
  98724. a_word = signal[channel][sample];
  98725. *buf_++ = (FLAC__byte)a_word;
  98726. }
  98727. }
  98728. }
  98729. }
  98730. else { /* bytes_per_sample == 4, maybe optimize more later */
  98731. for(sample = 0; sample < samples; sample++) {
  98732. for(channel = 0; channel < channels; channel++) {
  98733. a_word = signal[channel][sample];
  98734. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98735. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98736. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98737. *buf_++ = (FLAC__byte)a_word;
  98738. }
  98739. }
  98740. }
  98741. }
  98742. /*
  98743. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98744. */
  98745. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98746. {
  98747. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98748. /* overflow check */
  98749. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98750. return false;
  98751. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98752. return false;
  98753. if(ctx->capacity < bytes_needed) {
  98754. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98755. if(0 == tmp) {
  98756. free(ctx->internal_buf);
  98757. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98758. return false;
  98759. }
  98760. ctx->internal_buf = tmp;
  98761. ctx->capacity = bytes_needed;
  98762. }
  98763. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98764. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98765. return true;
  98766. }
  98767. #endif
  98768. /*** End of inlined file: md5.c ***/
  98769. /*** Start of inlined file: memory.c ***/
  98770. /*** Start of inlined file: juce_FlacHeader.h ***/
  98771. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98772. // tasks..
  98773. #define VERSION "1.2.1"
  98774. #define FLAC__NO_DLL 1
  98775. #if JUCE_MSVC
  98776. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98777. #endif
  98778. #if JUCE_MAC
  98779. #define FLAC__SYS_DARWIN 1
  98780. #endif
  98781. /*** End of inlined file: juce_FlacHeader.h ***/
  98782. #if JUCE_USE_FLAC
  98783. #if HAVE_CONFIG_H
  98784. # include <config.h>
  98785. #endif
  98786. /*** Start of inlined file: memory.h ***/
  98787. #ifndef FLAC__PRIVATE__MEMORY_H
  98788. #define FLAC__PRIVATE__MEMORY_H
  98789. #ifdef HAVE_CONFIG_H
  98790. #include <config.h>
  98791. #endif
  98792. #include <stdlib.h> /* for size_t */
  98793. /* Returns the unaligned address returned by malloc.
  98794. * Use free() on this address to deallocate.
  98795. */
  98796. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98797. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98798. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98799. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98800. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98801. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98802. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98803. #endif
  98804. #endif
  98805. /*** End of inlined file: memory.h ***/
  98806. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98807. {
  98808. void *x;
  98809. FLAC__ASSERT(0 != aligned_address);
  98810. #ifdef FLAC__ALIGN_MALLOC_DATA
  98811. /* align on 32-byte (256-bit) boundary */
  98812. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98813. #ifdef SIZEOF_VOIDP
  98814. #if SIZEOF_VOIDP == 4
  98815. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98816. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98817. #elif SIZEOF_VOIDP == 8
  98818. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98819. #else
  98820. # error Unsupported sizeof(void*)
  98821. #endif
  98822. #else
  98823. /* there's got to be a better way to do this right for all archs */
  98824. if(sizeof(void*) == sizeof(unsigned))
  98825. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98826. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98827. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98828. else
  98829. return 0;
  98830. #endif
  98831. #else
  98832. x = safe_malloc_(bytes);
  98833. *aligned_address = x;
  98834. #endif
  98835. return x;
  98836. }
  98837. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98838. {
  98839. FLAC__int32 *pu; /* unaligned pointer */
  98840. union { /* union needed to comply with C99 pointer aliasing rules */
  98841. FLAC__int32 *pa; /* aligned pointer */
  98842. void *pv; /* aligned pointer alias */
  98843. } u;
  98844. FLAC__ASSERT(elements > 0);
  98845. FLAC__ASSERT(0 != unaligned_pointer);
  98846. FLAC__ASSERT(0 != aligned_pointer);
  98847. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98848. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98849. if(0 == pu) {
  98850. return false;
  98851. }
  98852. else {
  98853. if(*unaligned_pointer != 0)
  98854. free(*unaligned_pointer);
  98855. *unaligned_pointer = pu;
  98856. *aligned_pointer = u.pa;
  98857. return true;
  98858. }
  98859. }
  98860. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98861. {
  98862. FLAC__uint32 *pu; /* unaligned pointer */
  98863. union { /* union needed to comply with C99 pointer aliasing rules */
  98864. FLAC__uint32 *pa; /* aligned pointer */
  98865. void *pv; /* aligned pointer alias */
  98866. } u;
  98867. FLAC__ASSERT(elements > 0);
  98868. FLAC__ASSERT(0 != unaligned_pointer);
  98869. FLAC__ASSERT(0 != aligned_pointer);
  98870. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98871. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98872. if(0 == pu) {
  98873. return false;
  98874. }
  98875. else {
  98876. if(*unaligned_pointer != 0)
  98877. free(*unaligned_pointer);
  98878. *unaligned_pointer = pu;
  98879. *aligned_pointer = u.pa;
  98880. return true;
  98881. }
  98882. }
  98883. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98884. {
  98885. FLAC__uint64 *pu; /* unaligned pointer */
  98886. union { /* union needed to comply with C99 pointer aliasing rules */
  98887. FLAC__uint64 *pa; /* aligned pointer */
  98888. void *pv; /* aligned pointer alias */
  98889. } u;
  98890. FLAC__ASSERT(elements > 0);
  98891. FLAC__ASSERT(0 != unaligned_pointer);
  98892. FLAC__ASSERT(0 != aligned_pointer);
  98893. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98894. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98895. if(0 == pu) {
  98896. return false;
  98897. }
  98898. else {
  98899. if(*unaligned_pointer != 0)
  98900. free(*unaligned_pointer);
  98901. *unaligned_pointer = pu;
  98902. *aligned_pointer = u.pa;
  98903. return true;
  98904. }
  98905. }
  98906. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98907. {
  98908. unsigned *pu; /* unaligned pointer */
  98909. union { /* union needed to comply with C99 pointer aliasing rules */
  98910. unsigned *pa; /* aligned pointer */
  98911. void *pv; /* aligned pointer alias */
  98912. } u;
  98913. FLAC__ASSERT(elements > 0);
  98914. FLAC__ASSERT(0 != unaligned_pointer);
  98915. FLAC__ASSERT(0 != aligned_pointer);
  98916. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98917. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98918. if(0 == pu) {
  98919. return false;
  98920. }
  98921. else {
  98922. if(*unaligned_pointer != 0)
  98923. free(*unaligned_pointer);
  98924. *unaligned_pointer = pu;
  98925. *aligned_pointer = u.pa;
  98926. return true;
  98927. }
  98928. }
  98929. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98930. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98931. {
  98932. FLAC__real *pu; /* unaligned pointer */
  98933. union { /* union needed to comply with C99 pointer aliasing rules */
  98934. FLAC__real *pa; /* aligned pointer */
  98935. void *pv; /* aligned pointer alias */
  98936. } u;
  98937. FLAC__ASSERT(elements > 0);
  98938. FLAC__ASSERT(0 != unaligned_pointer);
  98939. FLAC__ASSERT(0 != aligned_pointer);
  98940. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98941. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98942. if(0 == pu) {
  98943. return false;
  98944. }
  98945. else {
  98946. if(*unaligned_pointer != 0)
  98947. free(*unaligned_pointer);
  98948. *unaligned_pointer = pu;
  98949. *aligned_pointer = u.pa;
  98950. return true;
  98951. }
  98952. }
  98953. #endif
  98954. #endif
  98955. /*** End of inlined file: memory.c ***/
  98956. /*** Start of inlined file: stream_decoder.c ***/
  98957. /*** Start of inlined file: juce_FlacHeader.h ***/
  98958. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98959. // tasks..
  98960. #define VERSION "1.2.1"
  98961. #define FLAC__NO_DLL 1
  98962. #if JUCE_MSVC
  98963. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98964. #endif
  98965. #if JUCE_MAC
  98966. #define FLAC__SYS_DARWIN 1
  98967. #endif
  98968. /*** End of inlined file: juce_FlacHeader.h ***/
  98969. #if JUCE_USE_FLAC
  98970. #if HAVE_CONFIG_H
  98971. # include <config.h>
  98972. #endif
  98973. #if defined _MSC_VER || defined __MINGW32__
  98974. #include <io.h> /* for _setmode() */
  98975. #include <fcntl.h> /* for _O_BINARY */
  98976. #endif
  98977. #if defined __CYGWIN__ || defined __EMX__
  98978. #include <io.h> /* for setmode(), O_BINARY */
  98979. #include <fcntl.h> /* for _O_BINARY */
  98980. #endif
  98981. #include <stdio.h>
  98982. #include <stdlib.h> /* for malloc() */
  98983. #include <string.h> /* for memset/memcpy() */
  98984. #include <sys/stat.h> /* for stat() */
  98985. #include <sys/types.h> /* for off_t */
  98986. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98987. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98988. #define fseeko fseek
  98989. #define ftello ftell
  98990. #endif
  98991. #endif
  98992. /*** Start of inlined file: stream_decoder.h ***/
  98993. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98994. #define FLAC__PROTECTED__STREAM_DECODER_H
  98995. #if FLAC__HAS_OGG
  98996. #include "include/private/ogg_decoder_aspect.h"
  98997. #endif
  98998. typedef struct FLAC__StreamDecoderProtected {
  98999. FLAC__StreamDecoderState state;
  99000. unsigned channels;
  99001. FLAC__ChannelAssignment channel_assignment;
  99002. unsigned bits_per_sample;
  99003. unsigned sample_rate; /* in Hz */
  99004. unsigned blocksize; /* in samples (per channel) */
  99005. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99006. #if FLAC__HAS_OGG
  99007. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99008. #endif
  99009. } FLAC__StreamDecoderProtected;
  99010. /*
  99011. * return the number of input bytes consumed
  99012. */
  99013. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99014. #endif
  99015. /*** End of inlined file: stream_decoder.h ***/
  99016. #ifdef max
  99017. #undef max
  99018. #endif
  99019. #define max(a,b) ((a)>(b)?(a):(b))
  99020. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99021. #ifdef _MSC_VER
  99022. #define FLAC__U64L(x) x
  99023. #else
  99024. #define FLAC__U64L(x) x##LLU
  99025. #endif
  99026. /* technically this should be in an "export.c" but this is convenient enough */
  99027. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99028. #if FLAC__HAS_OGG
  99029. 1
  99030. #else
  99031. 0
  99032. #endif
  99033. ;
  99034. /***********************************************************************
  99035. *
  99036. * Private static data
  99037. *
  99038. ***********************************************************************/
  99039. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99040. /***********************************************************************
  99041. *
  99042. * Private class method prototypes
  99043. *
  99044. ***********************************************************************/
  99045. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99046. static FILE *get_binary_stdin_(void);
  99047. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99048. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99049. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99050. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99051. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99052. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99053. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99054. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99055. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99056. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99057. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99058. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99059. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99060. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99061. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99062. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99063. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99064. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99065. 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);
  99066. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99067. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99068. #if FLAC__HAS_OGG
  99069. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99070. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99071. #endif
  99072. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99073. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99074. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99075. #if FLAC__HAS_OGG
  99076. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99077. #endif
  99078. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99079. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99080. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99081. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99082. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99083. /***********************************************************************
  99084. *
  99085. * Private class data
  99086. *
  99087. ***********************************************************************/
  99088. typedef struct FLAC__StreamDecoderPrivate {
  99089. #if FLAC__HAS_OGG
  99090. FLAC__bool is_ogg;
  99091. #endif
  99092. FLAC__StreamDecoderReadCallback read_callback;
  99093. FLAC__StreamDecoderSeekCallback seek_callback;
  99094. FLAC__StreamDecoderTellCallback tell_callback;
  99095. FLAC__StreamDecoderLengthCallback length_callback;
  99096. FLAC__StreamDecoderEofCallback eof_callback;
  99097. FLAC__StreamDecoderWriteCallback write_callback;
  99098. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99099. FLAC__StreamDecoderErrorCallback error_callback;
  99100. /* generic 32-bit datapath: */
  99101. 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[]);
  99102. /* generic 64-bit datapath: */
  99103. 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[]);
  99104. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99105. 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[]);
  99106. /* 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: */
  99107. 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[]);
  99108. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99109. void *client_data;
  99110. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99111. FLAC__BitReader *input;
  99112. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99113. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99114. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99115. unsigned output_capacity, output_channels;
  99116. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99117. FLAC__uint64 samples_decoded;
  99118. FLAC__bool has_stream_info, has_seek_table;
  99119. FLAC__StreamMetadata stream_info;
  99120. FLAC__StreamMetadata seek_table;
  99121. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99122. FLAC__byte *metadata_filter_ids;
  99123. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99124. FLAC__Frame frame;
  99125. FLAC__bool cached; /* true if there is a byte in lookahead */
  99126. FLAC__CPUInfo cpuinfo;
  99127. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99128. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99129. /* unaligned (original) pointers to allocated data */
  99130. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99131. 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 */
  99132. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99133. FLAC__bool is_seeking;
  99134. FLAC__MD5Context md5context;
  99135. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99136. /* (the rest of these are only used for seeking) */
  99137. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99138. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99139. FLAC__uint64 target_sample;
  99140. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99141. #if FLAC__HAS_OGG
  99142. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99143. #endif
  99144. } FLAC__StreamDecoderPrivate;
  99145. /***********************************************************************
  99146. *
  99147. * Public static class data
  99148. *
  99149. ***********************************************************************/
  99150. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99151. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99152. "FLAC__STREAM_DECODER_READ_METADATA",
  99153. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99154. "FLAC__STREAM_DECODER_READ_FRAME",
  99155. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99156. "FLAC__STREAM_DECODER_OGG_ERROR",
  99157. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99158. "FLAC__STREAM_DECODER_ABORTED",
  99159. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99160. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99161. };
  99162. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99163. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99164. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99165. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99166. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99167. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99168. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99169. };
  99170. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99171. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99172. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99173. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99174. };
  99175. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99176. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99177. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99178. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99179. };
  99180. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99181. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99182. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99183. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99184. };
  99185. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99186. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99187. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99188. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99189. };
  99190. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99191. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99192. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99193. };
  99194. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99195. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99196. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99197. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99198. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99199. };
  99200. /***********************************************************************
  99201. *
  99202. * Class constructor/destructor
  99203. *
  99204. ***********************************************************************/
  99205. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99206. {
  99207. FLAC__StreamDecoder *decoder;
  99208. unsigned i;
  99209. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99210. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99211. if(decoder == 0) {
  99212. return 0;
  99213. }
  99214. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99215. if(decoder->protected_ == 0) {
  99216. free(decoder);
  99217. return 0;
  99218. }
  99219. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99220. if(decoder->private_ == 0) {
  99221. free(decoder->protected_);
  99222. free(decoder);
  99223. return 0;
  99224. }
  99225. decoder->private_->input = FLAC__bitreader_new();
  99226. if(decoder->private_->input == 0) {
  99227. free(decoder->private_);
  99228. free(decoder->protected_);
  99229. free(decoder);
  99230. return 0;
  99231. }
  99232. decoder->private_->metadata_filter_ids_capacity = 16;
  99233. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99234. FLAC__bitreader_delete(decoder->private_->input);
  99235. free(decoder->private_);
  99236. free(decoder->protected_);
  99237. free(decoder);
  99238. return 0;
  99239. }
  99240. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99241. decoder->private_->output[i] = 0;
  99242. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99243. }
  99244. decoder->private_->output_capacity = 0;
  99245. decoder->private_->output_channels = 0;
  99246. decoder->private_->has_seek_table = false;
  99247. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99248. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99249. decoder->private_->file = 0;
  99250. set_defaults_dec(decoder);
  99251. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99252. return decoder;
  99253. }
  99254. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99255. {
  99256. unsigned i;
  99257. FLAC__ASSERT(0 != decoder);
  99258. FLAC__ASSERT(0 != decoder->protected_);
  99259. FLAC__ASSERT(0 != decoder->private_);
  99260. FLAC__ASSERT(0 != decoder->private_->input);
  99261. (void)FLAC__stream_decoder_finish(decoder);
  99262. if(0 != decoder->private_->metadata_filter_ids)
  99263. free(decoder->private_->metadata_filter_ids);
  99264. FLAC__bitreader_delete(decoder->private_->input);
  99265. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99266. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99267. free(decoder->private_);
  99268. free(decoder->protected_);
  99269. free(decoder);
  99270. }
  99271. /***********************************************************************
  99272. *
  99273. * Public class methods
  99274. *
  99275. ***********************************************************************/
  99276. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99277. FLAC__StreamDecoder *decoder,
  99278. FLAC__StreamDecoderReadCallback read_callback,
  99279. FLAC__StreamDecoderSeekCallback seek_callback,
  99280. FLAC__StreamDecoderTellCallback tell_callback,
  99281. FLAC__StreamDecoderLengthCallback length_callback,
  99282. FLAC__StreamDecoderEofCallback eof_callback,
  99283. FLAC__StreamDecoderWriteCallback write_callback,
  99284. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99285. FLAC__StreamDecoderErrorCallback error_callback,
  99286. void *client_data,
  99287. FLAC__bool is_ogg
  99288. )
  99289. {
  99290. FLAC__ASSERT(0 != decoder);
  99291. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99292. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99293. #if !FLAC__HAS_OGG
  99294. if(is_ogg)
  99295. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99296. #endif
  99297. if(
  99298. 0 == read_callback ||
  99299. 0 == write_callback ||
  99300. 0 == error_callback ||
  99301. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99302. )
  99303. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99304. #if FLAC__HAS_OGG
  99305. decoder->private_->is_ogg = is_ogg;
  99306. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99307. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99308. #endif
  99309. /*
  99310. * get the CPU info and set the function pointers
  99311. */
  99312. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99313. /* first default to the non-asm routines */
  99314. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99315. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99316. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99317. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99318. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99319. /* now override with asm where appropriate */
  99320. #ifndef FLAC__NO_ASM
  99321. if(decoder->private_->cpuinfo.use_asm) {
  99322. #ifdef FLAC__CPU_IA32
  99323. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99324. #ifdef FLAC__HAS_NASM
  99325. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99326. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99327. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99328. #endif
  99329. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99330. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99331. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99332. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99333. }
  99334. else {
  99335. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99336. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99337. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99338. }
  99339. #endif
  99340. #elif defined FLAC__CPU_PPC
  99341. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99342. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99343. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99344. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99345. }
  99346. #endif
  99347. }
  99348. #endif
  99349. /* from here on, errors are fatal */
  99350. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99351. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99352. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99353. }
  99354. decoder->private_->read_callback = read_callback;
  99355. decoder->private_->seek_callback = seek_callback;
  99356. decoder->private_->tell_callback = tell_callback;
  99357. decoder->private_->length_callback = length_callback;
  99358. decoder->private_->eof_callback = eof_callback;
  99359. decoder->private_->write_callback = write_callback;
  99360. decoder->private_->metadata_callback = metadata_callback;
  99361. decoder->private_->error_callback = error_callback;
  99362. decoder->private_->client_data = client_data;
  99363. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99364. decoder->private_->samples_decoded = 0;
  99365. decoder->private_->has_stream_info = false;
  99366. decoder->private_->cached = false;
  99367. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99368. decoder->private_->is_seeking = false;
  99369. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99370. if(!FLAC__stream_decoder_reset(decoder)) {
  99371. /* above call sets the state for us */
  99372. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99373. }
  99374. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99375. }
  99376. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99377. FLAC__StreamDecoder *decoder,
  99378. FLAC__StreamDecoderReadCallback read_callback,
  99379. FLAC__StreamDecoderSeekCallback seek_callback,
  99380. FLAC__StreamDecoderTellCallback tell_callback,
  99381. FLAC__StreamDecoderLengthCallback length_callback,
  99382. FLAC__StreamDecoderEofCallback eof_callback,
  99383. FLAC__StreamDecoderWriteCallback write_callback,
  99384. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99385. FLAC__StreamDecoderErrorCallback error_callback,
  99386. void *client_data
  99387. )
  99388. {
  99389. return init_stream_internal_dec(
  99390. decoder,
  99391. read_callback,
  99392. seek_callback,
  99393. tell_callback,
  99394. length_callback,
  99395. eof_callback,
  99396. write_callback,
  99397. metadata_callback,
  99398. error_callback,
  99399. client_data,
  99400. /*is_ogg=*/false
  99401. );
  99402. }
  99403. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99404. FLAC__StreamDecoder *decoder,
  99405. FLAC__StreamDecoderReadCallback read_callback,
  99406. FLAC__StreamDecoderSeekCallback seek_callback,
  99407. FLAC__StreamDecoderTellCallback tell_callback,
  99408. FLAC__StreamDecoderLengthCallback length_callback,
  99409. FLAC__StreamDecoderEofCallback eof_callback,
  99410. FLAC__StreamDecoderWriteCallback write_callback,
  99411. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99412. FLAC__StreamDecoderErrorCallback error_callback,
  99413. void *client_data
  99414. )
  99415. {
  99416. return init_stream_internal_dec(
  99417. decoder,
  99418. read_callback,
  99419. seek_callback,
  99420. tell_callback,
  99421. length_callback,
  99422. eof_callback,
  99423. write_callback,
  99424. metadata_callback,
  99425. error_callback,
  99426. client_data,
  99427. /*is_ogg=*/true
  99428. );
  99429. }
  99430. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99431. FLAC__StreamDecoder *decoder,
  99432. FILE *file,
  99433. FLAC__StreamDecoderWriteCallback write_callback,
  99434. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99435. FLAC__StreamDecoderErrorCallback error_callback,
  99436. void *client_data,
  99437. FLAC__bool is_ogg
  99438. )
  99439. {
  99440. FLAC__ASSERT(0 != decoder);
  99441. FLAC__ASSERT(0 != file);
  99442. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99443. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99444. if(0 == write_callback || 0 == error_callback)
  99445. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99446. /*
  99447. * To make sure that our file does not go unclosed after an error, we
  99448. * must assign the FILE pointer before any further error can occur in
  99449. * this routine.
  99450. */
  99451. if(file == stdin)
  99452. file = get_binary_stdin_(); /* just to be safe */
  99453. decoder->private_->file = file;
  99454. return init_stream_internal_dec(
  99455. decoder,
  99456. file_read_callback_dec,
  99457. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99458. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99459. decoder->private_->file == stdin? 0: file_length_callback_,
  99460. file_eof_callback_,
  99461. write_callback,
  99462. metadata_callback,
  99463. error_callback,
  99464. client_data,
  99465. is_ogg
  99466. );
  99467. }
  99468. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99469. FLAC__StreamDecoder *decoder,
  99470. FILE *file,
  99471. FLAC__StreamDecoderWriteCallback write_callback,
  99472. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99473. FLAC__StreamDecoderErrorCallback error_callback,
  99474. void *client_data
  99475. )
  99476. {
  99477. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99478. }
  99479. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99480. FLAC__StreamDecoder *decoder,
  99481. FILE *file,
  99482. FLAC__StreamDecoderWriteCallback write_callback,
  99483. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99484. FLAC__StreamDecoderErrorCallback error_callback,
  99485. void *client_data
  99486. )
  99487. {
  99488. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99489. }
  99490. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99491. FLAC__StreamDecoder *decoder,
  99492. const char *filename,
  99493. FLAC__StreamDecoderWriteCallback write_callback,
  99494. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99495. FLAC__StreamDecoderErrorCallback error_callback,
  99496. void *client_data,
  99497. FLAC__bool is_ogg
  99498. )
  99499. {
  99500. FILE *file;
  99501. FLAC__ASSERT(0 != decoder);
  99502. /*
  99503. * To make sure that our file does not go unclosed after an error, we
  99504. * have to do the same entrance checks here that are later performed
  99505. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99506. */
  99507. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99508. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99509. if(0 == write_callback || 0 == error_callback)
  99510. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99511. file = filename? fopen(filename, "rb") : stdin;
  99512. if(0 == file)
  99513. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99514. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99515. }
  99516. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99517. FLAC__StreamDecoder *decoder,
  99518. const char *filename,
  99519. FLAC__StreamDecoderWriteCallback write_callback,
  99520. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99521. FLAC__StreamDecoderErrorCallback error_callback,
  99522. void *client_data
  99523. )
  99524. {
  99525. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99526. }
  99527. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99528. FLAC__StreamDecoder *decoder,
  99529. const char *filename,
  99530. FLAC__StreamDecoderWriteCallback write_callback,
  99531. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99532. FLAC__StreamDecoderErrorCallback error_callback,
  99533. void *client_data
  99534. )
  99535. {
  99536. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99537. }
  99538. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99539. {
  99540. FLAC__bool md5_failed = false;
  99541. unsigned i;
  99542. FLAC__ASSERT(0 != decoder);
  99543. FLAC__ASSERT(0 != decoder->private_);
  99544. FLAC__ASSERT(0 != decoder->protected_);
  99545. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99546. return true;
  99547. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99548. * always call FLAC__MD5Final()
  99549. */
  99550. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99551. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99552. free(decoder->private_->seek_table.data.seek_table.points);
  99553. decoder->private_->seek_table.data.seek_table.points = 0;
  99554. decoder->private_->has_seek_table = false;
  99555. }
  99556. FLAC__bitreader_free(decoder->private_->input);
  99557. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99558. /* WATCHOUT:
  99559. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99560. * output arrays have a buffer of up to 3 zeroes in front
  99561. * (at negative indices) for alignment purposes; we use 4
  99562. * to keep the data well-aligned.
  99563. */
  99564. if(0 != decoder->private_->output[i]) {
  99565. free(decoder->private_->output[i]-4);
  99566. decoder->private_->output[i] = 0;
  99567. }
  99568. if(0 != decoder->private_->residual_unaligned[i]) {
  99569. free(decoder->private_->residual_unaligned[i]);
  99570. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99571. }
  99572. }
  99573. decoder->private_->output_capacity = 0;
  99574. decoder->private_->output_channels = 0;
  99575. #if FLAC__HAS_OGG
  99576. if(decoder->private_->is_ogg)
  99577. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99578. #endif
  99579. if(0 != decoder->private_->file) {
  99580. if(decoder->private_->file != stdin)
  99581. fclose(decoder->private_->file);
  99582. decoder->private_->file = 0;
  99583. }
  99584. if(decoder->private_->do_md5_checking) {
  99585. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99586. md5_failed = true;
  99587. }
  99588. decoder->private_->is_seeking = false;
  99589. set_defaults_dec(decoder);
  99590. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99591. return !md5_failed;
  99592. }
  99593. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99594. {
  99595. FLAC__ASSERT(0 != decoder);
  99596. FLAC__ASSERT(0 != decoder->private_);
  99597. FLAC__ASSERT(0 != decoder->protected_);
  99598. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99599. return false;
  99600. #if FLAC__HAS_OGG
  99601. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99602. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99603. return true;
  99604. #else
  99605. (void)value;
  99606. return false;
  99607. #endif
  99608. }
  99609. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99610. {
  99611. FLAC__ASSERT(0 != decoder);
  99612. FLAC__ASSERT(0 != decoder->protected_);
  99613. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99614. return false;
  99615. decoder->protected_->md5_checking = value;
  99616. return true;
  99617. }
  99618. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99619. {
  99620. FLAC__ASSERT(0 != decoder);
  99621. FLAC__ASSERT(0 != decoder->private_);
  99622. FLAC__ASSERT(0 != decoder->protected_);
  99623. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99624. /* double protection */
  99625. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99626. return false;
  99627. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99628. return false;
  99629. decoder->private_->metadata_filter[type] = true;
  99630. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99631. decoder->private_->metadata_filter_ids_count = 0;
  99632. return true;
  99633. }
  99634. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99635. {
  99636. FLAC__ASSERT(0 != decoder);
  99637. FLAC__ASSERT(0 != decoder->private_);
  99638. FLAC__ASSERT(0 != decoder->protected_);
  99639. FLAC__ASSERT(0 != id);
  99640. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99641. return false;
  99642. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99643. return true;
  99644. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99645. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99646. 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))) {
  99647. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99648. return false;
  99649. }
  99650. decoder->private_->metadata_filter_ids_capacity *= 2;
  99651. }
  99652. 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));
  99653. decoder->private_->metadata_filter_ids_count++;
  99654. return true;
  99655. }
  99656. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99657. {
  99658. unsigned i;
  99659. FLAC__ASSERT(0 != decoder);
  99660. FLAC__ASSERT(0 != decoder->private_);
  99661. FLAC__ASSERT(0 != decoder->protected_);
  99662. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99663. return false;
  99664. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99665. decoder->private_->metadata_filter[i] = true;
  99666. decoder->private_->metadata_filter_ids_count = 0;
  99667. return true;
  99668. }
  99669. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99670. {
  99671. FLAC__ASSERT(0 != decoder);
  99672. FLAC__ASSERT(0 != decoder->private_);
  99673. FLAC__ASSERT(0 != decoder->protected_);
  99674. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99675. /* double protection */
  99676. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99677. return false;
  99678. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99679. return false;
  99680. decoder->private_->metadata_filter[type] = false;
  99681. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99682. decoder->private_->metadata_filter_ids_count = 0;
  99683. return true;
  99684. }
  99685. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99686. {
  99687. FLAC__ASSERT(0 != decoder);
  99688. FLAC__ASSERT(0 != decoder->private_);
  99689. FLAC__ASSERT(0 != decoder->protected_);
  99690. FLAC__ASSERT(0 != id);
  99691. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99692. return false;
  99693. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99694. return true;
  99695. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99696. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99697. 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))) {
  99698. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99699. return false;
  99700. }
  99701. decoder->private_->metadata_filter_ids_capacity *= 2;
  99702. }
  99703. 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));
  99704. decoder->private_->metadata_filter_ids_count++;
  99705. return true;
  99706. }
  99707. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99708. {
  99709. FLAC__ASSERT(0 != decoder);
  99710. FLAC__ASSERT(0 != decoder->private_);
  99711. FLAC__ASSERT(0 != decoder->protected_);
  99712. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99713. return false;
  99714. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99715. decoder->private_->metadata_filter_ids_count = 0;
  99716. return true;
  99717. }
  99718. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99719. {
  99720. FLAC__ASSERT(0 != decoder);
  99721. FLAC__ASSERT(0 != decoder->protected_);
  99722. return decoder->protected_->state;
  99723. }
  99724. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99725. {
  99726. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99727. }
  99728. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99729. {
  99730. FLAC__ASSERT(0 != decoder);
  99731. FLAC__ASSERT(0 != decoder->protected_);
  99732. return decoder->protected_->md5_checking;
  99733. }
  99734. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99735. {
  99736. FLAC__ASSERT(0 != decoder);
  99737. FLAC__ASSERT(0 != decoder->protected_);
  99738. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99739. }
  99740. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99741. {
  99742. FLAC__ASSERT(0 != decoder);
  99743. FLAC__ASSERT(0 != decoder->protected_);
  99744. return decoder->protected_->channels;
  99745. }
  99746. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99747. {
  99748. FLAC__ASSERT(0 != decoder);
  99749. FLAC__ASSERT(0 != decoder->protected_);
  99750. return decoder->protected_->channel_assignment;
  99751. }
  99752. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99753. {
  99754. FLAC__ASSERT(0 != decoder);
  99755. FLAC__ASSERT(0 != decoder->protected_);
  99756. return decoder->protected_->bits_per_sample;
  99757. }
  99758. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99759. {
  99760. FLAC__ASSERT(0 != decoder);
  99761. FLAC__ASSERT(0 != decoder->protected_);
  99762. return decoder->protected_->sample_rate;
  99763. }
  99764. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99765. {
  99766. FLAC__ASSERT(0 != decoder);
  99767. FLAC__ASSERT(0 != decoder->protected_);
  99768. return decoder->protected_->blocksize;
  99769. }
  99770. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99771. {
  99772. FLAC__ASSERT(0 != decoder);
  99773. FLAC__ASSERT(0 != decoder->private_);
  99774. FLAC__ASSERT(0 != position);
  99775. #if FLAC__HAS_OGG
  99776. if(decoder->private_->is_ogg)
  99777. return false;
  99778. #endif
  99779. if(0 == decoder->private_->tell_callback)
  99780. return false;
  99781. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99782. return false;
  99783. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99784. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99785. return false;
  99786. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99787. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99788. return true;
  99789. }
  99790. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99791. {
  99792. FLAC__ASSERT(0 != decoder);
  99793. FLAC__ASSERT(0 != decoder->private_);
  99794. FLAC__ASSERT(0 != decoder->protected_);
  99795. decoder->private_->samples_decoded = 0;
  99796. decoder->private_->do_md5_checking = false;
  99797. #if FLAC__HAS_OGG
  99798. if(decoder->private_->is_ogg)
  99799. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99800. #endif
  99801. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99802. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99803. return false;
  99804. }
  99805. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99806. return true;
  99807. }
  99808. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99809. {
  99810. FLAC__ASSERT(0 != decoder);
  99811. FLAC__ASSERT(0 != decoder->private_);
  99812. FLAC__ASSERT(0 != decoder->protected_);
  99813. if(!FLAC__stream_decoder_flush(decoder)) {
  99814. /* above call sets the state for us */
  99815. return false;
  99816. }
  99817. #if FLAC__HAS_OGG
  99818. /*@@@ could go in !internal_reset_hack block below */
  99819. if(decoder->private_->is_ogg)
  99820. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99821. #endif
  99822. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99823. * (internal_reset_hack) don't try to rewind since we are already at
  99824. * the beginning of the stream and don't want to fail if the input is
  99825. * not seekable.
  99826. */
  99827. if(!decoder->private_->internal_reset_hack) {
  99828. if(decoder->private_->file == stdin)
  99829. return false; /* can't rewind stdin, reset fails */
  99830. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99831. return false; /* seekable and seek fails, reset fails */
  99832. }
  99833. else
  99834. decoder->private_->internal_reset_hack = false;
  99835. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99836. decoder->private_->has_stream_info = false;
  99837. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99838. free(decoder->private_->seek_table.data.seek_table.points);
  99839. decoder->private_->seek_table.data.seek_table.points = 0;
  99840. decoder->private_->has_seek_table = false;
  99841. }
  99842. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99843. /*
  99844. * This goes in reset() and not flush() because according to the spec, a
  99845. * fixed-blocksize stream must stay that way through the whole stream.
  99846. */
  99847. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99848. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99849. * is because md5 checking may be turned on to start and then turned off if
  99850. * a seek occurs. So we init the context here and finalize it in
  99851. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99852. * properly.
  99853. */
  99854. FLAC__MD5Init(&decoder->private_->md5context);
  99855. decoder->private_->first_frame_offset = 0;
  99856. decoder->private_->unparseable_frame_count = 0;
  99857. return true;
  99858. }
  99859. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99860. {
  99861. FLAC__bool got_a_frame;
  99862. FLAC__ASSERT(0 != decoder);
  99863. FLAC__ASSERT(0 != decoder->protected_);
  99864. while(1) {
  99865. switch(decoder->protected_->state) {
  99866. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99867. if(!find_metadata_(decoder))
  99868. return false; /* above function sets the status for us */
  99869. break;
  99870. case FLAC__STREAM_DECODER_READ_METADATA:
  99871. if(!read_metadata_(decoder))
  99872. return false; /* above function sets the status for us */
  99873. else
  99874. return true;
  99875. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99876. if(!frame_sync_(decoder))
  99877. return true; /* above function sets the status for us */
  99878. break;
  99879. case FLAC__STREAM_DECODER_READ_FRAME:
  99880. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99881. return false; /* above function sets the status for us */
  99882. if(got_a_frame)
  99883. return true; /* above function sets the status for us */
  99884. break;
  99885. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99886. case FLAC__STREAM_DECODER_ABORTED:
  99887. return true;
  99888. default:
  99889. FLAC__ASSERT(0);
  99890. return false;
  99891. }
  99892. }
  99893. }
  99894. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99895. {
  99896. FLAC__ASSERT(0 != decoder);
  99897. FLAC__ASSERT(0 != decoder->protected_);
  99898. while(1) {
  99899. switch(decoder->protected_->state) {
  99900. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99901. if(!find_metadata_(decoder))
  99902. return false; /* above function sets the status for us */
  99903. break;
  99904. case FLAC__STREAM_DECODER_READ_METADATA:
  99905. if(!read_metadata_(decoder))
  99906. return false; /* above function sets the status for us */
  99907. break;
  99908. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99909. case FLAC__STREAM_DECODER_READ_FRAME:
  99910. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99911. case FLAC__STREAM_DECODER_ABORTED:
  99912. return true;
  99913. default:
  99914. FLAC__ASSERT(0);
  99915. return false;
  99916. }
  99917. }
  99918. }
  99919. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99920. {
  99921. FLAC__bool dummy;
  99922. FLAC__ASSERT(0 != decoder);
  99923. FLAC__ASSERT(0 != decoder->protected_);
  99924. while(1) {
  99925. switch(decoder->protected_->state) {
  99926. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99927. if(!find_metadata_(decoder))
  99928. return false; /* above function sets the status for us */
  99929. break;
  99930. case FLAC__STREAM_DECODER_READ_METADATA:
  99931. if(!read_metadata_(decoder))
  99932. return false; /* above function sets the status for us */
  99933. break;
  99934. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99935. if(!frame_sync_(decoder))
  99936. return true; /* above function sets the status for us */
  99937. break;
  99938. case FLAC__STREAM_DECODER_READ_FRAME:
  99939. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99940. return false; /* above function sets the status for us */
  99941. break;
  99942. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99943. case FLAC__STREAM_DECODER_ABORTED:
  99944. return true;
  99945. default:
  99946. FLAC__ASSERT(0);
  99947. return false;
  99948. }
  99949. }
  99950. }
  99951. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99952. {
  99953. FLAC__bool got_a_frame;
  99954. FLAC__ASSERT(0 != decoder);
  99955. FLAC__ASSERT(0 != decoder->protected_);
  99956. while(1) {
  99957. switch(decoder->protected_->state) {
  99958. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99959. case FLAC__STREAM_DECODER_READ_METADATA:
  99960. return false; /* above function sets the status for us */
  99961. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99962. if(!frame_sync_(decoder))
  99963. return true; /* above function sets the status for us */
  99964. break;
  99965. case FLAC__STREAM_DECODER_READ_FRAME:
  99966. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99967. return false; /* above function sets the status for us */
  99968. if(got_a_frame)
  99969. return true; /* above function sets the status for us */
  99970. break;
  99971. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99972. case FLAC__STREAM_DECODER_ABORTED:
  99973. return true;
  99974. default:
  99975. FLAC__ASSERT(0);
  99976. return false;
  99977. }
  99978. }
  99979. }
  99980. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99981. {
  99982. FLAC__uint64 length;
  99983. FLAC__ASSERT(0 != decoder);
  99984. if(
  99985. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99986. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99987. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99988. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99989. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99990. )
  99991. return false;
  99992. if(0 == decoder->private_->seek_callback)
  99993. return false;
  99994. FLAC__ASSERT(decoder->private_->seek_callback);
  99995. FLAC__ASSERT(decoder->private_->tell_callback);
  99996. FLAC__ASSERT(decoder->private_->length_callback);
  99997. FLAC__ASSERT(decoder->private_->eof_callback);
  99998. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99999. return false;
  100000. decoder->private_->is_seeking = true;
  100001. /* turn off md5 checking if a seek is attempted */
  100002. decoder->private_->do_md5_checking = false;
  100003. /* 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) */
  100004. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100005. decoder->private_->is_seeking = false;
  100006. return false;
  100007. }
  100008. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100009. if(
  100010. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100011. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100012. ) {
  100013. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100014. /* above call sets the state for us */
  100015. decoder->private_->is_seeking = false;
  100016. return false;
  100017. }
  100018. /* check this again in case we didn't know total_samples the first time */
  100019. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100020. decoder->private_->is_seeking = false;
  100021. return false;
  100022. }
  100023. }
  100024. {
  100025. const FLAC__bool ok =
  100026. #if FLAC__HAS_OGG
  100027. decoder->private_->is_ogg?
  100028. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100029. #endif
  100030. seek_to_absolute_sample_(decoder, length, sample)
  100031. ;
  100032. decoder->private_->is_seeking = false;
  100033. return ok;
  100034. }
  100035. }
  100036. /***********************************************************************
  100037. *
  100038. * Protected class methods
  100039. *
  100040. ***********************************************************************/
  100041. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100042. {
  100043. FLAC__ASSERT(0 != decoder);
  100044. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100045. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100046. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100047. }
  100048. /***********************************************************************
  100049. *
  100050. * Private class methods
  100051. *
  100052. ***********************************************************************/
  100053. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100054. {
  100055. #if FLAC__HAS_OGG
  100056. decoder->private_->is_ogg = false;
  100057. #endif
  100058. decoder->private_->read_callback = 0;
  100059. decoder->private_->seek_callback = 0;
  100060. decoder->private_->tell_callback = 0;
  100061. decoder->private_->length_callback = 0;
  100062. decoder->private_->eof_callback = 0;
  100063. decoder->private_->write_callback = 0;
  100064. decoder->private_->metadata_callback = 0;
  100065. decoder->private_->error_callback = 0;
  100066. decoder->private_->client_data = 0;
  100067. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100068. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100069. decoder->private_->metadata_filter_ids_count = 0;
  100070. decoder->protected_->md5_checking = false;
  100071. #if FLAC__HAS_OGG
  100072. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100073. #endif
  100074. }
  100075. /*
  100076. * This will forcibly set stdin to binary mode (for OSes that require it)
  100077. */
  100078. FILE *get_binary_stdin_(void)
  100079. {
  100080. /* if something breaks here it is probably due to the presence or
  100081. * absence of an underscore before the identifiers 'setmode',
  100082. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100083. */
  100084. #if defined _MSC_VER || defined __MINGW32__
  100085. _setmode(_fileno(stdin), _O_BINARY);
  100086. #elif defined __CYGWIN__
  100087. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100088. setmode(_fileno(stdin), _O_BINARY);
  100089. #elif defined __EMX__
  100090. setmode(fileno(stdin), O_BINARY);
  100091. #endif
  100092. return stdin;
  100093. }
  100094. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100095. {
  100096. unsigned i;
  100097. FLAC__int32 *tmp;
  100098. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100099. return true;
  100100. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100101. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100102. if(0 != decoder->private_->output[i]) {
  100103. free(decoder->private_->output[i]-4);
  100104. decoder->private_->output[i] = 0;
  100105. }
  100106. if(0 != decoder->private_->residual_unaligned[i]) {
  100107. free(decoder->private_->residual_unaligned[i]);
  100108. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100109. }
  100110. }
  100111. for(i = 0; i < channels; i++) {
  100112. /* WATCHOUT:
  100113. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100114. * output arrays have a buffer of up to 3 zeroes in front
  100115. * (at negative indices) for alignment purposes; we use 4
  100116. * to keep the data well-aligned.
  100117. */
  100118. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100119. if(tmp == 0) {
  100120. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100121. return false;
  100122. }
  100123. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100124. decoder->private_->output[i] = tmp + 4;
  100125. /* WATCHOUT:
  100126. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100127. */
  100128. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100129. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100130. return false;
  100131. }
  100132. }
  100133. decoder->private_->output_capacity = size;
  100134. decoder->private_->output_channels = channels;
  100135. return true;
  100136. }
  100137. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100138. {
  100139. size_t i;
  100140. FLAC__ASSERT(0 != decoder);
  100141. FLAC__ASSERT(0 != decoder->private_);
  100142. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100143. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100144. return true;
  100145. return false;
  100146. }
  100147. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100148. {
  100149. FLAC__uint32 x;
  100150. unsigned i, id_;
  100151. FLAC__bool first = true;
  100152. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100153. for(i = id_ = 0; i < 4; ) {
  100154. if(decoder->private_->cached) {
  100155. x = (FLAC__uint32)decoder->private_->lookahead;
  100156. decoder->private_->cached = false;
  100157. }
  100158. else {
  100159. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100160. return false; /* read_callback_ sets the state for us */
  100161. }
  100162. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100163. first = true;
  100164. i++;
  100165. id_ = 0;
  100166. continue;
  100167. }
  100168. if(x == ID3V2_TAG_[id_]) {
  100169. id_++;
  100170. i = 0;
  100171. if(id_ == 3) {
  100172. if(!skip_id3v2_tag_(decoder))
  100173. return false; /* skip_id3v2_tag_ sets the state for us */
  100174. }
  100175. continue;
  100176. }
  100177. id_ = 0;
  100178. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100179. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100180. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100181. return false; /* read_callback_ sets the state for us */
  100182. /* 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 */
  100183. /* else we have to check if the second byte is the end of a sync code */
  100184. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100185. decoder->private_->lookahead = (FLAC__byte)x;
  100186. decoder->private_->cached = true;
  100187. }
  100188. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100189. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100190. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100191. return true;
  100192. }
  100193. }
  100194. i = 0;
  100195. if(first) {
  100196. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100197. first = false;
  100198. }
  100199. }
  100200. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100201. return true;
  100202. }
  100203. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100204. {
  100205. FLAC__bool is_last;
  100206. FLAC__uint32 i, x, type, length;
  100207. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100208. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100209. return false; /* read_callback_ sets the state for us */
  100210. is_last = x? true : false;
  100211. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100212. return false; /* read_callback_ sets the state for us */
  100213. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100214. return false; /* read_callback_ sets the state for us */
  100215. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100216. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100217. return false;
  100218. decoder->private_->has_stream_info = true;
  100219. 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))
  100220. decoder->private_->do_md5_checking = false;
  100221. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100222. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100223. }
  100224. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100225. if(!read_metadata_seektable_(decoder, is_last, length))
  100226. return false;
  100227. decoder->private_->has_seek_table = true;
  100228. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100229. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100230. }
  100231. else {
  100232. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100233. unsigned real_length = length;
  100234. FLAC__StreamMetadata block;
  100235. block.is_last = is_last;
  100236. block.type = (FLAC__MetadataType)type;
  100237. block.length = length;
  100238. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100239. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100240. return false; /* read_callback_ sets the state for us */
  100241. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100242. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100243. return false;
  100244. }
  100245. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100246. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100247. skip_it = !skip_it;
  100248. }
  100249. if(skip_it) {
  100250. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100251. return false; /* read_callback_ sets the state for us */
  100252. }
  100253. else {
  100254. switch(type) {
  100255. case FLAC__METADATA_TYPE_PADDING:
  100256. /* skip the padding bytes */
  100257. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100258. return false; /* read_callback_ sets the state for us */
  100259. break;
  100260. case FLAC__METADATA_TYPE_APPLICATION:
  100261. /* remember, we read the ID already */
  100262. if(real_length > 0) {
  100263. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100264. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100265. return false;
  100266. }
  100267. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100268. return false; /* read_callback_ sets the state for us */
  100269. }
  100270. else
  100271. block.data.application.data = 0;
  100272. break;
  100273. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100274. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100275. return false;
  100276. break;
  100277. case FLAC__METADATA_TYPE_CUESHEET:
  100278. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100279. return false;
  100280. break;
  100281. case FLAC__METADATA_TYPE_PICTURE:
  100282. if(!read_metadata_picture_(decoder, &block.data.picture))
  100283. return false;
  100284. break;
  100285. case FLAC__METADATA_TYPE_STREAMINFO:
  100286. case FLAC__METADATA_TYPE_SEEKTABLE:
  100287. FLAC__ASSERT(0);
  100288. break;
  100289. default:
  100290. if(real_length > 0) {
  100291. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100292. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100293. return false;
  100294. }
  100295. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100296. return false; /* read_callback_ sets the state for us */
  100297. }
  100298. else
  100299. block.data.unknown.data = 0;
  100300. break;
  100301. }
  100302. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100303. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100304. /* now we have to free any malloc()ed data in the block */
  100305. switch(type) {
  100306. case FLAC__METADATA_TYPE_PADDING:
  100307. break;
  100308. case FLAC__METADATA_TYPE_APPLICATION:
  100309. if(0 != block.data.application.data)
  100310. free(block.data.application.data);
  100311. break;
  100312. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100313. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100314. free(block.data.vorbis_comment.vendor_string.entry);
  100315. if(block.data.vorbis_comment.num_comments > 0)
  100316. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100317. if(0 != block.data.vorbis_comment.comments[i].entry)
  100318. free(block.data.vorbis_comment.comments[i].entry);
  100319. if(0 != block.data.vorbis_comment.comments)
  100320. free(block.data.vorbis_comment.comments);
  100321. break;
  100322. case FLAC__METADATA_TYPE_CUESHEET:
  100323. if(block.data.cue_sheet.num_tracks > 0)
  100324. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100325. if(0 != block.data.cue_sheet.tracks[i].indices)
  100326. free(block.data.cue_sheet.tracks[i].indices);
  100327. if(0 != block.data.cue_sheet.tracks)
  100328. free(block.data.cue_sheet.tracks);
  100329. break;
  100330. case FLAC__METADATA_TYPE_PICTURE:
  100331. if(0 != block.data.picture.mime_type)
  100332. free(block.data.picture.mime_type);
  100333. if(0 != block.data.picture.description)
  100334. free(block.data.picture.description);
  100335. if(0 != block.data.picture.data)
  100336. free(block.data.picture.data);
  100337. break;
  100338. case FLAC__METADATA_TYPE_STREAMINFO:
  100339. case FLAC__METADATA_TYPE_SEEKTABLE:
  100340. FLAC__ASSERT(0);
  100341. default:
  100342. if(0 != block.data.unknown.data)
  100343. free(block.data.unknown.data);
  100344. break;
  100345. }
  100346. }
  100347. }
  100348. if(is_last) {
  100349. /* if this fails, it's OK, it's just a hint for the seek routine */
  100350. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100351. decoder->private_->first_frame_offset = 0;
  100352. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100353. }
  100354. return true;
  100355. }
  100356. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100357. {
  100358. FLAC__uint32 x;
  100359. unsigned bits, used_bits = 0;
  100360. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100361. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100362. decoder->private_->stream_info.is_last = is_last;
  100363. decoder->private_->stream_info.length = length;
  100364. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100365. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100366. return false; /* read_callback_ sets the state for us */
  100367. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100368. used_bits += bits;
  100369. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100370. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100371. return false; /* read_callback_ sets the state for us */
  100372. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100373. used_bits += bits;
  100374. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100375. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100376. return false; /* read_callback_ sets the state for us */
  100377. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100378. used_bits += bits;
  100379. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100381. return false; /* read_callback_ sets the state for us */
  100382. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100383. used_bits += bits;
  100384. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100385. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100386. return false; /* read_callback_ sets the state for us */
  100387. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100388. used_bits += bits;
  100389. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100390. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100391. return false; /* read_callback_ sets the state for us */
  100392. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100393. used_bits += bits;
  100394. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100395. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100396. return false; /* read_callback_ sets the state for us */
  100397. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100398. used_bits += bits;
  100399. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100400. 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))
  100401. return false; /* read_callback_ sets the state for us */
  100402. used_bits += bits;
  100403. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100404. return false; /* read_callback_ sets the state for us */
  100405. used_bits += 16*8;
  100406. /* skip the rest of the block */
  100407. FLAC__ASSERT(used_bits % 8 == 0);
  100408. length -= (used_bits / 8);
  100409. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100410. return false; /* read_callback_ sets the state for us */
  100411. return true;
  100412. }
  100413. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100414. {
  100415. FLAC__uint32 i, x;
  100416. FLAC__uint64 xx;
  100417. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100418. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100419. decoder->private_->seek_table.is_last = is_last;
  100420. decoder->private_->seek_table.length = length;
  100421. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100422. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100423. 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)))) {
  100424. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100425. return false;
  100426. }
  100427. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100428. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100429. return false; /* read_callback_ sets the state for us */
  100430. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100431. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100432. return false; /* read_callback_ sets the state for us */
  100433. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100434. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100435. return false; /* read_callback_ sets the state for us */
  100436. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100437. }
  100438. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100439. /* if there is a partial point left, skip over it */
  100440. if(length > 0) {
  100441. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100442. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100443. return false; /* read_callback_ sets the state for us */
  100444. }
  100445. return true;
  100446. }
  100447. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100448. {
  100449. FLAC__uint32 i;
  100450. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100451. /* read vendor string */
  100452. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100453. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100454. return false; /* read_callback_ sets the state for us */
  100455. if(obj->vendor_string.length > 0) {
  100456. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100457. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100458. return false;
  100459. }
  100460. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100461. return false; /* read_callback_ sets the state for us */
  100462. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100463. }
  100464. else
  100465. obj->vendor_string.entry = 0;
  100466. /* read num comments */
  100467. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100468. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100469. return false; /* read_callback_ sets the state for us */
  100470. /* read comments */
  100471. if(obj->num_comments > 0) {
  100472. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100473. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100474. return false;
  100475. }
  100476. for(i = 0; i < obj->num_comments; i++) {
  100477. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100478. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100479. return false; /* read_callback_ sets the state for us */
  100480. if(obj->comments[i].length > 0) {
  100481. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100482. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100483. return false;
  100484. }
  100485. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100486. return false; /* read_callback_ sets the state for us */
  100487. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100488. }
  100489. else
  100490. obj->comments[i].entry = 0;
  100491. }
  100492. }
  100493. else {
  100494. obj->comments = 0;
  100495. }
  100496. return true;
  100497. }
  100498. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100499. {
  100500. FLAC__uint32 i, j, x;
  100501. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100502. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100503. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100504. 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))
  100505. return false; /* read_callback_ sets the state for us */
  100506. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100507. return false; /* read_callback_ sets the state for us */
  100508. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100509. return false; /* read_callback_ sets the state for us */
  100510. obj->is_cd = x? true : false;
  100511. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100512. return false; /* read_callback_ sets the state for us */
  100513. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100514. return false; /* read_callback_ sets the state for us */
  100515. obj->num_tracks = x;
  100516. if(obj->num_tracks > 0) {
  100517. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100518. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100519. return false;
  100520. }
  100521. for(i = 0; i < obj->num_tracks; i++) {
  100522. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100523. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100524. return false; /* read_callback_ sets the state for us */
  100525. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100526. return false; /* read_callback_ sets the state for us */
  100527. track->number = (FLAC__byte)x;
  100528. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100529. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100530. return false; /* read_callback_ sets the state for us */
  100531. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100532. return false; /* read_callback_ sets the state for us */
  100533. track->type = x;
  100534. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100535. return false; /* read_callback_ sets the state for us */
  100536. track->pre_emphasis = x;
  100537. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100538. return false; /* read_callback_ sets the state for us */
  100539. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100540. return false; /* read_callback_ sets the state for us */
  100541. track->num_indices = (FLAC__byte)x;
  100542. if(track->num_indices > 0) {
  100543. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100544. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100545. return false;
  100546. }
  100547. for(j = 0; j < track->num_indices; j++) {
  100548. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100549. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100550. return false; /* read_callback_ sets the state for us */
  100551. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100552. return false; /* read_callback_ sets the state for us */
  100553. index->number = (FLAC__byte)x;
  100554. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100555. return false; /* read_callback_ sets the state for us */
  100556. }
  100557. }
  100558. }
  100559. }
  100560. return true;
  100561. }
  100562. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100563. {
  100564. FLAC__uint32 x;
  100565. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100566. /* read type */
  100567. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100568. return false; /* read_callback_ sets the state for us */
  100569. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100570. /* read MIME type */
  100571. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100572. return false; /* read_callback_ sets the state for us */
  100573. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100574. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100575. return false;
  100576. }
  100577. if(x > 0) {
  100578. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100579. return false; /* read_callback_ sets the state for us */
  100580. }
  100581. obj->mime_type[x] = '\0';
  100582. /* read description */
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100584. return false; /* read_callback_ sets the state for us */
  100585. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100586. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100587. return false;
  100588. }
  100589. if(x > 0) {
  100590. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100591. return false; /* read_callback_ sets the state for us */
  100592. }
  100593. obj->description[x] = '\0';
  100594. /* read width */
  100595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100596. return false; /* read_callback_ sets the state for us */
  100597. /* read height */
  100598. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100599. return false; /* read_callback_ sets the state for us */
  100600. /* read depth */
  100601. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100602. return false; /* read_callback_ sets the state for us */
  100603. /* read colors */
  100604. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100605. return false; /* read_callback_ sets the state for us */
  100606. /* read data */
  100607. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100608. return false; /* read_callback_ sets the state for us */
  100609. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100610. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100611. return false;
  100612. }
  100613. if(obj->data_length > 0) {
  100614. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100615. return false; /* read_callback_ sets the state for us */
  100616. }
  100617. return true;
  100618. }
  100619. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100620. {
  100621. FLAC__uint32 x;
  100622. unsigned i, skip;
  100623. /* skip the version and flags bytes */
  100624. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100625. return false; /* read_callback_ sets the state for us */
  100626. /* get the size (in bytes) to skip */
  100627. skip = 0;
  100628. for(i = 0; i < 4; i++) {
  100629. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100630. return false; /* read_callback_ sets the state for us */
  100631. skip <<= 7;
  100632. skip |= (x & 0x7f);
  100633. }
  100634. /* skip the rest of the tag */
  100635. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100636. return false; /* read_callback_ sets the state for us */
  100637. return true;
  100638. }
  100639. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100640. {
  100641. FLAC__uint32 x;
  100642. FLAC__bool first = true;
  100643. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100644. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100645. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100646. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100647. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100648. return true;
  100649. }
  100650. }
  100651. /* make sure we're byte aligned */
  100652. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100653. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100654. return false; /* read_callback_ sets the state for us */
  100655. }
  100656. while(1) {
  100657. if(decoder->private_->cached) {
  100658. x = (FLAC__uint32)decoder->private_->lookahead;
  100659. decoder->private_->cached = false;
  100660. }
  100661. else {
  100662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100663. return false; /* read_callback_ sets the state for us */
  100664. }
  100665. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100666. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100667. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100668. return false; /* read_callback_ sets the state for us */
  100669. /* 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 */
  100670. /* else we have to check if the second byte is the end of a sync code */
  100671. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100672. decoder->private_->lookahead = (FLAC__byte)x;
  100673. decoder->private_->cached = true;
  100674. }
  100675. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100676. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100677. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100678. return true;
  100679. }
  100680. }
  100681. if(first) {
  100682. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100683. first = false;
  100684. }
  100685. }
  100686. return true;
  100687. }
  100688. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100689. {
  100690. unsigned channel;
  100691. unsigned i;
  100692. FLAC__int32 mid, side;
  100693. unsigned frame_crc; /* the one we calculate from the input stream */
  100694. FLAC__uint32 x;
  100695. *got_a_frame = false;
  100696. /* init the CRC */
  100697. frame_crc = 0;
  100698. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100699. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100700. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100701. if(!read_frame_header_(decoder))
  100702. return false;
  100703. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100704. return true;
  100705. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100706. return false;
  100707. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100708. /*
  100709. * first figure the correct bits-per-sample of the subframe
  100710. */
  100711. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100712. switch(decoder->private_->frame.header.channel_assignment) {
  100713. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100714. /* no adjustment needed */
  100715. break;
  100716. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100717. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100718. if(channel == 1)
  100719. bps++;
  100720. break;
  100721. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100722. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100723. if(channel == 0)
  100724. bps++;
  100725. break;
  100726. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100727. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100728. if(channel == 1)
  100729. bps++;
  100730. break;
  100731. default:
  100732. FLAC__ASSERT(0);
  100733. }
  100734. /*
  100735. * now read it
  100736. */
  100737. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100738. return false;
  100739. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100740. return true;
  100741. }
  100742. if(!read_zero_padding_(decoder))
  100743. return false;
  100744. 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) */
  100745. return true;
  100746. /*
  100747. * Read the frame CRC-16 from the footer and check
  100748. */
  100749. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100750. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100751. return false; /* read_callback_ sets the state for us */
  100752. if(frame_crc == x) {
  100753. if(do_full_decode) {
  100754. /* Undo any special channel coding */
  100755. switch(decoder->private_->frame.header.channel_assignment) {
  100756. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100757. /* do nothing */
  100758. break;
  100759. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100760. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100761. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100762. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100763. break;
  100764. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100765. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100766. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100767. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100768. break;
  100769. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100770. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100771. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100772. #if 1
  100773. mid = decoder->private_->output[0][i];
  100774. side = decoder->private_->output[1][i];
  100775. mid <<= 1;
  100776. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100777. decoder->private_->output[0][i] = (mid + side) >> 1;
  100778. decoder->private_->output[1][i] = (mid - side) >> 1;
  100779. #else
  100780. /* OPT: without 'side' temp variable */
  100781. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100782. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100783. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100784. #endif
  100785. }
  100786. break;
  100787. default:
  100788. FLAC__ASSERT(0);
  100789. break;
  100790. }
  100791. }
  100792. }
  100793. else {
  100794. /* Bad frame, emit error and zero the output signal */
  100795. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100796. if(do_full_decode) {
  100797. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100798. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100799. }
  100800. }
  100801. }
  100802. *got_a_frame = true;
  100803. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100804. if(decoder->private_->next_fixed_block_size)
  100805. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100806. /* put the latest values into the public section of the decoder instance */
  100807. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100808. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100809. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100810. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100811. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100812. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100813. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100814. /* write it */
  100815. if(do_full_decode) {
  100816. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100817. return false;
  100818. }
  100819. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100820. return true;
  100821. }
  100822. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100823. {
  100824. FLAC__uint32 x;
  100825. FLAC__uint64 xx;
  100826. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100827. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100828. unsigned raw_header_len;
  100829. FLAC__bool is_unparseable = false;
  100830. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100831. /* init the raw header with the saved bits from synchronization */
  100832. raw_header[0] = decoder->private_->header_warmup[0];
  100833. raw_header[1] = decoder->private_->header_warmup[1];
  100834. raw_header_len = 2;
  100835. /* check to make sure that reserved bit is 0 */
  100836. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100837. is_unparseable = true;
  100838. /*
  100839. * Note that along the way as we read the header, we look for a sync
  100840. * code inside. If we find one it would indicate that our original
  100841. * sync was bad since there cannot be a sync code in a valid header.
  100842. *
  100843. * Three kinds of things can go wrong when reading the frame header:
  100844. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100845. * If we don't find a sync code, it can end up looking like we read
  100846. * a valid but unparseable header, until getting to the frame header
  100847. * CRC. Even then we could get a false positive on the CRC.
  100848. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100849. * future encoder).
  100850. * 3) We may be on a damaged frame which appears valid but unparseable.
  100851. *
  100852. * For all these reasons, we try and read a complete frame header as
  100853. * long as it seems valid, even if unparseable, up until the frame
  100854. * header CRC.
  100855. */
  100856. /*
  100857. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100858. */
  100859. for(i = 0; i < 2; i++) {
  100860. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100861. return false; /* read_callback_ sets the state for us */
  100862. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100863. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100864. decoder->private_->lookahead = (FLAC__byte)x;
  100865. decoder->private_->cached = true;
  100866. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100867. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100868. return true;
  100869. }
  100870. raw_header[raw_header_len++] = (FLAC__byte)x;
  100871. }
  100872. switch(x = raw_header[2] >> 4) {
  100873. case 0:
  100874. is_unparseable = true;
  100875. break;
  100876. case 1:
  100877. decoder->private_->frame.header.blocksize = 192;
  100878. break;
  100879. case 2:
  100880. case 3:
  100881. case 4:
  100882. case 5:
  100883. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100884. break;
  100885. case 6:
  100886. case 7:
  100887. blocksize_hint = x;
  100888. break;
  100889. case 8:
  100890. case 9:
  100891. case 10:
  100892. case 11:
  100893. case 12:
  100894. case 13:
  100895. case 14:
  100896. case 15:
  100897. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100898. break;
  100899. default:
  100900. FLAC__ASSERT(0);
  100901. break;
  100902. }
  100903. switch(x = raw_header[2] & 0x0f) {
  100904. case 0:
  100905. if(decoder->private_->has_stream_info)
  100906. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100907. else
  100908. is_unparseable = true;
  100909. break;
  100910. case 1:
  100911. decoder->private_->frame.header.sample_rate = 88200;
  100912. break;
  100913. case 2:
  100914. decoder->private_->frame.header.sample_rate = 176400;
  100915. break;
  100916. case 3:
  100917. decoder->private_->frame.header.sample_rate = 192000;
  100918. break;
  100919. case 4:
  100920. decoder->private_->frame.header.sample_rate = 8000;
  100921. break;
  100922. case 5:
  100923. decoder->private_->frame.header.sample_rate = 16000;
  100924. break;
  100925. case 6:
  100926. decoder->private_->frame.header.sample_rate = 22050;
  100927. break;
  100928. case 7:
  100929. decoder->private_->frame.header.sample_rate = 24000;
  100930. break;
  100931. case 8:
  100932. decoder->private_->frame.header.sample_rate = 32000;
  100933. break;
  100934. case 9:
  100935. decoder->private_->frame.header.sample_rate = 44100;
  100936. break;
  100937. case 10:
  100938. decoder->private_->frame.header.sample_rate = 48000;
  100939. break;
  100940. case 11:
  100941. decoder->private_->frame.header.sample_rate = 96000;
  100942. break;
  100943. case 12:
  100944. case 13:
  100945. case 14:
  100946. sample_rate_hint = x;
  100947. break;
  100948. case 15:
  100949. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100950. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100951. return true;
  100952. default:
  100953. FLAC__ASSERT(0);
  100954. }
  100955. x = (unsigned)(raw_header[3] >> 4);
  100956. if(x & 8) {
  100957. decoder->private_->frame.header.channels = 2;
  100958. switch(x & 7) {
  100959. case 0:
  100960. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100961. break;
  100962. case 1:
  100963. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100964. break;
  100965. case 2:
  100966. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100967. break;
  100968. default:
  100969. is_unparseable = true;
  100970. break;
  100971. }
  100972. }
  100973. else {
  100974. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100975. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100976. }
  100977. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100978. case 0:
  100979. if(decoder->private_->has_stream_info)
  100980. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100981. else
  100982. is_unparseable = true;
  100983. break;
  100984. case 1:
  100985. decoder->private_->frame.header.bits_per_sample = 8;
  100986. break;
  100987. case 2:
  100988. decoder->private_->frame.header.bits_per_sample = 12;
  100989. break;
  100990. case 4:
  100991. decoder->private_->frame.header.bits_per_sample = 16;
  100992. break;
  100993. case 5:
  100994. decoder->private_->frame.header.bits_per_sample = 20;
  100995. break;
  100996. case 6:
  100997. decoder->private_->frame.header.bits_per_sample = 24;
  100998. break;
  100999. case 3:
  101000. case 7:
  101001. is_unparseable = true;
  101002. break;
  101003. default:
  101004. FLAC__ASSERT(0);
  101005. break;
  101006. }
  101007. /* check to make sure that reserved bit is 0 */
  101008. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101009. is_unparseable = true;
  101010. /* read the frame's starting sample number (or frame number as the case may be) */
  101011. if(
  101012. raw_header[1] & 0x01 ||
  101013. /*@@@ 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 */
  101014. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101015. ) { /* variable blocksize */
  101016. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101017. return false; /* read_callback_ sets the state for us */
  101018. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101019. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101020. decoder->private_->cached = true;
  101021. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101022. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101023. return true;
  101024. }
  101025. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101026. decoder->private_->frame.header.number.sample_number = xx;
  101027. }
  101028. else { /* fixed blocksize */
  101029. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101030. return false; /* read_callback_ sets the state for us */
  101031. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101032. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101033. decoder->private_->cached = true;
  101034. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101035. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101036. return true;
  101037. }
  101038. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101039. decoder->private_->frame.header.number.frame_number = x;
  101040. }
  101041. if(blocksize_hint) {
  101042. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101043. return false; /* read_callback_ sets the state for us */
  101044. raw_header[raw_header_len++] = (FLAC__byte)x;
  101045. if(blocksize_hint == 7) {
  101046. FLAC__uint32 _x;
  101047. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101048. return false; /* read_callback_ sets the state for us */
  101049. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101050. x = (x << 8) | _x;
  101051. }
  101052. decoder->private_->frame.header.blocksize = x+1;
  101053. }
  101054. if(sample_rate_hint) {
  101055. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101056. return false; /* read_callback_ sets the state for us */
  101057. raw_header[raw_header_len++] = (FLAC__byte)x;
  101058. if(sample_rate_hint != 12) {
  101059. FLAC__uint32 _x;
  101060. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101061. return false; /* read_callback_ sets the state for us */
  101062. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101063. x = (x << 8) | _x;
  101064. }
  101065. if(sample_rate_hint == 12)
  101066. decoder->private_->frame.header.sample_rate = x*1000;
  101067. else if(sample_rate_hint == 13)
  101068. decoder->private_->frame.header.sample_rate = x;
  101069. else
  101070. decoder->private_->frame.header.sample_rate = x*10;
  101071. }
  101072. /* read the CRC-8 byte */
  101073. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101074. return false; /* read_callback_ sets the state for us */
  101075. crc8 = (FLAC__byte)x;
  101076. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101077. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101078. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101079. return true;
  101080. }
  101081. /* calculate the sample number from the frame number if needed */
  101082. decoder->private_->next_fixed_block_size = 0;
  101083. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101084. x = decoder->private_->frame.header.number.frame_number;
  101085. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101086. if(decoder->private_->fixed_block_size)
  101087. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101088. else if(decoder->private_->has_stream_info) {
  101089. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101090. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101091. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101092. }
  101093. else
  101094. is_unparseable = true;
  101095. }
  101096. else if(x == 0) {
  101097. decoder->private_->frame.header.number.sample_number = 0;
  101098. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101099. }
  101100. else {
  101101. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101102. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101103. }
  101104. }
  101105. if(is_unparseable) {
  101106. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101107. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101108. return true;
  101109. }
  101110. return true;
  101111. }
  101112. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101113. {
  101114. FLAC__uint32 x;
  101115. FLAC__bool wasted_bits;
  101116. unsigned i;
  101117. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101118. return false; /* read_callback_ sets the state for us */
  101119. wasted_bits = (x & 1);
  101120. x &= 0xfe;
  101121. if(wasted_bits) {
  101122. unsigned u;
  101123. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101124. return false; /* read_callback_ sets the state for us */
  101125. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101126. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101127. }
  101128. else
  101129. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101130. /*
  101131. * Lots of magic numbers here
  101132. */
  101133. if(x & 0x80) {
  101134. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101135. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101136. return true;
  101137. }
  101138. else if(x == 0) {
  101139. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101140. return false;
  101141. }
  101142. else if(x == 2) {
  101143. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101144. return false;
  101145. }
  101146. else if(x < 16) {
  101147. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101148. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101149. return true;
  101150. }
  101151. else if(x <= 24) {
  101152. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101153. return false;
  101154. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101155. return true;
  101156. }
  101157. else if(x < 64) {
  101158. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101159. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101160. return true;
  101161. }
  101162. else {
  101163. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101164. return false;
  101165. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101166. return true;
  101167. }
  101168. if(wasted_bits && do_full_decode) {
  101169. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101170. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101171. decoder->private_->output[channel][i] <<= x;
  101172. }
  101173. return true;
  101174. }
  101175. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101176. {
  101177. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101178. FLAC__int32 x;
  101179. unsigned i;
  101180. FLAC__int32 *output = decoder->private_->output[channel];
  101181. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101182. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101183. return false; /* read_callback_ sets the state for us */
  101184. subframe->value = x;
  101185. /* decode the subframe */
  101186. if(do_full_decode) {
  101187. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101188. output[i] = x;
  101189. }
  101190. return true;
  101191. }
  101192. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101193. {
  101194. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101195. FLAC__int32 i32;
  101196. FLAC__uint32 u32;
  101197. unsigned u;
  101198. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101199. subframe->residual = decoder->private_->residual[channel];
  101200. subframe->order = order;
  101201. /* read warm-up samples */
  101202. for(u = 0; u < order; u++) {
  101203. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101204. return false; /* read_callback_ sets the state for us */
  101205. subframe->warmup[u] = i32;
  101206. }
  101207. /* read entropy coding method info */
  101208. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101209. return false; /* read_callback_ sets the state for us */
  101210. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101211. switch(subframe->entropy_coding_method.type) {
  101212. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101213. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101214. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101215. return false; /* read_callback_ sets the state for us */
  101216. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101217. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101218. break;
  101219. default:
  101220. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101221. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101222. return true;
  101223. }
  101224. /* read residual */
  101225. switch(subframe->entropy_coding_method.type) {
  101226. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101227. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101228. 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))
  101229. return false;
  101230. break;
  101231. default:
  101232. FLAC__ASSERT(0);
  101233. }
  101234. /* decode the subframe */
  101235. if(do_full_decode) {
  101236. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101237. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101238. }
  101239. return true;
  101240. }
  101241. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101242. {
  101243. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101244. FLAC__int32 i32;
  101245. FLAC__uint32 u32;
  101246. unsigned u;
  101247. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101248. subframe->residual = decoder->private_->residual[channel];
  101249. subframe->order = order;
  101250. /* read warm-up samples */
  101251. for(u = 0; u < order; u++) {
  101252. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101253. return false; /* read_callback_ sets the state for us */
  101254. subframe->warmup[u] = i32;
  101255. }
  101256. /* read qlp coeff precision */
  101257. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101258. return false; /* read_callback_ sets the state for us */
  101259. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101260. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101261. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101262. return true;
  101263. }
  101264. subframe->qlp_coeff_precision = u32+1;
  101265. /* read qlp shift */
  101266. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101267. return false; /* read_callback_ sets the state for us */
  101268. subframe->quantization_level = i32;
  101269. /* read quantized lp coefficiencts */
  101270. for(u = 0; u < order; u++) {
  101271. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101272. return false; /* read_callback_ sets the state for us */
  101273. subframe->qlp_coeff[u] = i32;
  101274. }
  101275. /* read entropy coding method info */
  101276. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101277. return false; /* read_callback_ sets the state for us */
  101278. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101279. switch(subframe->entropy_coding_method.type) {
  101280. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101281. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101282. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101283. return false; /* read_callback_ sets the state for us */
  101284. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101285. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101286. break;
  101287. default:
  101288. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101289. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101290. return true;
  101291. }
  101292. /* read residual */
  101293. switch(subframe->entropy_coding_method.type) {
  101294. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101295. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101296. 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))
  101297. return false;
  101298. break;
  101299. default:
  101300. FLAC__ASSERT(0);
  101301. }
  101302. /* decode the subframe */
  101303. if(do_full_decode) {
  101304. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101305. /*@@@@@@ technically not pessimistic enough, should be more like
  101306. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101307. */
  101308. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101309. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101310. if(order <= 8)
  101311. 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);
  101312. else
  101313. 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);
  101314. }
  101315. else
  101316. 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);
  101317. else
  101318. 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);
  101319. }
  101320. return true;
  101321. }
  101322. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101323. {
  101324. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101325. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101326. unsigned i;
  101327. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101328. subframe->data = residual;
  101329. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101330. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101331. return false; /* read_callback_ sets the state for us */
  101332. residual[i] = x;
  101333. }
  101334. /* decode the subframe */
  101335. if(do_full_decode)
  101336. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101337. return true;
  101338. }
  101339. 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)
  101340. {
  101341. FLAC__uint32 rice_parameter;
  101342. int i;
  101343. unsigned partition, sample, u;
  101344. const unsigned partitions = 1u << partition_order;
  101345. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101346. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101347. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101348. /* sanity checks */
  101349. if(partition_order == 0) {
  101350. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101351. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101352. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101353. return true;
  101354. }
  101355. }
  101356. else {
  101357. if(partition_samples < predictor_order) {
  101358. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101359. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101360. return true;
  101361. }
  101362. }
  101363. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101364. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101365. return false;
  101366. }
  101367. sample = 0;
  101368. for(partition = 0; partition < partitions; partition++) {
  101369. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101370. return false; /* read_callback_ sets the state for us */
  101371. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101372. if(rice_parameter < pesc) {
  101373. partitioned_rice_contents->raw_bits[partition] = 0;
  101374. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101375. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101376. return false; /* read_callback_ sets the state for us */
  101377. sample += u;
  101378. }
  101379. else {
  101380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101381. return false; /* read_callback_ sets the state for us */
  101382. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101383. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101384. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101385. return false; /* read_callback_ sets the state for us */
  101386. residual[sample] = i;
  101387. }
  101388. }
  101389. }
  101390. return true;
  101391. }
  101392. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101393. {
  101394. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101395. FLAC__uint32 zero = 0;
  101396. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101397. return false; /* read_callback_ sets the state for us */
  101398. if(zero != 0) {
  101399. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101400. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101401. }
  101402. }
  101403. return true;
  101404. }
  101405. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101406. {
  101407. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101408. if(
  101409. #if FLAC__HAS_OGG
  101410. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101411. !decoder->private_->is_ogg &&
  101412. #endif
  101413. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101414. ) {
  101415. *bytes = 0;
  101416. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101417. return false;
  101418. }
  101419. else if(*bytes > 0) {
  101420. /* While seeking, it is possible for our seek to land in the
  101421. * middle of audio data that looks exactly like a frame header
  101422. * from a future version of an encoder. When that happens, our
  101423. * error callback will get an
  101424. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101425. * unparseable_frame_count. But there is a remote possibility
  101426. * that it is properly synced at such a "future-codec frame",
  101427. * so to make sure, we wait to see many "unparseable" errors in
  101428. * a row before bailing out.
  101429. */
  101430. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101431. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101432. return false;
  101433. }
  101434. else {
  101435. const FLAC__StreamDecoderReadStatus status =
  101436. #if FLAC__HAS_OGG
  101437. decoder->private_->is_ogg?
  101438. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101439. #endif
  101440. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101441. ;
  101442. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101443. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101444. return false;
  101445. }
  101446. else if(*bytes == 0) {
  101447. if(
  101448. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101449. (
  101450. #if FLAC__HAS_OGG
  101451. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101452. !decoder->private_->is_ogg &&
  101453. #endif
  101454. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101455. )
  101456. ) {
  101457. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101458. return false;
  101459. }
  101460. else
  101461. return true;
  101462. }
  101463. else
  101464. return true;
  101465. }
  101466. }
  101467. else {
  101468. /* abort to avoid a deadlock */
  101469. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101470. return false;
  101471. }
  101472. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101473. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101474. * and at the same time hit the end of the stream (for example, seeking
  101475. * to a point that is after the beginning of the last Ogg page). There
  101476. * is no way to report an Ogg sync loss through the callbacks (see note
  101477. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101478. * So to keep the decoder from stopping at this point we gate the call
  101479. * to the eof_callback and let the Ogg decoder aspect set the
  101480. * end-of-stream state when it is needed.
  101481. */
  101482. }
  101483. #if FLAC__HAS_OGG
  101484. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101485. {
  101486. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101487. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101488. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101489. /* we don't really have a way to handle lost sync via read
  101490. * callback so we'll let it pass and let the underlying
  101491. * FLAC decoder catch the error
  101492. */
  101493. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101494. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101495. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101496. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101497. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101498. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101499. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101500. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101501. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101502. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101503. default:
  101504. FLAC__ASSERT(0);
  101505. /* double protection */
  101506. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101507. }
  101508. }
  101509. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101510. {
  101511. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101512. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101513. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101514. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101515. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101516. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101517. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101518. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101519. default:
  101520. /* double protection: */
  101521. FLAC__ASSERT(0);
  101522. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101523. }
  101524. }
  101525. #endif
  101526. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101527. {
  101528. if(decoder->private_->is_seeking) {
  101529. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101530. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101531. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101532. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101533. #if FLAC__HAS_OGG
  101534. decoder->private_->got_a_frame = true;
  101535. #endif
  101536. decoder->private_->last_frame = *frame; /* save the frame */
  101537. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101538. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101539. /* kick out of seek mode */
  101540. decoder->private_->is_seeking = false;
  101541. /* shift out the samples before target_sample */
  101542. if(delta > 0) {
  101543. unsigned channel;
  101544. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101545. for(channel = 0; channel < frame->header.channels; channel++)
  101546. newbuffer[channel] = buffer[channel] + delta;
  101547. decoder->private_->last_frame.header.blocksize -= delta;
  101548. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101549. /* write the relevant samples */
  101550. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101551. }
  101552. else {
  101553. /* write the relevant samples */
  101554. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101555. }
  101556. }
  101557. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101558. }
  101559. /*
  101560. * If we never got STREAMINFO, turn off MD5 checking to save
  101561. * cycles since we don't have a sum to compare to anyway
  101562. */
  101563. if(!decoder->private_->has_stream_info)
  101564. decoder->private_->do_md5_checking = false;
  101565. if(decoder->private_->do_md5_checking) {
  101566. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101567. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101568. }
  101569. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101570. }
  101571. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101572. {
  101573. if(!decoder->private_->is_seeking)
  101574. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101575. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101576. decoder->private_->unparseable_frame_count++;
  101577. }
  101578. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101579. {
  101580. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101581. FLAC__int64 pos = -1;
  101582. int i;
  101583. unsigned approx_bytes_per_frame;
  101584. FLAC__bool first_seek = true;
  101585. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101586. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101587. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101588. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101589. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101590. /* take these from the current frame in case they've changed mid-stream */
  101591. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101592. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101593. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101594. /* use values from stream info if we didn't decode a frame */
  101595. if(channels == 0)
  101596. channels = decoder->private_->stream_info.data.stream_info.channels;
  101597. if(bps == 0)
  101598. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101599. /* we are just guessing here */
  101600. if(max_framesize > 0)
  101601. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101602. /*
  101603. * Check if it's a known fixed-blocksize stream. Note that though
  101604. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101605. * never get a STREAMINFO block when decoding so the value of
  101606. * min_blocksize might be zero.
  101607. */
  101608. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101609. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101610. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101611. }
  101612. else
  101613. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101614. /*
  101615. * First, we set an upper and lower bound on where in the
  101616. * stream we will search. For now we assume the worst case
  101617. * scenario, which is our best guess at the beginning of
  101618. * the first frame and end of the stream.
  101619. */
  101620. lower_bound = first_frame_offset;
  101621. lower_bound_sample = 0;
  101622. upper_bound = stream_length;
  101623. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101624. /*
  101625. * Now we refine the bounds if we have a seektable with
  101626. * suitable points. Note that according to the spec they
  101627. * must be ordered by ascending sample number.
  101628. *
  101629. * Note: to protect against invalid seek tables we will ignore points
  101630. * that have frame_samples==0 or sample_number>=total_samples
  101631. */
  101632. if(seek_table) {
  101633. FLAC__uint64 new_lower_bound = lower_bound;
  101634. FLAC__uint64 new_upper_bound = upper_bound;
  101635. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101636. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101637. /* find the closest seek point <= target_sample, if it exists */
  101638. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101639. if(
  101640. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101641. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101642. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101643. seek_table->points[i].sample_number <= target_sample
  101644. )
  101645. break;
  101646. }
  101647. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101648. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101649. new_lower_bound_sample = seek_table->points[i].sample_number;
  101650. }
  101651. /* find the closest seek point > target_sample, if it exists */
  101652. for(i = 0; i < (int)seek_table->num_points; i++) {
  101653. if(
  101654. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101655. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101656. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101657. seek_table->points[i].sample_number > target_sample
  101658. )
  101659. break;
  101660. }
  101661. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101662. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101663. new_upper_bound_sample = seek_table->points[i].sample_number;
  101664. }
  101665. /* final protection against unsorted seek tables; keep original values if bogus */
  101666. if(new_upper_bound >= new_lower_bound) {
  101667. lower_bound = new_lower_bound;
  101668. upper_bound = new_upper_bound;
  101669. lower_bound_sample = new_lower_bound_sample;
  101670. upper_bound_sample = new_upper_bound_sample;
  101671. }
  101672. }
  101673. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101674. /* there are 2 insidious ways that the following equality occurs, which
  101675. * we need to fix:
  101676. * 1) total_samples is 0 (unknown) and target_sample is 0
  101677. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101678. * exactly equal to the last seek point in the seek table; this
  101679. * means there is no seek point above it, and upper_bound_samples
  101680. * remains equal to the estimate (of target_samples) we made above
  101681. * in either case it does not hurt to move upper_bound_sample up by 1
  101682. */
  101683. if(upper_bound_sample == lower_bound_sample)
  101684. upper_bound_sample++;
  101685. decoder->private_->target_sample = target_sample;
  101686. while(1) {
  101687. /* check if the bounds are still ok */
  101688. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101689. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101690. return false;
  101691. }
  101692. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101693. #if defined _MSC_VER || defined __MINGW32__
  101694. /* with VC++ you have to spoon feed it the casting */
  101695. 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;
  101696. #else
  101697. 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;
  101698. #endif
  101699. #else
  101700. /* a little less accurate: */
  101701. if(upper_bound - lower_bound < 0xffffffff)
  101702. 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;
  101703. else /* @@@ WATCHOUT, ~2TB limit */
  101704. 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;
  101705. #endif
  101706. if(pos >= (FLAC__int64)upper_bound)
  101707. pos = (FLAC__int64)upper_bound - 1;
  101708. if(pos < (FLAC__int64)lower_bound)
  101709. pos = (FLAC__int64)lower_bound;
  101710. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101711. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101712. return false;
  101713. }
  101714. if(!FLAC__stream_decoder_flush(decoder)) {
  101715. /* above call sets the state for us */
  101716. return false;
  101717. }
  101718. /* Now we need to get a frame. First we need to reset our
  101719. * unparseable_frame_count; if we get too many unparseable
  101720. * frames in a row, the read callback will return
  101721. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101722. * FLAC__stream_decoder_process_single() to return false.
  101723. */
  101724. decoder->private_->unparseable_frame_count = 0;
  101725. if(!FLAC__stream_decoder_process_single(decoder)) {
  101726. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101727. return false;
  101728. }
  101729. /* our write callback will change the state when it gets to the target frame */
  101730. /* 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 */
  101731. #if 0
  101732. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101733. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101734. break;
  101735. #endif
  101736. if(!decoder->private_->is_seeking)
  101737. break;
  101738. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101739. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101740. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101741. if (pos == (FLAC__int64)lower_bound) {
  101742. /* can't move back any more than the first frame, something is fatally wrong */
  101743. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101744. return false;
  101745. }
  101746. /* our last move backwards wasn't big enough, try again */
  101747. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101748. continue;
  101749. }
  101750. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101751. first_seek = false;
  101752. /* make sure we are not seeking in corrupted stream */
  101753. if (this_frame_sample < lower_bound_sample) {
  101754. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101755. return false;
  101756. }
  101757. /* we need to narrow the search */
  101758. if(target_sample < this_frame_sample) {
  101759. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101760. /*@@@@@@ what will decode position be if at end of stream? */
  101761. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101762. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101763. return false;
  101764. }
  101765. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101766. }
  101767. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101768. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101769. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101770. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101771. return false;
  101772. }
  101773. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101774. }
  101775. }
  101776. return true;
  101777. }
  101778. #if FLAC__HAS_OGG
  101779. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101780. {
  101781. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101782. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101783. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101784. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101785. FLAC__bool did_a_seek;
  101786. unsigned iteration = 0;
  101787. /* In the first iterations, we will calculate the target byte position
  101788. * by the distance from the target sample to left_sample and
  101789. * right_sample (let's call it "proportional search"). After that, we
  101790. * will switch to binary search.
  101791. */
  101792. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101793. /* We will switch to a linear search once our current sample is less
  101794. * than this number of samples ahead of the target sample
  101795. */
  101796. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101797. /* If the total number of samples is unknown, use a large value, and
  101798. * force binary search immediately.
  101799. */
  101800. if(right_sample == 0) {
  101801. right_sample = (FLAC__uint64)(-1);
  101802. BINARY_SEARCH_AFTER_ITERATION = 0;
  101803. }
  101804. decoder->private_->target_sample = target_sample;
  101805. for( ; ; iteration++) {
  101806. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101807. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101808. pos = (right_pos + left_pos) / 2;
  101809. }
  101810. else {
  101811. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101812. #if defined _MSC_VER || defined __MINGW32__
  101813. /* with MSVC you have to spoon feed it the casting */
  101814. 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));
  101815. #else
  101816. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101817. #endif
  101818. #else
  101819. /* a little less accurate: */
  101820. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101821. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101822. else /* @@@ WATCHOUT, ~2TB limit */
  101823. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101824. #endif
  101825. /* @@@ TODO: might want to limit pos to some distance
  101826. * before EOF, to make sure we land before the last frame,
  101827. * thereby getting a this_frame_sample and so having a better
  101828. * estimate.
  101829. */
  101830. }
  101831. /* physical seek */
  101832. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101833. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101834. return false;
  101835. }
  101836. if(!FLAC__stream_decoder_flush(decoder)) {
  101837. /* above call sets the state for us */
  101838. return false;
  101839. }
  101840. did_a_seek = true;
  101841. }
  101842. else
  101843. did_a_seek = false;
  101844. decoder->private_->got_a_frame = false;
  101845. if(!FLAC__stream_decoder_process_single(decoder)) {
  101846. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101847. return false;
  101848. }
  101849. if(!decoder->private_->got_a_frame) {
  101850. if(did_a_seek) {
  101851. /* this can happen if we seek to a point after the last frame; we drop
  101852. * to binary search right away in this case to avoid any wasted
  101853. * iterations of proportional search.
  101854. */
  101855. right_pos = pos;
  101856. BINARY_SEARCH_AFTER_ITERATION = 0;
  101857. }
  101858. else {
  101859. /* this can probably only happen if total_samples is unknown and the
  101860. * target_sample is past the end of the stream
  101861. */
  101862. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101863. return false;
  101864. }
  101865. }
  101866. /* our write callback will change the state when it gets to the target frame */
  101867. else if(!decoder->private_->is_seeking) {
  101868. break;
  101869. }
  101870. else {
  101871. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101872. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101873. if (did_a_seek) {
  101874. if (this_frame_sample <= target_sample) {
  101875. /* The 'equal' case should not happen, since
  101876. * FLAC__stream_decoder_process_single()
  101877. * should recognize that it has hit the
  101878. * target sample and we would exit through
  101879. * the 'break' above.
  101880. */
  101881. FLAC__ASSERT(this_frame_sample != target_sample);
  101882. left_sample = this_frame_sample;
  101883. /* sanity check to avoid infinite loop */
  101884. if (left_pos == pos) {
  101885. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101886. return false;
  101887. }
  101888. left_pos = pos;
  101889. }
  101890. else if(this_frame_sample > target_sample) {
  101891. right_sample = this_frame_sample;
  101892. /* sanity check to avoid infinite loop */
  101893. if (right_pos == pos) {
  101894. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101895. return false;
  101896. }
  101897. right_pos = pos;
  101898. }
  101899. }
  101900. }
  101901. }
  101902. return true;
  101903. }
  101904. #endif
  101905. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101906. {
  101907. (void)client_data;
  101908. if(*bytes > 0) {
  101909. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101910. if(ferror(decoder->private_->file))
  101911. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101912. else if(*bytes == 0)
  101913. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101914. else
  101915. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101916. }
  101917. else
  101918. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101919. }
  101920. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101921. {
  101922. (void)client_data;
  101923. if(decoder->private_->file == stdin)
  101924. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101925. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101926. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101927. else
  101928. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101929. }
  101930. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101931. {
  101932. off_t pos;
  101933. (void)client_data;
  101934. if(decoder->private_->file == stdin)
  101935. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101936. else if((pos = ftello(decoder->private_->file)) < 0)
  101937. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101938. else {
  101939. *absolute_byte_offset = (FLAC__uint64)pos;
  101940. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101941. }
  101942. }
  101943. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101944. {
  101945. struct stat filestats;
  101946. (void)client_data;
  101947. if(decoder->private_->file == stdin)
  101948. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101949. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101950. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101951. else {
  101952. *stream_length = (FLAC__uint64)filestats.st_size;
  101953. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101954. }
  101955. }
  101956. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101957. {
  101958. (void)client_data;
  101959. return feof(decoder->private_->file)? true : false;
  101960. }
  101961. #endif
  101962. /*** End of inlined file: stream_decoder.c ***/
  101963. /*** Start of inlined file: stream_encoder.c ***/
  101964. /*** Start of inlined file: juce_FlacHeader.h ***/
  101965. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101966. // tasks..
  101967. #define VERSION "1.2.1"
  101968. #define FLAC__NO_DLL 1
  101969. #if JUCE_MSVC
  101970. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101971. #endif
  101972. #if JUCE_MAC
  101973. #define FLAC__SYS_DARWIN 1
  101974. #endif
  101975. /*** End of inlined file: juce_FlacHeader.h ***/
  101976. #if JUCE_USE_FLAC
  101977. #if HAVE_CONFIG_H
  101978. # include <config.h>
  101979. #endif
  101980. #if defined _MSC_VER || defined __MINGW32__
  101981. #include <io.h> /* for _setmode() */
  101982. #include <fcntl.h> /* for _O_BINARY */
  101983. #endif
  101984. #if defined __CYGWIN__ || defined __EMX__
  101985. #include <io.h> /* for setmode(), O_BINARY */
  101986. #include <fcntl.h> /* for _O_BINARY */
  101987. #endif
  101988. #include <limits.h>
  101989. #include <stdio.h>
  101990. #include <stdlib.h> /* for malloc() */
  101991. #include <string.h> /* for memcpy() */
  101992. #include <sys/types.h> /* for off_t */
  101993. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101994. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101995. #define fseeko fseek
  101996. #define ftello ftell
  101997. #endif
  101998. #endif
  101999. /*** Start of inlined file: stream_encoder.h ***/
  102000. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102001. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102002. #if FLAC__HAS_OGG
  102003. #include "private/ogg_encoder_aspect.h"
  102004. #endif
  102005. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102006. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102007. typedef enum {
  102008. FLAC__APODIZATION_BARTLETT,
  102009. FLAC__APODIZATION_BARTLETT_HANN,
  102010. FLAC__APODIZATION_BLACKMAN,
  102011. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102012. FLAC__APODIZATION_CONNES,
  102013. FLAC__APODIZATION_FLATTOP,
  102014. FLAC__APODIZATION_GAUSS,
  102015. FLAC__APODIZATION_HAMMING,
  102016. FLAC__APODIZATION_HANN,
  102017. FLAC__APODIZATION_KAISER_BESSEL,
  102018. FLAC__APODIZATION_NUTTALL,
  102019. FLAC__APODIZATION_RECTANGLE,
  102020. FLAC__APODIZATION_TRIANGLE,
  102021. FLAC__APODIZATION_TUKEY,
  102022. FLAC__APODIZATION_WELCH
  102023. } FLAC__ApodizationFunction;
  102024. typedef struct {
  102025. FLAC__ApodizationFunction type;
  102026. union {
  102027. struct {
  102028. FLAC__real stddev;
  102029. } gauss;
  102030. struct {
  102031. FLAC__real p;
  102032. } tukey;
  102033. } parameters;
  102034. } FLAC__ApodizationSpecification;
  102035. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102036. typedef struct FLAC__StreamEncoderProtected {
  102037. FLAC__StreamEncoderState state;
  102038. FLAC__bool verify;
  102039. FLAC__bool streamable_subset;
  102040. FLAC__bool do_md5;
  102041. FLAC__bool do_mid_side_stereo;
  102042. FLAC__bool loose_mid_side_stereo;
  102043. unsigned channels;
  102044. unsigned bits_per_sample;
  102045. unsigned sample_rate;
  102046. unsigned blocksize;
  102047. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102048. unsigned num_apodizations;
  102049. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102050. #endif
  102051. unsigned max_lpc_order;
  102052. unsigned qlp_coeff_precision;
  102053. FLAC__bool do_qlp_coeff_prec_search;
  102054. FLAC__bool do_exhaustive_model_search;
  102055. FLAC__bool do_escape_coding;
  102056. unsigned min_residual_partition_order;
  102057. unsigned max_residual_partition_order;
  102058. unsigned rice_parameter_search_dist;
  102059. FLAC__uint64 total_samples_estimate;
  102060. FLAC__StreamMetadata **metadata;
  102061. unsigned num_metadata_blocks;
  102062. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102063. #if FLAC__HAS_OGG
  102064. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102065. #endif
  102066. } FLAC__StreamEncoderProtected;
  102067. #endif
  102068. /*** End of inlined file: stream_encoder.h ***/
  102069. #if FLAC__HAS_OGG
  102070. #include "include/private/ogg_helper.h"
  102071. #include "include/private/ogg_mapping.h"
  102072. #endif
  102073. /*** Start of inlined file: stream_encoder_framing.h ***/
  102074. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102075. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102076. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102077. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102078. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102079. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102080. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102081. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102082. #endif
  102083. /*** End of inlined file: stream_encoder_framing.h ***/
  102084. /*** Start of inlined file: window.h ***/
  102085. #ifndef FLAC__PRIVATE__WINDOW_H
  102086. #define FLAC__PRIVATE__WINDOW_H
  102087. #ifdef HAVE_CONFIG_H
  102088. #include <config.h>
  102089. #endif
  102090. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102091. /*
  102092. * FLAC__window_*()
  102093. * --------------------------------------------------------------------
  102094. * Calculates window coefficients according to different apodization
  102095. * functions.
  102096. *
  102097. * OUT window[0,L-1]
  102098. * IN L (number of points in window)
  102099. */
  102100. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102101. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102102. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102103. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102104. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102105. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102106. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102107. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102108. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102109. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102110. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102111. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102112. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102113. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102114. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102115. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102116. #endif
  102117. /*** End of inlined file: window.h ***/
  102118. #ifndef FLaC__INLINE
  102119. #define FLaC__INLINE
  102120. #endif
  102121. #ifdef min
  102122. #undef min
  102123. #endif
  102124. #define min(x,y) ((x)<(y)?(x):(y))
  102125. #ifdef max
  102126. #undef max
  102127. #endif
  102128. #define max(x,y) ((x)>(y)?(x):(y))
  102129. /* Exact Rice codeword length calculation is off by default. The simple
  102130. * (and fast) estimation (of how many bits a residual value will be
  102131. * encoded with) in this encoder is very good, almost always yielding
  102132. * compression within 0.1% of exact calculation.
  102133. */
  102134. #undef EXACT_RICE_BITS_CALCULATION
  102135. /* Rice parameter searching is off by default. The simple (and fast)
  102136. * parameter estimation in this encoder is very good, almost always
  102137. * yielding compression within 0.1% of the optimal parameters.
  102138. */
  102139. #undef ENABLE_RICE_PARAMETER_SEARCH
  102140. typedef struct {
  102141. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102142. unsigned size; /* of each data[] in samples */
  102143. unsigned tail;
  102144. } verify_input_fifo;
  102145. typedef struct {
  102146. const FLAC__byte *data;
  102147. unsigned capacity;
  102148. unsigned bytes;
  102149. } verify_output;
  102150. typedef enum {
  102151. ENCODER_IN_MAGIC = 0,
  102152. ENCODER_IN_METADATA = 1,
  102153. ENCODER_IN_AUDIO = 2
  102154. } EncoderStateHint;
  102155. static struct CompressionLevels {
  102156. FLAC__bool do_mid_side_stereo;
  102157. FLAC__bool loose_mid_side_stereo;
  102158. unsigned max_lpc_order;
  102159. unsigned qlp_coeff_precision;
  102160. FLAC__bool do_qlp_coeff_prec_search;
  102161. FLAC__bool do_escape_coding;
  102162. FLAC__bool do_exhaustive_model_search;
  102163. unsigned min_residual_partition_order;
  102164. unsigned max_residual_partition_order;
  102165. unsigned rice_parameter_search_dist;
  102166. } compression_levels_[] = {
  102167. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102168. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102169. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102170. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102171. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102172. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102173. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102174. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102175. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102176. };
  102177. /***********************************************************************
  102178. *
  102179. * Private class method prototypes
  102180. *
  102181. ***********************************************************************/
  102182. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102183. static void free_(FLAC__StreamEncoder *encoder);
  102184. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102185. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102186. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102187. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102188. #if FLAC__HAS_OGG
  102189. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102190. #endif
  102191. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102192. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102193. static FLAC__bool process_subframe_(
  102194. FLAC__StreamEncoder *encoder,
  102195. unsigned min_partition_order,
  102196. unsigned max_partition_order,
  102197. const FLAC__FrameHeader *frame_header,
  102198. unsigned subframe_bps,
  102199. const FLAC__int32 integer_signal[],
  102200. FLAC__Subframe *subframe[2],
  102201. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102202. FLAC__int32 *residual[2],
  102203. unsigned *best_subframe,
  102204. unsigned *best_bits
  102205. );
  102206. static FLAC__bool add_subframe_(
  102207. FLAC__StreamEncoder *encoder,
  102208. unsigned blocksize,
  102209. unsigned subframe_bps,
  102210. const FLAC__Subframe *subframe,
  102211. FLAC__BitWriter *frame
  102212. );
  102213. static unsigned evaluate_constant_subframe_(
  102214. FLAC__StreamEncoder *encoder,
  102215. const FLAC__int32 signal,
  102216. unsigned blocksize,
  102217. unsigned subframe_bps,
  102218. FLAC__Subframe *subframe
  102219. );
  102220. static unsigned evaluate_fixed_subframe_(
  102221. FLAC__StreamEncoder *encoder,
  102222. const FLAC__int32 signal[],
  102223. FLAC__int32 residual[],
  102224. FLAC__uint64 abs_residual_partition_sums[],
  102225. unsigned raw_bits_per_partition[],
  102226. unsigned blocksize,
  102227. unsigned subframe_bps,
  102228. unsigned order,
  102229. unsigned rice_parameter,
  102230. unsigned rice_parameter_limit,
  102231. unsigned min_partition_order,
  102232. unsigned max_partition_order,
  102233. FLAC__bool do_escape_coding,
  102234. unsigned rice_parameter_search_dist,
  102235. FLAC__Subframe *subframe,
  102236. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102237. );
  102238. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102239. static unsigned evaluate_lpc_subframe_(
  102240. FLAC__StreamEncoder *encoder,
  102241. const FLAC__int32 signal[],
  102242. FLAC__int32 residual[],
  102243. FLAC__uint64 abs_residual_partition_sums[],
  102244. unsigned raw_bits_per_partition[],
  102245. const FLAC__real lp_coeff[],
  102246. unsigned blocksize,
  102247. unsigned subframe_bps,
  102248. unsigned order,
  102249. unsigned qlp_coeff_precision,
  102250. unsigned rice_parameter,
  102251. unsigned rice_parameter_limit,
  102252. unsigned min_partition_order,
  102253. unsigned max_partition_order,
  102254. FLAC__bool do_escape_coding,
  102255. unsigned rice_parameter_search_dist,
  102256. FLAC__Subframe *subframe,
  102257. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102258. );
  102259. #endif
  102260. static unsigned evaluate_verbatim_subframe_(
  102261. FLAC__StreamEncoder *encoder,
  102262. const FLAC__int32 signal[],
  102263. unsigned blocksize,
  102264. unsigned subframe_bps,
  102265. FLAC__Subframe *subframe
  102266. );
  102267. static unsigned find_best_partition_order_(
  102268. struct FLAC__StreamEncoderPrivate *private_,
  102269. const FLAC__int32 residual[],
  102270. FLAC__uint64 abs_residual_partition_sums[],
  102271. unsigned raw_bits_per_partition[],
  102272. unsigned residual_samples,
  102273. unsigned predictor_order,
  102274. unsigned rice_parameter,
  102275. unsigned rice_parameter_limit,
  102276. unsigned min_partition_order,
  102277. unsigned max_partition_order,
  102278. unsigned bps,
  102279. FLAC__bool do_escape_coding,
  102280. unsigned rice_parameter_search_dist,
  102281. FLAC__EntropyCodingMethod *best_ecm
  102282. );
  102283. static void precompute_partition_info_sums_(
  102284. const FLAC__int32 residual[],
  102285. FLAC__uint64 abs_residual_partition_sums[],
  102286. unsigned residual_samples,
  102287. unsigned predictor_order,
  102288. unsigned min_partition_order,
  102289. unsigned max_partition_order,
  102290. unsigned bps
  102291. );
  102292. static void precompute_partition_info_escapes_(
  102293. const FLAC__int32 residual[],
  102294. unsigned raw_bits_per_partition[],
  102295. unsigned residual_samples,
  102296. unsigned predictor_order,
  102297. unsigned min_partition_order,
  102298. unsigned max_partition_order
  102299. );
  102300. static FLAC__bool set_partitioned_rice_(
  102301. #ifdef EXACT_RICE_BITS_CALCULATION
  102302. const FLAC__int32 residual[],
  102303. #endif
  102304. const FLAC__uint64 abs_residual_partition_sums[],
  102305. const unsigned raw_bits_per_partition[],
  102306. const unsigned residual_samples,
  102307. const unsigned predictor_order,
  102308. const unsigned suggested_rice_parameter,
  102309. const unsigned rice_parameter_limit,
  102310. const unsigned rice_parameter_search_dist,
  102311. const unsigned partition_order,
  102312. const FLAC__bool search_for_escapes,
  102313. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102314. unsigned *bits
  102315. );
  102316. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102317. /* verify-related routines: */
  102318. static void append_to_verify_fifo_(
  102319. verify_input_fifo *fifo,
  102320. const FLAC__int32 * const input[],
  102321. unsigned input_offset,
  102322. unsigned channels,
  102323. unsigned wide_samples
  102324. );
  102325. static void append_to_verify_fifo_interleaved_(
  102326. verify_input_fifo *fifo,
  102327. const FLAC__int32 input[],
  102328. unsigned input_offset,
  102329. unsigned channels,
  102330. unsigned wide_samples
  102331. );
  102332. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102333. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102334. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102335. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102336. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102337. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102338. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102339. 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);
  102340. static FILE *get_binary_stdout_(void);
  102341. /***********************************************************************
  102342. *
  102343. * Private class data
  102344. *
  102345. ***********************************************************************/
  102346. typedef struct FLAC__StreamEncoderPrivate {
  102347. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102348. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102349. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102350. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102351. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102352. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102353. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102354. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102355. #endif
  102356. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102357. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102358. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102359. FLAC__int32 *residual_workspace_mid_side[2][2];
  102360. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102361. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102362. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102363. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102364. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102365. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102366. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102367. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102368. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102369. unsigned best_subframe_mid_side[2];
  102370. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102371. unsigned best_subframe_bits_mid_side[2];
  102372. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102373. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102374. FLAC__BitWriter *frame; /* the current frame being worked on */
  102375. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102376. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102377. FLAC__ChannelAssignment last_channel_assignment;
  102378. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102379. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102380. unsigned current_sample_number;
  102381. unsigned current_frame_number;
  102382. FLAC__MD5Context md5context;
  102383. FLAC__CPUInfo cpuinfo;
  102384. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102385. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102386. #else
  102387. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102388. #endif
  102389. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102390. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102391. 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[]);
  102392. 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[]);
  102393. 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[]);
  102394. #endif
  102395. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102396. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102397. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102398. FLAC__bool disable_constant_subframes;
  102399. FLAC__bool disable_fixed_subframes;
  102400. FLAC__bool disable_verbatim_subframes;
  102401. #if FLAC__HAS_OGG
  102402. FLAC__bool is_ogg;
  102403. #endif
  102404. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102405. FLAC__StreamEncoderSeekCallback seek_callback;
  102406. FLAC__StreamEncoderTellCallback tell_callback;
  102407. FLAC__StreamEncoderWriteCallback write_callback;
  102408. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102409. FLAC__StreamEncoderProgressCallback progress_callback;
  102410. void *client_data;
  102411. unsigned first_seekpoint_to_check;
  102412. FILE *file; /* only used when encoding to a file */
  102413. FLAC__uint64 bytes_written;
  102414. FLAC__uint64 samples_written;
  102415. unsigned frames_written;
  102416. unsigned total_frames_estimate;
  102417. /* unaligned (original) pointers to allocated data */
  102418. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102419. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102420. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102421. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102422. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102423. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102424. FLAC__real *windowed_signal_unaligned;
  102425. #endif
  102426. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102427. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102428. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102429. unsigned *raw_bits_per_partition_unaligned;
  102430. /*
  102431. * These fields have been moved here from private function local
  102432. * declarations merely to save stack space during encoding.
  102433. */
  102434. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102435. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102436. #endif
  102437. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102438. /*
  102439. * The data for the verify section
  102440. */
  102441. struct {
  102442. FLAC__StreamDecoder *decoder;
  102443. EncoderStateHint state_hint;
  102444. FLAC__bool needs_magic_hack;
  102445. verify_input_fifo input_fifo;
  102446. verify_output output;
  102447. struct {
  102448. FLAC__uint64 absolute_sample;
  102449. unsigned frame_number;
  102450. unsigned channel;
  102451. unsigned sample;
  102452. FLAC__int32 expected;
  102453. FLAC__int32 got;
  102454. } error_stats;
  102455. } verify;
  102456. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102457. } FLAC__StreamEncoderPrivate;
  102458. /***********************************************************************
  102459. *
  102460. * Public static class data
  102461. *
  102462. ***********************************************************************/
  102463. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102464. "FLAC__STREAM_ENCODER_OK",
  102465. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102466. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102467. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102468. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102469. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102470. "FLAC__STREAM_ENCODER_IO_ERROR",
  102471. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102472. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102473. };
  102474. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102475. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102476. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102477. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102478. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102479. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102480. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102481. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102482. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102483. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102484. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102485. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102486. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102487. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102488. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102489. };
  102490. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102491. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102492. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102493. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102494. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102495. };
  102496. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102497. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102498. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102499. };
  102500. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102501. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102502. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102503. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102504. };
  102505. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102506. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102507. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102508. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102509. };
  102510. /* Number of samples that will be overread to watch for end of stream. By
  102511. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102512. * always try to read blocksize+1 samples before encoding a block, so that
  102513. * even if the stream has a total sample count that is an integral multiple
  102514. * of the blocksize, we will still notice when we are encoding the last
  102515. * block. This is needed, for example, to correctly set the end-of-stream
  102516. * marker in Ogg FLAC.
  102517. *
  102518. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102519. * not really any reason to change it.
  102520. */
  102521. static const unsigned OVERREAD_ = 1;
  102522. /***********************************************************************
  102523. *
  102524. * Class constructor/destructor
  102525. *
  102526. */
  102527. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102528. {
  102529. FLAC__StreamEncoder *encoder;
  102530. unsigned i;
  102531. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102532. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102533. if(encoder == 0) {
  102534. return 0;
  102535. }
  102536. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102537. if(encoder->protected_ == 0) {
  102538. free(encoder);
  102539. return 0;
  102540. }
  102541. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102542. if(encoder->private_ == 0) {
  102543. free(encoder->protected_);
  102544. free(encoder);
  102545. return 0;
  102546. }
  102547. encoder->private_->frame = FLAC__bitwriter_new();
  102548. if(encoder->private_->frame == 0) {
  102549. free(encoder->private_);
  102550. free(encoder->protected_);
  102551. free(encoder);
  102552. return 0;
  102553. }
  102554. encoder->private_->file = 0;
  102555. set_defaults_enc(encoder);
  102556. encoder->private_->is_being_deleted = false;
  102557. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102558. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102559. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102560. }
  102561. for(i = 0; i < 2; i++) {
  102562. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102563. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102564. }
  102565. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102566. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102567. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102568. }
  102569. for(i = 0; i < 2; i++) {
  102570. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102571. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102572. }
  102573. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102574. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102575. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102576. }
  102577. for(i = 0; i < 2; i++) {
  102578. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102579. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102580. }
  102581. for(i = 0; i < 2; i++)
  102582. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102583. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102584. return encoder;
  102585. }
  102586. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102587. {
  102588. unsigned i;
  102589. FLAC__ASSERT(0 != encoder);
  102590. FLAC__ASSERT(0 != encoder->protected_);
  102591. FLAC__ASSERT(0 != encoder->private_);
  102592. FLAC__ASSERT(0 != encoder->private_->frame);
  102593. encoder->private_->is_being_deleted = true;
  102594. (void)FLAC__stream_encoder_finish(encoder);
  102595. if(0 != encoder->private_->verify.decoder)
  102596. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102597. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102598. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102599. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102600. }
  102601. for(i = 0; i < 2; i++) {
  102602. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102603. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102604. }
  102605. for(i = 0; i < 2; i++)
  102606. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102607. FLAC__bitwriter_delete(encoder->private_->frame);
  102608. free(encoder->private_);
  102609. free(encoder->protected_);
  102610. free(encoder);
  102611. }
  102612. /***********************************************************************
  102613. *
  102614. * Public class methods
  102615. *
  102616. ***********************************************************************/
  102617. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102618. FLAC__StreamEncoder *encoder,
  102619. FLAC__StreamEncoderReadCallback read_callback,
  102620. FLAC__StreamEncoderWriteCallback write_callback,
  102621. FLAC__StreamEncoderSeekCallback seek_callback,
  102622. FLAC__StreamEncoderTellCallback tell_callback,
  102623. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102624. void *client_data,
  102625. FLAC__bool is_ogg
  102626. )
  102627. {
  102628. unsigned i;
  102629. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102630. FLAC__ASSERT(0 != encoder);
  102631. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102632. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102633. #if !FLAC__HAS_OGG
  102634. if(is_ogg)
  102635. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102636. #endif
  102637. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102638. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102639. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102640. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102641. if(encoder->protected_->channels != 2) {
  102642. encoder->protected_->do_mid_side_stereo = false;
  102643. encoder->protected_->loose_mid_side_stereo = false;
  102644. }
  102645. else if(!encoder->protected_->do_mid_side_stereo)
  102646. encoder->protected_->loose_mid_side_stereo = false;
  102647. if(encoder->protected_->bits_per_sample >= 32)
  102648. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102649. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102650. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102651. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102652. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102653. if(encoder->protected_->blocksize == 0) {
  102654. if(encoder->protected_->max_lpc_order == 0)
  102655. encoder->protected_->blocksize = 1152;
  102656. else
  102657. encoder->protected_->blocksize = 4096;
  102658. }
  102659. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102660. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102661. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102662. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102663. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102664. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102665. if(encoder->protected_->qlp_coeff_precision == 0) {
  102666. if(encoder->protected_->bits_per_sample < 16) {
  102667. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102668. /* @@@ until then we'll make a guess */
  102669. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102670. }
  102671. else if(encoder->protected_->bits_per_sample == 16) {
  102672. if(encoder->protected_->blocksize <= 192)
  102673. encoder->protected_->qlp_coeff_precision = 7;
  102674. else if(encoder->protected_->blocksize <= 384)
  102675. encoder->protected_->qlp_coeff_precision = 8;
  102676. else if(encoder->protected_->blocksize <= 576)
  102677. encoder->protected_->qlp_coeff_precision = 9;
  102678. else if(encoder->protected_->blocksize <= 1152)
  102679. encoder->protected_->qlp_coeff_precision = 10;
  102680. else if(encoder->protected_->blocksize <= 2304)
  102681. encoder->protected_->qlp_coeff_precision = 11;
  102682. else if(encoder->protected_->blocksize <= 4608)
  102683. encoder->protected_->qlp_coeff_precision = 12;
  102684. else
  102685. encoder->protected_->qlp_coeff_precision = 13;
  102686. }
  102687. else {
  102688. if(encoder->protected_->blocksize <= 384)
  102689. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102690. else if(encoder->protected_->blocksize <= 1152)
  102691. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102692. else
  102693. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102694. }
  102695. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102696. }
  102697. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102698. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102699. if(encoder->protected_->streamable_subset) {
  102700. if(
  102701. encoder->protected_->blocksize != 192 &&
  102702. encoder->protected_->blocksize != 576 &&
  102703. encoder->protected_->blocksize != 1152 &&
  102704. encoder->protected_->blocksize != 2304 &&
  102705. encoder->protected_->blocksize != 4608 &&
  102706. encoder->protected_->blocksize != 256 &&
  102707. encoder->protected_->blocksize != 512 &&
  102708. encoder->protected_->blocksize != 1024 &&
  102709. encoder->protected_->blocksize != 2048 &&
  102710. encoder->protected_->blocksize != 4096 &&
  102711. encoder->protected_->blocksize != 8192 &&
  102712. encoder->protected_->blocksize != 16384
  102713. )
  102714. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102715. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102716. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102717. if(
  102718. encoder->protected_->bits_per_sample != 8 &&
  102719. encoder->protected_->bits_per_sample != 12 &&
  102720. encoder->protected_->bits_per_sample != 16 &&
  102721. encoder->protected_->bits_per_sample != 20 &&
  102722. encoder->protected_->bits_per_sample != 24
  102723. )
  102724. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102725. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102726. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102727. if(
  102728. encoder->protected_->sample_rate <= 48000 &&
  102729. (
  102730. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102731. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102732. )
  102733. ) {
  102734. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102735. }
  102736. }
  102737. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102738. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102739. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102740. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102741. #if FLAC__HAS_OGG
  102742. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102743. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102744. unsigned i;
  102745. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102746. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102747. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102748. for( ; i > 0; i--)
  102749. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102750. encoder->protected_->metadata[0] = vc;
  102751. break;
  102752. }
  102753. }
  102754. }
  102755. #endif
  102756. /* keep track of any SEEKTABLE block */
  102757. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102758. unsigned i;
  102759. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102760. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102761. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102762. break; /* take only the first one */
  102763. }
  102764. }
  102765. }
  102766. /* validate metadata */
  102767. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102768. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102769. metadata_has_seektable = false;
  102770. metadata_has_vorbis_comment = false;
  102771. metadata_picture_has_type1 = false;
  102772. metadata_picture_has_type2 = false;
  102773. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102774. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102775. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102776. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102777. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102778. if(metadata_has_seektable) /* only one is allowed */
  102779. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102780. metadata_has_seektable = true;
  102781. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102782. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102783. }
  102784. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102785. if(metadata_has_vorbis_comment) /* only one is allowed */
  102786. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102787. metadata_has_vorbis_comment = true;
  102788. }
  102789. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102790. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102791. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102792. }
  102793. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102794. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102795. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102796. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102797. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102799. metadata_picture_has_type1 = true;
  102800. /* standard icon must be 32x32 pixel PNG */
  102801. if(
  102802. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102803. (
  102804. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102805. m->data.picture.width != 32 ||
  102806. m->data.picture.height != 32
  102807. )
  102808. )
  102809. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102810. }
  102811. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102812. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102813. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102814. metadata_picture_has_type2 = true;
  102815. }
  102816. }
  102817. }
  102818. encoder->private_->input_capacity = 0;
  102819. for(i = 0; i < encoder->protected_->channels; i++) {
  102820. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102821. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102822. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102823. #endif
  102824. }
  102825. for(i = 0; i < 2; i++) {
  102826. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102827. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102828. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102829. #endif
  102830. }
  102831. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102832. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102833. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102834. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102835. #endif
  102836. for(i = 0; i < encoder->protected_->channels; i++) {
  102837. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102838. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102839. encoder->private_->best_subframe[i] = 0;
  102840. }
  102841. for(i = 0; i < 2; i++) {
  102842. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102843. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102844. encoder->private_->best_subframe_mid_side[i] = 0;
  102845. }
  102846. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102847. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102848. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102849. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102850. #else
  102851. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102852. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102853. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102854. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102855. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102856. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102857. 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);
  102858. #endif
  102859. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102860. encoder->private_->loose_mid_side_stereo_frames = 1;
  102861. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102862. encoder->private_->current_sample_number = 0;
  102863. encoder->private_->current_frame_number = 0;
  102864. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102865. 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? */
  102866. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102867. /*
  102868. * get the CPU info and set the function pointers
  102869. */
  102870. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102871. /* first default to the non-asm routines */
  102872. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102873. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102874. #endif
  102875. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102876. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102877. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102878. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102879. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102880. #endif
  102881. /* now override with asm where appropriate */
  102882. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102883. # ifndef FLAC__NO_ASM
  102884. if(encoder->private_->cpuinfo.use_asm) {
  102885. # ifdef FLAC__CPU_IA32
  102886. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102887. # ifdef FLAC__HAS_NASM
  102888. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102889. if(encoder->protected_->max_lpc_order < 4)
  102890. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102891. else if(encoder->protected_->max_lpc_order < 8)
  102892. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102893. else if(encoder->protected_->max_lpc_order < 12)
  102894. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102895. else
  102896. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102897. }
  102898. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102899. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102900. else
  102901. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102902. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102903. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102904. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102905. }
  102906. else {
  102907. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102908. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102909. }
  102910. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102911. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102912. # endif /* FLAC__HAS_NASM */
  102913. # endif /* FLAC__CPU_IA32 */
  102914. }
  102915. # endif /* !FLAC__NO_ASM */
  102916. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102917. /* finally override based on wide-ness if necessary */
  102918. if(encoder->private_->use_wide_by_block) {
  102919. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102920. }
  102921. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102922. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102923. #if FLAC__HAS_OGG
  102924. encoder->private_->is_ogg = is_ogg;
  102925. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102926. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102927. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102928. }
  102929. #endif
  102930. encoder->private_->read_callback = read_callback;
  102931. encoder->private_->write_callback = write_callback;
  102932. encoder->private_->seek_callback = seek_callback;
  102933. encoder->private_->tell_callback = tell_callback;
  102934. encoder->private_->metadata_callback = metadata_callback;
  102935. encoder->private_->client_data = client_data;
  102936. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102937. /* the above function sets the state for us in case of an error */
  102938. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102939. }
  102940. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102941. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102942. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102943. }
  102944. /*
  102945. * Set up the verify stuff if necessary
  102946. */
  102947. if(encoder->protected_->verify) {
  102948. /*
  102949. * First, set up the fifo which will hold the
  102950. * original signal to compare against
  102951. */
  102952. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102953. for(i = 0; i < encoder->protected_->channels; i++) {
  102954. 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))) {
  102955. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102956. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102957. }
  102958. }
  102959. encoder->private_->verify.input_fifo.tail = 0;
  102960. /*
  102961. * Now set up a stream decoder for verification
  102962. */
  102963. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102964. if(0 == encoder->private_->verify.decoder) {
  102965. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102966. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102967. }
  102968. 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) {
  102969. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102970. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102971. }
  102972. }
  102973. encoder->private_->verify.error_stats.absolute_sample = 0;
  102974. encoder->private_->verify.error_stats.frame_number = 0;
  102975. encoder->private_->verify.error_stats.channel = 0;
  102976. encoder->private_->verify.error_stats.sample = 0;
  102977. encoder->private_->verify.error_stats.expected = 0;
  102978. encoder->private_->verify.error_stats.got = 0;
  102979. /*
  102980. * These must be done before we write any metadata, because that
  102981. * calls the write_callback, which uses these values.
  102982. */
  102983. encoder->private_->first_seekpoint_to_check = 0;
  102984. encoder->private_->samples_written = 0;
  102985. encoder->protected_->streaminfo_offset = 0;
  102986. encoder->protected_->seektable_offset = 0;
  102987. encoder->protected_->audio_offset = 0;
  102988. /*
  102989. * write the stream header
  102990. */
  102991. if(encoder->protected_->verify)
  102992. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102993. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102994. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102995. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102996. }
  102997. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102998. /* the above function sets the state for us in case of an error */
  102999. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103000. }
  103001. /*
  103002. * write the STREAMINFO metadata block
  103003. */
  103004. if(encoder->protected_->verify)
  103005. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103006. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103007. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103008. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103009. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103010. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103011. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103012. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103013. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103014. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103015. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103016. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103017. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103018. if(encoder->protected_->do_md5)
  103019. FLAC__MD5Init(&encoder->private_->md5context);
  103020. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103021. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103022. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103023. }
  103024. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103025. /* the above function sets the state for us in case of an error */
  103026. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103027. }
  103028. /*
  103029. * Now that the STREAMINFO block is written, we can init this to an
  103030. * absurdly-high value...
  103031. */
  103032. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103033. /* ... and clear this to 0 */
  103034. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103035. /*
  103036. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103037. * if not, we will write an empty one (FLAC__add_metadata_block()
  103038. * automatically supplies the vendor string).
  103039. *
  103040. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103041. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103042. * true it will have already insured that the metadata list is properly
  103043. * ordered.)
  103044. */
  103045. if(!metadata_has_vorbis_comment) {
  103046. FLAC__StreamMetadata vorbis_comment;
  103047. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103048. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103049. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103050. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103051. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103052. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103053. vorbis_comment.data.vorbis_comment.comments = 0;
  103054. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103055. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103056. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103057. }
  103058. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103059. /* the above function sets the state for us in case of an error */
  103060. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103061. }
  103062. }
  103063. /*
  103064. * write the user's metadata blocks
  103065. */
  103066. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103067. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103068. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103069. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103070. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103071. }
  103072. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103073. /* the above function sets the state for us in case of an error */
  103074. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103075. }
  103076. }
  103077. /* now that all the metadata is written, we save the stream offset */
  103078. 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 */
  103079. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103080. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103081. }
  103082. if(encoder->protected_->verify)
  103083. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103084. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103085. }
  103086. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103087. FLAC__StreamEncoder *encoder,
  103088. FLAC__StreamEncoderWriteCallback write_callback,
  103089. FLAC__StreamEncoderSeekCallback seek_callback,
  103090. FLAC__StreamEncoderTellCallback tell_callback,
  103091. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103092. void *client_data
  103093. )
  103094. {
  103095. return init_stream_internal_enc(
  103096. encoder,
  103097. /*read_callback=*/0,
  103098. write_callback,
  103099. seek_callback,
  103100. tell_callback,
  103101. metadata_callback,
  103102. client_data,
  103103. /*is_ogg=*/false
  103104. );
  103105. }
  103106. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103107. FLAC__StreamEncoder *encoder,
  103108. FLAC__StreamEncoderReadCallback read_callback,
  103109. FLAC__StreamEncoderWriteCallback write_callback,
  103110. FLAC__StreamEncoderSeekCallback seek_callback,
  103111. FLAC__StreamEncoderTellCallback tell_callback,
  103112. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103113. void *client_data
  103114. )
  103115. {
  103116. return init_stream_internal_enc(
  103117. encoder,
  103118. read_callback,
  103119. write_callback,
  103120. seek_callback,
  103121. tell_callback,
  103122. metadata_callback,
  103123. client_data,
  103124. /*is_ogg=*/true
  103125. );
  103126. }
  103127. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103128. FLAC__StreamEncoder *encoder,
  103129. FILE *file,
  103130. FLAC__StreamEncoderProgressCallback progress_callback,
  103131. void *client_data,
  103132. FLAC__bool is_ogg
  103133. )
  103134. {
  103135. FLAC__StreamEncoderInitStatus init_status;
  103136. FLAC__ASSERT(0 != encoder);
  103137. FLAC__ASSERT(0 != file);
  103138. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103139. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103140. /* double protection */
  103141. if(file == 0) {
  103142. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103143. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103144. }
  103145. /*
  103146. * To make sure that our file does not go unclosed after an error, we
  103147. * must assign the FILE pointer before any further error can occur in
  103148. * this routine.
  103149. */
  103150. if(file == stdout)
  103151. file = get_binary_stdout_(); /* just to be safe */
  103152. encoder->private_->file = file;
  103153. encoder->private_->progress_callback = progress_callback;
  103154. encoder->private_->bytes_written = 0;
  103155. encoder->private_->samples_written = 0;
  103156. encoder->private_->frames_written = 0;
  103157. init_status = init_stream_internal_enc(
  103158. encoder,
  103159. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103160. file_write_callback_,
  103161. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103162. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103163. /*metadata_callback=*/0,
  103164. client_data,
  103165. is_ogg
  103166. );
  103167. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103168. /* the above function sets the state for us in case of an error */
  103169. return init_status;
  103170. }
  103171. {
  103172. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103173. FLAC__ASSERT(blocksize != 0);
  103174. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103175. }
  103176. return init_status;
  103177. }
  103178. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103179. FLAC__StreamEncoder *encoder,
  103180. FILE *file,
  103181. FLAC__StreamEncoderProgressCallback progress_callback,
  103182. void *client_data
  103183. )
  103184. {
  103185. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103186. }
  103187. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103188. FLAC__StreamEncoder *encoder,
  103189. FILE *file,
  103190. FLAC__StreamEncoderProgressCallback progress_callback,
  103191. void *client_data
  103192. )
  103193. {
  103194. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103195. }
  103196. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103197. FLAC__StreamEncoder *encoder,
  103198. const char *filename,
  103199. FLAC__StreamEncoderProgressCallback progress_callback,
  103200. void *client_data,
  103201. FLAC__bool is_ogg
  103202. )
  103203. {
  103204. FILE *file;
  103205. FLAC__ASSERT(0 != encoder);
  103206. /*
  103207. * To make sure that our file does not go unclosed after an error, we
  103208. * have to do the same entrance checks here that are later performed
  103209. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103210. */
  103211. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103212. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103213. file = filename? fopen(filename, "w+b") : stdout;
  103214. if(file == 0) {
  103215. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103216. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103217. }
  103218. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103219. }
  103220. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103221. FLAC__StreamEncoder *encoder,
  103222. const char *filename,
  103223. FLAC__StreamEncoderProgressCallback progress_callback,
  103224. void *client_data
  103225. )
  103226. {
  103227. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103228. }
  103229. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103230. FLAC__StreamEncoder *encoder,
  103231. const char *filename,
  103232. FLAC__StreamEncoderProgressCallback progress_callback,
  103233. void *client_data
  103234. )
  103235. {
  103236. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103237. }
  103238. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103239. {
  103240. FLAC__bool error = false;
  103241. FLAC__ASSERT(0 != encoder);
  103242. FLAC__ASSERT(0 != encoder->private_);
  103243. FLAC__ASSERT(0 != encoder->protected_);
  103244. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103245. return true;
  103246. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103247. if(encoder->private_->current_sample_number != 0) {
  103248. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103249. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103250. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103251. error = true;
  103252. }
  103253. }
  103254. if(encoder->protected_->do_md5)
  103255. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103256. if(!encoder->private_->is_being_deleted) {
  103257. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103258. if(encoder->private_->seek_callback) {
  103259. #if FLAC__HAS_OGG
  103260. if(encoder->private_->is_ogg)
  103261. update_ogg_metadata_(encoder);
  103262. else
  103263. #endif
  103264. update_metadata_(encoder);
  103265. /* check if an error occurred while updating metadata */
  103266. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103267. error = true;
  103268. }
  103269. if(encoder->private_->metadata_callback)
  103270. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103271. }
  103272. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103273. if(!error)
  103274. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103275. error = true;
  103276. }
  103277. }
  103278. if(0 != encoder->private_->file) {
  103279. if(encoder->private_->file != stdout)
  103280. fclose(encoder->private_->file);
  103281. encoder->private_->file = 0;
  103282. }
  103283. #if FLAC__HAS_OGG
  103284. if(encoder->private_->is_ogg)
  103285. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103286. #endif
  103287. free_(encoder);
  103288. set_defaults_enc(encoder);
  103289. if(!error)
  103290. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103291. return !error;
  103292. }
  103293. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103294. {
  103295. FLAC__ASSERT(0 != encoder);
  103296. FLAC__ASSERT(0 != encoder->private_);
  103297. FLAC__ASSERT(0 != encoder->protected_);
  103298. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103299. return false;
  103300. #if FLAC__HAS_OGG
  103301. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103302. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103303. return true;
  103304. #else
  103305. (void)value;
  103306. return false;
  103307. #endif
  103308. }
  103309. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103310. {
  103311. FLAC__ASSERT(0 != encoder);
  103312. FLAC__ASSERT(0 != encoder->private_);
  103313. FLAC__ASSERT(0 != encoder->protected_);
  103314. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103315. return false;
  103316. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103317. encoder->protected_->verify = value;
  103318. #endif
  103319. return true;
  103320. }
  103321. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103322. {
  103323. FLAC__ASSERT(0 != encoder);
  103324. FLAC__ASSERT(0 != encoder->private_);
  103325. FLAC__ASSERT(0 != encoder->protected_);
  103326. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103327. return false;
  103328. encoder->protected_->streamable_subset = value;
  103329. return true;
  103330. }
  103331. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103332. {
  103333. FLAC__ASSERT(0 != encoder);
  103334. FLAC__ASSERT(0 != encoder->private_);
  103335. FLAC__ASSERT(0 != encoder->protected_);
  103336. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103337. return false;
  103338. encoder->protected_->do_md5 = value;
  103339. return true;
  103340. }
  103341. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103342. {
  103343. FLAC__ASSERT(0 != encoder);
  103344. FLAC__ASSERT(0 != encoder->private_);
  103345. FLAC__ASSERT(0 != encoder->protected_);
  103346. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103347. return false;
  103348. encoder->protected_->channels = value;
  103349. return true;
  103350. }
  103351. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103352. {
  103353. FLAC__ASSERT(0 != encoder);
  103354. FLAC__ASSERT(0 != encoder->private_);
  103355. FLAC__ASSERT(0 != encoder->protected_);
  103356. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103357. return false;
  103358. encoder->protected_->bits_per_sample = value;
  103359. return true;
  103360. }
  103361. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103362. {
  103363. FLAC__ASSERT(0 != encoder);
  103364. FLAC__ASSERT(0 != encoder->private_);
  103365. FLAC__ASSERT(0 != encoder->protected_);
  103366. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103367. return false;
  103368. encoder->protected_->sample_rate = value;
  103369. return true;
  103370. }
  103371. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103372. {
  103373. FLAC__bool ok = true;
  103374. FLAC__ASSERT(0 != encoder);
  103375. FLAC__ASSERT(0 != encoder->private_);
  103376. FLAC__ASSERT(0 != encoder->protected_);
  103377. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103378. return false;
  103379. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103380. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103381. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103382. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103383. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103384. #if 0
  103385. /* was: */
  103386. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103387. /* but it's too hard to specify the string in a locale-specific way */
  103388. #else
  103389. encoder->protected_->num_apodizations = 1;
  103390. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103391. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103392. #endif
  103393. #endif
  103394. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103395. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103396. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103397. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103398. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103399. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103400. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103401. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103402. return ok;
  103403. }
  103404. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103405. {
  103406. FLAC__ASSERT(0 != encoder);
  103407. FLAC__ASSERT(0 != encoder->private_);
  103408. FLAC__ASSERT(0 != encoder->protected_);
  103409. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103410. return false;
  103411. encoder->protected_->blocksize = value;
  103412. return true;
  103413. }
  103414. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103415. {
  103416. FLAC__ASSERT(0 != encoder);
  103417. FLAC__ASSERT(0 != encoder->private_);
  103418. FLAC__ASSERT(0 != encoder->protected_);
  103419. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103420. return false;
  103421. encoder->protected_->do_mid_side_stereo = value;
  103422. return true;
  103423. }
  103424. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103425. {
  103426. FLAC__ASSERT(0 != encoder);
  103427. FLAC__ASSERT(0 != encoder->private_);
  103428. FLAC__ASSERT(0 != encoder->protected_);
  103429. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103430. return false;
  103431. encoder->protected_->loose_mid_side_stereo = value;
  103432. return true;
  103433. }
  103434. /*@@@@add to tests*/
  103435. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103436. {
  103437. FLAC__ASSERT(0 != encoder);
  103438. FLAC__ASSERT(0 != encoder->private_);
  103439. FLAC__ASSERT(0 != encoder->protected_);
  103440. FLAC__ASSERT(0 != specification);
  103441. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103442. return false;
  103443. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103444. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103445. #else
  103446. encoder->protected_->num_apodizations = 0;
  103447. while(1) {
  103448. const char *s = strchr(specification, ';');
  103449. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103450. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103451. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103452. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103453. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103454. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103455. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103456. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103457. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103458. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103459. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103460. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103461. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103462. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103463. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103464. if (stddev > 0.0 && stddev <= 0.5) {
  103465. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103466. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103467. }
  103468. }
  103469. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103470. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103471. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103472. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103473. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103474. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103475. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103476. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103477. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103478. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103479. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103480. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103481. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103482. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103483. if (p >= 0.0 && p <= 1.0) {
  103484. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103485. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103486. }
  103487. }
  103488. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103489. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103490. if (encoder->protected_->num_apodizations == 32)
  103491. break;
  103492. if (s)
  103493. specification = s+1;
  103494. else
  103495. break;
  103496. }
  103497. if(encoder->protected_->num_apodizations == 0) {
  103498. encoder->protected_->num_apodizations = 1;
  103499. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103500. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103501. }
  103502. #endif
  103503. return true;
  103504. }
  103505. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103506. {
  103507. FLAC__ASSERT(0 != encoder);
  103508. FLAC__ASSERT(0 != encoder->private_);
  103509. FLAC__ASSERT(0 != encoder->protected_);
  103510. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103511. return false;
  103512. encoder->protected_->max_lpc_order = value;
  103513. return true;
  103514. }
  103515. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103516. {
  103517. FLAC__ASSERT(0 != encoder);
  103518. FLAC__ASSERT(0 != encoder->private_);
  103519. FLAC__ASSERT(0 != encoder->protected_);
  103520. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103521. return false;
  103522. encoder->protected_->qlp_coeff_precision = value;
  103523. return true;
  103524. }
  103525. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103526. {
  103527. FLAC__ASSERT(0 != encoder);
  103528. FLAC__ASSERT(0 != encoder->private_);
  103529. FLAC__ASSERT(0 != encoder->protected_);
  103530. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103531. return false;
  103532. encoder->protected_->do_qlp_coeff_prec_search = value;
  103533. return true;
  103534. }
  103535. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103536. {
  103537. FLAC__ASSERT(0 != encoder);
  103538. FLAC__ASSERT(0 != encoder->private_);
  103539. FLAC__ASSERT(0 != encoder->protected_);
  103540. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103541. return false;
  103542. #if 0
  103543. /*@@@ deprecated: */
  103544. encoder->protected_->do_escape_coding = value;
  103545. #else
  103546. (void)value;
  103547. #endif
  103548. return true;
  103549. }
  103550. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103551. {
  103552. FLAC__ASSERT(0 != encoder);
  103553. FLAC__ASSERT(0 != encoder->private_);
  103554. FLAC__ASSERT(0 != encoder->protected_);
  103555. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103556. return false;
  103557. encoder->protected_->do_exhaustive_model_search = value;
  103558. return true;
  103559. }
  103560. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103561. {
  103562. FLAC__ASSERT(0 != encoder);
  103563. FLAC__ASSERT(0 != encoder->private_);
  103564. FLAC__ASSERT(0 != encoder->protected_);
  103565. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103566. return false;
  103567. encoder->protected_->min_residual_partition_order = value;
  103568. return true;
  103569. }
  103570. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103571. {
  103572. FLAC__ASSERT(0 != encoder);
  103573. FLAC__ASSERT(0 != encoder->private_);
  103574. FLAC__ASSERT(0 != encoder->protected_);
  103575. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103576. return false;
  103577. encoder->protected_->max_residual_partition_order = value;
  103578. return true;
  103579. }
  103580. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103581. {
  103582. FLAC__ASSERT(0 != encoder);
  103583. FLAC__ASSERT(0 != encoder->private_);
  103584. FLAC__ASSERT(0 != encoder->protected_);
  103585. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103586. return false;
  103587. #if 0
  103588. /*@@@ deprecated: */
  103589. encoder->protected_->rice_parameter_search_dist = value;
  103590. #else
  103591. (void)value;
  103592. #endif
  103593. return true;
  103594. }
  103595. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103596. {
  103597. FLAC__ASSERT(0 != encoder);
  103598. FLAC__ASSERT(0 != encoder->private_);
  103599. FLAC__ASSERT(0 != encoder->protected_);
  103600. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103601. return false;
  103602. encoder->protected_->total_samples_estimate = value;
  103603. return true;
  103604. }
  103605. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103606. {
  103607. FLAC__ASSERT(0 != encoder);
  103608. FLAC__ASSERT(0 != encoder->private_);
  103609. FLAC__ASSERT(0 != encoder->protected_);
  103610. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103611. return false;
  103612. if(0 == metadata)
  103613. num_blocks = 0;
  103614. if(0 == num_blocks)
  103615. metadata = 0;
  103616. /* realloc() does not do exactly what we want so... */
  103617. if(encoder->protected_->metadata) {
  103618. free(encoder->protected_->metadata);
  103619. encoder->protected_->metadata = 0;
  103620. encoder->protected_->num_metadata_blocks = 0;
  103621. }
  103622. if(num_blocks) {
  103623. FLAC__StreamMetadata **m;
  103624. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103625. return false;
  103626. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103627. encoder->protected_->metadata = m;
  103628. encoder->protected_->num_metadata_blocks = num_blocks;
  103629. }
  103630. #if FLAC__HAS_OGG
  103631. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103632. return false;
  103633. #endif
  103634. return true;
  103635. }
  103636. /*
  103637. * These three functions are not static, but not publically exposed in
  103638. * include/FLAC/ either. They are used by the test suite.
  103639. */
  103640. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103641. {
  103642. FLAC__ASSERT(0 != encoder);
  103643. FLAC__ASSERT(0 != encoder->private_);
  103644. FLAC__ASSERT(0 != encoder->protected_);
  103645. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103646. return false;
  103647. encoder->private_->disable_constant_subframes = value;
  103648. return true;
  103649. }
  103650. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103651. {
  103652. FLAC__ASSERT(0 != encoder);
  103653. FLAC__ASSERT(0 != encoder->private_);
  103654. FLAC__ASSERT(0 != encoder->protected_);
  103655. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103656. return false;
  103657. encoder->private_->disable_fixed_subframes = value;
  103658. return true;
  103659. }
  103660. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103661. {
  103662. FLAC__ASSERT(0 != encoder);
  103663. FLAC__ASSERT(0 != encoder->private_);
  103664. FLAC__ASSERT(0 != encoder->protected_);
  103665. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103666. return false;
  103667. encoder->private_->disable_verbatim_subframes = value;
  103668. return true;
  103669. }
  103670. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103671. {
  103672. FLAC__ASSERT(0 != encoder);
  103673. FLAC__ASSERT(0 != encoder->private_);
  103674. FLAC__ASSERT(0 != encoder->protected_);
  103675. return encoder->protected_->state;
  103676. }
  103677. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103678. {
  103679. FLAC__ASSERT(0 != encoder);
  103680. FLAC__ASSERT(0 != encoder->private_);
  103681. FLAC__ASSERT(0 != encoder->protected_);
  103682. if(encoder->protected_->verify)
  103683. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103684. else
  103685. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103686. }
  103687. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103688. {
  103689. FLAC__ASSERT(0 != encoder);
  103690. FLAC__ASSERT(0 != encoder->private_);
  103691. FLAC__ASSERT(0 != encoder->protected_);
  103692. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103693. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103694. else
  103695. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103696. }
  103697. 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)
  103698. {
  103699. FLAC__ASSERT(0 != encoder);
  103700. FLAC__ASSERT(0 != encoder->private_);
  103701. FLAC__ASSERT(0 != encoder->protected_);
  103702. if(0 != absolute_sample)
  103703. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103704. if(0 != frame_number)
  103705. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103706. if(0 != channel)
  103707. *channel = encoder->private_->verify.error_stats.channel;
  103708. if(0 != sample)
  103709. *sample = encoder->private_->verify.error_stats.sample;
  103710. if(0 != expected)
  103711. *expected = encoder->private_->verify.error_stats.expected;
  103712. if(0 != got)
  103713. *got = encoder->private_->verify.error_stats.got;
  103714. }
  103715. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103716. {
  103717. FLAC__ASSERT(0 != encoder);
  103718. FLAC__ASSERT(0 != encoder->private_);
  103719. FLAC__ASSERT(0 != encoder->protected_);
  103720. return encoder->protected_->verify;
  103721. }
  103722. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103723. {
  103724. FLAC__ASSERT(0 != encoder);
  103725. FLAC__ASSERT(0 != encoder->private_);
  103726. FLAC__ASSERT(0 != encoder->protected_);
  103727. return encoder->protected_->streamable_subset;
  103728. }
  103729. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103730. {
  103731. FLAC__ASSERT(0 != encoder);
  103732. FLAC__ASSERT(0 != encoder->private_);
  103733. FLAC__ASSERT(0 != encoder->protected_);
  103734. return encoder->protected_->do_md5;
  103735. }
  103736. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103737. {
  103738. FLAC__ASSERT(0 != encoder);
  103739. FLAC__ASSERT(0 != encoder->private_);
  103740. FLAC__ASSERT(0 != encoder->protected_);
  103741. return encoder->protected_->channels;
  103742. }
  103743. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103744. {
  103745. FLAC__ASSERT(0 != encoder);
  103746. FLAC__ASSERT(0 != encoder->private_);
  103747. FLAC__ASSERT(0 != encoder->protected_);
  103748. return encoder->protected_->bits_per_sample;
  103749. }
  103750. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103751. {
  103752. FLAC__ASSERT(0 != encoder);
  103753. FLAC__ASSERT(0 != encoder->private_);
  103754. FLAC__ASSERT(0 != encoder->protected_);
  103755. return encoder->protected_->sample_rate;
  103756. }
  103757. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103758. {
  103759. FLAC__ASSERT(0 != encoder);
  103760. FLAC__ASSERT(0 != encoder->private_);
  103761. FLAC__ASSERT(0 != encoder->protected_);
  103762. return encoder->protected_->blocksize;
  103763. }
  103764. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103765. {
  103766. FLAC__ASSERT(0 != encoder);
  103767. FLAC__ASSERT(0 != encoder->private_);
  103768. FLAC__ASSERT(0 != encoder->protected_);
  103769. return encoder->protected_->do_mid_side_stereo;
  103770. }
  103771. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103772. {
  103773. FLAC__ASSERT(0 != encoder);
  103774. FLAC__ASSERT(0 != encoder->private_);
  103775. FLAC__ASSERT(0 != encoder->protected_);
  103776. return encoder->protected_->loose_mid_side_stereo;
  103777. }
  103778. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103779. {
  103780. FLAC__ASSERT(0 != encoder);
  103781. FLAC__ASSERT(0 != encoder->private_);
  103782. FLAC__ASSERT(0 != encoder->protected_);
  103783. return encoder->protected_->max_lpc_order;
  103784. }
  103785. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103786. {
  103787. FLAC__ASSERT(0 != encoder);
  103788. FLAC__ASSERT(0 != encoder->private_);
  103789. FLAC__ASSERT(0 != encoder->protected_);
  103790. return encoder->protected_->qlp_coeff_precision;
  103791. }
  103792. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103793. {
  103794. FLAC__ASSERT(0 != encoder);
  103795. FLAC__ASSERT(0 != encoder->private_);
  103796. FLAC__ASSERT(0 != encoder->protected_);
  103797. return encoder->protected_->do_qlp_coeff_prec_search;
  103798. }
  103799. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103800. {
  103801. FLAC__ASSERT(0 != encoder);
  103802. FLAC__ASSERT(0 != encoder->private_);
  103803. FLAC__ASSERT(0 != encoder->protected_);
  103804. return encoder->protected_->do_escape_coding;
  103805. }
  103806. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103807. {
  103808. FLAC__ASSERT(0 != encoder);
  103809. FLAC__ASSERT(0 != encoder->private_);
  103810. FLAC__ASSERT(0 != encoder->protected_);
  103811. return encoder->protected_->do_exhaustive_model_search;
  103812. }
  103813. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103814. {
  103815. FLAC__ASSERT(0 != encoder);
  103816. FLAC__ASSERT(0 != encoder->private_);
  103817. FLAC__ASSERT(0 != encoder->protected_);
  103818. return encoder->protected_->min_residual_partition_order;
  103819. }
  103820. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103821. {
  103822. FLAC__ASSERT(0 != encoder);
  103823. FLAC__ASSERT(0 != encoder->private_);
  103824. FLAC__ASSERT(0 != encoder->protected_);
  103825. return encoder->protected_->max_residual_partition_order;
  103826. }
  103827. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103828. {
  103829. FLAC__ASSERT(0 != encoder);
  103830. FLAC__ASSERT(0 != encoder->private_);
  103831. FLAC__ASSERT(0 != encoder->protected_);
  103832. return encoder->protected_->rice_parameter_search_dist;
  103833. }
  103834. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103835. {
  103836. FLAC__ASSERT(0 != encoder);
  103837. FLAC__ASSERT(0 != encoder->private_);
  103838. FLAC__ASSERT(0 != encoder->protected_);
  103839. return encoder->protected_->total_samples_estimate;
  103840. }
  103841. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103842. {
  103843. unsigned i, j = 0, channel;
  103844. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103845. FLAC__ASSERT(0 != encoder);
  103846. FLAC__ASSERT(0 != encoder->private_);
  103847. FLAC__ASSERT(0 != encoder->protected_);
  103848. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103849. do {
  103850. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103851. if(encoder->protected_->verify)
  103852. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103853. for(channel = 0; channel < channels; channel++)
  103854. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103855. if(encoder->protected_->do_mid_side_stereo) {
  103856. FLAC__ASSERT(channels == 2);
  103857. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103858. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103859. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103860. 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' ! */
  103861. }
  103862. }
  103863. else
  103864. j += n;
  103865. encoder->private_->current_sample_number += n;
  103866. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103867. if(encoder->private_->current_sample_number > blocksize) {
  103868. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103869. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103870. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103871. return false;
  103872. /* move unprocessed overread samples to beginnings of arrays */
  103873. for(channel = 0; channel < channels; channel++)
  103874. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103875. if(encoder->protected_->do_mid_side_stereo) {
  103876. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103877. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103878. }
  103879. encoder->private_->current_sample_number = 1;
  103880. }
  103881. } while(j < samples);
  103882. return true;
  103883. }
  103884. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103885. {
  103886. unsigned i, j, k, channel;
  103887. FLAC__int32 x, mid, side;
  103888. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103889. FLAC__ASSERT(0 != encoder);
  103890. FLAC__ASSERT(0 != encoder->private_);
  103891. FLAC__ASSERT(0 != encoder->protected_);
  103892. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103893. j = k = 0;
  103894. /*
  103895. * we have several flavors of the same basic loop, optimized for
  103896. * different conditions:
  103897. */
  103898. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103899. /*
  103900. * stereo coding: unroll channel loop
  103901. */
  103902. do {
  103903. if(encoder->protected_->verify)
  103904. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103905. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103906. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103907. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103908. x = buffer[k++];
  103909. encoder->private_->integer_signal[1][i] = x;
  103910. mid += x;
  103911. side -= x;
  103912. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103913. encoder->private_->integer_signal_mid_side[1][i] = side;
  103914. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103915. }
  103916. encoder->private_->current_sample_number = i;
  103917. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103918. if(i > blocksize) {
  103919. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103920. return false;
  103921. /* move unprocessed overread samples to beginnings of arrays */
  103922. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103923. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103924. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103925. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103926. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103927. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103928. encoder->private_->current_sample_number = 1;
  103929. }
  103930. } while(j < samples);
  103931. }
  103932. else {
  103933. /*
  103934. * independent channel coding: buffer each channel in inner loop
  103935. */
  103936. do {
  103937. if(encoder->protected_->verify)
  103938. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103939. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103940. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103941. for(channel = 0; channel < channels; channel++)
  103942. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103943. }
  103944. encoder->private_->current_sample_number = i;
  103945. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103946. if(i > blocksize) {
  103947. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103948. return false;
  103949. /* move unprocessed overread samples to beginnings of arrays */
  103950. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103951. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103952. for(channel = 0; channel < channels; channel++)
  103953. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103954. encoder->private_->current_sample_number = 1;
  103955. }
  103956. } while(j < samples);
  103957. }
  103958. return true;
  103959. }
  103960. /***********************************************************************
  103961. *
  103962. * Private class methods
  103963. *
  103964. ***********************************************************************/
  103965. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103966. {
  103967. FLAC__ASSERT(0 != encoder);
  103968. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103969. encoder->protected_->verify = true;
  103970. #else
  103971. encoder->protected_->verify = false;
  103972. #endif
  103973. encoder->protected_->streamable_subset = true;
  103974. encoder->protected_->do_md5 = true;
  103975. encoder->protected_->do_mid_side_stereo = false;
  103976. encoder->protected_->loose_mid_side_stereo = false;
  103977. encoder->protected_->channels = 2;
  103978. encoder->protected_->bits_per_sample = 16;
  103979. encoder->protected_->sample_rate = 44100;
  103980. encoder->protected_->blocksize = 0;
  103981. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103982. encoder->protected_->num_apodizations = 1;
  103983. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103984. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103985. #endif
  103986. encoder->protected_->max_lpc_order = 0;
  103987. encoder->protected_->qlp_coeff_precision = 0;
  103988. encoder->protected_->do_qlp_coeff_prec_search = false;
  103989. encoder->protected_->do_exhaustive_model_search = false;
  103990. encoder->protected_->do_escape_coding = false;
  103991. encoder->protected_->min_residual_partition_order = 0;
  103992. encoder->protected_->max_residual_partition_order = 0;
  103993. encoder->protected_->rice_parameter_search_dist = 0;
  103994. encoder->protected_->total_samples_estimate = 0;
  103995. encoder->protected_->metadata = 0;
  103996. encoder->protected_->num_metadata_blocks = 0;
  103997. encoder->private_->seek_table = 0;
  103998. encoder->private_->disable_constant_subframes = false;
  103999. encoder->private_->disable_fixed_subframes = false;
  104000. encoder->private_->disable_verbatim_subframes = false;
  104001. #if FLAC__HAS_OGG
  104002. encoder->private_->is_ogg = false;
  104003. #endif
  104004. encoder->private_->read_callback = 0;
  104005. encoder->private_->write_callback = 0;
  104006. encoder->private_->seek_callback = 0;
  104007. encoder->private_->tell_callback = 0;
  104008. encoder->private_->metadata_callback = 0;
  104009. encoder->private_->progress_callback = 0;
  104010. encoder->private_->client_data = 0;
  104011. #if FLAC__HAS_OGG
  104012. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104013. #endif
  104014. }
  104015. void free_(FLAC__StreamEncoder *encoder)
  104016. {
  104017. unsigned i, channel;
  104018. FLAC__ASSERT(0 != encoder);
  104019. if(encoder->protected_->metadata) {
  104020. free(encoder->protected_->metadata);
  104021. encoder->protected_->metadata = 0;
  104022. encoder->protected_->num_metadata_blocks = 0;
  104023. }
  104024. for(i = 0; i < encoder->protected_->channels; i++) {
  104025. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104026. free(encoder->private_->integer_signal_unaligned[i]);
  104027. encoder->private_->integer_signal_unaligned[i] = 0;
  104028. }
  104029. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104030. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104031. free(encoder->private_->real_signal_unaligned[i]);
  104032. encoder->private_->real_signal_unaligned[i] = 0;
  104033. }
  104034. #endif
  104035. }
  104036. for(i = 0; i < 2; i++) {
  104037. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104038. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104039. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104040. }
  104041. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104042. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104043. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104044. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104045. }
  104046. #endif
  104047. }
  104048. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104049. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104050. if(0 != encoder->private_->window_unaligned[i]) {
  104051. free(encoder->private_->window_unaligned[i]);
  104052. encoder->private_->window_unaligned[i] = 0;
  104053. }
  104054. }
  104055. if(0 != encoder->private_->windowed_signal_unaligned) {
  104056. free(encoder->private_->windowed_signal_unaligned);
  104057. encoder->private_->windowed_signal_unaligned = 0;
  104058. }
  104059. #endif
  104060. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104061. for(i = 0; i < 2; i++) {
  104062. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104063. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104064. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104065. }
  104066. }
  104067. }
  104068. for(channel = 0; channel < 2; channel++) {
  104069. for(i = 0; i < 2; i++) {
  104070. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104071. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104072. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104073. }
  104074. }
  104075. }
  104076. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104077. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104078. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104079. }
  104080. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104081. free(encoder->private_->raw_bits_per_partition_unaligned);
  104082. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104083. }
  104084. if(encoder->protected_->verify) {
  104085. for(i = 0; i < encoder->protected_->channels; i++) {
  104086. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104087. free(encoder->private_->verify.input_fifo.data[i]);
  104088. encoder->private_->verify.input_fifo.data[i] = 0;
  104089. }
  104090. }
  104091. }
  104092. FLAC__bitwriter_free(encoder->private_->frame);
  104093. }
  104094. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104095. {
  104096. FLAC__bool ok;
  104097. unsigned i, channel;
  104098. FLAC__ASSERT(new_blocksize > 0);
  104099. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104100. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104101. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104102. if(new_blocksize <= encoder->private_->input_capacity)
  104103. return true;
  104104. ok = true;
  104105. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104106. * requires that the input arrays (in our case the integer signals)
  104107. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104108. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104109. */
  104110. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104111. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104112. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104113. encoder->private_->integer_signal[i] += 4;
  104114. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104115. #if 0 /* @@@ currently unused */
  104116. if(encoder->protected_->max_lpc_order > 0)
  104117. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104118. #endif
  104119. #endif
  104120. }
  104121. for(i = 0; ok && i < 2; i++) {
  104122. 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]);
  104123. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104124. encoder->private_->integer_signal_mid_side[i] += 4;
  104125. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104126. #if 0 /* @@@ currently unused */
  104127. if(encoder->protected_->max_lpc_order > 0)
  104128. 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]);
  104129. #endif
  104130. #endif
  104131. }
  104132. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104133. if(ok && encoder->protected_->max_lpc_order > 0) {
  104134. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104135. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104136. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104137. }
  104138. #endif
  104139. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104140. for(i = 0; ok && i < 2; i++) {
  104141. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104142. }
  104143. }
  104144. for(channel = 0; ok && channel < 2; channel++) {
  104145. for(i = 0; ok && i < 2; i++) {
  104146. 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]);
  104147. }
  104148. }
  104149. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104150. /*@@@ 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) */
  104151. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104152. if(encoder->protected_->do_escape_coding)
  104153. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104154. /* now adjust the windows if the blocksize has changed */
  104155. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104156. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104157. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104158. switch(encoder->protected_->apodizations[i].type) {
  104159. case FLAC__APODIZATION_BARTLETT:
  104160. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104161. break;
  104162. case FLAC__APODIZATION_BARTLETT_HANN:
  104163. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104164. break;
  104165. case FLAC__APODIZATION_BLACKMAN:
  104166. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104167. break;
  104168. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104169. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104170. break;
  104171. case FLAC__APODIZATION_CONNES:
  104172. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104173. break;
  104174. case FLAC__APODIZATION_FLATTOP:
  104175. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104176. break;
  104177. case FLAC__APODIZATION_GAUSS:
  104178. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104179. break;
  104180. case FLAC__APODIZATION_HAMMING:
  104181. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104182. break;
  104183. case FLAC__APODIZATION_HANN:
  104184. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104185. break;
  104186. case FLAC__APODIZATION_KAISER_BESSEL:
  104187. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104188. break;
  104189. case FLAC__APODIZATION_NUTTALL:
  104190. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104191. break;
  104192. case FLAC__APODIZATION_RECTANGLE:
  104193. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104194. break;
  104195. case FLAC__APODIZATION_TRIANGLE:
  104196. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104197. break;
  104198. case FLAC__APODIZATION_TUKEY:
  104199. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104200. break;
  104201. case FLAC__APODIZATION_WELCH:
  104202. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104203. break;
  104204. default:
  104205. FLAC__ASSERT(0);
  104206. /* double protection */
  104207. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104208. break;
  104209. }
  104210. }
  104211. }
  104212. #endif
  104213. if(ok)
  104214. encoder->private_->input_capacity = new_blocksize;
  104215. else
  104216. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104217. return ok;
  104218. }
  104219. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104220. {
  104221. const FLAC__byte *buffer;
  104222. size_t bytes;
  104223. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104224. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104225. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104226. return false;
  104227. }
  104228. if(encoder->protected_->verify) {
  104229. encoder->private_->verify.output.data = buffer;
  104230. encoder->private_->verify.output.bytes = bytes;
  104231. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104232. encoder->private_->verify.needs_magic_hack = true;
  104233. }
  104234. else {
  104235. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104236. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104237. FLAC__bitwriter_clear(encoder->private_->frame);
  104238. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104239. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104240. return false;
  104241. }
  104242. }
  104243. }
  104244. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104245. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104246. FLAC__bitwriter_clear(encoder->private_->frame);
  104247. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104248. return false;
  104249. }
  104250. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104251. FLAC__bitwriter_clear(encoder->private_->frame);
  104252. if(samples > 0) {
  104253. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104254. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104255. }
  104256. return true;
  104257. }
  104258. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104259. {
  104260. FLAC__StreamEncoderWriteStatus status;
  104261. FLAC__uint64 output_position = 0;
  104262. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104263. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104264. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104265. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104266. }
  104267. /*
  104268. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104269. */
  104270. if(samples == 0) {
  104271. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104272. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104273. encoder->protected_->streaminfo_offset = output_position;
  104274. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104275. encoder->protected_->seektable_offset = output_position;
  104276. }
  104277. /*
  104278. * Mark the current seek point if hit (if audio_offset == 0 that
  104279. * means we're still writing metadata and haven't hit the first
  104280. * frame yet)
  104281. */
  104282. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104283. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104284. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104285. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104286. FLAC__uint64 test_sample;
  104287. unsigned i;
  104288. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104289. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104290. if(test_sample > frame_last_sample) {
  104291. break;
  104292. }
  104293. else if(test_sample >= frame_first_sample) {
  104294. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104295. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104296. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104297. encoder->private_->first_seekpoint_to_check++;
  104298. /* DO NOT: "break;" and here's why:
  104299. * The seektable template may contain more than one target
  104300. * sample for any given frame; we will keep looping, generating
  104301. * duplicate seekpoints for them, and we'll clean it up later,
  104302. * just before writing the seektable back to the metadata.
  104303. */
  104304. }
  104305. else {
  104306. encoder->private_->first_seekpoint_to_check++;
  104307. }
  104308. }
  104309. }
  104310. #if FLAC__HAS_OGG
  104311. if(encoder->private_->is_ogg) {
  104312. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104313. &encoder->protected_->ogg_encoder_aspect,
  104314. buffer,
  104315. bytes,
  104316. samples,
  104317. encoder->private_->current_frame_number,
  104318. is_last_block,
  104319. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104320. encoder,
  104321. encoder->private_->client_data
  104322. );
  104323. }
  104324. else
  104325. #endif
  104326. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104327. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104328. encoder->private_->bytes_written += bytes;
  104329. encoder->private_->samples_written += samples;
  104330. /* we keep a high watermark on the number of frames written because
  104331. * when the encoder goes back to write metadata, 'current_frame'
  104332. * will drop back to 0.
  104333. */
  104334. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104335. }
  104336. else
  104337. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104338. return status;
  104339. }
  104340. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104341. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104342. {
  104343. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104344. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104345. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104346. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104347. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104348. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104349. FLAC__StreamEncoderSeekStatus seek_status;
  104350. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104351. /* All this is based on intimate knowledge of the stream header
  104352. * layout, but a change to the header format that would break this
  104353. * would also break all streams encoded in the previous format.
  104354. */
  104355. /*
  104356. * Write MD5 signature
  104357. */
  104358. {
  104359. const unsigned md5_offset =
  104360. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104361. (
  104362. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104363. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104364. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104365. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104366. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104367. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104368. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104369. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104370. ) / 8;
  104371. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104372. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104373. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104374. return;
  104375. }
  104376. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104377. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104378. return;
  104379. }
  104380. }
  104381. /*
  104382. * Write total samples
  104383. */
  104384. {
  104385. const unsigned total_samples_byte_offset =
  104386. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104387. (
  104388. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104389. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104390. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104391. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104392. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104393. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104394. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104395. - 4
  104396. ) / 8;
  104397. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104398. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104399. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104400. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104401. b[4] = (FLAC__byte)(samples & 0xFF);
  104402. 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) {
  104403. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104404. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104405. return;
  104406. }
  104407. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104408. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104409. return;
  104410. }
  104411. }
  104412. /*
  104413. * Write min/max framesize
  104414. */
  104415. {
  104416. const unsigned min_framesize_offset =
  104417. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104418. (
  104419. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104420. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104421. ) / 8;
  104422. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104423. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104424. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104425. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104426. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104427. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104428. 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) {
  104429. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104430. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104431. return;
  104432. }
  104433. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104434. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104435. return;
  104436. }
  104437. }
  104438. /*
  104439. * Write seektable
  104440. */
  104441. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104442. unsigned i;
  104443. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104444. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104445. 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) {
  104446. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104447. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104448. return;
  104449. }
  104450. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104451. FLAC__uint64 xx;
  104452. unsigned x;
  104453. xx = encoder->private_->seek_table->points[i].sample_number;
  104454. b[7] = (FLAC__byte)xx; xx >>= 8;
  104455. b[6] = (FLAC__byte)xx; xx >>= 8;
  104456. b[5] = (FLAC__byte)xx; xx >>= 8;
  104457. b[4] = (FLAC__byte)xx; xx >>= 8;
  104458. b[3] = (FLAC__byte)xx; xx >>= 8;
  104459. b[2] = (FLAC__byte)xx; xx >>= 8;
  104460. b[1] = (FLAC__byte)xx; xx >>= 8;
  104461. b[0] = (FLAC__byte)xx; xx >>= 8;
  104462. xx = encoder->private_->seek_table->points[i].stream_offset;
  104463. b[15] = (FLAC__byte)xx; xx >>= 8;
  104464. b[14] = (FLAC__byte)xx; xx >>= 8;
  104465. b[13] = (FLAC__byte)xx; xx >>= 8;
  104466. b[12] = (FLAC__byte)xx; xx >>= 8;
  104467. b[11] = (FLAC__byte)xx; xx >>= 8;
  104468. b[10] = (FLAC__byte)xx; xx >>= 8;
  104469. b[9] = (FLAC__byte)xx; xx >>= 8;
  104470. b[8] = (FLAC__byte)xx; xx >>= 8;
  104471. x = encoder->private_->seek_table->points[i].frame_samples;
  104472. b[17] = (FLAC__byte)x; x >>= 8;
  104473. b[16] = (FLAC__byte)x; x >>= 8;
  104474. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104475. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104476. return;
  104477. }
  104478. }
  104479. }
  104480. }
  104481. #if FLAC__HAS_OGG
  104482. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104483. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104484. {
  104485. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104486. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104487. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104488. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104489. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104490. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104491. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104492. FLAC__STREAM_SYNC_LENGTH
  104493. ;
  104494. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104495. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104496. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104497. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104498. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104499. ogg_page page;
  104500. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104501. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104502. /* Pre-check that client supports seeking, since we don't want the
  104503. * ogg_helper code to ever have to deal with this condition.
  104504. */
  104505. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104506. return;
  104507. /* All this is based on intimate knowledge of the stream header
  104508. * layout, but a change to the header format that would break this
  104509. * would also break all streams encoded in the previous format.
  104510. */
  104511. /**
  104512. ** Write STREAMINFO stats
  104513. **/
  104514. simple_ogg_page__init(&page);
  104515. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104516. simple_ogg_page__clear(&page);
  104517. return; /* state already set */
  104518. }
  104519. /*
  104520. * Write MD5 signature
  104521. */
  104522. {
  104523. const unsigned md5_offset =
  104524. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104525. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104526. (
  104527. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104528. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104529. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104530. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104531. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104532. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104533. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104534. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104535. ) / 8;
  104536. if(md5_offset + 16 > (unsigned)page.body_len) {
  104537. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104538. simple_ogg_page__clear(&page);
  104539. return;
  104540. }
  104541. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104542. }
  104543. /*
  104544. * Write total samples
  104545. */
  104546. {
  104547. const unsigned total_samples_byte_offset =
  104548. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104549. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104550. (
  104551. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104552. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104553. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104554. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104555. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104556. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104557. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104558. - 4
  104559. ) / 8;
  104560. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104561. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104562. simple_ogg_page__clear(&page);
  104563. return;
  104564. }
  104565. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104566. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104567. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104568. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104569. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104570. b[4] = (FLAC__byte)(samples & 0xFF);
  104571. memcpy(page.body + total_samples_byte_offset, b, 5);
  104572. }
  104573. /*
  104574. * Write min/max framesize
  104575. */
  104576. {
  104577. const unsigned min_framesize_offset =
  104578. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104579. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104580. (
  104581. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104582. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104583. ) / 8;
  104584. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104585. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104586. simple_ogg_page__clear(&page);
  104587. return;
  104588. }
  104589. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104590. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104591. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104592. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104593. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104594. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104595. memcpy(page.body + min_framesize_offset, b, 6);
  104596. }
  104597. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104598. simple_ogg_page__clear(&page);
  104599. return; /* state already set */
  104600. }
  104601. simple_ogg_page__clear(&page);
  104602. /*
  104603. * Write seektable
  104604. */
  104605. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104606. unsigned i;
  104607. FLAC__byte *p;
  104608. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104609. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104610. simple_ogg_page__init(&page);
  104611. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104612. simple_ogg_page__clear(&page);
  104613. return; /* state already set */
  104614. }
  104615. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104616. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104617. simple_ogg_page__clear(&page);
  104618. return;
  104619. }
  104620. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104621. FLAC__uint64 xx;
  104622. unsigned x;
  104623. xx = encoder->private_->seek_table->points[i].sample_number;
  104624. b[7] = (FLAC__byte)xx; xx >>= 8;
  104625. b[6] = (FLAC__byte)xx; xx >>= 8;
  104626. b[5] = (FLAC__byte)xx; xx >>= 8;
  104627. b[4] = (FLAC__byte)xx; xx >>= 8;
  104628. b[3] = (FLAC__byte)xx; xx >>= 8;
  104629. b[2] = (FLAC__byte)xx; xx >>= 8;
  104630. b[1] = (FLAC__byte)xx; xx >>= 8;
  104631. b[0] = (FLAC__byte)xx; xx >>= 8;
  104632. xx = encoder->private_->seek_table->points[i].stream_offset;
  104633. b[15] = (FLAC__byte)xx; xx >>= 8;
  104634. b[14] = (FLAC__byte)xx; xx >>= 8;
  104635. b[13] = (FLAC__byte)xx; xx >>= 8;
  104636. b[12] = (FLAC__byte)xx; xx >>= 8;
  104637. b[11] = (FLAC__byte)xx; xx >>= 8;
  104638. b[10] = (FLAC__byte)xx; xx >>= 8;
  104639. b[9] = (FLAC__byte)xx; xx >>= 8;
  104640. b[8] = (FLAC__byte)xx; xx >>= 8;
  104641. x = encoder->private_->seek_table->points[i].frame_samples;
  104642. b[17] = (FLAC__byte)x; x >>= 8;
  104643. b[16] = (FLAC__byte)x; x >>= 8;
  104644. memcpy(p, b, 18);
  104645. }
  104646. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104647. simple_ogg_page__clear(&page);
  104648. return; /* state already set */
  104649. }
  104650. simple_ogg_page__clear(&page);
  104651. }
  104652. }
  104653. #endif
  104654. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104655. {
  104656. FLAC__uint16 crc;
  104657. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104658. /*
  104659. * Accumulate raw signal to the MD5 signature
  104660. */
  104661. 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)) {
  104662. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104663. return false;
  104664. }
  104665. /*
  104666. * Process the frame header and subframes into the frame bitbuffer
  104667. */
  104668. if(!process_subframes_(encoder, is_fractional_block)) {
  104669. /* the above function sets the state for us in case of an error */
  104670. return false;
  104671. }
  104672. /*
  104673. * Zero-pad the frame to a byte_boundary
  104674. */
  104675. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104676. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104677. return false;
  104678. }
  104679. /*
  104680. * CRC-16 the whole thing
  104681. */
  104682. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104683. if(
  104684. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104685. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104686. ) {
  104687. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104688. return false;
  104689. }
  104690. /*
  104691. * Write it
  104692. */
  104693. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104694. /* the above function sets the state for us in case of an error */
  104695. return false;
  104696. }
  104697. /*
  104698. * Get ready for the next frame
  104699. */
  104700. encoder->private_->current_sample_number = 0;
  104701. encoder->private_->current_frame_number++;
  104702. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104703. return true;
  104704. }
  104705. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104706. {
  104707. FLAC__FrameHeader frame_header;
  104708. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104709. FLAC__bool do_independent, do_mid_side;
  104710. /*
  104711. * Calculate the min,max Rice partition orders
  104712. */
  104713. if(is_fractional_block) {
  104714. max_partition_order = 0;
  104715. }
  104716. else {
  104717. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104718. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104719. }
  104720. min_partition_order = min(min_partition_order, max_partition_order);
  104721. /*
  104722. * Setup the frame
  104723. */
  104724. frame_header.blocksize = encoder->protected_->blocksize;
  104725. frame_header.sample_rate = encoder->protected_->sample_rate;
  104726. frame_header.channels = encoder->protected_->channels;
  104727. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104728. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104729. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104730. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104731. /*
  104732. * Figure out what channel assignments to try
  104733. */
  104734. if(encoder->protected_->do_mid_side_stereo) {
  104735. if(encoder->protected_->loose_mid_side_stereo) {
  104736. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104737. do_independent = true;
  104738. do_mid_side = true;
  104739. }
  104740. else {
  104741. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104742. do_mid_side = !do_independent;
  104743. }
  104744. }
  104745. else {
  104746. do_independent = true;
  104747. do_mid_side = true;
  104748. }
  104749. }
  104750. else {
  104751. do_independent = true;
  104752. do_mid_side = false;
  104753. }
  104754. FLAC__ASSERT(do_independent || do_mid_side);
  104755. /*
  104756. * Check for wasted bits; set effective bps for each subframe
  104757. */
  104758. if(do_independent) {
  104759. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104760. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104761. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104762. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104763. }
  104764. }
  104765. if(do_mid_side) {
  104766. FLAC__ASSERT(encoder->protected_->channels == 2);
  104767. for(channel = 0; channel < 2; channel++) {
  104768. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104769. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104770. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104771. }
  104772. }
  104773. /*
  104774. * First do a normal encoding pass of each independent channel
  104775. */
  104776. if(do_independent) {
  104777. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104778. if(!
  104779. process_subframe_(
  104780. encoder,
  104781. min_partition_order,
  104782. max_partition_order,
  104783. &frame_header,
  104784. encoder->private_->subframe_bps[channel],
  104785. encoder->private_->integer_signal[channel],
  104786. encoder->private_->subframe_workspace_ptr[channel],
  104787. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104788. encoder->private_->residual_workspace[channel],
  104789. encoder->private_->best_subframe+channel,
  104790. encoder->private_->best_subframe_bits+channel
  104791. )
  104792. )
  104793. return false;
  104794. }
  104795. }
  104796. /*
  104797. * Now do mid and side channels if requested
  104798. */
  104799. if(do_mid_side) {
  104800. FLAC__ASSERT(encoder->protected_->channels == 2);
  104801. for(channel = 0; channel < 2; channel++) {
  104802. if(!
  104803. process_subframe_(
  104804. encoder,
  104805. min_partition_order,
  104806. max_partition_order,
  104807. &frame_header,
  104808. encoder->private_->subframe_bps_mid_side[channel],
  104809. encoder->private_->integer_signal_mid_side[channel],
  104810. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104811. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104812. encoder->private_->residual_workspace_mid_side[channel],
  104813. encoder->private_->best_subframe_mid_side+channel,
  104814. encoder->private_->best_subframe_bits_mid_side+channel
  104815. )
  104816. )
  104817. return false;
  104818. }
  104819. }
  104820. /*
  104821. * Compose the frame bitbuffer
  104822. */
  104823. if(do_mid_side) {
  104824. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104825. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104826. FLAC__ChannelAssignment channel_assignment;
  104827. FLAC__ASSERT(encoder->protected_->channels == 2);
  104828. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104829. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104830. }
  104831. else {
  104832. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104833. unsigned min_bits;
  104834. int ca;
  104835. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104836. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104837. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104838. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104839. FLAC__ASSERT(do_independent && do_mid_side);
  104840. /* We have to figure out which channel assignent results in the smallest frame */
  104841. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104842. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104843. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104844. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104845. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104846. min_bits = bits[channel_assignment];
  104847. for(ca = 1; ca <= 3; ca++) {
  104848. if(bits[ca] < min_bits) {
  104849. min_bits = bits[ca];
  104850. channel_assignment = (FLAC__ChannelAssignment)ca;
  104851. }
  104852. }
  104853. }
  104854. frame_header.channel_assignment = channel_assignment;
  104855. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104856. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104857. return false;
  104858. }
  104859. switch(channel_assignment) {
  104860. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104861. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104862. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104863. break;
  104864. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104865. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104866. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104867. break;
  104868. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104869. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104870. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104871. break;
  104872. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104873. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104874. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104875. break;
  104876. default:
  104877. FLAC__ASSERT(0);
  104878. }
  104879. switch(channel_assignment) {
  104880. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104881. left_bps = encoder->private_->subframe_bps [0];
  104882. right_bps = encoder->private_->subframe_bps [1];
  104883. break;
  104884. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104885. left_bps = encoder->private_->subframe_bps [0];
  104886. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104887. break;
  104888. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104889. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104890. right_bps = encoder->private_->subframe_bps [1];
  104891. break;
  104892. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104893. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104894. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104895. break;
  104896. default:
  104897. FLAC__ASSERT(0);
  104898. }
  104899. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104900. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104901. return false;
  104902. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104903. return false;
  104904. }
  104905. else {
  104906. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104907. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104908. return false;
  104909. }
  104910. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104911. 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)) {
  104912. /* the above function sets the state for us in case of an error */
  104913. return false;
  104914. }
  104915. }
  104916. }
  104917. if(encoder->protected_->loose_mid_side_stereo) {
  104918. encoder->private_->loose_mid_side_stereo_frame_count++;
  104919. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104920. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104921. }
  104922. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104923. return true;
  104924. }
  104925. FLAC__bool process_subframe_(
  104926. FLAC__StreamEncoder *encoder,
  104927. unsigned min_partition_order,
  104928. unsigned max_partition_order,
  104929. const FLAC__FrameHeader *frame_header,
  104930. unsigned subframe_bps,
  104931. const FLAC__int32 integer_signal[],
  104932. FLAC__Subframe *subframe[2],
  104933. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104934. FLAC__int32 *residual[2],
  104935. unsigned *best_subframe,
  104936. unsigned *best_bits
  104937. )
  104938. {
  104939. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104940. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104941. #else
  104942. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104943. #endif
  104944. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104945. FLAC__double lpc_residual_bits_per_sample;
  104946. 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 */
  104947. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104948. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104949. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104950. #endif
  104951. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104952. unsigned rice_parameter;
  104953. unsigned _candidate_bits, _best_bits;
  104954. unsigned _best_subframe;
  104955. /* only use RICE2 partitions if stream bps > 16 */
  104956. 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;
  104957. FLAC__ASSERT(frame_header->blocksize > 0);
  104958. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104959. _best_subframe = 0;
  104960. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104961. _best_bits = UINT_MAX;
  104962. else
  104963. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104964. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104965. unsigned signal_is_constant = false;
  104966. 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);
  104967. /* check for constant subframe */
  104968. if(
  104969. !encoder->private_->disable_constant_subframes &&
  104970. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104971. fixed_residual_bits_per_sample[1] == 0.0
  104972. #else
  104973. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104974. #endif
  104975. ) {
  104976. /* the above means it's possible all samples are the same value; now double-check it: */
  104977. unsigned i;
  104978. signal_is_constant = true;
  104979. for(i = 1; i < frame_header->blocksize; i++) {
  104980. if(integer_signal[0] != integer_signal[i]) {
  104981. signal_is_constant = false;
  104982. break;
  104983. }
  104984. }
  104985. }
  104986. if(signal_is_constant) {
  104987. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104988. if(_candidate_bits < _best_bits) {
  104989. _best_subframe = !_best_subframe;
  104990. _best_bits = _candidate_bits;
  104991. }
  104992. }
  104993. else {
  104994. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104995. /* encode fixed */
  104996. if(encoder->protected_->do_exhaustive_model_search) {
  104997. min_fixed_order = 0;
  104998. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104999. }
  105000. else {
  105001. min_fixed_order = max_fixed_order = guess_fixed_order;
  105002. }
  105003. if(max_fixed_order >= frame_header->blocksize)
  105004. max_fixed_order = frame_header->blocksize - 1;
  105005. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105006. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105007. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105008. continue; /* don't even try */
  105009. 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 */
  105010. #else
  105011. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105012. continue; /* don't even try */
  105013. 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 */
  105014. #endif
  105015. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105016. if(rice_parameter >= rice_parameter_limit) {
  105017. #ifdef DEBUG_VERBOSE
  105018. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105019. #endif
  105020. rice_parameter = rice_parameter_limit - 1;
  105021. }
  105022. _candidate_bits =
  105023. evaluate_fixed_subframe_(
  105024. encoder,
  105025. integer_signal,
  105026. residual[!_best_subframe],
  105027. encoder->private_->abs_residual_partition_sums,
  105028. encoder->private_->raw_bits_per_partition,
  105029. frame_header->blocksize,
  105030. subframe_bps,
  105031. fixed_order,
  105032. rice_parameter,
  105033. rice_parameter_limit,
  105034. min_partition_order,
  105035. max_partition_order,
  105036. encoder->protected_->do_escape_coding,
  105037. encoder->protected_->rice_parameter_search_dist,
  105038. subframe[!_best_subframe],
  105039. partitioned_rice_contents[!_best_subframe]
  105040. );
  105041. if(_candidate_bits < _best_bits) {
  105042. _best_subframe = !_best_subframe;
  105043. _best_bits = _candidate_bits;
  105044. }
  105045. }
  105046. }
  105047. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105048. /* encode lpc */
  105049. if(encoder->protected_->max_lpc_order > 0) {
  105050. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105051. max_lpc_order = frame_header->blocksize-1;
  105052. else
  105053. max_lpc_order = encoder->protected_->max_lpc_order;
  105054. if(max_lpc_order > 0) {
  105055. unsigned a;
  105056. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105057. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105058. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105059. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105060. if(autoc[0] != 0.0) {
  105061. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105062. if(encoder->protected_->do_exhaustive_model_search) {
  105063. min_lpc_order = 1;
  105064. }
  105065. else {
  105066. const unsigned guess_lpc_order =
  105067. FLAC__lpc_compute_best_order(
  105068. lpc_error,
  105069. max_lpc_order,
  105070. frame_header->blocksize,
  105071. subframe_bps + (
  105072. encoder->protected_->do_qlp_coeff_prec_search?
  105073. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105074. encoder->protected_->qlp_coeff_precision
  105075. )
  105076. );
  105077. min_lpc_order = max_lpc_order = guess_lpc_order;
  105078. }
  105079. if(max_lpc_order >= frame_header->blocksize)
  105080. max_lpc_order = frame_header->blocksize - 1;
  105081. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105082. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105083. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105084. continue; /* don't even try */
  105085. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105086. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105087. if(rice_parameter >= rice_parameter_limit) {
  105088. #ifdef DEBUG_VERBOSE
  105089. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105090. #endif
  105091. rice_parameter = rice_parameter_limit - 1;
  105092. }
  105093. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105094. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105095. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105096. if(subframe_bps <= 17) {
  105097. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105098. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105099. }
  105100. else
  105101. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105102. }
  105103. else {
  105104. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105105. }
  105106. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105107. _candidate_bits =
  105108. evaluate_lpc_subframe_(
  105109. encoder,
  105110. integer_signal,
  105111. residual[!_best_subframe],
  105112. encoder->private_->abs_residual_partition_sums,
  105113. encoder->private_->raw_bits_per_partition,
  105114. encoder->private_->lp_coeff[lpc_order-1],
  105115. frame_header->blocksize,
  105116. subframe_bps,
  105117. lpc_order,
  105118. qlp_coeff_precision,
  105119. rice_parameter,
  105120. rice_parameter_limit,
  105121. min_partition_order,
  105122. max_partition_order,
  105123. encoder->protected_->do_escape_coding,
  105124. encoder->protected_->rice_parameter_search_dist,
  105125. subframe[!_best_subframe],
  105126. partitioned_rice_contents[!_best_subframe]
  105127. );
  105128. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105129. if(_candidate_bits < _best_bits) {
  105130. _best_subframe = !_best_subframe;
  105131. _best_bits = _candidate_bits;
  105132. }
  105133. }
  105134. }
  105135. }
  105136. }
  105137. }
  105138. }
  105139. }
  105140. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105141. }
  105142. }
  105143. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105144. if(_best_bits == UINT_MAX) {
  105145. FLAC__ASSERT(_best_subframe == 0);
  105146. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105147. }
  105148. *best_subframe = _best_subframe;
  105149. *best_bits = _best_bits;
  105150. return true;
  105151. }
  105152. FLAC__bool add_subframe_(
  105153. FLAC__StreamEncoder *encoder,
  105154. unsigned blocksize,
  105155. unsigned subframe_bps,
  105156. const FLAC__Subframe *subframe,
  105157. FLAC__BitWriter *frame
  105158. )
  105159. {
  105160. switch(subframe->type) {
  105161. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105162. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105163. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105164. return false;
  105165. }
  105166. break;
  105167. case FLAC__SUBFRAME_TYPE_FIXED:
  105168. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105169. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105170. return false;
  105171. }
  105172. break;
  105173. case FLAC__SUBFRAME_TYPE_LPC:
  105174. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105175. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105176. return false;
  105177. }
  105178. break;
  105179. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105180. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105181. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105182. return false;
  105183. }
  105184. break;
  105185. default:
  105186. FLAC__ASSERT(0);
  105187. }
  105188. return true;
  105189. }
  105190. #define SPOTCHECK_ESTIMATE 0
  105191. #if SPOTCHECK_ESTIMATE
  105192. static void spotcheck_subframe_estimate_(
  105193. FLAC__StreamEncoder *encoder,
  105194. unsigned blocksize,
  105195. unsigned subframe_bps,
  105196. const FLAC__Subframe *subframe,
  105197. unsigned estimate
  105198. )
  105199. {
  105200. FLAC__bool ret;
  105201. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105202. if(frame == 0) {
  105203. fprintf(stderr, "EST: can't allocate frame\n");
  105204. return;
  105205. }
  105206. if(!FLAC__bitwriter_init(frame)) {
  105207. fprintf(stderr, "EST: can't init frame\n");
  105208. return;
  105209. }
  105210. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105211. FLAC__ASSERT(ret);
  105212. {
  105213. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105214. if(estimate != actual)
  105215. 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);
  105216. }
  105217. FLAC__bitwriter_delete(frame);
  105218. }
  105219. #endif
  105220. unsigned evaluate_constant_subframe_(
  105221. FLAC__StreamEncoder *encoder,
  105222. const FLAC__int32 signal,
  105223. unsigned blocksize,
  105224. unsigned subframe_bps,
  105225. FLAC__Subframe *subframe
  105226. )
  105227. {
  105228. unsigned estimate;
  105229. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105230. subframe->data.constant.value = signal;
  105231. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105232. #if SPOTCHECK_ESTIMATE
  105233. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105234. #else
  105235. (void)encoder, (void)blocksize;
  105236. #endif
  105237. return estimate;
  105238. }
  105239. unsigned evaluate_fixed_subframe_(
  105240. FLAC__StreamEncoder *encoder,
  105241. const FLAC__int32 signal[],
  105242. FLAC__int32 residual[],
  105243. FLAC__uint64 abs_residual_partition_sums[],
  105244. unsigned raw_bits_per_partition[],
  105245. unsigned blocksize,
  105246. unsigned subframe_bps,
  105247. unsigned order,
  105248. unsigned rice_parameter,
  105249. unsigned rice_parameter_limit,
  105250. unsigned min_partition_order,
  105251. unsigned max_partition_order,
  105252. FLAC__bool do_escape_coding,
  105253. unsigned rice_parameter_search_dist,
  105254. FLAC__Subframe *subframe,
  105255. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105256. )
  105257. {
  105258. unsigned i, residual_bits, estimate;
  105259. const unsigned residual_samples = blocksize - order;
  105260. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105261. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105262. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105263. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105264. subframe->data.fixed.residual = residual;
  105265. residual_bits =
  105266. find_best_partition_order_(
  105267. encoder->private_,
  105268. residual,
  105269. abs_residual_partition_sums,
  105270. raw_bits_per_partition,
  105271. residual_samples,
  105272. order,
  105273. rice_parameter,
  105274. rice_parameter_limit,
  105275. min_partition_order,
  105276. max_partition_order,
  105277. subframe_bps,
  105278. do_escape_coding,
  105279. rice_parameter_search_dist,
  105280. &subframe->data.fixed.entropy_coding_method
  105281. );
  105282. subframe->data.fixed.order = order;
  105283. for(i = 0; i < order; i++)
  105284. subframe->data.fixed.warmup[i] = signal[i];
  105285. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105286. #if SPOTCHECK_ESTIMATE
  105287. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105288. #endif
  105289. return estimate;
  105290. }
  105291. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105292. unsigned evaluate_lpc_subframe_(
  105293. FLAC__StreamEncoder *encoder,
  105294. const FLAC__int32 signal[],
  105295. FLAC__int32 residual[],
  105296. FLAC__uint64 abs_residual_partition_sums[],
  105297. unsigned raw_bits_per_partition[],
  105298. const FLAC__real lp_coeff[],
  105299. unsigned blocksize,
  105300. unsigned subframe_bps,
  105301. unsigned order,
  105302. unsigned qlp_coeff_precision,
  105303. unsigned rice_parameter,
  105304. unsigned rice_parameter_limit,
  105305. unsigned min_partition_order,
  105306. unsigned max_partition_order,
  105307. FLAC__bool do_escape_coding,
  105308. unsigned rice_parameter_search_dist,
  105309. FLAC__Subframe *subframe,
  105310. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105311. )
  105312. {
  105313. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105314. unsigned i, residual_bits, estimate;
  105315. int quantization, ret;
  105316. const unsigned residual_samples = blocksize - order;
  105317. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105318. if(subframe_bps <= 16) {
  105319. FLAC__ASSERT(order > 0);
  105320. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105321. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105322. }
  105323. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105324. if(ret != 0)
  105325. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105326. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105327. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105328. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105329. else
  105330. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105331. else
  105332. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105333. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105334. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105335. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105336. subframe->data.lpc.residual = residual;
  105337. residual_bits =
  105338. find_best_partition_order_(
  105339. encoder->private_,
  105340. residual,
  105341. abs_residual_partition_sums,
  105342. raw_bits_per_partition,
  105343. residual_samples,
  105344. order,
  105345. rice_parameter,
  105346. rice_parameter_limit,
  105347. min_partition_order,
  105348. max_partition_order,
  105349. subframe_bps,
  105350. do_escape_coding,
  105351. rice_parameter_search_dist,
  105352. &subframe->data.lpc.entropy_coding_method
  105353. );
  105354. subframe->data.lpc.order = order;
  105355. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105356. subframe->data.lpc.quantization_level = quantization;
  105357. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105358. for(i = 0; i < order; i++)
  105359. subframe->data.lpc.warmup[i] = signal[i];
  105360. 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;
  105361. #if SPOTCHECK_ESTIMATE
  105362. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105363. #endif
  105364. return estimate;
  105365. }
  105366. #endif
  105367. unsigned evaluate_verbatim_subframe_(
  105368. FLAC__StreamEncoder *encoder,
  105369. const FLAC__int32 signal[],
  105370. unsigned blocksize,
  105371. unsigned subframe_bps,
  105372. FLAC__Subframe *subframe
  105373. )
  105374. {
  105375. unsigned estimate;
  105376. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105377. subframe->data.verbatim.data = signal;
  105378. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105379. #if SPOTCHECK_ESTIMATE
  105380. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105381. #else
  105382. (void)encoder;
  105383. #endif
  105384. return estimate;
  105385. }
  105386. unsigned find_best_partition_order_(
  105387. FLAC__StreamEncoderPrivate *private_,
  105388. const FLAC__int32 residual[],
  105389. FLAC__uint64 abs_residual_partition_sums[],
  105390. unsigned raw_bits_per_partition[],
  105391. unsigned residual_samples,
  105392. unsigned predictor_order,
  105393. unsigned rice_parameter,
  105394. unsigned rice_parameter_limit,
  105395. unsigned min_partition_order,
  105396. unsigned max_partition_order,
  105397. unsigned bps,
  105398. FLAC__bool do_escape_coding,
  105399. unsigned rice_parameter_search_dist,
  105400. FLAC__EntropyCodingMethod *best_ecm
  105401. )
  105402. {
  105403. unsigned residual_bits, best_residual_bits = 0;
  105404. unsigned best_parameters_index = 0;
  105405. unsigned best_partition_order = 0;
  105406. const unsigned blocksize = residual_samples + predictor_order;
  105407. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105408. min_partition_order = min(min_partition_order, max_partition_order);
  105409. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105410. if(do_escape_coding)
  105411. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105412. {
  105413. int partition_order;
  105414. unsigned sum;
  105415. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105416. if(!
  105417. set_partitioned_rice_(
  105418. #ifdef EXACT_RICE_BITS_CALCULATION
  105419. residual,
  105420. #endif
  105421. abs_residual_partition_sums+sum,
  105422. raw_bits_per_partition+sum,
  105423. residual_samples,
  105424. predictor_order,
  105425. rice_parameter,
  105426. rice_parameter_limit,
  105427. rice_parameter_search_dist,
  105428. (unsigned)partition_order,
  105429. do_escape_coding,
  105430. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105431. &residual_bits
  105432. )
  105433. )
  105434. {
  105435. FLAC__ASSERT(best_residual_bits != 0);
  105436. break;
  105437. }
  105438. sum += 1u << partition_order;
  105439. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105440. best_residual_bits = residual_bits;
  105441. best_parameters_index = !best_parameters_index;
  105442. best_partition_order = partition_order;
  105443. }
  105444. }
  105445. }
  105446. best_ecm->data.partitioned_rice.order = best_partition_order;
  105447. {
  105448. /*
  105449. * We are allowed to de-const the pointer based on our special
  105450. * knowledge; it is const to the outside world.
  105451. */
  105452. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105453. unsigned partition;
  105454. /* save best parameters and raw_bits */
  105455. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105456. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105457. if(do_escape_coding)
  105458. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105459. /*
  105460. * Now need to check if the type should be changed to
  105461. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105462. * size of the rice parameters.
  105463. */
  105464. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105465. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105466. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105467. break;
  105468. }
  105469. }
  105470. }
  105471. return best_residual_bits;
  105472. }
  105473. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105474. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105475. const FLAC__int32 residual[],
  105476. FLAC__uint64 abs_residual_partition_sums[],
  105477. unsigned blocksize,
  105478. unsigned predictor_order,
  105479. unsigned min_partition_order,
  105480. unsigned max_partition_order
  105481. );
  105482. #endif
  105483. void precompute_partition_info_sums_(
  105484. const FLAC__int32 residual[],
  105485. FLAC__uint64 abs_residual_partition_sums[],
  105486. unsigned residual_samples,
  105487. unsigned predictor_order,
  105488. unsigned min_partition_order,
  105489. unsigned max_partition_order,
  105490. unsigned bps
  105491. )
  105492. {
  105493. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105494. unsigned partitions = 1u << max_partition_order;
  105495. FLAC__ASSERT(default_partition_samples > predictor_order);
  105496. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105497. /* slightly pessimistic but still catches all common cases */
  105498. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105499. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105500. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105501. return;
  105502. }
  105503. #endif
  105504. /* first do max_partition_order */
  105505. {
  105506. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105507. /* slightly pessimistic but still catches all common cases */
  105508. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105509. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105510. FLAC__uint32 abs_residual_partition_sum;
  105511. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105512. end += default_partition_samples;
  105513. abs_residual_partition_sum = 0;
  105514. for( ; residual_sample < end; residual_sample++)
  105515. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105516. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105517. }
  105518. }
  105519. else { /* have to pessimistically use 64 bits for accumulator */
  105520. FLAC__uint64 abs_residual_partition_sum;
  105521. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105522. end += default_partition_samples;
  105523. abs_residual_partition_sum = 0;
  105524. for( ; residual_sample < end; residual_sample++)
  105525. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105526. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105527. }
  105528. }
  105529. }
  105530. /* now merge partitions for lower orders */
  105531. {
  105532. unsigned from_partition = 0, to_partition = partitions;
  105533. int partition_order;
  105534. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105535. unsigned i;
  105536. partitions >>= 1;
  105537. for(i = 0; i < partitions; i++) {
  105538. abs_residual_partition_sums[to_partition++] =
  105539. abs_residual_partition_sums[from_partition ] +
  105540. abs_residual_partition_sums[from_partition+1];
  105541. from_partition += 2;
  105542. }
  105543. }
  105544. }
  105545. }
  105546. void precompute_partition_info_escapes_(
  105547. const FLAC__int32 residual[],
  105548. unsigned raw_bits_per_partition[],
  105549. unsigned residual_samples,
  105550. unsigned predictor_order,
  105551. unsigned min_partition_order,
  105552. unsigned max_partition_order
  105553. )
  105554. {
  105555. int partition_order;
  105556. unsigned from_partition, to_partition = 0;
  105557. const unsigned blocksize = residual_samples + predictor_order;
  105558. /* first do max_partition_order */
  105559. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105560. FLAC__int32 r;
  105561. FLAC__uint32 rmax;
  105562. unsigned partition, partition_sample, partition_samples, residual_sample;
  105563. const unsigned partitions = 1u << partition_order;
  105564. const unsigned default_partition_samples = blocksize >> partition_order;
  105565. FLAC__ASSERT(default_partition_samples > predictor_order);
  105566. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105567. partition_samples = default_partition_samples;
  105568. if(partition == 0)
  105569. partition_samples -= predictor_order;
  105570. rmax = 0;
  105571. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105572. r = residual[residual_sample++];
  105573. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105574. if(r < 0)
  105575. rmax |= ~r;
  105576. else
  105577. rmax |= r;
  105578. }
  105579. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105580. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105581. }
  105582. to_partition = partitions;
  105583. break; /*@@@ yuck, should remove the 'for' loop instead */
  105584. }
  105585. /* now merge partitions for lower orders */
  105586. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105587. unsigned m;
  105588. unsigned i;
  105589. const unsigned partitions = 1u << partition_order;
  105590. for(i = 0; i < partitions; i++) {
  105591. m = raw_bits_per_partition[from_partition];
  105592. from_partition++;
  105593. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105594. from_partition++;
  105595. to_partition++;
  105596. }
  105597. }
  105598. }
  105599. #ifdef EXACT_RICE_BITS_CALCULATION
  105600. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105601. const unsigned rice_parameter,
  105602. const unsigned partition_samples,
  105603. const FLAC__int32 *residual
  105604. )
  105605. {
  105606. unsigned i, partition_bits =
  105607. 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 */
  105608. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105609. ;
  105610. for(i = 0; i < partition_samples; i++)
  105611. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105612. return partition_bits;
  105613. }
  105614. #else
  105615. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105616. const unsigned rice_parameter,
  105617. const unsigned partition_samples,
  105618. const FLAC__uint64 abs_residual_partition_sum
  105619. )
  105620. {
  105621. return
  105622. 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 */
  105623. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105624. (
  105625. rice_parameter?
  105626. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105627. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105628. )
  105629. - (partition_samples >> 1)
  105630. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105631. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105632. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105633. * So the subtraction term tries to guess how many extra bits were contributed.
  105634. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105635. */
  105636. ;
  105637. }
  105638. #endif
  105639. FLAC__bool set_partitioned_rice_(
  105640. #ifdef EXACT_RICE_BITS_CALCULATION
  105641. const FLAC__int32 residual[],
  105642. #endif
  105643. const FLAC__uint64 abs_residual_partition_sums[],
  105644. const unsigned raw_bits_per_partition[],
  105645. const unsigned residual_samples,
  105646. const unsigned predictor_order,
  105647. const unsigned suggested_rice_parameter,
  105648. const unsigned rice_parameter_limit,
  105649. const unsigned rice_parameter_search_dist,
  105650. const unsigned partition_order,
  105651. const FLAC__bool search_for_escapes,
  105652. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105653. unsigned *bits
  105654. )
  105655. {
  105656. unsigned rice_parameter, partition_bits;
  105657. unsigned best_partition_bits, best_rice_parameter = 0;
  105658. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105659. unsigned *parameters, *raw_bits;
  105660. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105661. unsigned min_rice_parameter, max_rice_parameter;
  105662. #else
  105663. (void)rice_parameter_search_dist;
  105664. #endif
  105665. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105666. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105667. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105668. parameters = partitioned_rice_contents->parameters;
  105669. raw_bits = partitioned_rice_contents->raw_bits;
  105670. if(partition_order == 0) {
  105671. best_partition_bits = (unsigned)(-1);
  105672. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105673. if(rice_parameter_search_dist) {
  105674. if(suggested_rice_parameter < rice_parameter_search_dist)
  105675. min_rice_parameter = 0;
  105676. else
  105677. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105678. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105679. if(max_rice_parameter >= rice_parameter_limit) {
  105680. #ifdef DEBUG_VERBOSE
  105681. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105682. #endif
  105683. max_rice_parameter = rice_parameter_limit - 1;
  105684. }
  105685. }
  105686. else
  105687. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105688. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105689. #else
  105690. rice_parameter = suggested_rice_parameter;
  105691. #endif
  105692. #ifdef EXACT_RICE_BITS_CALCULATION
  105693. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105694. #else
  105695. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105696. #endif
  105697. if(partition_bits < best_partition_bits) {
  105698. best_rice_parameter = rice_parameter;
  105699. best_partition_bits = partition_bits;
  105700. }
  105701. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105702. }
  105703. #endif
  105704. if(search_for_escapes) {
  105705. 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;
  105706. if(partition_bits <= best_partition_bits) {
  105707. raw_bits[0] = raw_bits_per_partition[0];
  105708. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105709. best_partition_bits = partition_bits;
  105710. }
  105711. else
  105712. raw_bits[0] = 0;
  105713. }
  105714. parameters[0] = best_rice_parameter;
  105715. bits_ += best_partition_bits;
  105716. }
  105717. else {
  105718. unsigned partition, residual_sample;
  105719. unsigned partition_samples;
  105720. FLAC__uint64 mean, k;
  105721. const unsigned partitions = 1u << partition_order;
  105722. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105723. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105724. if(partition == 0) {
  105725. if(partition_samples <= predictor_order)
  105726. return false;
  105727. else
  105728. partition_samples -= predictor_order;
  105729. }
  105730. mean = abs_residual_partition_sums[partition];
  105731. /* we are basically calculating the size in bits of the
  105732. * average residual magnitude in the partition:
  105733. * rice_parameter = floor(log2(mean/partition_samples))
  105734. * 'mean' is not a good name for the variable, it is
  105735. * actually the sum of magnitudes of all residual values
  105736. * in the partition, so the actual mean is
  105737. * mean/partition_samples
  105738. */
  105739. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105740. ;
  105741. if(rice_parameter >= rice_parameter_limit) {
  105742. #ifdef DEBUG_VERBOSE
  105743. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105744. #endif
  105745. rice_parameter = rice_parameter_limit - 1;
  105746. }
  105747. best_partition_bits = (unsigned)(-1);
  105748. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105749. if(rice_parameter_search_dist) {
  105750. if(rice_parameter < rice_parameter_search_dist)
  105751. min_rice_parameter = 0;
  105752. else
  105753. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105754. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105755. if(max_rice_parameter >= rice_parameter_limit) {
  105756. #ifdef DEBUG_VERBOSE
  105757. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105758. #endif
  105759. max_rice_parameter = rice_parameter_limit - 1;
  105760. }
  105761. }
  105762. else
  105763. min_rice_parameter = max_rice_parameter = rice_parameter;
  105764. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105765. #endif
  105766. #ifdef EXACT_RICE_BITS_CALCULATION
  105767. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105768. #else
  105769. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105770. #endif
  105771. if(partition_bits < best_partition_bits) {
  105772. best_rice_parameter = rice_parameter;
  105773. best_partition_bits = partition_bits;
  105774. }
  105775. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105776. }
  105777. #endif
  105778. if(search_for_escapes) {
  105779. 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;
  105780. if(partition_bits <= best_partition_bits) {
  105781. raw_bits[partition] = raw_bits_per_partition[partition];
  105782. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105783. best_partition_bits = partition_bits;
  105784. }
  105785. else
  105786. raw_bits[partition] = 0;
  105787. }
  105788. parameters[partition] = best_rice_parameter;
  105789. bits_ += best_partition_bits;
  105790. residual_sample += partition_samples;
  105791. }
  105792. }
  105793. *bits = bits_;
  105794. return true;
  105795. }
  105796. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105797. {
  105798. unsigned i, shift;
  105799. FLAC__int32 x = 0;
  105800. for(i = 0; i < samples && !(x&1); i++)
  105801. x |= signal[i];
  105802. if(x == 0) {
  105803. shift = 0;
  105804. }
  105805. else {
  105806. for(shift = 0; !(x&1); shift++)
  105807. x >>= 1;
  105808. }
  105809. if(shift > 0) {
  105810. for(i = 0; i < samples; i++)
  105811. signal[i] >>= shift;
  105812. }
  105813. return shift;
  105814. }
  105815. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105816. {
  105817. unsigned channel;
  105818. for(channel = 0; channel < channels; channel++)
  105819. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105820. fifo->tail += wide_samples;
  105821. FLAC__ASSERT(fifo->tail <= fifo->size);
  105822. }
  105823. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105824. {
  105825. unsigned channel;
  105826. unsigned sample, wide_sample;
  105827. unsigned tail = fifo->tail;
  105828. sample = input_offset * channels;
  105829. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105830. for(channel = 0; channel < channels; channel++)
  105831. fifo->data[channel][tail] = input[sample++];
  105832. tail++;
  105833. }
  105834. fifo->tail = tail;
  105835. FLAC__ASSERT(fifo->tail <= fifo->size);
  105836. }
  105837. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105838. {
  105839. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105840. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105841. (void)decoder;
  105842. if(encoder->private_->verify.needs_magic_hack) {
  105843. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105844. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105845. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105846. encoder->private_->verify.needs_magic_hack = false;
  105847. }
  105848. else {
  105849. if(encoded_bytes == 0) {
  105850. /*
  105851. * If we get here, a FIFO underflow has occurred,
  105852. * which means there is a bug somewhere.
  105853. */
  105854. FLAC__ASSERT(0);
  105855. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105856. }
  105857. else if(encoded_bytes < *bytes)
  105858. *bytes = encoded_bytes;
  105859. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105860. encoder->private_->verify.output.data += *bytes;
  105861. encoder->private_->verify.output.bytes -= *bytes;
  105862. }
  105863. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105864. }
  105865. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105866. {
  105867. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105868. unsigned channel;
  105869. const unsigned channels = frame->header.channels;
  105870. const unsigned blocksize = frame->header.blocksize;
  105871. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105872. (void)decoder;
  105873. for(channel = 0; channel < channels; channel++) {
  105874. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105875. unsigned i, sample = 0;
  105876. FLAC__int32 expect = 0, got = 0;
  105877. for(i = 0; i < blocksize; i++) {
  105878. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105879. sample = i;
  105880. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105881. got = (FLAC__int32)buffer[channel][i];
  105882. break;
  105883. }
  105884. }
  105885. FLAC__ASSERT(i < blocksize);
  105886. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105887. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105888. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105889. encoder->private_->verify.error_stats.channel = channel;
  105890. encoder->private_->verify.error_stats.sample = sample;
  105891. encoder->private_->verify.error_stats.expected = expect;
  105892. encoder->private_->verify.error_stats.got = got;
  105893. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105894. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105895. }
  105896. }
  105897. /* dequeue the frame from the fifo */
  105898. encoder->private_->verify.input_fifo.tail -= blocksize;
  105899. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105900. for(channel = 0; channel < channels; channel++)
  105901. 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]));
  105902. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105903. }
  105904. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105905. {
  105906. (void)decoder, (void)metadata, (void)client_data;
  105907. }
  105908. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105909. {
  105910. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105911. (void)decoder, (void)status;
  105912. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105913. }
  105914. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105915. {
  105916. (void)client_data;
  105917. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105918. if (*bytes == 0) {
  105919. if (feof(encoder->private_->file))
  105920. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105921. else if (ferror(encoder->private_->file))
  105922. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105923. }
  105924. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105925. }
  105926. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105927. {
  105928. (void)client_data;
  105929. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105930. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105931. else
  105932. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105933. }
  105934. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105935. {
  105936. off_t offset;
  105937. (void)client_data;
  105938. offset = ftello(encoder->private_->file);
  105939. if(offset < 0) {
  105940. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105941. }
  105942. else {
  105943. *absolute_byte_offset = (FLAC__uint64)offset;
  105944. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105945. }
  105946. }
  105947. #ifdef FLAC__VALGRIND_TESTING
  105948. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105949. {
  105950. size_t ret = fwrite(ptr, size, nmemb, stream);
  105951. if(!ferror(stream))
  105952. fflush(stream);
  105953. return ret;
  105954. }
  105955. #else
  105956. #define local__fwrite fwrite
  105957. #endif
  105958. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105959. {
  105960. (void)client_data, (void)current_frame;
  105961. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105962. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105963. #if FLAC__HAS_OGG
  105964. /* We would like to be able to use 'samples > 0' in the
  105965. * clause here but currently because of the nature of our
  105966. * Ogg writing implementation, 'samples' is always 0 (see
  105967. * ogg_encoder_aspect.c). The downside is extra progress
  105968. * callbacks.
  105969. */
  105970. encoder->private_->is_ogg? true :
  105971. #endif
  105972. samples > 0
  105973. );
  105974. if(call_it) {
  105975. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105976. * because at this point in the callback chain, the stats
  105977. * have not been updated. Only after we return and control
  105978. * gets back to write_frame_() are the stats updated
  105979. */
  105980. 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);
  105981. }
  105982. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105983. }
  105984. else
  105985. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105986. }
  105987. /*
  105988. * This will forcibly set stdout to binary mode (for OSes that require it)
  105989. */
  105990. FILE *get_binary_stdout_(void)
  105991. {
  105992. /* if something breaks here it is probably due to the presence or
  105993. * absence of an underscore before the identifiers 'setmode',
  105994. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105995. */
  105996. #if defined _MSC_VER || defined __MINGW32__
  105997. _setmode(_fileno(stdout), _O_BINARY);
  105998. #elif defined __CYGWIN__
  105999. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106000. setmode(_fileno(stdout), _O_BINARY);
  106001. #elif defined __EMX__
  106002. setmode(fileno(stdout), O_BINARY);
  106003. #endif
  106004. return stdout;
  106005. }
  106006. #endif
  106007. /*** End of inlined file: stream_encoder.c ***/
  106008. /*** Start of inlined file: stream_encoder_framing.c ***/
  106009. /*** Start of inlined file: juce_FlacHeader.h ***/
  106010. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106011. // tasks..
  106012. #define VERSION "1.2.1"
  106013. #define FLAC__NO_DLL 1
  106014. #if JUCE_MSVC
  106015. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106016. #endif
  106017. #if JUCE_MAC
  106018. #define FLAC__SYS_DARWIN 1
  106019. #endif
  106020. /*** End of inlined file: juce_FlacHeader.h ***/
  106021. #if JUCE_USE_FLAC
  106022. #if HAVE_CONFIG_H
  106023. # include <config.h>
  106024. #endif
  106025. #include <stdio.h>
  106026. #include <string.h> /* for strlen() */
  106027. #ifdef max
  106028. #undef max
  106029. #endif
  106030. #define max(x,y) ((x)>(y)?(x):(y))
  106031. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106032. 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);
  106033. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106034. {
  106035. unsigned i, j;
  106036. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106037. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106038. return false;
  106039. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106040. return false;
  106041. /*
  106042. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106043. */
  106044. i = metadata->length;
  106045. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106046. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106047. i -= metadata->data.vorbis_comment.vendor_string.length;
  106048. i += vendor_string_length;
  106049. }
  106050. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106051. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106052. return false;
  106053. switch(metadata->type) {
  106054. case FLAC__METADATA_TYPE_STREAMINFO:
  106055. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106056. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106057. return false;
  106058. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106059. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106060. return false;
  106061. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106062. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106063. return false;
  106064. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106065. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106066. return false;
  106067. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106068. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106069. return false;
  106070. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106071. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106072. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106073. return false;
  106074. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106075. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106076. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106077. return false;
  106078. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106079. return false;
  106080. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106081. return false;
  106082. break;
  106083. case FLAC__METADATA_TYPE_PADDING:
  106084. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106085. return false;
  106086. break;
  106087. case FLAC__METADATA_TYPE_APPLICATION:
  106088. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106089. return false;
  106090. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106091. return false;
  106092. break;
  106093. case FLAC__METADATA_TYPE_SEEKTABLE:
  106094. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106095. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106096. return false;
  106097. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106098. return false;
  106099. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106100. return false;
  106101. }
  106102. break;
  106103. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106104. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106105. return false;
  106106. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106107. return false;
  106108. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106109. return false;
  106110. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106111. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106112. return false;
  106113. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106114. return false;
  106115. }
  106116. break;
  106117. case FLAC__METADATA_TYPE_CUESHEET:
  106118. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106119. 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))
  106120. return false;
  106121. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106122. return false;
  106123. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106124. return false;
  106125. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106126. return false;
  106127. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106128. return false;
  106129. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106130. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106131. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106132. return false;
  106133. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106134. return false;
  106135. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106136. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106137. return false;
  106138. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106139. return false;
  106140. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106141. return false;
  106142. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106143. return false;
  106144. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106145. return false;
  106146. for(j = 0; j < track->num_indices; j++) {
  106147. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106148. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106149. return false;
  106150. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106151. return false;
  106152. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106153. return false;
  106154. }
  106155. }
  106156. break;
  106157. case FLAC__METADATA_TYPE_PICTURE:
  106158. {
  106159. size_t len;
  106160. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106161. return false;
  106162. len = strlen(metadata->data.picture.mime_type);
  106163. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106164. return false;
  106165. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106166. return false;
  106167. len = strlen((const char *)metadata->data.picture.description);
  106168. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106169. return false;
  106170. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106171. return false;
  106172. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106173. return false;
  106174. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106175. return false;
  106176. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106177. return false;
  106178. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106179. return false;
  106180. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106181. return false;
  106182. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106183. return false;
  106184. }
  106185. break;
  106186. default:
  106187. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106188. return false;
  106189. break;
  106190. }
  106191. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106192. return true;
  106193. }
  106194. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106195. {
  106196. unsigned u, blocksize_hint, sample_rate_hint;
  106197. FLAC__byte crc;
  106198. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106199. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106200. return false;
  106201. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106202. return false;
  106203. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106204. return false;
  106205. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106206. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106207. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106208. blocksize_hint = 0;
  106209. switch(header->blocksize) {
  106210. case 192: u = 1; break;
  106211. case 576: u = 2; break;
  106212. case 1152: u = 3; break;
  106213. case 2304: u = 4; break;
  106214. case 4608: u = 5; break;
  106215. case 256: u = 8; break;
  106216. case 512: u = 9; break;
  106217. case 1024: u = 10; break;
  106218. case 2048: u = 11; break;
  106219. case 4096: u = 12; break;
  106220. case 8192: u = 13; break;
  106221. case 16384: u = 14; break;
  106222. case 32768: u = 15; break;
  106223. default:
  106224. if(header->blocksize <= 0x100)
  106225. blocksize_hint = u = 6;
  106226. else
  106227. blocksize_hint = u = 7;
  106228. break;
  106229. }
  106230. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106231. return false;
  106232. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106233. sample_rate_hint = 0;
  106234. switch(header->sample_rate) {
  106235. case 88200: u = 1; break;
  106236. case 176400: u = 2; break;
  106237. case 192000: u = 3; break;
  106238. case 8000: u = 4; break;
  106239. case 16000: u = 5; break;
  106240. case 22050: u = 6; break;
  106241. case 24000: u = 7; break;
  106242. case 32000: u = 8; break;
  106243. case 44100: u = 9; break;
  106244. case 48000: u = 10; break;
  106245. case 96000: u = 11; break;
  106246. default:
  106247. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106248. sample_rate_hint = u = 12;
  106249. else if(header->sample_rate % 10 == 0)
  106250. sample_rate_hint = u = 14;
  106251. else if(header->sample_rate <= 0xffff)
  106252. sample_rate_hint = u = 13;
  106253. else
  106254. u = 0;
  106255. break;
  106256. }
  106257. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106258. return false;
  106259. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106260. switch(header->channel_assignment) {
  106261. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106262. u = header->channels - 1;
  106263. break;
  106264. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106265. FLAC__ASSERT(header->channels == 2);
  106266. u = 8;
  106267. break;
  106268. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106269. FLAC__ASSERT(header->channels == 2);
  106270. u = 9;
  106271. break;
  106272. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106273. FLAC__ASSERT(header->channels == 2);
  106274. u = 10;
  106275. break;
  106276. default:
  106277. FLAC__ASSERT(0);
  106278. }
  106279. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106280. return false;
  106281. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106282. switch(header->bits_per_sample) {
  106283. case 8 : u = 1; break;
  106284. case 12: u = 2; break;
  106285. case 16: u = 4; break;
  106286. case 20: u = 5; break;
  106287. case 24: u = 6; break;
  106288. default: u = 0; break;
  106289. }
  106290. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106291. return false;
  106292. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106293. return false;
  106294. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106295. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106296. return false;
  106297. }
  106298. else {
  106299. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106300. return false;
  106301. }
  106302. if(blocksize_hint)
  106303. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106304. return false;
  106305. switch(sample_rate_hint) {
  106306. case 12:
  106307. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106308. return false;
  106309. break;
  106310. case 13:
  106311. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106312. return false;
  106313. break;
  106314. case 14:
  106315. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106316. return false;
  106317. break;
  106318. }
  106319. /* write the CRC */
  106320. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106321. return false;
  106322. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106323. return false;
  106324. return true;
  106325. }
  106326. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106327. {
  106328. FLAC__bool ok;
  106329. ok =
  106330. 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) &&
  106331. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106332. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106333. ;
  106334. return ok;
  106335. }
  106336. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106337. {
  106338. unsigned i;
  106339. 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))
  106340. return false;
  106341. if(wasted_bits)
  106342. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106343. return false;
  106344. for(i = 0; i < subframe->order; i++)
  106345. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106346. return false;
  106347. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106348. return false;
  106349. switch(subframe->entropy_coding_method.type) {
  106350. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106351. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106352. if(!add_residual_partitioned_rice_(
  106353. bw,
  106354. subframe->residual,
  106355. residual_samples,
  106356. subframe->order,
  106357. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106358. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106359. subframe->entropy_coding_method.data.partitioned_rice.order,
  106360. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106361. ))
  106362. return false;
  106363. break;
  106364. default:
  106365. FLAC__ASSERT(0);
  106366. }
  106367. return true;
  106368. }
  106369. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106370. {
  106371. unsigned i;
  106372. 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))
  106373. return false;
  106374. if(wasted_bits)
  106375. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106376. return false;
  106377. for(i = 0; i < subframe->order; i++)
  106378. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106379. return false;
  106380. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106381. return false;
  106382. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106383. return false;
  106384. for(i = 0; i < subframe->order; i++)
  106385. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106386. return false;
  106387. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106388. return false;
  106389. switch(subframe->entropy_coding_method.type) {
  106390. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106391. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106392. if(!add_residual_partitioned_rice_(
  106393. bw,
  106394. subframe->residual,
  106395. residual_samples,
  106396. subframe->order,
  106397. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106398. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106399. subframe->entropy_coding_method.data.partitioned_rice.order,
  106400. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106401. ))
  106402. return false;
  106403. break;
  106404. default:
  106405. FLAC__ASSERT(0);
  106406. }
  106407. return true;
  106408. }
  106409. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106410. {
  106411. unsigned i;
  106412. const FLAC__int32 *signal = subframe->data;
  106413. 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))
  106414. return false;
  106415. if(wasted_bits)
  106416. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106417. return false;
  106418. for(i = 0; i < samples; i++)
  106419. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106420. return false;
  106421. return true;
  106422. }
  106423. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106424. {
  106425. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106426. return false;
  106427. switch(method->type) {
  106428. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106429. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106430. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106431. return false;
  106432. break;
  106433. default:
  106434. FLAC__ASSERT(0);
  106435. }
  106436. return true;
  106437. }
  106438. 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)
  106439. {
  106440. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106441. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106442. if(partition_order == 0) {
  106443. unsigned i;
  106444. if(raw_bits[0] == 0) {
  106445. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106446. return false;
  106447. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106448. return false;
  106449. }
  106450. else {
  106451. FLAC__ASSERT(rice_parameters[0] == 0);
  106452. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106453. return false;
  106454. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106455. return false;
  106456. for(i = 0; i < residual_samples; i++) {
  106457. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106458. return false;
  106459. }
  106460. }
  106461. return true;
  106462. }
  106463. else {
  106464. unsigned i, j, k = 0, k_last = 0;
  106465. unsigned partition_samples;
  106466. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106467. for(i = 0; i < (1u<<partition_order); i++) {
  106468. partition_samples = default_partition_samples;
  106469. if(i == 0)
  106470. partition_samples -= predictor_order;
  106471. k += partition_samples;
  106472. if(raw_bits[i] == 0) {
  106473. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106474. return false;
  106475. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106476. return false;
  106477. }
  106478. else {
  106479. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106480. return false;
  106481. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106482. return false;
  106483. for(j = k_last; j < k; j++) {
  106484. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106485. return false;
  106486. }
  106487. }
  106488. k_last = k;
  106489. }
  106490. return true;
  106491. }
  106492. }
  106493. #endif
  106494. /*** End of inlined file: stream_encoder_framing.c ***/
  106495. /*** Start of inlined file: window_flac.c ***/
  106496. /*** Start of inlined file: juce_FlacHeader.h ***/
  106497. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106498. // tasks..
  106499. #define VERSION "1.2.1"
  106500. #define FLAC__NO_DLL 1
  106501. #if JUCE_MSVC
  106502. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106503. #endif
  106504. #if JUCE_MAC
  106505. #define FLAC__SYS_DARWIN 1
  106506. #endif
  106507. /*** End of inlined file: juce_FlacHeader.h ***/
  106508. #if JUCE_USE_FLAC
  106509. #if HAVE_CONFIG_H
  106510. # include <config.h>
  106511. #endif
  106512. #include <math.h>
  106513. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106514. #ifndef M_PI
  106515. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106516. #define M_PI 3.14159265358979323846
  106517. #endif
  106518. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106519. {
  106520. const FLAC__int32 N = L - 1;
  106521. FLAC__int32 n;
  106522. if (L & 1) {
  106523. for (n = 0; n <= N/2; n++)
  106524. window[n] = 2.0f * n / (float)N;
  106525. for (; n <= N; n++)
  106526. window[n] = 2.0f - 2.0f * n / (float)N;
  106527. }
  106528. else {
  106529. for (n = 0; n <= L/2-1; n++)
  106530. window[n] = 2.0f * n / (float)N;
  106531. for (; n <= N; n++)
  106532. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106533. }
  106534. }
  106535. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106536. {
  106537. const FLAC__int32 N = L - 1;
  106538. FLAC__int32 n;
  106539. for (n = 0; n < L; n++)
  106540. 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)));
  106541. }
  106542. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106543. {
  106544. const FLAC__int32 N = L - 1;
  106545. FLAC__int32 n;
  106546. for (n = 0; n < L; n++)
  106547. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106548. }
  106549. /* 4-term -92dB side-lobe */
  106550. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106551. {
  106552. const FLAC__int32 N = L - 1;
  106553. FLAC__int32 n;
  106554. for (n = 0; n <= N; n++)
  106555. 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));
  106556. }
  106557. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106558. {
  106559. const FLAC__int32 N = L - 1;
  106560. const double N2 = (double)N / 2.;
  106561. FLAC__int32 n;
  106562. for (n = 0; n <= N; n++) {
  106563. double k = ((double)n - N2) / N2;
  106564. k = 1.0f - k * k;
  106565. window[n] = (FLAC__real)(k * k);
  106566. }
  106567. }
  106568. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106569. {
  106570. const FLAC__int32 N = L - 1;
  106571. FLAC__int32 n;
  106572. for (n = 0; n < L; n++)
  106573. 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));
  106574. }
  106575. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106576. {
  106577. const FLAC__int32 N = L - 1;
  106578. const double N2 = (double)N / 2.;
  106579. FLAC__int32 n;
  106580. for (n = 0; n <= N; n++) {
  106581. const double k = ((double)n - N2) / (stddev * N2);
  106582. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106583. }
  106584. }
  106585. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106586. {
  106587. const FLAC__int32 N = L - 1;
  106588. FLAC__int32 n;
  106589. for (n = 0; n < L; n++)
  106590. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106591. }
  106592. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106593. {
  106594. const FLAC__int32 N = L - 1;
  106595. FLAC__int32 n;
  106596. for (n = 0; n < L; n++)
  106597. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106598. }
  106599. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106600. {
  106601. const FLAC__int32 N = L - 1;
  106602. FLAC__int32 n;
  106603. for (n = 0; n < L; n++)
  106604. 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));
  106605. }
  106606. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106607. {
  106608. const FLAC__int32 N = L - 1;
  106609. FLAC__int32 n;
  106610. for (n = 0; n < L; n++)
  106611. 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));
  106612. }
  106613. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106614. {
  106615. FLAC__int32 n;
  106616. for (n = 0; n < L; n++)
  106617. window[n] = 1.0f;
  106618. }
  106619. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106620. {
  106621. FLAC__int32 n;
  106622. if (L & 1) {
  106623. for (n = 1; n <= L+1/2; n++)
  106624. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106625. for (; n <= L; n++)
  106626. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106627. }
  106628. else {
  106629. for (n = 1; n <= L/2; n++)
  106630. window[n-1] = 2.0f * n / (float)L;
  106631. for (; n <= L; n++)
  106632. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106633. }
  106634. }
  106635. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106636. {
  106637. if (p <= 0.0)
  106638. FLAC__window_rectangle(window, L);
  106639. else if (p >= 1.0)
  106640. FLAC__window_hann(window, L);
  106641. else {
  106642. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106643. FLAC__int32 n;
  106644. /* start with rectangle... */
  106645. FLAC__window_rectangle(window, L);
  106646. /* ...replace ends with hann */
  106647. if (Np > 0) {
  106648. for (n = 0; n <= Np; n++) {
  106649. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106650. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106651. }
  106652. }
  106653. }
  106654. }
  106655. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106656. {
  106657. const FLAC__int32 N = L - 1;
  106658. const double N2 = (double)N / 2.;
  106659. FLAC__int32 n;
  106660. for (n = 0; n <= N; n++) {
  106661. const double k = ((double)n - N2) / N2;
  106662. window[n] = (FLAC__real)(1.0f - k * k);
  106663. }
  106664. }
  106665. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106666. #endif
  106667. /*** End of inlined file: window_flac.c ***/
  106668. #else
  106669. #include <FLAC/all.h>
  106670. #endif
  106671. }
  106672. #undef max
  106673. #undef min
  106674. BEGIN_JUCE_NAMESPACE
  106675. static const char* const flacFormatName = "FLAC file";
  106676. static const char* const flacExtensions[] = { ".flac", 0 };
  106677. class FlacReader : public AudioFormatReader
  106678. {
  106679. public:
  106680. FlacReader (InputStream* const in)
  106681. : AudioFormatReader (in, TRANS (flacFormatName)),
  106682. reservoir (2, 0),
  106683. reservoirStart (0),
  106684. samplesInReservoir (0),
  106685. scanningForLength (false)
  106686. {
  106687. using namespace FlacNamespace;
  106688. lengthInSamples = 0;
  106689. decoder = FLAC__stream_decoder_new();
  106690. ok = FLAC__stream_decoder_init_stream (decoder,
  106691. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106692. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106693. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106694. if (ok)
  106695. {
  106696. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106697. if (lengthInSamples == 0 && sampleRate > 0)
  106698. {
  106699. // the length hasn't been stored in the metadata, so we'll need to
  106700. // work it out the length the hard way, by scanning the whole file..
  106701. scanningForLength = true;
  106702. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106703. scanningForLength = false;
  106704. const int64 tempLength = lengthInSamples;
  106705. FLAC__stream_decoder_reset (decoder);
  106706. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106707. lengthInSamples = tempLength;
  106708. }
  106709. }
  106710. }
  106711. ~FlacReader()
  106712. {
  106713. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106714. }
  106715. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106716. {
  106717. sampleRate = info.sample_rate;
  106718. bitsPerSample = info.bits_per_sample;
  106719. lengthInSamples = (unsigned int) info.total_samples;
  106720. numChannels = info.channels;
  106721. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106722. }
  106723. // returns the number of samples read
  106724. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106725. int64 startSampleInFile, int numSamples)
  106726. {
  106727. using namespace FlacNamespace;
  106728. if (! ok)
  106729. return false;
  106730. while (numSamples > 0)
  106731. {
  106732. if (startSampleInFile >= reservoirStart
  106733. && startSampleInFile < reservoirStart + samplesInReservoir)
  106734. {
  106735. const int num = (int) jmin ((int64) numSamples,
  106736. reservoirStart + samplesInReservoir - startSampleInFile);
  106737. jassert (num > 0);
  106738. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106739. if (destSamples[i] != 0)
  106740. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106741. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106742. sizeof (int) * num);
  106743. startOffsetInDestBuffer += num;
  106744. startSampleInFile += num;
  106745. numSamples -= num;
  106746. }
  106747. else
  106748. {
  106749. if (startSampleInFile >= (int) lengthInSamples)
  106750. {
  106751. samplesInReservoir = 0;
  106752. }
  106753. else if (startSampleInFile < reservoirStart
  106754. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106755. {
  106756. // had some problems with flac crashing if the read pos is aligned more
  106757. // accurately than this. Probably fixed in newer versions of the library, though.
  106758. reservoirStart = (int) (startSampleInFile & ~511);
  106759. samplesInReservoir = 0;
  106760. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106761. }
  106762. else
  106763. {
  106764. reservoirStart += samplesInReservoir;
  106765. samplesInReservoir = 0;
  106766. FLAC__stream_decoder_process_single (decoder);
  106767. }
  106768. if (samplesInReservoir == 0)
  106769. break;
  106770. }
  106771. }
  106772. if (numSamples > 0)
  106773. {
  106774. for (int i = numDestChannels; --i >= 0;)
  106775. if (destSamples[i] != 0)
  106776. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106777. sizeof (int) * numSamples);
  106778. }
  106779. return true;
  106780. }
  106781. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106782. {
  106783. if (scanningForLength)
  106784. {
  106785. lengthInSamples += numSamples;
  106786. }
  106787. else
  106788. {
  106789. if (numSamples > reservoir.getNumSamples())
  106790. reservoir.setSize (numChannels, numSamples, false, false, true);
  106791. const int bitsToShift = 32 - bitsPerSample;
  106792. for (int i = 0; i < (int) numChannels; ++i)
  106793. {
  106794. const FlacNamespace::FLAC__int32* src = buffer[i];
  106795. int n = i;
  106796. while (src == 0 && n > 0)
  106797. src = buffer [--n];
  106798. if (src != 0)
  106799. {
  106800. int* dest = (int*) reservoir.getSampleData(i);
  106801. for (int j = 0; j < numSamples; ++j)
  106802. dest[j] = src[j] << bitsToShift;
  106803. }
  106804. }
  106805. samplesInReservoir = numSamples;
  106806. }
  106807. }
  106808. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106809. {
  106810. using namespace FlacNamespace;
  106811. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106812. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106813. }
  106814. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106815. {
  106816. using namespace FlacNamespace;
  106817. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106818. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106819. }
  106820. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106821. {
  106822. using namespace FlacNamespace;
  106823. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106824. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106825. }
  106826. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106827. {
  106828. using namespace FlacNamespace;
  106829. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106830. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106831. }
  106832. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106833. {
  106834. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106835. }
  106836. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106837. const FlacNamespace::FLAC__Frame* frame,
  106838. const FlacNamespace::FLAC__int32* const buffer[],
  106839. void* client_data)
  106840. {
  106841. using namespace FlacNamespace;
  106842. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106843. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106844. }
  106845. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106846. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106847. void* client_data)
  106848. {
  106849. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106850. }
  106851. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106852. {
  106853. }
  106854. juce_UseDebuggingNewOperator
  106855. private:
  106856. FlacNamespace::FLAC__StreamDecoder* decoder;
  106857. AudioSampleBuffer reservoir;
  106858. int reservoirStart, samplesInReservoir;
  106859. bool ok, scanningForLength;
  106860. FlacReader (const FlacReader&);
  106861. FlacReader& operator= (const FlacReader&);
  106862. };
  106863. class FlacWriter : public AudioFormatWriter
  106864. {
  106865. public:
  106866. FlacWriter (OutputStream* const out,
  106867. const double sampleRate_,
  106868. const int numChannels_,
  106869. const int bitsPerSample_)
  106870. : AudioFormatWriter (out, TRANS (flacFormatName),
  106871. sampleRate_,
  106872. numChannels_,
  106873. bitsPerSample_)
  106874. {
  106875. using namespace FlacNamespace;
  106876. encoder = FLAC__stream_encoder_new();
  106877. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106878. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106879. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106880. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106881. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106882. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106883. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106884. ok = FLAC__stream_encoder_init_stream (encoder,
  106885. encodeWriteCallback, encodeSeekCallback,
  106886. encodeTellCallback, encodeMetadataCallback,
  106887. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106888. }
  106889. ~FlacWriter()
  106890. {
  106891. if (ok)
  106892. {
  106893. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106894. output->flush();
  106895. }
  106896. else
  106897. {
  106898. output = 0; // to stop the base class deleting this, as it needs to be returned
  106899. // to the caller of createWriter()
  106900. }
  106901. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106902. }
  106903. bool write (const int** samplesToWrite, int numSamples)
  106904. {
  106905. using namespace FlacNamespace;
  106906. if (! ok)
  106907. return false;
  106908. int* buf[3];
  106909. const int bitsToShift = 32 - bitsPerSample;
  106910. if (bitsToShift > 0)
  106911. {
  106912. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106913. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106914. buf[0] = (int*) temp.getData();
  106915. buf[1] = buf[0] + numSamples;
  106916. buf[2] = 0;
  106917. for (int i = numChannelsToWrite; --i >= 0;)
  106918. {
  106919. if (samplesToWrite[i] != 0)
  106920. {
  106921. for (int j = 0; j < numSamples; ++j)
  106922. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106923. }
  106924. }
  106925. samplesToWrite = (const int**) buf;
  106926. }
  106927. return FLAC__stream_encoder_process (encoder,
  106928. (const FLAC__int32**) samplesToWrite,
  106929. numSamples) != 0;
  106930. }
  106931. bool writeData (const void* const data, const int size) const
  106932. {
  106933. return output->write (data, size);
  106934. }
  106935. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106936. {
  106937. using namespace FlacNamespace;
  106938. b += bytes;
  106939. for (int i = 0; i < bytes; ++i)
  106940. {
  106941. *(--b) = (FLAC__byte) (val & 0xff);
  106942. val >>= 8;
  106943. }
  106944. }
  106945. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106946. {
  106947. using namespace FlacNamespace;
  106948. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106949. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106950. const unsigned int channelsMinus1 = info.channels - 1;
  106951. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106952. packUint32 (info.min_blocksize, buffer, 2);
  106953. packUint32 (info.max_blocksize, buffer + 2, 2);
  106954. packUint32 (info.min_framesize, buffer + 4, 3);
  106955. packUint32 (info.max_framesize, buffer + 7, 3);
  106956. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106957. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106958. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106959. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106960. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106961. memcpy (buffer + 18, info.md5sum, 16);
  106962. const bool seekOk = output->setPosition (4);
  106963. (void) seekOk;
  106964. // if this fails, you've given it an output stream that can't seek! It needs
  106965. // to be able to seek back to write the header
  106966. jassert (seekOk);
  106967. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106968. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106969. }
  106970. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106971. const FlacNamespace::FLAC__byte buffer[],
  106972. size_t bytes,
  106973. unsigned int /*samples*/,
  106974. unsigned int /*current_frame*/,
  106975. void* client_data)
  106976. {
  106977. using namespace FlacNamespace;
  106978. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106979. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106980. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106981. }
  106982. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106983. {
  106984. using namespace FlacNamespace;
  106985. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106986. }
  106987. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106988. {
  106989. using namespace FlacNamespace;
  106990. if (client_data == 0)
  106991. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106992. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106993. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106994. }
  106995. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106996. {
  106997. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106998. }
  106999. juce_UseDebuggingNewOperator
  107000. bool ok;
  107001. private:
  107002. FlacNamespace::FLAC__StreamEncoder* encoder;
  107003. MemoryBlock temp;
  107004. FlacWriter (const FlacWriter&);
  107005. FlacWriter& operator= (const FlacWriter&);
  107006. };
  107007. FlacAudioFormat::FlacAudioFormat()
  107008. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107009. {
  107010. }
  107011. FlacAudioFormat::~FlacAudioFormat()
  107012. {
  107013. }
  107014. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107015. {
  107016. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107017. return Array <int> (rates);
  107018. }
  107019. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107020. {
  107021. const int depths[] = { 16, 24, 0 };
  107022. return Array <int> (depths);
  107023. }
  107024. bool FlacAudioFormat::canDoStereo()
  107025. {
  107026. return true;
  107027. }
  107028. bool FlacAudioFormat::canDoMono()
  107029. {
  107030. return true;
  107031. }
  107032. bool FlacAudioFormat::isCompressed()
  107033. {
  107034. return true;
  107035. }
  107036. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107037. const bool deleteStreamIfOpeningFails)
  107038. {
  107039. ScopedPointer<FlacReader> r (new FlacReader (in));
  107040. if (r->sampleRate != 0)
  107041. return r.release();
  107042. if (! deleteStreamIfOpeningFails)
  107043. r->input = 0;
  107044. return 0;
  107045. }
  107046. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107047. double sampleRate,
  107048. unsigned int numberOfChannels,
  107049. int bitsPerSample,
  107050. const StringPairArray& /*metadataValues*/,
  107051. int /*qualityOptionIndex*/)
  107052. {
  107053. if (getPossibleBitDepths().contains (bitsPerSample))
  107054. {
  107055. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  107056. if (w->ok)
  107057. return w.release();
  107058. }
  107059. return 0;
  107060. }
  107061. END_JUCE_NAMESPACE
  107062. #endif
  107063. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107064. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107065. #if JUCE_USE_OGGVORBIS
  107066. #if JUCE_MAC
  107067. #define __MACOSX__ 1
  107068. #endif
  107069. namespace OggVorbisNamespace
  107070. {
  107071. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107072. /*** Start of inlined file: vorbisenc.h ***/
  107073. #ifndef _OV_ENC_H_
  107074. #define _OV_ENC_H_
  107075. #ifdef __cplusplus
  107076. extern "C"
  107077. {
  107078. #endif /* __cplusplus */
  107079. /*** Start of inlined file: codec.h ***/
  107080. #ifndef _vorbis_codec_h_
  107081. #define _vorbis_codec_h_
  107082. #ifdef __cplusplus
  107083. extern "C"
  107084. {
  107085. #endif /* __cplusplus */
  107086. /*** Start of inlined file: ogg.h ***/
  107087. #ifndef _OGG_H
  107088. #define _OGG_H
  107089. #ifdef __cplusplus
  107090. extern "C" {
  107091. #endif
  107092. /*** Start of inlined file: os_types.h ***/
  107093. #ifndef _OS_TYPES_H
  107094. #define _OS_TYPES_H
  107095. /* make it easy on the folks that want to compile the libs with a
  107096. different malloc than stdlib */
  107097. #define _ogg_malloc malloc
  107098. #define _ogg_calloc calloc
  107099. #define _ogg_realloc realloc
  107100. #define _ogg_free free
  107101. #if defined(_WIN32)
  107102. # if defined(__CYGWIN__)
  107103. # include <_G_config.h>
  107104. typedef _G_int64_t ogg_int64_t;
  107105. typedef _G_int32_t ogg_int32_t;
  107106. typedef _G_uint32_t ogg_uint32_t;
  107107. typedef _G_int16_t ogg_int16_t;
  107108. typedef _G_uint16_t ogg_uint16_t;
  107109. # elif defined(__MINGW32__)
  107110. typedef short ogg_int16_t;
  107111. typedef unsigned short ogg_uint16_t;
  107112. typedef int ogg_int32_t;
  107113. typedef unsigned int ogg_uint32_t;
  107114. typedef long long ogg_int64_t;
  107115. typedef unsigned long long ogg_uint64_t;
  107116. # elif defined(__MWERKS__)
  107117. typedef long long ogg_int64_t;
  107118. typedef int ogg_int32_t;
  107119. typedef unsigned int ogg_uint32_t;
  107120. typedef short ogg_int16_t;
  107121. typedef unsigned short ogg_uint16_t;
  107122. # else
  107123. /* MSVC/Borland */
  107124. typedef __int64 ogg_int64_t;
  107125. typedef __int32 ogg_int32_t;
  107126. typedef unsigned __int32 ogg_uint32_t;
  107127. typedef __int16 ogg_int16_t;
  107128. typedef unsigned __int16 ogg_uint16_t;
  107129. # endif
  107130. #elif defined(__MACOS__)
  107131. # include <sys/types.h>
  107132. typedef SInt16 ogg_int16_t;
  107133. typedef UInt16 ogg_uint16_t;
  107134. typedef SInt32 ogg_int32_t;
  107135. typedef UInt32 ogg_uint32_t;
  107136. typedef SInt64 ogg_int64_t;
  107137. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107138. # include <sys/types.h>
  107139. typedef int16_t ogg_int16_t;
  107140. typedef u_int16_t ogg_uint16_t;
  107141. typedef int32_t ogg_int32_t;
  107142. typedef u_int32_t ogg_uint32_t;
  107143. typedef int64_t ogg_int64_t;
  107144. #elif defined(__BEOS__)
  107145. /* Be */
  107146. # include <inttypes.h>
  107147. typedef int16_t ogg_int16_t;
  107148. typedef u_int16_t ogg_uint16_t;
  107149. typedef int32_t ogg_int32_t;
  107150. typedef u_int32_t ogg_uint32_t;
  107151. typedef int64_t ogg_int64_t;
  107152. #elif defined (__EMX__)
  107153. /* OS/2 GCC */
  107154. typedef short ogg_int16_t;
  107155. typedef unsigned short ogg_uint16_t;
  107156. typedef int ogg_int32_t;
  107157. typedef unsigned int ogg_uint32_t;
  107158. typedef long long ogg_int64_t;
  107159. #elif defined (DJGPP)
  107160. /* DJGPP */
  107161. typedef short ogg_int16_t;
  107162. typedef int ogg_int32_t;
  107163. typedef unsigned int ogg_uint32_t;
  107164. typedef long long ogg_int64_t;
  107165. #elif defined(R5900)
  107166. /* PS2 EE */
  107167. typedef long ogg_int64_t;
  107168. typedef int ogg_int32_t;
  107169. typedef unsigned ogg_uint32_t;
  107170. typedef short ogg_int16_t;
  107171. #elif defined(__SYMBIAN32__)
  107172. /* Symbian GCC */
  107173. typedef signed short ogg_int16_t;
  107174. typedef unsigned short ogg_uint16_t;
  107175. typedef signed int ogg_int32_t;
  107176. typedef unsigned int ogg_uint32_t;
  107177. typedef long long int ogg_int64_t;
  107178. #else
  107179. # include <sys/types.h>
  107180. /*** Start of inlined file: config_types.h ***/
  107181. #ifndef __CONFIG_TYPES_H__
  107182. #define __CONFIG_TYPES_H__
  107183. typedef int16_t ogg_int16_t;
  107184. typedef unsigned short ogg_uint16_t;
  107185. typedef int32_t ogg_int32_t;
  107186. typedef unsigned int ogg_uint32_t;
  107187. typedef int64_t ogg_int64_t;
  107188. #endif
  107189. /*** End of inlined file: config_types.h ***/
  107190. #endif
  107191. #endif /* _OS_TYPES_H */
  107192. /*** End of inlined file: os_types.h ***/
  107193. typedef struct {
  107194. long endbyte;
  107195. int endbit;
  107196. unsigned char *buffer;
  107197. unsigned char *ptr;
  107198. long storage;
  107199. } oggpack_buffer;
  107200. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107201. typedef struct {
  107202. unsigned char *header;
  107203. long header_len;
  107204. unsigned char *body;
  107205. long body_len;
  107206. } ogg_page;
  107207. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107208. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107209. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107210. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107211. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107212. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107213. }
  107214. /* ogg_stream_state contains the current encode/decode state of a logical
  107215. Ogg bitstream **********************************************************/
  107216. typedef struct {
  107217. unsigned char *body_data; /* bytes from packet bodies */
  107218. long body_storage; /* storage elements allocated */
  107219. long body_fill; /* elements stored; fill mark */
  107220. long body_returned; /* elements of fill returned */
  107221. int *lacing_vals; /* The values that will go to the segment table */
  107222. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107223. this way, but it is simple coupled to the
  107224. lacing fifo */
  107225. long lacing_storage;
  107226. long lacing_fill;
  107227. long lacing_packet;
  107228. long lacing_returned;
  107229. unsigned char header[282]; /* working space for header encode */
  107230. int header_fill;
  107231. int e_o_s; /* set when we have buffered the last packet in the
  107232. logical bitstream */
  107233. int b_o_s; /* set after we've written the initial page
  107234. of a logical bitstream */
  107235. long serialno;
  107236. long pageno;
  107237. ogg_int64_t packetno; /* sequence number for decode; the framing
  107238. knows where there's a hole in the data,
  107239. but we need coupling so that the codec
  107240. (which is in a seperate abstraction
  107241. layer) also knows about the gap */
  107242. ogg_int64_t granulepos;
  107243. } ogg_stream_state;
  107244. /* ogg_packet is used to encapsulate the data and metadata belonging
  107245. to a single raw Ogg/Vorbis packet *************************************/
  107246. typedef struct {
  107247. unsigned char *packet;
  107248. long bytes;
  107249. long b_o_s;
  107250. long e_o_s;
  107251. ogg_int64_t granulepos;
  107252. ogg_int64_t packetno; /* sequence number for decode; the framing
  107253. knows where there's a hole in the data,
  107254. but we need coupling so that the codec
  107255. (which is in a seperate abstraction
  107256. layer) also knows about the gap */
  107257. } ogg_packet;
  107258. typedef struct {
  107259. unsigned char *data;
  107260. int storage;
  107261. int fill;
  107262. int returned;
  107263. int unsynced;
  107264. int headerbytes;
  107265. int bodybytes;
  107266. } ogg_sync_state;
  107267. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107268. extern void oggpack_writeinit(oggpack_buffer *b);
  107269. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107270. extern void oggpack_writealign(oggpack_buffer *b);
  107271. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107272. extern void oggpack_reset(oggpack_buffer *b);
  107273. extern void oggpack_writeclear(oggpack_buffer *b);
  107274. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107275. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107276. extern long oggpack_look(oggpack_buffer *b,int bits);
  107277. extern long oggpack_look1(oggpack_buffer *b);
  107278. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107279. extern void oggpack_adv1(oggpack_buffer *b);
  107280. extern long oggpack_read(oggpack_buffer *b,int bits);
  107281. extern long oggpack_read1(oggpack_buffer *b);
  107282. extern long oggpack_bytes(oggpack_buffer *b);
  107283. extern long oggpack_bits(oggpack_buffer *b);
  107284. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107285. extern void oggpackB_writeinit(oggpack_buffer *b);
  107286. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107287. extern void oggpackB_writealign(oggpack_buffer *b);
  107288. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107289. extern void oggpackB_reset(oggpack_buffer *b);
  107290. extern void oggpackB_writeclear(oggpack_buffer *b);
  107291. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107292. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107293. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107294. extern long oggpackB_look1(oggpack_buffer *b);
  107295. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107296. extern void oggpackB_adv1(oggpack_buffer *b);
  107297. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107298. extern long oggpackB_read1(oggpack_buffer *b);
  107299. extern long oggpackB_bytes(oggpack_buffer *b);
  107300. extern long oggpackB_bits(oggpack_buffer *b);
  107301. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107302. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107303. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107304. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107305. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107306. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107307. extern int ogg_sync_init(ogg_sync_state *oy);
  107308. extern int ogg_sync_clear(ogg_sync_state *oy);
  107309. extern int ogg_sync_reset(ogg_sync_state *oy);
  107310. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107311. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107312. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107313. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107314. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107315. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107316. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107317. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107318. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107319. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107320. extern int ogg_stream_clear(ogg_stream_state *os);
  107321. extern int ogg_stream_reset(ogg_stream_state *os);
  107322. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107323. extern int ogg_stream_destroy(ogg_stream_state *os);
  107324. extern int ogg_stream_eos(ogg_stream_state *os);
  107325. extern void ogg_page_checksum_set(ogg_page *og);
  107326. extern int ogg_page_version(ogg_page *og);
  107327. extern int ogg_page_continued(ogg_page *og);
  107328. extern int ogg_page_bos(ogg_page *og);
  107329. extern int ogg_page_eos(ogg_page *og);
  107330. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107331. extern int ogg_page_serialno(ogg_page *og);
  107332. extern long ogg_page_pageno(ogg_page *og);
  107333. extern int ogg_page_packets(ogg_page *og);
  107334. extern void ogg_packet_clear(ogg_packet *op);
  107335. #ifdef __cplusplus
  107336. }
  107337. #endif
  107338. #endif /* _OGG_H */
  107339. /*** End of inlined file: ogg.h ***/
  107340. typedef struct vorbis_info{
  107341. int version;
  107342. int channels;
  107343. long rate;
  107344. /* The below bitrate declarations are *hints*.
  107345. Combinations of the three values carry the following implications:
  107346. all three set to the same value:
  107347. implies a fixed rate bitstream
  107348. only nominal set:
  107349. implies a VBR stream that averages the nominal bitrate. No hard
  107350. upper/lower limit
  107351. upper and or lower set:
  107352. implies a VBR bitstream that obeys the bitrate limits. nominal
  107353. may also be set to give a nominal rate.
  107354. none set:
  107355. the coder does not care to speculate.
  107356. */
  107357. long bitrate_upper;
  107358. long bitrate_nominal;
  107359. long bitrate_lower;
  107360. long bitrate_window;
  107361. void *codec_setup;
  107362. } vorbis_info;
  107363. /* vorbis_dsp_state buffers the current vorbis audio
  107364. analysis/synthesis state. The DSP state belongs to a specific
  107365. logical bitstream ****************************************************/
  107366. typedef struct vorbis_dsp_state{
  107367. int analysisp;
  107368. vorbis_info *vi;
  107369. float **pcm;
  107370. float **pcmret;
  107371. int pcm_storage;
  107372. int pcm_current;
  107373. int pcm_returned;
  107374. int preextrapolate;
  107375. int eofflag;
  107376. long lW;
  107377. long W;
  107378. long nW;
  107379. long centerW;
  107380. ogg_int64_t granulepos;
  107381. ogg_int64_t sequence;
  107382. ogg_int64_t glue_bits;
  107383. ogg_int64_t time_bits;
  107384. ogg_int64_t floor_bits;
  107385. ogg_int64_t res_bits;
  107386. void *backend_state;
  107387. } vorbis_dsp_state;
  107388. typedef struct vorbis_block{
  107389. /* necessary stream state for linking to the framing abstraction */
  107390. float **pcm; /* this is a pointer into local storage */
  107391. oggpack_buffer opb;
  107392. long lW;
  107393. long W;
  107394. long nW;
  107395. int pcmend;
  107396. int mode;
  107397. int eofflag;
  107398. ogg_int64_t granulepos;
  107399. ogg_int64_t sequence;
  107400. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107401. /* local storage to avoid remallocing; it's up to the mapping to
  107402. structure it */
  107403. void *localstore;
  107404. long localtop;
  107405. long localalloc;
  107406. long totaluse;
  107407. struct alloc_chain *reap;
  107408. /* bitmetrics for the frame */
  107409. long glue_bits;
  107410. long time_bits;
  107411. long floor_bits;
  107412. long res_bits;
  107413. void *internal;
  107414. } vorbis_block;
  107415. /* vorbis_block is a single block of data to be processed as part of
  107416. the analysis/synthesis stream; it belongs to a specific logical
  107417. bitstream, but is independant from other vorbis_blocks belonging to
  107418. that logical bitstream. *************************************************/
  107419. struct alloc_chain{
  107420. void *ptr;
  107421. struct alloc_chain *next;
  107422. };
  107423. /* vorbis_info contains all the setup information specific to the
  107424. specific compression/decompression mode in progress (eg,
  107425. psychoacoustic settings, channel setup, options, codebook
  107426. etc). vorbis_info and substructures are in backends.h.
  107427. *********************************************************************/
  107428. /* the comments are not part of vorbis_info so that vorbis_info can be
  107429. static storage */
  107430. typedef struct vorbis_comment{
  107431. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107432. whatever vendor is set to in encode */
  107433. char **user_comments;
  107434. int *comment_lengths;
  107435. int comments;
  107436. char *vendor;
  107437. } vorbis_comment;
  107438. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107439. and produce a packet (see docs/analysis.txt). The packet is then
  107440. coded into a framed OggSquish bitstream by the second layer (see
  107441. docs/framing.txt). Decode is the reverse process; we sync/frame
  107442. the bitstream and extract individual packets, then decode the
  107443. packet back into PCM audio.
  107444. The extra framing/packetizing is used in streaming formats, such as
  107445. files. Over the net (such as with UDP), the framing and
  107446. packetization aren't necessary as they're provided by the transport
  107447. and the streaming layer is not used */
  107448. /* Vorbis PRIMITIVES: general ***************************************/
  107449. extern void vorbis_info_init(vorbis_info *vi);
  107450. extern void vorbis_info_clear(vorbis_info *vi);
  107451. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107452. extern void vorbis_comment_init(vorbis_comment *vc);
  107453. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107454. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107455. const char *tag, char *contents);
  107456. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107457. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107458. extern void vorbis_comment_clear(vorbis_comment *vc);
  107459. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107460. extern int vorbis_block_clear(vorbis_block *vb);
  107461. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107462. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107463. ogg_int64_t granulepos);
  107464. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107465. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107466. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107467. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107468. vorbis_comment *vc,
  107469. ogg_packet *op,
  107470. ogg_packet *op_comm,
  107471. ogg_packet *op_code);
  107472. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107473. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107474. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107475. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107476. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107477. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107478. ogg_packet *op);
  107479. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107480. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107481. ogg_packet *op);
  107482. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107483. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107484. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107485. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107486. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107487. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107488. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107489. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107490. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107491. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107492. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107493. /* Vorbis ERRORS and return codes ***********************************/
  107494. #define OV_FALSE -1
  107495. #define OV_EOF -2
  107496. #define OV_HOLE -3
  107497. #define OV_EREAD -128
  107498. #define OV_EFAULT -129
  107499. #define OV_EIMPL -130
  107500. #define OV_EINVAL -131
  107501. #define OV_ENOTVORBIS -132
  107502. #define OV_EBADHEADER -133
  107503. #define OV_EVERSION -134
  107504. #define OV_ENOTAUDIO -135
  107505. #define OV_EBADPACKET -136
  107506. #define OV_EBADLINK -137
  107507. #define OV_ENOSEEK -138
  107508. #ifdef __cplusplus
  107509. }
  107510. #endif /* __cplusplus */
  107511. #endif
  107512. /*** End of inlined file: codec.h ***/
  107513. extern int vorbis_encode_init(vorbis_info *vi,
  107514. long channels,
  107515. long rate,
  107516. long max_bitrate,
  107517. long nominal_bitrate,
  107518. long min_bitrate);
  107519. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107520. long channels,
  107521. long rate,
  107522. long max_bitrate,
  107523. long nominal_bitrate,
  107524. long min_bitrate);
  107525. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107526. long channels,
  107527. long rate,
  107528. float quality /* quality level from 0. (lo) to 1. (hi) */
  107529. );
  107530. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107531. long channels,
  107532. long rate,
  107533. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107534. );
  107535. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107536. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107537. /* deprecated rate management supported only for compatability */
  107538. #define OV_ECTL_RATEMANAGE_GET 0x10
  107539. #define OV_ECTL_RATEMANAGE_SET 0x11
  107540. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107541. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107542. struct ovectl_ratemanage_arg {
  107543. int management_active;
  107544. long bitrate_hard_min;
  107545. long bitrate_hard_max;
  107546. double bitrate_hard_window;
  107547. long bitrate_av_lo;
  107548. long bitrate_av_hi;
  107549. double bitrate_av_window;
  107550. double bitrate_av_window_center;
  107551. };
  107552. /* new rate setup */
  107553. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107554. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107555. struct ovectl_ratemanage2_arg {
  107556. int management_active;
  107557. long bitrate_limit_min_kbps;
  107558. long bitrate_limit_max_kbps;
  107559. long bitrate_limit_reservoir_bits;
  107560. double bitrate_limit_reservoir_bias;
  107561. long bitrate_average_kbps;
  107562. double bitrate_average_damping;
  107563. };
  107564. #define OV_ECTL_LOWPASS_GET 0x20
  107565. #define OV_ECTL_LOWPASS_SET 0x21
  107566. #define OV_ECTL_IBLOCK_GET 0x30
  107567. #define OV_ECTL_IBLOCK_SET 0x31
  107568. #ifdef __cplusplus
  107569. }
  107570. #endif /* __cplusplus */
  107571. #endif
  107572. /*** End of inlined file: vorbisenc.h ***/
  107573. /*** Start of inlined file: vorbisfile.h ***/
  107574. #ifndef _OV_FILE_H_
  107575. #define _OV_FILE_H_
  107576. #ifdef __cplusplus
  107577. extern "C"
  107578. {
  107579. #endif /* __cplusplus */
  107580. #include <stdio.h>
  107581. /* The function prototypes for the callbacks are basically the same as for
  107582. * the stdio functions fread, fseek, fclose, ftell.
  107583. * The one difference is that the FILE * arguments have been replaced with
  107584. * a void * - this is to be used as a pointer to whatever internal data these
  107585. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107586. *
  107587. * If you use other functions, check the docs for these functions and return
  107588. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107589. * unseekable
  107590. */
  107591. typedef struct {
  107592. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107593. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107594. int (*close_func) (void *datasource);
  107595. long (*tell_func) (void *datasource);
  107596. } ov_callbacks;
  107597. #define NOTOPEN 0
  107598. #define PARTOPEN 1
  107599. #define OPENED 2
  107600. #define STREAMSET 3
  107601. #define INITSET 4
  107602. typedef struct OggVorbis_File {
  107603. void *datasource; /* Pointer to a FILE *, etc. */
  107604. int seekable;
  107605. ogg_int64_t offset;
  107606. ogg_int64_t end;
  107607. ogg_sync_state oy;
  107608. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107609. stream appears */
  107610. int links;
  107611. ogg_int64_t *offsets;
  107612. ogg_int64_t *dataoffsets;
  107613. long *serialnos;
  107614. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107615. compatability; x2 size, stores both
  107616. beginning and end values */
  107617. vorbis_info *vi;
  107618. vorbis_comment *vc;
  107619. /* Decoding working state local storage */
  107620. ogg_int64_t pcm_offset;
  107621. int ready_state;
  107622. long current_serialno;
  107623. int current_link;
  107624. double bittrack;
  107625. double samptrack;
  107626. ogg_stream_state os; /* take physical pages, weld into a logical
  107627. stream of packets */
  107628. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107629. vorbis_block vb; /* local working space for packet->PCM decode */
  107630. ov_callbacks callbacks;
  107631. } OggVorbis_File;
  107632. extern int ov_clear(OggVorbis_File *vf);
  107633. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107634. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107635. char *initial, long ibytes, ov_callbacks callbacks);
  107636. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107637. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107638. char *initial, long ibytes, ov_callbacks callbacks);
  107639. extern int ov_test_open(OggVorbis_File *vf);
  107640. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107641. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107642. extern long ov_streams(OggVorbis_File *vf);
  107643. extern long ov_seekable(OggVorbis_File *vf);
  107644. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107645. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107646. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107647. extern double ov_time_total(OggVorbis_File *vf,int i);
  107648. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107649. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107650. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107651. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107652. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107653. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107654. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107655. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107656. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107657. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107658. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107659. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107660. extern double ov_time_tell(OggVorbis_File *vf);
  107661. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107662. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107663. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107664. int *bitstream);
  107665. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107666. int bigendianp,int word,int sgned,int *bitstream);
  107667. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107668. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107669. extern int ov_halfrate_p(OggVorbis_File *vf);
  107670. #ifdef __cplusplus
  107671. }
  107672. #endif /* __cplusplus */
  107673. #endif
  107674. /*** End of inlined file: vorbisfile.h ***/
  107675. /*** Start of inlined file: bitwise.c ***/
  107676. /* We're 'LSb' endian; if we write a word but read individual bits,
  107677. then we'll read the lsb first */
  107678. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107679. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107680. // tasks..
  107681. #if JUCE_MSVC
  107682. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107683. #endif
  107684. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107685. #if JUCE_USE_OGGVORBIS
  107686. #include <string.h>
  107687. #include <stdlib.h>
  107688. #define BUFFER_INCREMENT 256
  107689. static const unsigned long mask[]=
  107690. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107691. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107692. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107693. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107694. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107695. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107696. 0x3fffffff,0x7fffffff,0xffffffff };
  107697. static const unsigned int mask8B[]=
  107698. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107699. void oggpack_writeinit(oggpack_buffer *b){
  107700. memset(b,0,sizeof(*b));
  107701. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107702. b->buffer[0]='\0';
  107703. b->storage=BUFFER_INCREMENT;
  107704. }
  107705. void oggpackB_writeinit(oggpack_buffer *b){
  107706. oggpack_writeinit(b);
  107707. }
  107708. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107709. long bytes=bits>>3;
  107710. bits-=bytes*8;
  107711. b->ptr=b->buffer+bytes;
  107712. b->endbit=bits;
  107713. b->endbyte=bytes;
  107714. *b->ptr&=mask[bits];
  107715. }
  107716. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107717. long bytes=bits>>3;
  107718. bits-=bytes*8;
  107719. b->ptr=b->buffer+bytes;
  107720. b->endbit=bits;
  107721. b->endbyte=bytes;
  107722. *b->ptr&=mask8B[bits];
  107723. }
  107724. /* Takes only up to 32 bits. */
  107725. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107726. if(b->endbyte+4>=b->storage){
  107727. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107728. b->storage+=BUFFER_INCREMENT;
  107729. b->ptr=b->buffer+b->endbyte;
  107730. }
  107731. value&=mask[bits];
  107732. bits+=b->endbit;
  107733. b->ptr[0]|=value<<b->endbit;
  107734. if(bits>=8){
  107735. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107736. if(bits>=16){
  107737. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107738. if(bits>=24){
  107739. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107740. if(bits>=32){
  107741. if(b->endbit)
  107742. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107743. else
  107744. b->ptr[4]=0;
  107745. }
  107746. }
  107747. }
  107748. }
  107749. b->endbyte+=bits/8;
  107750. b->ptr+=bits/8;
  107751. b->endbit=bits&7;
  107752. }
  107753. /* Takes only up to 32 bits. */
  107754. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107755. if(b->endbyte+4>=b->storage){
  107756. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107757. b->storage+=BUFFER_INCREMENT;
  107758. b->ptr=b->buffer+b->endbyte;
  107759. }
  107760. value=(value&mask[bits])<<(32-bits);
  107761. bits+=b->endbit;
  107762. b->ptr[0]|=value>>(24+b->endbit);
  107763. if(bits>=8){
  107764. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107765. if(bits>=16){
  107766. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107767. if(bits>=24){
  107768. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107769. if(bits>=32){
  107770. if(b->endbit)
  107771. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107772. else
  107773. b->ptr[4]=0;
  107774. }
  107775. }
  107776. }
  107777. }
  107778. b->endbyte+=bits/8;
  107779. b->ptr+=bits/8;
  107780. b->endbit=bits&7;
  107781. }
  107782. void oggpack_writealign(oggpack_buffer *b){
  107783. int bits=8-b->endbit;
  107784. if(bits<8)
  107785. oggpack_write(b,0,bits);
  107786. }
  107787. void oggpackB_writealign(oggpack_buffer *b){
  107788. int bits=8-b->endbit;
  107789. if(bits<8)
  107790. oggpackB_write(b,0,bits);
  107791. }
  107792. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107793. void *source,
  107794. long bits,
  107795. void (*w)(oggpack_buffer *,
  107796. unsigned long,
  107797. int),
  107798. int msb){
  107799. unsigned char *ptr=(unsigned char *)source;
  107800. long bytes=bits/8;
  107801. bits-=bytes*8;
  107802. if(b->endbit){
  107803. int i;
  107804. /* unaligned copy. Do it the hard way. */
  107805. for(i=0;i<bytes;i++)
  107806. w(b,(unsigned long)(ptr[i]),8);
  107807. }else{
  107808. /* aligned block copy */
  107809. if(b->endbyte+bytes+1>=b->storage){
  107810. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107811. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107812. b->ptr=b->buffer+b->endbyte;
  107813. }
  107814. memmove(b->ptr,source,bytes);
  107815. b->ptr+=bytes;
  107816. b->endbyte+=bytes;
  107817. *b->ptr=0;
  107818. }
  107819. if(bits){
  107820. if(msb)
  107821. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107822. else
  107823. w(b,(unsigned long)(ptr[bytes]),bits);
  107824. }
  107825. }
  107826. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107827. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107828. }
  107829. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107830. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107831. }
  107832. void oggpack_reset(oggpack_buffer *b){
  107833. b->ptr=b->buffer;
  107834. b->buffer[0]=0;
  107835. b->endbit=b->endbyte=0;
  107836. }
  107837. void oggpackB_reset(oggpack_buffer *b){
  107838. oggpack_reset(b);
  107839. }
  107840. void oggpack_writeclear(oggpack_buffer *b){
  107841. _ogg_free(b->buffer);
  107842. memset(b,0,sizeof(*b));
  107843. }
  107844. void oggpackB_writeclear(oggpack_buffer *b){
  107845. oggpack_writeclear(b);
  107846. }
  107847. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107848. memset(b,0,sizeof(*b));
  107849. b->buffer=b->ptr=buf;
  107850. b->storage=bytes;
  107851. }
  107852. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107853. oggpack_readinit(b,buf,bytes);
  107854. }
  107855. /* Read in bits without advancing the bitptr; bits <= 32 */
  107856. long oggpack_look(oggpack_buffer *b,int bits){
  107857. unsigned long ret;
  107858. unsigned long m=mask[bits];
  107859. bits+=b->endbit;
  107860. if(b->endbyte+4>=b->storage){
  107861. /* not the main path */
  107862. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107863. }
  107864. ret=b->ptr[0]>>b->endbit;
  107865. if(bits>8){
  107866. ret|=b->ptr[1]<<(8-b->endbit);
  107867. if(bits>16){
  107868. ret|=b->ptr[2]<<(16-b->endbit);
  107869. if(bits>24){
  107870. ret|=b->ptr[3]<<(24-b->endbit);
  107871. if(bits>32 && b->endbit)
  107872. ret|=b->ptr[4]<<(32-b->endbit);
  107873. }
  107874. }
  107875. }
  107876. return(m&ret);
  107877. }
  107878. /* Read in bits without advancing the bitptr; bits <= 32 */
  107879. long oggpackB_look(oggpack_buffer *b,int bits){
  107880. unsigned long ret;
  107881. int m=32-bits;
  107882. bits+=b->endbit;
  107883. if(b->endbyte+4>=b->storage){
  107884. /* not the main path */
  107885. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107886. }
  107887. ret=b->ptr[0]<<(24+b->endbit);
  107888. if(bits>8){
  107889. ret|=b->ptr[1]<<(16+b->endbit);
  107890. if(bits>16){
  107891. ret|=b->ptr[2]<<(8+b->endbit);
  107892. if(bits>24){
  107893. ret|=b->ptr[3]<<(b->endbit);
  107894. if(bits>32 && b->endbit)
  107895. ret|=b->ptr[4]>>(8-b->endbit);
  107896. }
  107897. }
  107898. }
  107899. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107900. }
  107901. long oggpack_look1(oggpack_buffer *b){
  107902. if(b->endbyte>=b->storage)return(-1);
  107903. return((b->ptr[0]>>b->endbit)&1);
  107904. }
  107905. long oggpackB_look1(oggpack_buffer *b){
  107906. if(b->endbyte>=b->storage)return(-1);
  107907. return((b->ptr[0]>>(7-b->endbit))&1);
  107908. }
  107909. void oggpack_adv(oggpack_buffer *b,int bits){
  107910. bits+=b->endbit;
  107911. b->ptr+=bits/8;
  107912. b->endbyte+=bits/8;
  107913. b->endbit=bits&7;
  107914. }
  107915. void oggpackB_adv(oggpack_buffer *b,int bits){
  107916. oggpack_adv(b,bits);
  107917. }
  107918. void oggpack_adv1(oggpack_buffer *b){
  107919. if(++(b->endbit)>7){
  107920. b->endbit=0;
  107921. b->ptr++;
  107922. b->endbyte++;
  107923. }
  107924. }
  107925. void oggpackB_adv1(oggpack_buffer *b){
  107926. oggpack_adv1(b);
  107927. }
  107928. /* bits <= 32 */
  107929. long oggpack_read(oggpack_buffer *b,int bits){
  107930. long ret;
  107931. unsigned long m=mask[bits];
  107932. bits+=b->endbit;
  107933. if(b->endbyte+4>=b->storage){
  107934. /* not the main path */
  107935. ret=-1L;
  107936. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107937. }
  107938. ret=b->ptr[0]>>b->endbit;
  107939. if(bits>8){
  107940. ret|=b->ptr[1]<<(8-b->endbit);
  107941. if(bits>16){
  107942. ret|=b->ptr[2]<<(16-b->endbit);
  107943. if(bits>24){
  107944. ret|=b->ptr[3]<<(24-b->endbit);
  107945. if(bits>32 && b->endbit){
  107946. ret|=b->ptr[4]<<(32-b->endbit);
  107947. }
  107948. }
  107949. }
  107950. }
  107951. ret&=m;
  107952. overflow:
  107953. b->ptr+=bits/8;
  107954. b->endbyte+=bits/8;
  107955. b->endbit=bits&7;
  107956. return(ret);
  107957. }
  107958. /* bits <= 32 */
  107959. long oggpackB_read(oggpack_buffer *b,int bits){
  107960. long ret;
  107961. long m=32-bits;
  107962. bits+=b->endbit;
  107963. if(b->endbyte+4>=b->storage){
  107964. /* not the main path */
  107965. ret=-1L;
  107966. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107967. }
  107968. ret=b->ptr[0]<<(24+b->endbit);
  107969. if(bits>8){
  107970. ret|=b->ptr[1]<<(16+b->endbit);
  107971. if(bits>16){
  107972. ret|=b->ptr[2]<<(8+b->endbit);
  107973. if(bits>24){
  107974. ret|=b->ptr[3]<<(b->endbit);
  107975. if(bits>32 && b->endbit)
  107976. ret|=b->ptr[4]>>(8-b->endbit);
  107977. }
  107978. }
  107979. }
  107980. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107981. overflow:
  107982. b->ptr+=bits/8;
  107983. b->endbyte+=bits/8;
  107984. b->endbit=bits&7;
  107985. return(ret);
  107986. }
  107987. long oggpack_read1(oggpack_buffer *b){
  107988. long ret;
  107989. if(b->endbyte>=b->storage){
  107990. /* not the main path */
  107991. ret=-1L;
  107992. goto overflow;
  107993. }
  107994. ret=(b->ptr[0]>>b->endbit)&1;
  107995. overflow:
  107996. b->endbit++;
  107997. if(b->endbit>7){
  107998. b->endbit=0;
  107999. b->ptr++;
  108000. b->endbyte++;
  108001. }
  108002. return(ret);
  108003. }
  108004. long oggpackB_read1(oggpack_buffer *b){
  108005. long ret;
  108006. if(b->endbyte>=b->storage){
  108007. /* not the main path */
  108008. ret=-1L;
  108009. goto overflow;
  108010. }
  108011. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108012. overflow:
  108013. b->endbit++;
  108014. if(b->endbit>7){
  108015. b->endbit=0;
  108016. b->ptr++;
  108017. b->endbyte++;
  108018. }
  108019. return(ret);
  108020. }
  108021. long oggpack_bytes(oggpack_buffer *b){
  108022. return(b->endbyte+(b->endbit+7)/8);
  108023. }
  108024. long oggpack_bits(oggpack_buffer *b){
  108025. return(b->endbyte*8+b->endbit);
  108026. }
  108027. long oggpackB_bytes(oggpack_buffer *b){
  108028. return oggpack_bytes(b);
  108029. }
  108030. long oggpackB_bits(oggpack_buffer *b){
  108031. return oggpack_bits(b);
  108032. }
  108033. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108034. return(b->buffer);
  108035. }
  108036. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108037. return oggpack_get_buffer(b);
  108038. }
  108039. /* Self test of the bitwise routines; everything else is based on
  108040. them, so they damned well better be solid. */
  108041. #ifdef _V_SELFTEST
  108042. #include <stdio.h>
  108043. static int ilog(unsigned int v){
  108044. int ret=0;
  108045. while(v){
  108046. ret++;
  108047. v>>=1;
  108048. }
  108049. return(ret);
  108050. }
  108051. oggpack_buffer o;
  108052. oggpack_buffer r;
  108053. void report(char *in){
  108054. fprintf(stderr,"%s",in);
  108055. exit(1);
  108056. }
  108057. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108058. long bytes,i;
  108059. unsigned char *buffer;
  108060. oggpack_reset(&o);
  108061. for(i=0;i<vals;i++)
  108062. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108063. buffer=oggpack_get_buffer(&o);
  108064. bytes=oggpack_bytes(&o);
  108065. if(bytes!=compsize)report("wrong number of bytes!\n");
  108066. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108067. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108068. report("wrote incorrect value!\n");
  108069. }
  108070. oggpack_readinit(&r,buffer,bytes);
  108071. for(i=0;i<vals;i++){
  108072. int tbit=bits?bits:ilog(b[i]);
  108073. if(oggpack_look(&r,tbit)==-1)
  108074. report("out of data!\n");
  108075. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108076. report("looked at incorrect value!\n");
  108077. if(tbit==1)
  108078. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108079. report("looked at single bit incorrect value!\n");
  108080. if(tbit==1){
  108081. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108082. report("read incorrect single bit value!\n");
  108083. }else{
  108084. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108085. report("read incorrect value!\n");
  108086. }
  108087. }
  108088. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108089. }
  108090. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108091. long bytes,i;
  108092. unsigned char *buffer;
  108093. oggpackB_reset(&o);
  108094. for(i=0;i<vals;i++)
  108095. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108096. buffer=oggpackB_get_buffer(&o);
  108097. bytes=oggpackB_bytes(&o);
  108098. if(bytes!=compsize)report("wrong number of bytes!\n");
  108099. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108100. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108101. report("wrote incorrect value!\n");
  108102. }
  108103. oggpackB_readinit(&r,buffer,bytes);
  108104. for(i=0;i<vals;i++){
  108105. int tbit=bits?bits:ilog(b[i]);
  108106. if(oggpackB_look(&r,tbit)==-1)
  108107. report("out of data!\n");
  108108. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108109. report("looked at incorrect value!\n");
  108110. if(tbit==1)
  108111. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108112. report("looked at single bit incorrect value!\n");
  108113. if(tbit==1){
  108114. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108115. report("read incorrect single bit value!\n");
  108116. }else{
  108117. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108118. report("read incorrect value!\n");
  108119. }
  108120. }
  108121. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108122. }
  108123. int main(void){
  108124. unsigned char *buffer;
  108125. long bytes,i;
  108126. static unsigned long testbuffer1[]=
  108127. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108128. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108129. int test1size=43;
  108130. static unsigned long testbuffer2[]=
  108131. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108132. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108133. 85525151,0,12321,1,349528352};
  108134. int test2size=21;
  108135. static unsigned long testbuffer3[]=
  108136. {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,
  108137. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108138. int test3size=56;
  108139. static unsigned long large[]=
  108140. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108141. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108142. 85525151,0,12321,1,2146528352};
  108143. int onesize=33;
  108144. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108145. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108146. 223,4};
  108147. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108148. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108149. 245,251,128};
  108150. int twosize=6;
  108151. static int two[6]={61,255,255,251,231,29};
  108152. static int twoB[6]={247,63,255,253,249,120};
  108153. int threesize=54;
  108154. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108155. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108156. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108157. 100,52,4,14,18,86,77,1};
  108158. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108159. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108160. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108161. 200,20,254,4,58,106,176,144,0};
  108162. int foursize=38;
  108163. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108164. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108165. 28,2,133,0,1};
  108166. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108167. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108168. 129,10,4,32};
  108169. int fivesize=45;
  108170. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108171. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108172. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108173. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108174. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108175. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108176. int sixsize=7;
  108177. static int six[7]={17,177,170,242,169,19,148};
  108178. static int sixB[7]={136,141,85,79,149,200,41};
  108179. /* Test read/write together */
  108180. /* Later we test against pregenerated bitstreams */
  108181. oggpack_writeinit(&o);
  108182. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108183. cliptest(testbuffer1,test1size,0,one,onesize);
  108184. fprintf(stderr,"ok.");
  108185. fprintf(stderr,"\nNull bit call (LSb): ");
  108186. cliptest(testbuffer3,test3size,0,two,twosize);
  108187. fprintf(stderr,"ok.");
  108188. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108189. cliptest(testbuffer2,test2size,0,three,threesize);
  108190. fprintf(stderr,"ok.");
  108191. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108192. oggpack_reset(&o);
  108193. for(i=0;i<test2size;i++)
  108194. oggpack_write(&o,large[i],32);
  108195. buffer=oggpack_get_buffer(&o);
  108196. bytes=oggpack_bytes(&o);
  108197. oggpack_readinit(&r,buffer,bytes);
  108198. for(i=0;i<test2size;i++){
  108199. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108200. if(oggpack_look(&r,32)!=large[i]){
  108201. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108202. oggpack_look(&r,32),large[i]);
  108203. report("read incorrect value!\n");
  108204. }
  108205. oggpack_adv(&r,32);
  108206. }
  108207. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108208. fprintf(stderr,"ok.");
  108209. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108210. cliptest(testbuffer1,test1size,7,four,foursize);
  108211. fprintf(stderr,"ok.");
  108212. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108213. cliptest(testbuffer2,test2size,17,five,fivesize);
  108214. fprintf(stderr,"ok.");
  108215. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108216. cliptest(testbuffer3,test3size,1,six,sixsize);
  108217. fprintf(stderr,"ok.");
  108218. fprintf(stderr,"\nTesting read past end (LSb): ");
  108219. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108220. for(i=0;i<64;i++){
  108221. if(oggpack_read(&r,1)!=0){
  108222. fprintf(stderr,"failed; got -1 prematurely.\n");
  108223. exit(1);
  108224. }
  108225. }
  108226. if(oggpack_look(&r,1)!=-1 ||
  108227. oggpack_read(&r,1)!=-1){
  108228. fprintf(stderr,"failed; read past end without -1.\n");
  108229. exit(1);
  108230. }
  108231. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108232. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108233. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108234. exit(1);
  108235. }
  108236. if(oggpack_look(&r,18)!=0 ||
  108237. oggpack_look(&r,18)!=0){
  108238. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108239. exit(1);
  108240. }
  108241. if(oggpack_look(&r,19)!=-1 ||
  108242. oggpack_look(&r,19)!=-1){
  108243. fprintf(stderr,"failed; read past end without -1.\n");
  108244. exit(1);
  108245. }
  108246. if(oggpack_look(&r,32)!=-1 ||
  108247. oggpack_look(&r,32)!=-1){
  108248. fprintf(stderr,"failed; read past end without -1.\n");
  108249. exit(1);
  108250. }
  108251. oggpack_writeclear(&o);
  108252. fprintf(stderr,"ok.\n");
  108253. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108254. /* Test read/write together */
  108255. /* Later we test against pregenerated bitstreams */
  108256. oggpackB_writeinit(&o);
  108257. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108258. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108259. fprintf(stderr,"ok.");
  108260. fprintf(stderr,"\nNull bit call (MSb): ");
  108261. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108262. fprintf(stderr,"ok.");
  108263. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108264. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108265. fprintf(stderr,"ok.");
  108266. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108267. oggpackB_reset(&o);
  108268. for(i=0;i<test2size;i++)
  108269. oggpackB_write(&o,large[i],32);
  108270. buffer=oggpackB_get_buffer(&o);
  108271. bytes=oggpackB_bytes(&o);
  108272. oggpackB_readinit(&r,buffer,bytes);
  108273. for(i=0;i<test2size;i++){
  108274. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108275. if(oggpackB_look(&r,32)!=large[i]){
  108276. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108277. oggpackB_look(&r,32),large[i]);
  108278. report("read incorrect value!\n");
  108279. }
  108280. oggpackB_adv(&r,32);
  108281. }
  108282. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108283. fprintf(stderr,"ok.");
  108284. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108285. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108286. fprintf(stderr,"ok.");
  108287. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108288. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108289. fprintf(stderr,"ok.");
  108290. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108291. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108292. fprintf(stderr,"ok.");
  108293. fprintf(stderr,"\nTesting read past end (MSb): ");
  108294. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108295. for(i=0;i<64;i++){
  108296. if(oggpackB_read(&r,1)!=0){
  108297. fprintf(stderr,"failed; got -1 prematurely.\n");
  108298. exit(1);
  108299. }
  108300. }
  108301. if(oggpackB_look(&r,1)!=-1 ||
  108302. oggpackB_read(&r,1)!=-1){
  108303. fprintf(stderr,"failed; read past end without -1.\n");
  108304. exit(1);
  108305. }
  108306. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108307. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108308. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108309. exit(1);
  108310. }
  108311. if(oggpackB_look(&r,18)!=0 ||
  108312. oggpackB_look(&r,18)!=0){
  108313. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108314. exit(1);
  108315. }
  108316. if(oggpackB_look(&r,19)!=-1 ||
  108317. oggpackB_look(&r,19)!=-1){
  108318. fprintf(stderr,"failed; read past end without -1.\n");
  108319. exit(1);
  108320. }
  108321. if(oggpackB_look(&r,32)!=-1 ||
  108322. oggpackB_look(&r,32)!=-1){
  108323. fprintf(stderr,"failed; read past end without -1.\n");
  108324. exit(1);
  108325. }
  108326. oggpackB_writeclear(&o);
  108327. fprintf(stderr,"ok.\n\n");
  108328. return(0);
  108329. }
  108330. #endif /* _V_SELFTEST */
  108331. #undef BUFFER_INCREMENT
  108332. #endif
  108333. /*** End of inlined file: bitwise.c ***/
  108334. /*** Start of inlined file: framing.c ***/
  108335. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108336. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108337. // tasks..
  108338. #if JUCE_MSVC
  108339. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108340. #endif
  108341. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108342. #if JUCE_USE_OGGVORBIS
  108343. #include <stdlib.h>
  108344. #include <string.h>
  108345. /* A complete description of Ogg framing exists in docs/framing.html */
  108346. int ogg_page_version(ogg_page *og){
  108347. return((int)(og->header[4]));
  108348. }
  108349. int ogg_page_continued(ogg_page *og){
  108350. return((int)(og->header[5]&0x01));
  108351. }
  108352. int ogg_page_bos(ogg_page *og){
  108353. return((int)(og->header[5]&0x02));
  108354. }
  108355. int ogg_page_eos(ogg_page *og){
  108356. return((int)(og->header[5]&0x04));
  108357. }
  108358. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108359. unsigned char *page=og->header;
  108360. ogg_int64_t granulepos=page[13]&(0xff);
  108361. granulepos= (granulepos<<8)|(page[12]&0xff);
  108362. granulepos= (granulepos<<8)|(page[11]&0xff);
  108363. granulepos= (granulepos<<8)|(page[10]&0xff);
  108364. granulepos= (granulepos<<8)|(page[9]&0xff);
  108365. granulepos= (granulepos<<8)|(page[8]&0xff);
  108366. granulepos= (granulepos<<8)|(page[7]&0xff);
  108367. granulepos= (granulepos<<8)|(page[6]&0xff);
  108368. return(granulepos);
  108369. }
  108370. int ogg_page_serialno(ogg_page *og){
  108371. return(og->header[14] |
  108372. (og->header[15]<<8) |
  108373. (og->header[16]<<16) |
  108374. (og->header[17]<<24));
  108375. }
  108376. long ogg_page_pageno(ogg_page *og){
  108377. return(og->header[18] |
  108378. (og->header[19]<<8) |
  108379. (og->header[20]<<16) |
  108380. (og->header[21]<<24));
  108381. }
  108382. /* returns the number of packets that are completed on this page (if
  108383. the leading packet is begun on a previous page, but ends on this
  108384. page, it's counted */
  108385. /* NOTE:
  108386. If a page consists of a packet begun on a previous page, and a new
  108387. packet begun (but not completed) on this page, the return will be:
  108388. ogg_page_packets(page) ==1,
  108389. ogg_page_continued(page) !=0
  108390. If a page happens to be a single packet that was begun on a
  108391. previous page, and spans to the next page (in the case of a three or
  108392. more page packet), the return will be:
  108393. ogg_page_packets(page) ==0,
  108394. ogg_page_continued(page) !=0
  108395. */
  108396. int ogg_page_packets(ogg_page *og){
  108397. int i,n=og->header[26],count=0;
  108398. for(i=0;i<n;i++)
  108399. if(og->header[27+i]<255)count++;
  108400. return(count);
  108401. }
  108402. #if 0
  108403. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108404. use the static init below) */
  108405. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108406. int i;
  108407. unsigned long r;
  108408. r = index << 24;
  108409. for (i=0; i<8; i++)
  108410. if (r & 0x80000000UL)
  108411. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108412. polynomial, although we use an
  108413. unreflected alg and an init/final
  108414. of 0, not 0xffffffff */
  108415. else
  108416. r<<=1;
  108417. return (r & 0xffffffffUL);
  108418. }
  108419. #endif
  108420. static const ogg_uint32_t crc_lookup[256]={
  108421. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108422. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108423. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108424. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108425. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108426. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108427. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108428. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108429. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108430. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108431. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108432. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108433. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108434. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108435. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108436. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108437. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108438. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108439. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108440. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108441. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108442. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108443. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108444. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108445. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108446. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108447. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108448. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108449. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108450. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108451. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108452. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108453. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108454. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108455. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108456. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108457. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108458. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108459. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108460. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108461. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108462. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108463. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108464. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108465. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108466. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108467. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108468. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108469. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108470. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108471. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108472. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108473. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108474. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108475. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108476. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108477. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108478. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108479. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108480. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108481. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108482. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108483. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108484. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108485. /* init the encode/decode logical stream state */
  108486. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108487. if(os){
  108488. memset(os,0,sizeof(*os));
  108489. os->body_storage=16*1024;
  108490. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108491. os->lacing_storage=1024;
  108492. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108493. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108494. os->serialno=serialno;
  108495. return(0);
  108496. }
  108497. return(-1);
  108498. }
  108499. /* _clear does not free os, only the non-flat storage within */
  108500. int ogg_stream_clear(ogg_stream_state *os){
  108501. if(os){
  108502. if(os->body_data)_ogg_free(os->body_data);
  108503. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108504. if(os->granule_vals)_ogg_free(os->granule_vals);
  108505. memset(os,0,sizeof(*os));
  108506. }
  108507. return(0);
  108508. }
  108509. int ogg_stream_destroy(ogg_stream_state *os){
  108510. if(os){
  108511. ogg_stream_clear(os);
  108512. _ogg_free(os);
  108513. }
  108514. return(0);
  108515. }
  108516. /* Helpers for ogg_stream_encode; this keeps the structure and
  108517. what's happening fairly clear */
  108518. static void _os_body_expand(ogg_stream_state *os,int needed){
  108519. if(os->body_storage<=os->body_fill+needed){
  108520. os->body_storage+=(needed+1024);
  108521. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108522. }
  108523. }
  108524. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108525. if(os->lacing_storage<=os->lacing_fill+needed){
  108526. os->lacing_storage+=(needed+32);
  108527. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108528. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108529. }
  108530. }
  108531. /* checksum the page */
  108532. /* Direct table CRC; note that this will be faster in the future if we
  108533. perform the checksum silmultaneously with other copies */
  108534. void ogg_page_checksum_set(ogg_page *og){
  108535. if(og){
  108536. ogg_uint32_t crc_reg=0;
  108537. int i;
  108538. /* safety; needed for API behavior, but not framing code */
  108539. og->header[22]=0;
  108540. og->header[23]=0;
  108541. og->header[24]=0;
  108542. og->header[25]=0;
  108543. for(i=0;i<og->header_len;i++)
  108544. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108545. for(i=0;i<og->body_len;i++)
  108546. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108547. og->header[22]=(unsigned char)(crc_reg&0xff);
  108548. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108549. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108550. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108551. }
  108552. }
  108553. /* submit data to the internal buffer of the framing engine */
  108554. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108555. int lacing_vals=op->bytes/255+1,i;
  108556. if(os->body_returned){
  108557. /* advance packet data according to the body_returned pointer. We
  108558. had to keep it around to return a pointer into the buffer last
  108559. call */
  108560. os->body_fill-=os->body_returned;
  108561. if(os->body_fill)
  108562. memmove(os->body_data,os->body_data+os->body_returned,
  108563. os->body_fill);
  108564. os->body_returned=0;
  108565. }
  108566. /* make sure we have the buffer storage */
  108567. _os_body_expand(os,op->bytes);
  108568. _os_lacing_expand(os,lacing_vals);
  108569. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108570. the liability of overly clean abstraction for the time being. It
  108571. will actually be fairly easy to eliminate the extra copy in the
  108572. future */
  108573. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108574. os->body_fill+=op->bytes;
  108575. /* Store lacing vals for this packet */
  108576. for(i=0;i<lacing_vals-1;i++){
  108577. os->lacing_vals[os->lacing_fill+i]=255;
  108578. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108579. }
  108580. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108581. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108582. /* flag the first segment as the beginning of the packet */
  108583. os->lacing_vals[os->lacing_fill]|= 0x100;
  108584. os->lacing_fill+=lacing_vals;
  108585. /* for the sake of completeness */
  108586. os->packetno++;
  108587. if(op->e_o_s)os->e_o_s=1;
  108588. return(0);
  108589. }
  108590. /* This will flush remaining packets into a page (returning nonzero),
  108591. even if there is not enough data to trigger a flush normally
  108592. (undersized page). If there are no packets or partial packets to
  108593. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108594. try to flush a normal sized page like ogg_stream_pageout; a call to
  108595. ogg_stream_flush does not guarantee that all packets have flushed.
  108596. Only a return value of 0 from ogg_stream_flush indicates all packet
  108597. data is flushed into pages.
  108598. since ogg_stream_flush will flush the last page in a stream even if
  108599. it's undersized, you almost certainly want to use ogg_stream_pageout
  108600. (and *not* ogg_stream_flush) unless you specifically need to flush
  108601. an page regardless of size in the middle of a stream. */
  108602. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108603. int i;
  108604. int vals=0;
  108605. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108606. int bytes=0;
  108607. long acc=0;
  108608. ogg_int64_t granule_pos=-1;
  108609. if(maxvals==0)return(0);
  108610. /* construct a page */
  108611. /* decide how many segments to include */
  108612. /* If this is the initial header case, the first page must only include
  108613. the initial header packet */
  108614. if(os->b_o_s==0){ /* 'initial header page' case */
  108615. granule_pos=0;
  108616. for(vals=0;vals<maxvals;vals++){
  108617. if((os->lacing_vals[vals]&0x0ff)<255){
  108618. vals++;
  108619. break;
  108620. }
  108621. }
  108622. }else{
  108623. for(vals=0;vals<maxvals;vals++){
  108624. if(acc>4096)break;
  108625. acc+=os->lacing_vals[vals]&0x0ff;
  108626. if((os->lacing_vals[vals]&0xff)<255)
  108627. granule_pos=os->granule_vals[vals];
  108628. }
  108629. }
  108630. /* construct the header in temp storage */
  108631. memcpy(os->header,"OggS",4);
  108632. /* stream structure version */
  108633. os->header[4]=0x00;
  108634. /* continued packet flag? */
  108635. os->header[5]=0x00;
  108636. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108637. /* first page flag? */
  108638. if(os->b_o_s==0)os->header[5]|=0x02;
  108639. /* last page flag? */
  108640. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108641. os->b_o_s=1;
  108642. /* 64 bits of PCM position */
  108643. for(i=6;i<14;i++){
  108644. os->header[i]=(unsigned char)(granule_pos&0xff);
  108645. granule_pos>>=8;
  108646. }
  108647. /* 32 bits of stream serial number */
  108648. {
  108649. long serialno=os->serialno;
  108650. for(i=14;i<18;i++){
  108651. os->header[i]=(unsigned char)(serialno&0xff);
  108652. serialno>>=8;
  108653. }
  108654. }
  108655. /* 32 bits of page counter (we have both counter and page header
  108656. because this val can roll over) */
  108657. if(os->pageno==-1)os->pageno=0; /* because someone called
  108658. stream_reset; this would be a
  108659. strange thing to do in an
  108660. encode stream, but it has
  108661. plausible uses */
  108662. {
  108663. long pageno=os->pageno++;
  108664. for(i=18;i<22;i++){
  108665. os->header[i]=(unsigned char)(pageno&0xff);
  108666. pageno>>=8;
  108667. }
  108668. }
  108669. /* zero for computation; filled in later */
  108670. os->header[22]=0;
  108671. os->header[23]=0;
  108672. os->header[24]=0;
  108673. os->header[25]=0;
  108674. /* segment table */
  108675. os->header[26]=(unsigned char)(vals&0xff);
  108676. for(i=0;i<vals;i++)
  108677. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108678. /* set pointers in the ogg_page struct */
  108679. og->header=os->header;
  108680. og->header_len=os->header_fill=vals+27;
  108681. og->body=os->body_data+os->body_returned;
  108682. og->body_len=bytes;
  108683. /* advance the lacing data and set the body_returned pointer */
  108684. os->lacing_fill-=vals;
  108685. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108686. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108687. os->body_returned+=bytes;
  108688. /* calculate the checksum */
  108689. ogg_page_checksum_set(og);
  108690. /* done */
  108691. return(1);
  108692. }
  108693. /* This constructs pages from buffered packet segments. The pointers
  108694. returned are to static buffers; do not free. The returned buffers are
  108695. good only until the next call (using the same ogg_stream_state) */
  108696. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108697. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108698. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108699. os->lacing_fill>=255 || /* 'segment table full' case */
  108700. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108701. return(ogg_stream_flush(os,og));
  108702. }
  108703. /* not enough data to construct a page and not end of stream */
  108704. return(0);
  108705. }
  108706. int ogg_stream_eos(ogg_stream_state *os){
  108707. return os->e_o_s;
  108708. }
  108709. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108710. /* This has two layers to place more of the multi-serialno and paging
  108711. control in the application's hands. First, we expose a data buffer
  108712. using ogg_sync_buffer(). The app either copies into the
  108713. buffer, or passes it directly to read(), etc. We then call
  108714. ogg_sync_wrote() to tell how many bytes we just added.
  108715. Pages are returned (pointers into the buffer in ogg_sync_state)
  108716. by ogg_sync_pageout(). The page is then submitted to
  108717. ogg_stream_pagein() along with the appropriate
  108718. ogg_stream_state* (ie, matching serialno). We then get raw
  108719. packets out calling ogg_stream_packetout() with a
  108720. ogg_stream_state. */
  108721. /* initialize the struct to a known state */
  108722. int ogg_sync_init(ogg_sync_state *oy){
  108723. if(oy){
  108724. memset(oy,0,sizeof(*oy));
  108725. }
  108726. return(0);
  108727. }
  108728. /* clear non-flat storage within */
  108729. int ogg_sync_clear(ogg_sync_state *oy){
  108730. if(oy){
  108731. if(oy->data)_ogg_free(oy->data);
  108732. ogg_sync_init(oy);
  108733. }
  108734. return(0);
  108735. }
  108736. int ogg_sync_destroy(ogg_sync_state *oy){
  108737. if(oy){
  108738. ogg_sync_clear(oy);
  108739. _ogg_free(oy);
  108740. }
  108741. return(0);
  108742. }
  108743. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108744. /* first, clear out any space that has been previously returned */
  108745. if(oy->returned){
  108746. oy->fill-=oy->returned;
  108747. if(oy->fill>0)
  108748. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108749. oy->returned=0;
  108750. }
  108751. if(size>oy->storage-oy->fill){
  108752. /* We need to extend the internal buffer */
  108753. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108754. if(oy->data)
  108755. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108756. else
  108757. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108758. oy->storage=newsize;
  108759. }
  108760. /* expose a segment at least as large as requested at the fill mark */
  108761. return((char *)oy->data+oy->fill);
  108762. }
  108763. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108764. if(oy->fill+bytes>oy->storage)return(-1);
  108765. oy->fill+=bytes;
  108766. return(0);
  108767. }
  108768. /* sync the stream. This is meant to be useful for finding page
  108769. boundaries.
  108770. return values for this:
  108771. -n) skipped n bytes
  108772. 0) page not ready; more data (no bytes skipped)
  108773. n) page synced at current location; page length n bytes
  108774. */
  108775. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108776. unsigned char *page=oy->data+oy->returned;
  108777. unsigned char *next;
  108778. long bytes=oy->fill-oy->returned;
  108779. if(oy->headerbytes==0){
  108780. int headerbytes,i;
  108781. if(bytes<27)return(0); /* not enough for a header */
  108782. /* verify capture pattern */
  108783. if(memcmp(page,"OggS",4))goto sync_fail;
  108784. headerbytes=page[26]+27;
  108785. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108786. /* count up body length in the segment table */
  108787. for(i=0;i<page[26];i++)
  108788. oy->bodybytes+=page[27+i];
  108789. oy->headerbytes=headerbytes;
  108790. }
  108791. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108792. /* The whole test page is buffered. Verify the checksum */
  108793. {
  108794. /* Grab the checksum bytes, set the header field to zero */
  108795. char chksum[4];
  108796. ogg_page log;
  108797. memcpy(chksum,page+22,4);
  108798. memset(page+22,0,4);
  108799. /* set up a temp page struct and recompute the checksum */
  108800. log.header=page;
  108801. log.header_len=oy->headerbytes;
  108802. log.body=page+oy->headerbytes;
  108803. log.body_len=oy->bodybytes;
  108804. ogg_page_checksum_set(&log);
  108805. /* Compare */
  108806. if(memcmp(chksum,page+22,4)){
  108807. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108808. at all) */
  108809. /* replace the computed checksum with the one actually read in */
  108810. memcpy(page+22,chksum,4);
  108811. /* Bad checksum. Lose sync */
  108812. goto sync_fail;
  108813. }
  108814. }
  108815. /* yes, have a whole page all ready to go */
  108816. {
  108817. unsigned char *page=oy->data+oy->returned;
  108818. long bytes;
  108819. if(og){
  108820. og->header=page;
  108821. og->header_len=oy->headerbytes;
  108822. og->body=page+oy->headerbytes;
  108823. og->body_len=oy->bodybytes;
  108824. }
  108825. oy->unsynced=0;
  108826. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108827. oy->headerbytes=0;
  108828. oy->bodybytes=0;
  108829. return(bytes);
  108830. }
  108831. sync_fail:
  108832. oy->headerbytes=0;
  108833. oy->bodybytes=0;
  108834. /* search for possible capture */
  108835. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108836. if(!next)
  108837. next=oy->data+oy->fill;
  108838. oy->returned=next-oy->data;
  108839. return(-(next-page));
  108840. }
  108841. /* sync the stream and get a page. Keep trying until we find a page.
  108842. Supress 'sync errors' after reporting the first.
  108843. return values:
  108844. -1) recapture (hole in data)
  108845. 0) need more data
  108846. 1) page returned
  108847. Returns pointers into buffered data; invalidated by next call to
  108848. _stream, _clear, _init, or _buffer */
  108849. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108850. /* all we need to do is verify a page at the head of the stream
  108851. buffer. If it doesn't verify, we look for the next potential
  108852. frame */
  108853. for(;;){
  108854. long ret=ogg_sync_pageseek(oy,og);
  108855. if(ret>0){
  108856. /* have a page */
  108857. return(1);
  108858. }
  108859. if(ret==0){
  108860. /* need more data */
  108861. return(0);
  108862. }
  108863. /* head did not start a synced page... skipped some bytes */
  108864. if(!oy->unsynced){
  108865. oy->unsynced=1;
  108866. return(-1);
  108867. }
  108868. /* loop. keep looking */
  108869. }
  108870. }
  108871. /* add the incoming page to the stream state; we decompose the page
  108872. into packet segments here as well. */
  108873. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108874. unsigned char *header=og->header;
  108875. unsigned char *body=og->body;
  108876. long bodysize=og->body_len;
  108877. int segptr=0;
  108878. int version=ogg_page_version(og);
  108879. int continued=ogg_page_continued(og);
  108880. int bos=ogg_page_bos(og);
  108881. int eos=ogg_page_eos(og);
  108882. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108883. int serialno=ogg_page_serialno(og);
  108884. long pageno=ogg_page_pageno(og);
  108885. int segments=header[26];
  108886. /* clean up 'returned data' */
  108887. {
  108888. long lr=os->lacing_returned;
  108889. long br=os->body_returned;
  108890. /* body data */
  108891. if(br){
  108892. os->body_fill-=br;
  108893. if(os->body_fill)
  108894. memmove(os->body_data,os->body_data+br,os->body_fill);
  108895. os->body_returned=0;
  108896. }
  108897. if(lr){
  108898. /* segment table */
  108899. if(os->lacing_fill-lr){
  108900. memmove(os->lacing_vals,os->lacing_vals+lr,
  108901. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108902. memmove(os->granule_vals,os->granule_vals+lr,
  108903. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108904. }
  108905. os->lacing_fill-=lr;
  108906. os->lacing_packet-=lr;
  108907. os->lacing_returned=0;
  108908. }
  108909. }
  108910. /* check the serial number */
  108911. if(serialno!=os->serialno)return(-1);
  108912. if(version>0)return(-1);
  108913. _os_lacing_expand(os,segments+1);
  108914. /* are we in sequence? */
  108915. if(pageno!=os->pageno){
  108916. int i;
  108917. /* unroll previous partial packet (if any) */
  108918. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108919. os->body_fill-=os->lacing_vals[i]&0xff;
  108920. os->lacing_fill=os->lacing_packet;
  108921. /* make a note of dropped data in segment table */
  108922. if(os->pageno!=-1){
  108923. os->lacing_vals[os->lacing_fill++]=0x400;
  108924. os->lacing_packet++;
  108925. }
  108926. }
  108927. /* are we a 'continued packet' page? If so, we may need to skip
  108928. some segments */
  108929. if(continued){
  108930. if(os->lacing_fill<1 ||
  108931. os->lacing_vals[os->lacing_fill-1]==0x400){
  108932. bos=0;
  108933. for(;segptr<segments;segptr++){
  108934. int val=header[27+segptr];
  108935. body+=val;
  108936. bodysize-=val;
  108937. if(val<255){
  108938. segptr++;
  108939. break;
  108940. }
  108941. }
  108942. }
  108943. }
  108944. if(bodysize){
  108945. _os_body_expand(os,bodysize);
  108946. memcpy(os->body_data+os->body_fill,body,bodysize);
  108947. os->body_fill+=bodysize;
  108948. }
  108949. {
  108950. int saved=-1;
  108951. while(segptr<segments){
  108952. int val=header[27+segptr];
  108953. os->lacing_vals[os->lacing_fill]=val;
  108954. os->granule_vals[os->lacing_fill]=-1;
  108955. if(bos){
  108956. os->lacing_vals[os->lacing_fill]|=0x100;
  108957. bos=0;
  108958. }
  108959. if(val<255)saved=os->lacing_fill;
  108960. os->lacing_fill++;
  108961. segptr++;
  108962. if(val<255)os->lacing_packet=os->lacing_fill;
  108963. }
  108964. /* set the granulepos on the last granuleval of the last full packet */
  108965. if(saved!=-1){
  108966. os->granule_vals[saved]=granulepos;
  108967. }
  108968. }
  108969. if(eos){
  108970. os->e_o_s=1;
  108971. if(os->lacing_fill>0)
  108972. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108973. }
  108974. os->pageno=pageno+1;
  108975. return(0);
  108976. }
  108977. /* clear things to an initial state. Good to call, eg, before seeking */
  108978. int ogg_sync_reset(ogg_sync_state *oy){
  108979. oy->fill=0;
  108980. oy->returned=0;
  108981. oy->unsynced=0;
  108982. oy->headerbytes=0;
  108983. oy->bodybytes=0;
  108984. return(0);
  108985. }
  108986. int ogg_stream_reset(ogg_stream_state *os){
  108987. os->body_fill=0;
  108988. os->body_returned=0;
  108989. os->lacing_fill=0;
  108990. os->lacing_packet=0;
  108991. os->lacing_returned=0;
  108992. os->header_fill=0;
  108993. os->e_o_s=0;
  108994. os->b_o_s=0;
  108995. os->pageno=-1;
  108996. os->packetno=0;
  108997. os->granulepos=0;
  108998. return(0);
  108999. }
  109000. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109001. ogg_stream_reset(os);
  109002. os->serialno=serialno;
  109003. return(0);
  109004. }
  109005. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109006. /* The last part of decode. We have the stream broken into packet
  109007. segments. Now we need to group them into packets (or return the
  109008. out of sync markers) */
  109009. int ptr=os->lacing_returned;
  109010. if(os->lacing_packet<=ptr)return(0);
  109011. if(os->lacing_vals[ptr]&0x400){
  109012. /* we need to tell the codec there's a gap; it might need to
  109013. handle previous packet dependencies. */
  109014. os->lacing_returned++;
  109015. os->packetno++;
  109016. return(-1);
  109017. }
  109018. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109019. to ask if there's a whole packet
  109020. waiting */
  109021. /* Gather the whole packet. We'll have no holes or a partial packet */
  109022. {
  109023. int size=os->lacing_vals[ptr]&0xff;
  109024. int bytes=size;
  109025. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109026. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109027. while(size==255){
  109028. int val=os->lacing_vals[++ptr];
  109029. size=val&0xff;
  109030. if(val&0x200)eos=0x200;
  109031. bytes+=size;
  109032. }
  109033. if(op){
  109034. op->e_o_s=eos;
  109035. op->b_o_s=bos;
  109036. op->packet=os->body_data+os->body_returned;
  109037. op->packetno=os->packetno;
  109038. op->granulepos=os->granule_vals[ptr];
  109039. op->bytes=bytes;
  109040. }
  109041. if(adv){
  109042. os->body_returned+=bytes;
  109043. os->lacing_returned=ptr+1;
  109044. os->packetno++;
  109045. }
  109046. }
  109047. return(1);
  109048. }
  109049. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109050. return _packetout(os,op,1);
  109051. }
  109052. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109053. return _packetout(os,op,0);
  109054. }
  109055. void ogg_packet_clear(ogg_packet *op) {
  109056. _ogg_free(op->packet);
  109057. memset(op, 0, sizeof(*op));
  109058. }
  109059. #ifdef _V_SELFTEST
  109060. #include <stdio.h>
  109061. ogg_stream_state os_en, os_de;
  109062. ogg_sync_state oy;
  109063. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109064. long j;
  109065. static int sequence=0;
  109066. static int lastno=0;
  109067. if(op->bytes!=len){
  109068. fprintf(stderr,"incorrect packet length!\n");
  109069. exit(1);
  109070. }
  109071. if(op->granulepos!=pos){
  109072. fprintf(stderr,"incorrect packet position!\n");
  109073. exit(1);
  109074. }
  109075. /* packet number just follows sequence/gap; adjust the input number
  109076. for that */
  109077. if(no==0){
  109078. sequence=0;
  109079. }else{
  109080. sequence++;
  109081. if(no>lastno+1)
  109082. sequence++;
  109083. }
  109084. lastno=no;
  109085. if(op->packetno!=sequence){
  109086. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109087. (long)(op->packetno),sequence);
  109088. exit(1);
  109089. }
  109090. /* Test data */
  109091. for(j=0;j<op->bytes;j++)
  109092. if(op->packet[j]!=((j+no)&0xff)){
  109093. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109094. j,op->packet[j],(j+no)&0xff);
  109095. exit(1);
  109096. }
  109097. }
  109098. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109099. long j;
  109100. /* Test data */
  109101. for(j=0;j<og->body_len;j++)
  109102. if(og->body[j]!=data[j]){
  109103. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109104. j,data[j],og->body[j]);
  109105. exit(1);
  109106. }
  109107. /* Test header */
  109108. for(j=0;j<og->header_len;j++){
  109109. if(og->header[j]!=header[j]){
  109110. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109111. for(j=0;j<header[26]+27;j++)
  109112. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109113. fprintf(stderr,"\n");
  109114. exit(1);
  109115. }
  109116. }
  109117. if(og->header_len!=header[26]+27){
  109118. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109119. og->header_len,header[26]+27);
  109120. exit(1);
  109121. }
  109122. }
  109123. void print_header(ogg_page *og){
  109124. int j;
  109125. fprintf(stderr,"\nHEADER:\n");
  109126. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109127. og->header[0],og->header[1],og->header[2],og->header[3],
  109128. (int)og->header[4],(int)og->header[5]);
  109129. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109130. (og->header[9]<<24)|(og->header[8]<<16)|
  109131. (og->header[7]<<8)|og->header[6],
  109132. (og->header[17]<<24)|(og->header[16]<<16)|
  109133. (og->header[15]<<8)|og->header[14],
  109134. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109135. (og->header[19]<<8)|og->header[18]);
  109136. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109137. (int)og->header[22],(int)og->header[23],
  109138. (int)og->header[24],(int)og->header[25],
  109139. (int)og->header[26]);
  109140. for(j=27;j<og->header_len;j++)
  109141. fprintf(stderr,"%d ",(int)og->header[j]);
  109142. fprintf(stderr,")\n\n");
  109143. }
  109144. void copy_page(ogg_page *og){
  109145. unsigned char *temp=_ogg_malloc(og->header_len);
  109146. memcpy(temp,og->header,og->header_len);
  109147. og->header=temp;
  109148. temp=_ogg_malloc(og->body_len);
  109149. memcpy(temp,og->body,og->body_len);
  109150. og->body=temp;
  109151. }
  109152. void free_page(ogg_page *og){
  109153. _ogg_free (og->header);
  109154. _ogg_free (og->body);
  109155. }
  109156. void error(void){
  109157. fprintf(stderr,"error!\n");
  109158. exit(1);
  109159. }
  109160. /* 17 only */
  109161. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109162. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109163. 0x01,0x02,0x03,0x04,0,0,0,0,
  109164. 0x15,0xed,0xec,0x91,
  109165. 1,
  109166. 17};
  109167. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109168. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109169. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109170. 0x01,0x02,0x03,0x04,0,0,0,0,
  109171. 0x59,0x10,0x6c,0x2c,
  109172. 1,
  109173. 17};
  109174. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109175. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109176. 0x01,0x02,0x03,0x04,1,0,0,0,
  109177. 0x89,0x33,0x85,0xce,
  109178. 13,
  109179. 254,255,0,255,1,255,245,255,255,0,
  109180. 255,255,90};
  109181. /* nil packets; beginning,middle,end */
  109182. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109183. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109184. 0x01,0x02,0x03,0x04,0,0,0,0,
  109185. 0xff,0x7b,0x23,0x17,
  109186. 1,
  109187. 0};
  109188. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109189. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109190. 0x01,0x02,0x03,0x04,1,0,0,0,
  109191. 0x5c,0x3f,0x66,0xcb,
  109192. 17,
  109193. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109194. 255,255,90,0};
  109195. /* large initial packet */
  109196. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109197. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109198. 0x01,0x02,0x03,0x04,0,0,0,0,
  109199. 0x01,0x27,0x31,0xaa,
  109200. 18,
  109201. 255,255,255,255,255,255,255,255,
  109202. 255,255,255,255,255,255,255,255,255,10};
  109203. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109204. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109205. 0x01,0x02,0x03,0x04,1,0,0,0,
  109206. 0x7f,0x4e,0x8a,0xd2,
  109207. 4,
  109208. 255,4,255,0};
  109209. /* continuing packet test */
  109210. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109211. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109212. 0x01,0x02,0x03,0x04,0,0,0,0,
  109213. 0xff,0x7b,0x23,0x17,
  109214. 1,
  109215. 0};
  109216. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109217. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109218. 0x01,0x02,0x03,0x04,1,0,0,0,
  109219. 0x54,0x05,0x51,0xc8,
  109220. 17,
  109221. 255,255,255,255,255,255,255,255,
  109222. 255,255,255,255,255,255,255,255,255};
  109223. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109224. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109225. 0x01,0x02,0x03,0x04,2,0,0,0,
  109226. 0xc8,0xc3,0xcb,0xed,
  109227. 5,
  109228. 10,255,4,255,0};
  109229. /* page with the 255 segment limit */
  109230. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109231. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109232. 0x01,0x02,0x03,0x04,0,0,0,0,
  109233. 0xff,0x7b,0x23,0x17,
  109234. 1,
  109235. 0};
  109236. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109237. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109238. 0x01,0x02,0x03,0x04,1,0,0,0,
  109239. 0xed,0x2a,0x2e,0xa7,
  109240. 255,
  109241. 10,10,10,10,10,10,10,10,
  109242. 10,10,10,10,10,10,10,10,
  109243. 10,10,10,10,10,10,10,10,
  109244. 10,10,10,10,10,10,10,10,
  109245. 10,10,10,10,10,10,10,10,
  109246. 10,10,10,10,10,10,10,10,
  109247. 10,10,10,10,10,10,10,10,
  109248. 10,10,10,10,10,10,10,10,
  109249. 10,10,10,10,10,10,10,10,
  109250. 10,10,10,10,10,10,10,10,
  109251. 10,10,10,10,10,10,10,10,
  109252. 10,10,10,10,10,10,10,10,
  109253. 10,10,10,10,10,10,10,10,
  109254. 10,10,10,10,10,10,10,10,
  109255. 10,10,10,10,10,10,10,10,
  109256. 10,10,10,10,10,10,10,10,
  109257. 10,10,10,10,10,10,10,10,
  109258. 10,10,10,10,10,10,10,10,
  109259. 10,10,10,10,10,10,10,10,
  109260. 10,10,10,10,10,10,10,10,
  109261. 10,10,10,10,10,10,10,10,
  109262. 10,10,10,10,10,10,10,10,
  109263. 10,10,10,10,10,10,10,10,
  109264. 10,10,10,10,10,10,10,10,
  109265. 10,10,10,10,10,10,10,10,
  109266. 10,10,10,10,10,10,10,10,
  109267. 10,10,10,10,10,10,10,10,
  109268. 10,10,10,10,10,10,10,10,
  109269. 10,10,10,10,10,10,10,10,
  109270. 10,10,10,10,10,10,10,10,
  109271. 10,10,10,10,10,10,10,10,
  109272. 10,10,10,10,10,10,10};
  109273. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109274. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109275. 0x01,0x02,0x03,0x04,2,0,0,0,
  109276. 0x6c,0x3b,0x82,0x3d,
  109277. 1,
  109278. 50};
  109279. /* packet that overspans over an entire page */
  109280. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109281. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109282. 0x01,0x02,0x03,0x04,0,0,0,0,
  109283. 0xff,0x7b,0x23,0x17,
  109284. 1,
  109285. 0};
  109286. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109287. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109288. 0x01,0x02,0x03,0x04,1,0,0,0,
  109289. 0x3c,0xd9,0x4d,0x3f,
  109290. 17,
  109291. 100,255,255,255,255,255,255,255,255,
  109292. 255,255,255,255,255,255,255,255};
  109293. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109294. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109295. 0x01,0x02,0x03,0x04,2,0,0,0,
  109296. 0x01,0xd2,0xe5,0xe5,
  109297. 17,
  109298. 255,255,255,255,255,255,255,255,
  109299. 255,255,255,255,255,255,255,255,255};
  109300. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109301. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109302. 0x01,0x02,0x03,0x04,3,0,0,0,
  109303. 0xef,0xdd,0x88,0xde,
  109304. 7,
  109305. 255,255,75,255,4,255,0};
  109306. /* packet that overspans over an entire page */
  109307. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109308. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109309. 0x01,0x02,0x03,0x04,0,0,0,0,
  109310. 0xff,0x7b,0x23,0x17,
  109311. 1,
  109312. 0};
  109313. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109314. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109315. 0x01,0x02,0x03,0x04,1,0,0,0,
  109316. 0x3c,0xd9,0x4d,0x3f,
  109317. 17,
  109318. 100,255,255,255,255,255,255,255,255,
  109319. 255,255,255,255,255,255,255,255};
  109320. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109321. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109322. 0x01,0x02,0x03,0x04,2,0,0,0,
  109323. 0xd4,0xe0,0x60,0xe5,
  109324. 1,0};
  109325. void test_pack(const int *pl, const int **headers, int byteskip,
  109326. int pageskip, int packetskip){
  109327. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109328. long inptr=0;
  109329. long outptr=0;
  109330. long deptr=0;
  109331. long depacket=0;
  109332. long granule_pos=7,pageno=0;
  109333. int i,j,packets,pageout=pageskip;
  109334. int eosflag=0;
  109335. int bosflag=0;
  109336. int byteskipcount=0;
  109337. ogg_stream_reset(&os_en);
  109338. ogg_stream_reset(&os_de);
  109339. ogg_sync_reset(&oy);
  109340. for(packets=0;packets<packetskip;packets++)
  109341. depacket+=pl[packets];
  109342. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109343. for(i=0;i<packets;i++){
  109344. /* construct a test packet */
  109345. ogg_packet op;
  109346. int len=pl[i];
  109347. op.packet=data+inptr;
  109348. op.bytes=len;
  109349. op.e_o_s=(pl[i+1]<0?1:0);
  109350. op.granulepos=granule_pos;
  109351. granule_pos+=1024;
  109352. for(j=0;j<len;j++)data[inptr++]=i+j;
  109353. /* submit the test packet */
  109354. ogg_stream_packetin(&os_en,&op);
  109355. /* retrieve any finished pages */
  109356. {
  109357. ogg_page og;
  109358. while(ogg_stream_pageout(&os_en,&og)){
  109359. /* We have a page. Check it carefully */
  109360. fprintf(stderr,"%ld, ",pageno);
  109361. if(headers[pageno]==NULL){
  109362. fprintf(stderr,"coded too many pages!\n");
  109363. exit(1);
  109364. }
  109365. check_page(data+outptr,headers[pageno],&og);
  109366. outptr+=og.body_len;
  109367. pageno++;
  109368. if(pageskip){
  109369. bosflag=1;
  109370. pageskip--;
  109371. deptr+=og.body_len;
  109372. }
  109373. /* have a complete page; submit it to sync/decode */
  109374. {
  109375. ogg_page og_de;
  109376. ogg_packet op_de,op_de2;
  109377. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109378. char *next=buf;
  109379. byteskipcount+=og.header_len;
  109380. if(byteskipcount>byteskip){
  109381. memcpy(next,og.header,byteskipcount-byteskip);
  109382. next+=byteskipcount-byteskip;
  109383. byteskipcount=byteskip;
  109384. }
  109385. byteskipcount+=og.body_len;
  109386. if(byteskipcount>byteskip){
  109387. memcpy(next,og.body,byteskipcount-byteskip);
  109388. next+=byteskipcount-byteskip;
  109389. byteskipcount=byteskip;
  109390. }
  109391. ogg_sync_wrote(&oy,next-buf);
  109392. while(1){
  109393. int ret=ogg_sync_pageout(&oy,&og_de);
  109394. if(ret==0)break;
  109395. if(ret<0)continue;
  109396. /* got a page. Happy happy. Verify that it's good. */
  109397. fprintf(stderr,"(%ld), ",pageout);
  109398. check_page(data+deptr,headers[pageout],&og_de);
  109399. deptr+=og_de.body_len;
  109400. pageout++;
  109401. /* submit it to deconstitution */
  109402. ogg_stream_pagein(&os_de,&og_de);
  109403. /* packets out? */
  109404. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109405. ogg_stream_packetpeek(&os_de,NULL);
  109406. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109407. /* verify peek and out match */
  109408. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109409. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109410. depacket);
  109411. exit(1);
  109412. }
  109413. /* verify the packet! */
  109414. /* check data */
  109415. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109416. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109417. depacket);
  109418. exit(1);
  109419. }
  109420. /* check bos flag */
  109421. if(bosflag==0 && op_de.b_o_s==0){
  109422. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109423. exit(1);
  109424. }
  109425. if(bosflag && op_de.b_o_s){
  109426. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109427. exit(1);
  109428. }
  109429. bosflag=1;
  109430. depacket+=op_de.bytes;
  109431. /* check eos flag */
  109432. if(eosflag){
  109433. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109434. exit(1);
  109435. }
  109436. if(op_de.e_o_s)eosflag=1;
  109437. /* check granulepos flag */
  109438. if(op_de.granulepos!=-1){
  109439. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109440. }
  109441. }
  109442. }
  109443. }
  109444. }
  109445. }
  109446. }
  109447. _ogg_free(data);
  109448. if(headers[pageno]!=NULL){
  109449. fprintf(stderr,"did not write last page!\n");
  109450. exit(1);
  109451. }
  109452. if(headers[pageout]!=NULL){
  109453. fprintf(stderr,"did not decode last page!\n");
  109454. exit(1);
  109455. }
  109456. if(inptr!=outptr){
  109457. fprintf(stderr,"encoded page data incomplete!\n");
  109458. exit(1);
  109459. }
  109460. if(inptr!=deptr){
  109461. fprintf(stderr,"decoded page data incomplete!\n");
  109462. exit(1);
  109463. }
  109464. if(inptr!=depacket){
  109465. fprintf(stderr,"decoded packet data incomplete!\n");
  109466. exit(1);
  109467. }
  109468. if(!eosflag){
  109469. fprintf(stderr,"Never got a packet with EOS set!\n");
  109470. exit(1);
  109471. }
  109472. fprintf(stderr,"ok.\n");
  109473. }
  109474. int main(void){
  109475. ogg_stream_init(&os_en,0x04030201);
  109476. ogg_stream_init(&os_de,0x04030201);
  109477. ogg_sync_init(&oy);
  109478. /* Exercise each code path in the framing code. Also verify that
  109479. the checksums are working. */
  109480. {
  109481. /* 17 only */
  109482. const int packets[]={17, -1};
  109483. const int *headret[]={head1_0,NULL};
  109484. fprintf(stderr,"testing single page encoding... ");
  109485. test_pack(packets,headret,0,0,0);
  109486. }
  109487. {
  109488. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109489. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109490. const int *headret[]={head1_1,head2_1,NULL};
  109491. fprintf(stderr,"testing basic page encoding... ");
  109492. test_pack(packets,headret,0,0,0);
  109493. }
  109494. {
  109495. /* nil packets; beginning,middle,end */
  109496. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109497. const int *headret[]={head1_2,head2_2,NULL};
  109498. fprintf(stderr,"testing basic nil packets... ");
  109499. test_pack(packets,headret,0,0,0);
  109500. }
  109501. {
  109502. /* large initial packet */
  109503. const int packets[]={4345,259,255,-1};
  109504. const int *headret[]={head1_3,head2_3,NULL};
  109505. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109506. test_pack(packets,headret,0,0,0);
  109507. }
  109508. {
  109509. /* continuing packet test */
  109510. const int packets[]={0,4345,259,255,-1};
  109511. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109512. fprintf(stderr,"testing single packet page span... ");
  109513. test_pack(packets,headret,0,0,0);
  109514. }
  109515. /* page with the 255 segment limit */
  109516. {
  109517. const int packets[]={0,10,10,10,10,10,10,10,10,
  109518. 10,10,10,10,10,10,10,10,
  109519. 10,10,10,10,10,10,10,10,
  109520. 10,10,10,10,10,10,10,10,
  109521. 10,10,10,10,10,10,10,10,
  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,50,-1};
  109549. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109550. fprintf(stderr,"testing max packet segments... ");
  109551. test_pack(packets,headret,0,0,0);
  109552. }
  109553. {
  109554. /* packet that overspans over an entire page */
  109555. const int packets[]={0,100,9000,259,255,-1};
  109556. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109557. fprintf(stderr,"testing very large packets... ");
  109558. test_pack(packets,headret,0,0,0);
  109559. }
  109560. {
  109561. /* test for the libogg 1.1.1 resync in large continuation bug
  109562. found by Josh Coalson) */
  109563. const int packets[]={0,100,9000,259,255,-1};
  109564. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109565. fprintf(stderr,"testing continuation resync in very large packets... ");
  109566. test_pack(packets,headret,100,2,3);
  109567. }
  109568. {
  109569. /* term only page. why not? */
  109570. const int packets[]={0,100,4080,-1};
  109571. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109572. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109573. test_pack(packets,headret,0,0,0);
  109574. }
  109575. {
  109576. /* build a bunch of pages for testing */
  109577. unsigned char *data=_ogg_malloc(1024*1024);
  109578. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109579. int inptr=0,i,j;
  109580. ogg_page og[5];
  109581. ogg_stream_reset(&os_en);
  109582. for(i=0;pl[i]!=-1;i++){
  109583. ogg_packet op;
  109584. int len=pl[i];
  109585. op.packet=data+inptr;
  109586. op.bytes=len;
  109587. op.e_o_s=(pl[i+1]<0?1:0);
  109588. op.granulepos=(i+1)*1000;
  109589. for(j=0;j<len;j++)data[inptr++]=i+j;
  109590. ogg_stream_packetin(&os_en,&op);
  109591. }
  109592. _ogg_free(data);
  109593. /* retrieve finished pages */
  109594. for(i=0;i<5;i++){
  109595. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109596. fprintf(stderr,"Too few pages output building sync tests!\n");
  109597. exit(1);
  109598. }
  109599. copy_page(&og[i]);
  109600. }
  109601. /* Test lost pages on pagein/packetout: no rollback */
  109602. {
  109603. ogg_page temp;
  109604. ogg_packet test;
  109605. fprintf(stderr,"Testing loss of pages... ");
  109606. ogg_sync_reset(&oy);
  109607. ogg_stream_reset(&os_de);
  109608. for(i=0;i<5;i++){
  109609. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109610. og[i].header_len);
  109611. ogg_sync_wrote(&oy,og[i].header_len);
  109612. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109613. ogg_sync_wrote(&oy,og[i].body_len);
  109614. }
  109615. ogg_sync_pageout(&oy,&temp);
  109616. ogg_stream_pagein(&os_de,&temp);
  109617. ogg_sync_pageout(&oy,&temp);
  109618. ogg_stream_pagein(&os_de,&temp);
  109619. ogg_sync_pageout(&oy,&temp);
  109620. /* skip */
  109621. ogg_sync_pageout(&oy,&temp);
  109622. ogg_stream_pagein(&os_de,&temp);
  109623. /* do we get the expected results/packets? */
  109624. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109625. checkpacket(&test,0,0,0);
  109626. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109627. checkpacket(&test,100,1,-1);
  109628. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109629. checkpacket(&test,4079,2,3000);
  109630. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109631. fprintf(stderr,"Error: loss of page did not return error\n");
  109632. exit(1);
  109633. }
  109634. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109635. checkpacket(&test,76,5,-1);
  109636. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109637. checkpacket(&test,34,6,-1);
  109638. fprintf(stderr,"ok.\n");
  109639. }
  109640. /* Test lost pages on pagein/packetout: rollback with continuation */
  109641. {
  109642. ogg_page temp;
  109643. ogg_packet test;
  109644. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109645. ogg_sync_reset(&oy);
  109646. ogg_stream_reset(&os_de);
  109647. for(i=0;i<5;i++){
  109648. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109649. og[i].header_len);
  109650. ogg_sync_wrote(&oy,og[i].header_len);
  109651. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109652. ogg_sync_wrote(&oy,og[i].body_len);
  109653. }
  109654. ogg_sync_pageout(&oy,&temp);
  109655. ogg_stream_pagein(&os_de,&temp);
  109656. ogg_sync_pageout(&oy,&temp);
  109657. ogg_stream_pagein(&os_de,&temp);
  109658. ogg_sync_pageout(&oy,&temp);
  109659. ogg_stream_pagein(&os_de,&temp);
  109660. ogg_sync_pageout(&oy,&temp);
  109661. /* skip */
  109662. ogg_sync_pageout(&oy,&temp);
  109663. ogg_stream_pagein(&os_de,&temp);
  109664. /* do we get the expected results/packets? */
  109665. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109666. checkpacket(&test,0,0,0);
  109667. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109668. checkpacket(&test,100,1,-1);
  109669. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109670. checkpacket(&test,4079,2,3000);
  109671. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109672. checkpacket(&test,2956,3,4000);
  109673. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109674. fprintf(stderr,"Error: loss of page did not return error\n");
  109675. exit(1);
  109676. }
  109677. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109678. checkpacket(&test,300,13,14000);
  109679. fprintf(stderr,"ok.\n");
  109680. }
  109681. /* the rest only test sync */
  109682. {
  109683. ogg_page og_de;
  109684. /* Test fractional page inputs: incomplete capture */
  109685. fprintf(stderr,"Testing sync on partial inputs... ");
  109686. ogg_sync_reset(&oy);
  109687. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109688. 3);
  109689. ogg_sync_wrote(&oy,3);
  109690. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109691. /* Test fractional page inputs: incomplete fixed header */
  109692. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109693. 20);
  109694. ogg_sync_wrote(&oy,20);
  109695. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109696. /* Test fractional page inputs: incomplete header */
  109697. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109698. 5);
  109699. ogg_sync_wrote(&oy,5);
  109700. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109701. /* Test fractional page inputs: incomplete body */
  109702. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109703. og[1].header_len-28);
  109704. ogg_sync_wrote(&oy,og[1].header_len-28);
  109705. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109706. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109707. ogg_sync_wrote(&oy,1000);
  109708. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109709. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109710. og[1].body_len-1000);
  109711. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109712. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109713. fprintf(stderr,"ok.\n");
  109714. }
  109715. /* Test fractional page inputs: page + incomplete capture */
  109716. {
  109717. ogg_page og_de;
  109718. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109719. ogg_sync_reset(&oy);
  109720. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109721. og[1].header_len);
  109722. ogg_sync_wrote(&oy,og[1].header_len);
  109723. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109724. og[1].body_len);
  109725. ogg_sync_wrote(&oy,og[1].body_len);
  109726. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109727. 20);
  109728. ogg_sync_wrote(&oy,20);
  109729. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109730. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109731. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109732. og[1].header_len-20);
  109733. ogg_sync_wrote(&oy,og[1].header_len-20);
  109734. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109735. og[1].body_len);
  109736. ogg_sync_wrote(&oy,og[1].body_len);
  109737. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109738. fprintf(stderr,"ok.\n");
  109739. }
  109740. /* Test recapture: garbage + page */
  109741. {
  109742. ogg_page og_de;
  109743. fprintf(stderr,"Testing search for capture... ");
  109744. ogg_sync_reset(&oy);
  109745. /* 'garbage' */
  109746. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109747. og[1].body_len);
  109748. ogg_sync_wrote(&oy,og[1].body_len);
  109749. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109750. og[1].header_len);
  109751. ogg_sync_wrote(&oy,og[1].header_len);
  109752. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109753. og[1].body_len);
  109754. ogg_sync_wrote(&oy,og[1].body_len);
  109755. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109756. 20);
  109757. ogg_sync_wrote(&oy,20);
  109758. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109759. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109760. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109761. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109762. og[2].header_len-20);
  109763. ogg_sync_wrote(&oy,og[2].header_len-20);
  109764. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109765. og[2].body_len);
  109766. ogg_sync_wrote(&oy,og[2].body_len);
  109767. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109768. fprintf(stderr,"ok.\n");
  109769. }
  109770. /* Test recapture: page + garbage + page */
  109771. {
  109772. ogg_page og_de;
  109773. fprintf(stderr,"Testing recapture... ");
  109774. ogg_sync_reset(&oy);
  109775. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109776. og[1].header_len);
  109777. ogg_sync_wrote(&oy,og[1].header_len);
  109778. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109779. og[1].body_len);
  109780. ogg_sync_wrote(&oy,og[1].body_len);
  109781. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109782. og[2].header_len);
  109783. ogg_sync_wrote(&oy,og[2].header_len);
  109784. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109785. og[2].header_len);
  109786. ogg_sync_wrote(&oy,og[2].header_len);
  109787. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109788. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109789. og[2].body_len-5);
  109790. ogg_sync_wrote(&oy,og[2].body_len-5);
  109791. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109792. og[3].header_len);
  109793. ogg_sync_wrote(&oy,og[3].header_len);
  109794. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109795. og[3].body_len);
  109796. ogg_sync_wrote(&oy,og[3].body_len);
  109797. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109798. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109799. fprintf(stderr,"ok.\n");
  109800. }
  109801. /* Free page data that was previously copied */
  109802. {
  109803. for(i=0;i<5;i++){
  109804. free_page(&og[i]);
  109805. }
  109806. }
  109807. }
  109808. return(0);
  109809. }
  109810. #endif
  109811. #endif
  109812. /*** End of inlined file: framing.c ***/
  109813. /*** Start of inlined file: analysis.c ***/
  109814. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109815. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109816. // tasks..
  109817. #if JUCE_MSVC
  109818. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109819. #endif
  109820. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109821. #if JUCE_USE_OGGVORBIS
  109822. #include <stdio.h>
  109823. #include <string.h>
  109824. #include <math.h>
  109825. /*** Start of inlined file: codec_internal.h ***/
  109826. #ifndef _V_CODECI_H_
  109827. #define _V_CODECI_H_
  109828. /*** Start of inlined file: envelope.h ***/
  109829. #ifndef _V_ENVELOPE_
  109830. #define _V_ENVELOPE_
  109831. /*** Start of inlined file: mdct.h ***/
  109832. #ifndef _OGG_mdct_H_
  109833. #define _OGG_mdct_H_
  109834. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109835. #ifdef MDCT_INTEGERIZED
  109836. #define DATA_TYPE int
  109837. #define REG_TYPE register int
  109838. #define TRIGBITS 14
  109839. #define cPI3_8 6270
  109840. #define cPI2_8 11585
  109841. #define cPI1_8 15137
  109842. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109843. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109844. #define HALVE(x) ((x)>>1)
  109845. #else
  109846. #define DATA_TYPE float
  109847. #define REG_TYPE float
  109848. #define cPI3_8 .38268343236508977175F
  109849. #define cPI2_8 .70710678118654752441F
  109850. #define cPI1_8 .92387953251128675613F
  109851. #define FLOAT_CONV(x) (x)
  109852. #define MULT_NORM(x) (x)
  109853. #define HALVE(x) ((x)*.5f)
  109854. #endif
  109855. typedef struct {
  109856. int n;
  109857. int log2n;
  109858. DATA_TYPE *trig;
  109859. int *bitrev;
  109860. DATA_TYPE scale;
  109861. } mdct_lookup;
  109862. extern void mdct_init(mdct_lookup *lookup,int n);
  109863. extern void mdct_clear(mdct_lookup *l);
  109864. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109865. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109866. #endif
  109867. /*** End of inlined file: mdct.h ***/
  109868. #define VE_PRE 16
  109869. #define VE_WIN 4
  109870. #define VE_POST 2
  109871. #define VE_AMP (VE_PRE+VE_POST-1)
  109872. #define VE_BANDS 7
  109873. #define VE_NEARDC 15
  109874. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109875. #define VE_MAXSTRETCH 12 /* one-third full block */
  109876. typedef struct {
  109877. float ampbuf[VE_AMP];
  109878. int ampptr;
  109879. float nearDC[VE_NEARDC];
  109880. float nearDC_acc;
  109881. float nearDC_partialacc;
  109882. int nearptr;
  109883. } envelope_filter_state;
  109884. typedef struct {
  109885. int begin;
  109886. int end;
  109887. float *window;
  109888. float total;
  109889. } envelope_band;
  109890. typedef struct {
  109891. int ch;
  109892. int winlength;
  109893. int searchstep;
  109894. float minenergy;
  109895. mdct_lookup mdct;
  109896. float *mdct_win;
  109897. envelope_band band[VE_BANDS];
  109898. envelope_filter_state *filter;
  109899. int stretch;
  109900. int *mark;
  109901. long storage;
  109902. long current;
  109903. long curmark;
  109904. long cursor;
  109905. } envelope_lookup;
  109906. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109907. extern void _ve_envelope_clear(envelope_lookup *e);
  109908. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109909. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109910. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109911. #endif
  109912. /*** End of inlined file: envelope.h ***/
  109913. /*** Start of inlined file: codebook.h ***/
  109914. #ifndef _V_CODEBOOK_H_
  109915. #define _V_CODEBOOK_H_
  109916. /* This structure encapsulates huffman and VQ style encoding books; it
  109917. doesn't do anything specific to either.
  109918. valuelist/quantlist are nonNULL (and q_* significant) only if
  109919. there's entry->value mapping to be done.
  109920. If encode-side mapping must be done (and thus the entry needs to be
  109921. hunted), the auxiliary encode pointer will point to a decision
  109922. tree. This is true of both VQ and huffman, but is mostly useful
  109923. with VQ.
  109924. */
  109925. typedef struct static_codebook{
  109926. long dim; /* codebook dimensions (elements per vector) */
  109927. long entries; /* codebook entries */
  109928. long *lengthlist; /* codeword lengths in bits */
  109929. /* mapping ***************************************************************/
  109930. int maptype; /* 0=none
  109931. 1=implicitly populated values from map column
  109932. 2=listed arbitrary values */
  109933. /* The below does a linear, single monotonic sequence mapping. */
  109934. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109935. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109936. int q_quant; /* bits: 0 < quant <= 16 */
  109937. int q_sequencep; /* bitflag */
  109938. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109939. map == 2: list of dim*entries quantized entry vals
  109940. */
  109941. /* encode helpers ********************************************************/
  109942. struct encode_aux_nearestmatch *nearest_tree;
  109943. struct encode_aux_threshmatch *thresh_tree;
  109944. struct encode_aux_pigeonhole *pigeon_tree;
  109945. int allocedp;
  109946. } static_codebook;
  109947. /* this structures an arbitrary trained book to quickly find the
  109948. nearest cell match */
  109949. typedef struct encode_aux_nearestmatch{
  109950. /* pre-calculated partitioning tree */
  109951. long *ptr0;
  109952. long *ptr1;
  109953. long *p; /* decision points (each is an entry) */
  109954. long *q; /* decision points (each is an entry) */
  109955. long aux; /* number of tree entries */
  109956. long alloc;
  109957. } encode_aux_nearestmatch;
  109958. /* assumes a maptype of 1; encode side only, so that's OK */
  109959. typedef struct encode_aux_threshmatch{
  109960. float *quantthresh;
  109961. long *quantmap;
  109962. int quantvals;
  109963. int threshvals;
  109964. } encode_aux_threshmatch;
  109965. typedef struct encode_aux_pigeonhole{
  109966. float min;
  109967. float del;
  109968. int mapentries;
  109969. int quantvals;
  109970. long *pigeonmap;
  109971. long fittotal;
  109972. long *fitlist;
  109973. long *fitmap;
  109974. long *fitlength;
  109975. } encode_aux_pigeonhole;
  109976. typedef struct codebook{
  109977. long dim; /* codebook dimensions (elements per vector) */
  109978. long entries; /* codebook entries */
  109979. long used_entries; /* populated codebook entries */
  109980. const static_codebook *c;
  109981. /* for encode, the below are entry-ordered, fully populated */
  109982. /* for decode, the below are ordered by bitreversed codeword and only
  109983. used entries are populated */
  109984. float *valuelist; /* list of dim*entries actual entry values */
  109985. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109986. int *dec_index; /* only used if sparseness collapsed */
  109987. char *dec_codelengths;
  109988. ogg_uint32_t *dec_firsttable;
  109989. int dec_firsttablen;
  109990. int dec_maxlength;
  109991. } codebook;
  109992. extern void vorbis_staticbook_clear(static_codebook *b);
  109993. extern void vorbis_staticbook_destroy(static_codebook *b);
  109994. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109995. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109996. extern void vorbis_book_clear(codebook *b);
  109997. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109998. extern float *_book_logdist(const static_codebook *b,float *vals);
  109999. extern float _float32_unpack(long val);
  110000. extern long _float32_pack(float val);
  110001. extern int _best(codebook *book, float *a, int step);
  110002. extern int _ilog(unsigned int v);
  110003. extern long _book_maptype1_quantvals(const static_codebook *b);
  110004. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110005. extern long vorbis_book_codeword(codebook *book,int entry);
  110006. extern long vorbis_book_codelen(codebook *book,int entry);
  110007. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110008. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110009. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110010. extern int vorbis_book_errorv(codebook *book, float *a);
  110011. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110012. oggpack_buffer *b);
  110013. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110014. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110015. oggpack_buffer *b,int n);
  110016. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110017. oggpack_buffer *b,int n);
  110018. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110019. oggpack_buffer *b,int n);
  110020. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110021. long off,int ch,
  110022. oggpack_buffer *b,int n);
  110023. #endif
  110024. /*** End of inlined file: codebook.h ***/
  110025. #define BLOCKTYPE_IMPULSE 0
  110026. #define BLOCKTYPE_PADDING 1
  110027. #define BLOCKTYPE_TRANSITION 0
  110028. #define BLOCKTYPE_LONG 1
  110029. #define PACKETBLOBS 15
  110030. typedef struct vorbis_block_internal{
  110031. float **pcmdelay; /* this is a pointer into local storage */
  110032. float ampmax;
  110033. int blocktype;
  110034. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110035. blob [PACKETBLOBS/2] points to
  110036. the oggpack_buffer in the
  110037. main vorbis_block */
  110038. } vorbis_block_internal;
  110039. typedef void vorbis_look_floor;
  110040. typedef void vorbis_look_residue;
  110041. typedef void vorbis_look_transform;
  110042. /* mode ************************************************************/
  110043. typedef struct {
  110044. int blockflag;
  110045. int windowtype;
  110046. int transformtype;
  110047. int mapping;
  110048. } vorbis_info_mode;
  110049. typedef void vorbis_info_floor;
  110050. typedef void vorbis_info_residue;
  110051. typedef void vorbis_info_mapping;
  110052. /*** Start of inlined file: psy.h ***/
  110053. #ifndef _V_PSY_H_
  110054. #define _V_PSY_H_
  110055. /*** Start of inlined file: smallft.h ***/
  110056. #ifndef _V_SMFT_H_
  110057. #define _V_SMFT_H_
  110058. typedef struct {
  110059. int n;
  110060. float *trigcache;
  110061. int *splitcache;
  110062. } drft_lookup;
  110063. extern void drft_forward(drft_lookup *l,float *data);
  110064. extern void drft_backward(drft_lookup *l,float *data);
  110065. extern void drft_init(drft_lookup *l,int n);
  110066. extern void drft_clear(drft_lookup *l);
  110067. #endif
  110068. /*** End of inlined file: smallft.h ***/
  110069. /*** Start of inlined file: backends.h ***/
  110070. /* this is exposed up here because we need it for static modes.
  110071. Lookups for each backend aren't exposed because there's no reason
  110072. to do so */
  110073. #ifndef _vorbis_backend_h_
  110074. #define _vorbis_backend_h_
  110075. /* this would all be simpler/shorter with templates, but.... */
  110076. /* Floor backend generic *****************************************/
  110077. typedef struct{
  110078. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110079. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110080. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110081. void (*free_info) (vorbis_info_floor *);
  110082. void (*free_look) (vorbis_look_floor *);
  110083. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110084. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110085. void *buffer,float *);
  110086. } vorbis_func_floor;
  110087. typedef struct{
  110088. int order;
  110089. long rate;
  110090. long barkmap;
  110091. int ampbits;
  110092. int ampdB;
  110093. int numbooks; /* <= 16 */
  110094. int books[16];
  110095. float lessthan; /* encode-only config setting hacks for libvorbis */
  110096. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110097. } vorbis_info_floor0;
  110098. #define VIF_POSIT 63
  110099. #define VIF_CLASS 16
  110100. #define VIF_PARTS 31
  110101. typedef struct{
  110102. int partitions; /* 0 to 31 */
  110103. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110104. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110105. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110106. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110107. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110108. int mult; /* 1 2 3 or 4 */
  110109. int postlist[VIF_POSIT+2]; /* first two implicit */
  110110. /* encode side analysis parameters */
  110111. float maxover;
  110112. float maxunder;
  110113. float maxerr;
  110114. float twofitweight;
  110115. float twofitatten;
  110116. int n;
  110117. } vorbis_info_floor1;
  110118. /* Residue backend generic *****************************************/
  110119. typedef struct{
  110120. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110121. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110122. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110123. vorbis_info_residue *);
  110124. void (*free_info) (vorbis_info_residue *);
  110125. void (*free_look) (vorbis_look_residue *);
  110126. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110127. float **,int *,int);
  110128. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110129. vorbis_look_residue *,
  110130. float **,float **,int *,int,long **);
  110131. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110132. float **,int *,int);
  110133. } vorbis_func_residue;
  110134. typedef struct vorbis_info_residue0{
  110135. /* block-partitioned VQ coded straight residue */
  110136. long begin;
  110137. long end;
  110138. /* first stage (lossless partitioning) */
  110139. int grouping; /* group n vectors per partition */
  110140. int partitions; /* possible codebooks for a partition */
  110141. int groupbook; /* huffbook for partitioning */
  110142. int secondstages[64]; /* expanded out to pointers in lookup */
  110143. int booklist[256]; /* list of second stage books */
  110144. float classmetric1[64];
  110145. float classmetric2[64];
  110146. } vorbis_info_residue0;
  110147. /* Mapping backend generic *****************************************/
  110148. typedef struct{
  110149. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110150. oggpack_buffer *);
  110151. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110152. void (*free_info) (vorbis_info_mapping *);
  110153. int (*forward) (struct vorbis_block *vb);
  110154. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110155. } vorbis_func_mapping;
  110156. typedef struct vorbis_info_mapping0{
  110157. int submaps; /* <= 16 */
  110158. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110159. int floorsubmap[16]; /* [mux] submap to floors */
  110160. int residuesubmap[16]; /* [mux] submap to residue */
  110161. int coupling_steps;
  110162. int coupling_mag[256];
  110163. int coupling_ang[256];
  110164. } vorbis_info_mapping0;
  110165. #endif
  110166. /*** End of inlined file: backends.h ***/
  110167. #ifndef EHMER_MAX
  110168. #define EHMER_MAX 56
  110169. #endif
  110170. /* psychoacoustic setup ********************************************/
  110171. #define P_BANDS 17 /* 62Hz to 16kHz */
  110172. #define P_LEVELS 8 /* 30dB to 100dB */
  110173. #define P_LEVEL_0 30. /* 30 dB */
  110174. #define P_NOISECURVES 3
  110175. #define NOISE_COMPAND_LEVELS 40
  110176. typedef struct vorbis_info_psy{
  110177. int blockflag;
  110178. float ath_adjatt;
  110179. float ath_maxatt;
  110180. float tone_masteratt[P_NOISECURVES];
  110181. float tone_centerboost;
  110182. float tone_decay;
  110183. float tone_abs_limit;
  110184. float toneatt[P_BANDS];
  110185. int noisemaskp;
  110186. float noisemaxsupp;
  110187. float noisewindowlo;
  110188. float noisewindowhi;
  110189. int noisewindowlomin;
  110190. int noisewindowhimin;
  110191. int noisewindowfixed;
  110192. float noiseoff[P_NOISECURVES][P_BANDS];
  110193. float noisecompand[NOISE_COMPAND_LEVELS];
  110194. float max_curve_dB;
  110195. int normal_channel_p;
  110196. int normal_point_p;
  110197. int normal_start;
  110198. int normal_partition;
  110199. double normal_thresh;
  110200. } vorbis_info_psy;
  110201. typedef struct{
  110202. int eighth_octave_lines;
  110203. /* for block long/short tuning; encode only */
  110204. float preecho_thresh[VE_BANDS];
  110205. float postecho_thresh[VE_BANDS];
  110206. float stretch_penalty;
  110207. float preecho_minenergy;
  110208. float ampmax_att_per_sec;
  110209. /* channel coupling config */
  110210. int coupling_pkHz[PACKETBLOBS];
  110211. int coupling_pointlimit[2][PACKETBLOBS];
  110212. int coupling_prepointamp[PACKETBLOBS];
  110213. int coupling_postpointamp[PACKETBLOBS];
  110214. int sliding_lowpass[2][PACKETBLOBS];
  110215. } vorbis_info_psy_global;
  110216. typedef struct {
  110217. float ampmax;
  110218. int channels;
  110219. vorbis_info_psy_global *gi;
  110220. int coupling_pointlimit[2][P_NOISECURVES];
  110221. } vorbis_look_psy_global;
  110222. typedef struct {
  110223. int n;
  110224. struct vorbis_info_psy *vi;
  110225. float ***tonecurves;
  110226. float **noiseoffset;
  110227. float *ath;
  110228. long *octave; /* in n.ocshift format */
  110229. long *bark;
  110230. long firstoc;
  110231. long shiftoc;
  110232. int eighth_octave_lines; /* power of two, please */
  110233. int total_octave_lines;
  110234. long rate; /* cache it */
  110235. float m_val; /* Masking compensation value */
  110236. } vorbis_look_psy;
  110237. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110238. vorbis_info_psy_global *gi,int n,long rate);
  110239. extern void _vp_psy_clear(vorbis_look_psy *p);
  110240. extern void *_vi_psy_dup(void *source);
  110241. extern void _vi_psy_free(vorbis_info_psy *i);
  110242. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110243. extern void _vp_remove_floor(vorbis_look_psy *p,
  110244. float *mdct,
  110245. int *icodedflr,
  110246. float *residue,
  110247. int sliding_lowpass);
  110248. extern void _vp_noisemask(vorbis_look_psy *p,
  110249. float *logmdct,
  110250. float *logmask);
  110251. extern void _vp_tonemask(vorbis_look_psy *p,
  110252. float *logfft,
  110253. float *logmask,
  110254. float global_specmax,
  110255. float local_specmax);
  110256. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110257. float *noise,
  110258. float *tone,
  110259. int offset_select,
  110260. float *logmask,
  110261. float *mdct,
  110262. float *logmdct);
  110263. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110264. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110265. vorbis_info_psy_global *g,
  110266. vorbis_look_psy *p,
  110267. vorbis_info_mapping0 *vi,
  110268. float **mdct);
  110269. extern void _vp_couple(int blobno,
  110270. vorbis_info_psy_global *g,
  110271. vorbis_look_psy *p,
  110272. vorbis_info_mapping0 *vi,
  110273. float **res,
  110274. float **mag_memo,
  110275. int **mag_sort,
  110276. int **ifloor,
  110277. int *nonzero,
  110278. int sliding_lowpass);
  110279. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110280. float *in,float *out,int *sortedindex);
  110281. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110282. float *magnitudes,int *sortedindex);
  110283. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110284. vorbis_look_psy *p,
  110285. vorbis_info_mapping0 *vi,
  110286. float **mags);
  110287. extern void hf_reduction(vorbis_info_psy_global *g,
  110288. vorbis_look_psy *p,
  110289. vorbis_info_mapping0 *vi,
  110290. float **mdct);
  110291. #endif
  110292. /*** End of inlined file: psy.h ***/
  110293. /*** Start of inlined file: bitrate.h ***/
  110294. #ifndef _V_BITRATE_H_
  110295. #define _V_BITRATE_H_
  110296. /*** Start of inlined file: os.h ***/
  110297. #ifndef _OS_H
  110298. #define _OS_H
  110299. /********************************************************************
  110300. * *
  110301. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110302. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110303. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110304. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110305. * *
  110306. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110307. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110308. * *
  110309. ********************************************************************
  110310. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110311. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110312. ********************************************************************/
  110313. #ifdef HAVE_CONFIG_H
  110314. #include "config.h"
  110315. #endif
  110316. #include <math.h>
  110317. /*** Start of inlined file: misc.h ***/
  110318. #ifndef _V_RANDOM_H_
  110319. #define _V_RANDOM_H_
  110320. extern int analysis_noisy;
  110321. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110322. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110323. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110324. ogg_int64_t off);
  110325. #ifdef DEBUG_MALLOC
  110326. #define _VDBG_GRAPHFILE "malloc.m"
  110327. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110328. extern void _VDBG_free(void *ptr,char *file,long line);
  110329. #ifndef MISC_C
  110330. #undef _ogg_malloc
  110331. #undef _ogg_calloc
  110332. #undef _ogg_realloc
  110333. #undef _ogg_free
  110334. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110335. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110336. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110337. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110338. #endif
  110339. #endif
  110340. #endif
  110341. /*** End of inlined file: misc.h ***/
  110342. #ifndef _V_IFDEFJAIL_H_
  110343. # define _V_IFDEFJAIL_H_
  110344. # ifdef __GNUC__
  110345. # define STIN static __inline__
  110346. # elif _WIN32
  110347. # define STIN static __inline
  110348. # else
  110349. # define STIN static
  110350. # endif
  110351. #ifdef DJGPP
  110352. # define rint(x) (floor((x)+0.5f))
  110353. #endif
  110354. #ifndef M_PI
  110355. # define M_PI (3.1415926536f)
  110356. #endif
  110357. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110358. # include <malloc.h>
  110359. # define rint(x) (floor((x)+0.5f))
  110360. # define NO_FLOAT_MATH_LIB
  110361. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110362. #endif
  110363. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110364. void *_alloca(size_t size);
  110365. # define alloca _alloca
  110366. #endif
  110367. #ifndef FAST_HYPOT
  110368. # define FAST_HYPOT hypot
  110369. #endif
  110370. #endif
  110371. #ifdef HAVE_ALLOCA_H
  110372. # include <alloca.h>
  110373. #endif
  110374. #ifdef USE_MEMORY_H
  110375. # include <memory.h>
  110376. #endif
  110377. #ifndef min
  110378. # define min(x,y) ((x)>(y)?(y):(x))
  110379. #endif
  110380. #ifndef max
  110381. # define max(x,y) ((x)<(y)?(y):(x))
  110382. #endif
  110383. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110384. # define VORBIS_FPU_CONTROL
  110385. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110386. Because of encapsulation constraints (GCC can't see inside the asm
  110387. block and so we end up doing stupid things like a store/load that
  110388. is collectively a noop), we do it this way */
  110389. /* we must set up the fpu before this works!! */
  110390. typedef ogg_int16_t vorbis_fpu_control;
  110391. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110392. ogg_int16_t ret;
  110393. ogg_int16_t temp;
  110394. __asm__ __volatile__("fnstcw %0\n\t"
  110395. "movw %0,%%dx\n\t"
  110396. "orw $62463,%%dx\n\t"
  110397. "movw %%dx,%1\n\t"
  110398. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110399. *fpu=ret;
  110400. }
  110401. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110402. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110403. }
  110404. /* assumes the FPU is in round mode! */
  110405. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110406. we get extra fst/fld to
  110407. truncate precision */
  110408. int i;
  110409. __asm__("fistl %0": "=m"(i) : "t"(f));
  110410. return(i);
  110411. }
  110412. #endif
  110413. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110414. # define VORBIS_FPU_CONTROL
  110415. typedef ogg_int16_t vorbis_fpu_control;
  110416. static __inline int vorbis_ftoi(double f){
  110417. int i;
  110418. __asm{
  110419. fld f
  110420. fistp i
  110421. }
  110422. return i;
  110423. }
  110424. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110425. }
  110426. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110427. }
  110428. #endif
  110429. #ifndef VORBIS_FPU_CONTROL
  110430. typedef int vorbis_fpu_control;
  110431. static int vorbis_ftoi(double f){
  110432. return (int)(f+.5);
  110433. }
  110434. /* We don't have special code for this compiler/arch, so do it the slow way */
  110435. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110436. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110437. #endif
  110438. #endif /* _OS_H */
  110439. /*** End of inlined file: os.h ***/
  110440. /* encode side bitrate tracking */
  110441. typedef struct bitrate_manager_state {
  110442. int managed;
  110443. long avg_reservoir;
  110444. long minmax_reservoir;
  110445. long avg_bitsper;
  110446. long min_bitsper;
  110447. long max_bitsper;
  110448. long short_per_long;
  110449. double avgfloat;
  110450. vorbis_block *vb;
  110451. int choice;
  110452. } bitrate_manager_state;
  110453. typedef struct bitrate_manager_info{
  110454. long avg_rate;
  110455. long min_rate;
  110456. long max_rate;
  110457. long reservoir_bits;
  110458. double reservoir_bias;
  110459. double slew_damp;
  110460. } bitrate_manager_info;
  110461. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110462. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110463. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110464. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110465. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110466. #endif
  110467. /*** End of inlined file: bitrate.h ***/
  110468. static int ilog(unsigned int v){
  110469. int ret=0;
  110470. while(v){
  110471. ret++;
  110472. v>>=1;
  110473. }
  110474. return(ret);
  110475. }
  110476. static int ilog2(unsigned int v){
  110477. int ret=0;
  110478. if(v)--v;
  110479. while(v){
  110480. ret++;
  110481. v>>=1;
  110482. }
  110483. return(ret);
  110484. }
  110485. typedef struct private_state {
  110486. /* local lookup storage */
  110487. envelope_lookup *ve; /* envelope lookup */
  110488. int window[2];
  110489. vorbis_look_transform **transform[2]; /* block, type */
  110490. drft_lookup fft_look[2];
  110491. int modebits;
  110492. vorbis_look_floor **flr;
  110493. vorbis_look_residue **residue;
  110494. vorbis_look_psy *psy;
  110495. vorbis_look_psy_global *psy_g_look;
  110496. /* local storage, only used on the encoding side. This way the
  110497. application does not need to worry about freeing some packets'
  110498. memory and not others'; packet storage is always tracked.
  110499. Cleared next call to a _dsp_ function */
  110500. unsigned char *header;
  110501. unsigned char *header1;
  110502. unsigned char *header2;
  110503. bitrate_manager_state bms;
  110504. ogg_int64_t sample_count;
  110505. } private_state;
  110506. /* codec_setup_info contains all the setup information specific to the
  110507. specific compression/decompression mode in progress (eg,
  110508. psychoacoustic settings, channel setup, options, codebook
  110509. etc).
  110510. *********************************************************************/
  110511. /*** Start of inlined file: highlevel.h ***/
  110512. typedef struct highlevel_byblocktype {
  110513. double tone_mask_setting;
  110514. double tone_peaklimit_setting;
  110515. double noise_bias_setting;
  110516. double noise_compand_setting;
  110517. } highlevel_byblocktype;
  110518. typedef struct highlevel_encode_setup {
  110519. void *setup;
  110520. int set_in_stone;
  110521. double base_setting;
  110522. double long_setting;
  110523. double short_setting;
  110524. double impulse_noisetune;
  110525. int managed;
  110526. long bitrate_min;
  110527. long bitrate_av;
  110528. double bitrate_av_damp;
  110529. long bitrate_max;
  110530. long bitrate_reservoir;
  110531. double bitrate_reservoir_bias;
  110532. int impulse_block_p;
  110533. int noise_normalize_p;
  110534. double stereo_point_setting;
  110535. double lowpass_kHz;
  110536. double ath_floating_dB;
  110537. double ath_absolute_dB;
  110538. double amplitude_track_dBpersec;
  110539. double trigger_setting;
  110540. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110541. } highlevel_encode_setup;
  110542. /*** End of inlined file: highlevel.h ***/
  110543. typedef struct codec_setup_info {
  110544. /* Vorbis supports only short and long blocks, but allows the
  110545. encoder to choose the sizes */
  110546. long blocksizes[2];
  110547. /* modes are the primary means of supporting on-the-fly different
  110548. blocksizes, different channel mappings (LR or M/A),
  110549. different residue backends, etc. Each mode consists of a
  110550. blocksize flag and a mapping (along with the mapping setup */
  110551. int modes;
  110552. int maps;
  110553. int floors;
  110554. int residues;
  110555. int books;
  110556. int psys; /* encode only */
  110557. vorbis_info_mode *mode_param[64];
  110558. int map_type[64];
  110559. vorbis_info_mapping *map_param[64];
  110560. int floor_type[64];
  110561. vorbis_info_floor *floor_param[64];
  110562. int residue_type[64];
  110563. vorbis_info_residue *residue_param[64];
  110564. static_codebook *book_param[256];
  110565. codebook *fullbooks;
  110566. vorbis_info_psy *psy_param[4]; /* encode only */
  110567. vorbis_info_psy_global psy_g_param;
  110568. bitrate_manager_info bi;
  110569. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110570. highly redundant structure, but
  110571. improves clarity of program flow. */
  110572. int halfrate_flag; /* painless downsample for decode */
  110573. } codec_setup_info;
  110574. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110575. extern void _vp_global_free(vorbis_look_psy_global *look);
  110576. #endif
  110577. /*** End of inlined file: codec_internal.h ***/
  110578. /*** Start of inlined file: registry.h ***/
  110579. #ifndef _V_REG_H_
  110580. #define _V_REG_H_
  110581. #define VI_TRANSFORMB 1
  110582. #define VI_WINDOWB 1
  110583. #define VI_TIMEB 1
  110584. #define VI_FLOORB 2
  110585. #define VI_RESB 3
  110586. #define VI_MAPB 1
  110587. extern vorbis_func_floor *_floor_P[];
  110588. extern vorbis_func_residue *_residue_P[];
  110589. extern vorbis_func_mapping *_mapping_P[];
  110590. #endif
  110591. /*** End of inlined file: registry.h ***/
  110592. /*** Start of inlined file: scales.h ***/
  110593. #ifndef _V_SCALES_H_
  110594. #define _V_SCALES_H_
  110595. #include <math.h>
  110596. /* 20log10(x) */
  110597. #define VORBIS_IEEE_FLOAT32 1
  110598. #ifdef VORBIS_IEEE_FLOAT32
  110599. static float unitnorm(float x){
  110600. union {
  110601. ogg_uint32_t i;
  110602. float f;
  110603. } ix;
  110604. ix.f = x;
  110605. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110606. return ix.f;
  110607. }
  110608. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110609. static float todB(const float *x){
  110610. union {
  110611. ogg_uint32_t i;
  110612. float f;
  110613. } ix;
  110614. ix.f = *x;
  110615. ix.i = ix.i&0x7fffffff;
  110616. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110617. }
  110618. #define todB_nn(x) todB(x)
  110619. #else
  110620. static float unitnorm(float x){
  110621. if(x<0)return(-1.f);
  110622. return(1.f);
  110623. }
  110624. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110625. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110626. #endif
  110627. #define fromdB(x) (exp((x)*.11512925f))
  110628. /* The bark scale equations are approximations, since the original
  110629. table was somewhat hand rolled. The below are chosen to have the
  110630. best possible fit to the rolled tables, thus their somewhat odd
  110631. appearance (these are more accurate and over a longer range than
  110632. the oft-quoted bark equations found in the texts I have). The
  110633. approximations are valid from 0 - 30kHz (nyquist) or so.
  110634. all f in Hz, z in Bark */
  110635. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110636. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110637. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110638. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110639. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110640. 0.0 */
  110641. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110642. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110643. #endif
  110644. /*** End of inlined file: scales.h ***/
  110645. int analysis_noisy=1;
  110646. /* decides between modes, dispatches to the appropriate mapping. */
  110647. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110648. int ret,i;
  110649. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110650. vb->glue_bits=0;
  110651. vb->time_bits=0;
  110652. vb->floor_bits=0;
  110653. vb->res_bits=0;
  110654. /* first things first. Make sure encode is ready */
  110655. for(i=0;i<PACKETBLOBS;i++)
  110656. oggpack_reset(vbi->packetblob[i]);
  110657. /* we only have one mapping type (0), and we let the mapping code
  110658. itself figure out what soft mode to use. This allows easier
  110659. bitrate management */
  110660. if((ret=_mapping_P[0]->forward(vb)))
  110661. return(ret);
  110662. if(op){
  110663. if(vorbis_bitrate_managed(vb))
  110664. /* The app is using a bitmanaged mode... but not using the
  110665. bitrate management interface. */
  110666. return(OV_EINVAL);
  110667. op->packet=oggpack_get_buffer(&vb->opb);
  110668. op->bytes=oggpack_bytes(&vb->opb);
  110669. op->b_o_s=0;
  110670. op->e_o_s=vb->eofflag;
  110671. op->granulepos=vb->granulepos;
  110672. op->packetno=vb->sequence; /* for sake of completeness */
  110673. }
  110674. return(0);
  110675. }
  110676. /* there was no great place to put this.... */
  110677. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110678. int j;
  110679. FILE *of;
  110680. char buffer[80];
  110681. /* if(i==5870){*/
  110682. sprintf(buffer,"%s_%d.m",base,i);
  110683. of=fopen(buffer,"w");
  110684. if(!of)perror("failed to open data dump file");
  110685. for(j=0;j<n;j++){
  110686. if(bark){
  110687. float b=toBARK((4000.f*j/n)+.25);
  110688. fprintf(of,"%f ",b);
  110689. }else
  110690. if(off!=0)
  110691. fprintf(of,"%f ",(double)(j+off)/8000.);
  110692. else
  110693. fprintf(of,"%f ",(double)j);
  110694. if(dB){
  110695. float val;
  110696. if(v[j]==0.)
  110697. val=-140.;
  110698. else
  110699. val=todB(v+j);
  110700. fprintf(of,"%f\n",val);
  110701. }else{
  110702. fprintf(of,"%f\n",v[j]);
  110703. }
  110704. }
  110705. fclose(of);
  110706. /* } */
  110707. }
  110708. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110709. ogg_int64_t off){
  110710. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110711. }
  110712. #endif
  110713. /*** End of inlined file: analysis.c ***/
  110714. /*** Start of inlined file: bitrate.c ***/
  110715. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110716. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110717. // tasks..
  110718. #if JUCE_MSVC
  110719. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110720. #endif
  110721. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110722. #if JUCE_USE_OGGVORBIS
  110723. #include <stdlib.h>
  110724. #include <string.h>
  110725. #include <math.h>
  110726. /* compute bitrate tracking setup */
  110727. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110728. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110729. bitrate_manager_info *bi=&ci->bi;
  110730. memset(bm,0,sizeof(*bm));
  110731. if(bi && (bi->reservoir_bits>0)){
  110732. long ratesamples=vi->rate;
  110733. int halfsamples=ci->blocksizes[0]>>1;
  110734. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110735. bm->managed=1;
  110736. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110737. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110738. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110739. bm->avgfloat=PACKETBLOBS/2;
  110740. /* not a necessary fix, but one that leads to a more balanced
  110741. typical initialization */
  110742. {
  110743. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110744. bm->minmax_reservoir=desired_fill;
  110745. bm->avg_reservoir=desired_fill;
  110746. }
  110747. }
  110748. }
  110749. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110750. memset(bm,0,sizeof(*bm));
  110751. return;
  110752. }
  110753. int vorbis_bitrate_managed(vorbis_block *vb){
  110754. vorbis_dsp_state *vd=vb->vd;
  110755. private_state *b=(private_state*)vd->backend_state;
  110756. bitrate_manager_state *bm=&b->bms;
  110757. if(bm && bm->managed)return(1);
  110758. return(0);
  110759. }
  110760. /* finish taking in the block we just processed */
  110761. int vorbis_bitrate_addblock(vorbis_block *vb){
  110762. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110763. vorbis_dsp_state *vd=vb->vd;
  110764. private_state *b=(private_state*)vd->backend_state;
  110765. bitrate_manager_state *bm=&b->bms;
  110766. vorbis_info *vi=vd->vi;
  110767. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110768. bitrate_manager_info *bi=&ci->bi;
  110769. int choice=rint(bm->avgfloat);
  110770. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110771. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110772. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110773. int samples=ci->blocksizes[vb->W]>>1;
  110774. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110775. if(!bm->managed){
  110776. /* not a bitrate managed stream, but for API simplicity, we'll
  110777. buffer the packet to keep the code path clean */
  110778. if(bm->vb)return(-1); /* one has been submitted without
  110779. being claimed */
  110780. bm->vb=vb;
  110781. return(0);
  110782. }
  110783. bm->vb=vb;
  110784. /* look ahead for avg floater */
  110785. if(bm->avg_bitsper>0){
  110786. double slew=0.;
  110787. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110788. double slewlimit= 15./bi->slew_damp;
  110789. /* choosing a new floater:
  110790. if we're over target, we slew down
  110791. if we're under target, we slew up
  110792. choose slew as follows: look through packetblobs of this frame
  110793. and set slew as the first in the appropriate direction that
  110794. gives us the slew we want. This may mean no slew if delta is
  110795. already favorable.
  110796. Then limit slew to slew max */
  110797. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110798. while(choice>0 && this_bits>avg_target_bits &&
  110799. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110800. choice--;
  110801. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110802. }
  110803. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110804. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110805. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110806. choice++;
  110807. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110808. }
  110809. }
  110810. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110811. if(slew<-slewlimit)slew=-slewlimit;
  110812. if(slew>slewlimit)slew=slewlimit;
  110813. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110814. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110815. }
  110816. /* enforce min(if used) on the current floater (if used) */
  110817. if(bm->min_bitsper>0){
  110818. /* do we need to force the bitrate up? */
  110819. if(this_bits<min_target_bits){
  110820. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110821. choice++;
  110822. if(choice>=PACKETBLOBS)break;
  110823. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110824. }
  110825. }
  110826. }
  110827. /* enforce max (if used) on the current floater (if used) */
  110828. if(bm->max_bitsper>0){
  110829. /* do we need to force the bitrate down? */
  110830. if(this_bits>max_target_bits){
  110831. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110832. choice--;
  110833. if(choice<0)break;
  110834. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110835. }
  110836. }
  110837. }
  110838. /* Choice of packetblobs now made based on floater, and min/max
  110839. requirements. Now boundary check extreme choices */
  110840. if(choice<0){
  110841. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110842. frame will need to be truncated */
  110843. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110844. bm->choice=choice=0;
  110845. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110846. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110847. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110848. }
  110849. }else{
  110850. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110851. if(choice>=PACKETBLOBS)
  110852. choice=PACKETBLOBS-1;
  110853. bm->choice=choice;
  110854. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110855. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110856. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110857. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110858. }
  110859. /* now we have the final packet and the final packet size. Update statistics */
  110860. /* min and max reservoir */
  110861. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110862. if(max_target_bits>0 && this_bits>max_target_bits){
  110863. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110864. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110865. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110866. }else{
  110867. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110868. if(bm->minmax_reservoir>desired_fill){
  110869. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110870. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110871. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110872. }else{
  110873. bm->minmax_reservoir=desired_fill;
  110874. }
  110875. }else{
  110876. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110877. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110878. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110879. }else{
  110880. bm->minmax_reservoir=desired_fill;
  110881. }
  110882. }
  110883. }
  110884. }
  110885. /* avg reservoir */
  110886. if(bm->avg_bitsper>0){
  110887. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110888. bm->avg_reservoir+=this_bits-avg_target_bits;
  110889. }
  110890. return(0);
  110891. }
  110892. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110893. private_state *b=(private_state*)vd->backend_state;
  110894. bitrate_manager_state *bm=&b->bms;
  110895. vorbis_block *vb=bm->vb;
  110896. int choice=PACKETBLOBS/2;
  110897. if(!vb)return 0;
  110898. if(op){
  110899. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110900. if(vorbis_bitrate_managed(vb))
  110901. choice=bm->choice;
  110902. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110903. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110904. op->b_o_s=0;
  110905. op->e_o_s=vb->eofflag;
  110906. op->granulepos=vb->granulepos;
  110907. op->packetno=vb->sequence; /* for sake of completeness */
  110908. }
  110909. bm->vb=0;
  110910. return(1);
  110911. }
  110912. #endif
  110913. /*** End of inlined file: bitrate.c ***/
  110914. /*** Start of inlined file: block.c ***/
  110915. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110916. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110917. // tasks..
  110918. #if JUCE_MSVC
  110919. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110920. #endif
  110921. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110922. #if JUCE_USE_OGGVORBIS
  110923. #include <stdio.h>
  110924. #include <stdlib.h>
  110925. #include <string.h>
  110926. /*** Start of inlined file: window.h ***/
  110927. #ifndef _V_WINDOW_
  110928. #define _V_WINDOW_
  110929. extern float *_vorbis_window_get(int n);
  110930. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110931. int lW,int W,int nW);
  110932. #endif
  110933. /*** End of inlined file: window.h ***/
  110934. /*** Start of inlined file: lpc.h ***/
  110935. #ifndef _V_LPC_H_
  110936. #define _V_LPC_H_
  110937. /* simple linear scale LPC code */
  110938. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110939. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110940. float *data,long n);
  110941. #endif
  110942. /*** End of inlined file: lpc.h ***/
  110943. /* pcm accumulator examples (not exhaustive):
  110944. <-------------- lW ---------------->
  110945. <--------------- W ---------------->
  110946. : .....|..... _______________ |
  110947. : .''' | '''_--- | |\ |
  110948. :.....''' |_____--- '''......| | \_______|
  110949. :.................|__________________|_______|__|______|
  110950. |<------ Sl ------>| > Sr < |endW
  110951. |beginSl |endSl | |endSr
  110952. |beginW |endlW |beginSr
  110953. |< lW >|
  110954. <--------------- W ---------------->
  110955. | | .. ______________ |
  110956. | | ' `/ | ---_ |
  110957. |___.'___/`. | ---_____|
  110958. |_______|__|_______|_________________|
  110959. | >|Sl|< |<------ Sr ----->|endW
  110960. | | |endSl |beginSr |endSr
  110961. |beginW | |endlW
  110962. mult[0] |beginSl mult[n]
  110963. <-------------- lW ----------------->
  110964. |<--W-->|
  110965. : .............. ___ | |
  110966. : .''' |`/ \ | |
  110967. :.....''' |/`....\|...|
  110968. :.........................|___|___|___|
  110969. |Sl |Sr |endW
  110970. | | |endSr
  110971. | |beginSr
  110972. | |endSl
  110973. |beginSl
  110974. |beginW
  110975. */
  110976. /* block abstraction setup *********************************************/
  110977. #ifndef WORD_ALIGN
  110978. #define WORD_ALIGN 8
  110979. #endif
  110980. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110981. int i;
  110982. memset(vb,0,sizeof(*vb));
  110983. vb->vd=v;
  110984. vb->localalloc=0;
  110985. vb->localstore=NULL;
  110986. if(v->analysisp){
  110987. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110988. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110989. vbi->ampmax=-9999;
  110990. for(i=0;i<PACKETBLOBS;i++){
  110991. if(i==PACKETBLOBS/2){
  110992. vbi->packetblob[i]=&vb->opb;
  110993. }else{
  110994. vbi->packetblob[i]=
  110995. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110996. }
  110997. oggpack_writeinit(vbi->packetblob[i]);
  110998. }
  110999. }
  111000. return(0);
  111001. }
  111002. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111003. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111004. if(bytes+vb->localtop>vb->localalloc){
  111005. /* can't just _ogg_realloc... there are outstanding pointers */
  111006. if(vb->localstore){
  111007. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111008. vb->totaluse+=vb->localtop;
  111009. link->next=vb->reap;
  111010. link->ptr=vb->localstore;
  111011. vb->reap=link;
  111012. }
  111013. /* highly conservative */
  111014. vb->localalloc=bytes;
  111015. vb->localstore=_ogg_malloc(vb->localalloc);
  111016. vb->localtop=0;
  111017. }
  111018. {
  111019. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111020. vb->localtop+=bytes;
  111021. return ret;
  111022. }
  111023. }
  111024. /* reap the chain, pull the ripcord */
  111025. void _vorbis_block_ripcord(vorbis_block *vb){
  111026. /* reap the chain */
  111027. struct alloc_chain *reap=vb->reap;
  111028. while(reap){
  111029. struct alloc_chain *next=reap->next;
  111030. _ogg_free(reap->ptr);
  111031. memset(reap,0,sizeof(*reap));
  111032. _ogg_free(reap);
  111033. reap=next;
  111034. }
  111035. /* consolidate storage */
  111036. if(vb->totaluse){
  111037. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111038. vb->localalloc+=vb->totaluse;
  111039. vb->totaluse=0;
  111040. }
  111041. /* pull the ripcord */
  111042. vb->localtop=0;
  111043. vb->reap=NULL;
  111044. }
  111045. int vorbis_block_clear(vorbis_block *vb){
  111046. int i;
  111047. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111048. _vorbis_block_ripcord(vb);
  111049. if(vb->localstore)_ogg_free(vb->localstore);
  111050. if(vbi){
  111051. for(i=0;i<PACKETBLOBS;i++){
  111052. oggpack_writeclear(vbi->packetblob[i]);
  111053. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111054. }
  111055. _ogg_free(vbi);
  111056. }
  111057. memset(vb,0,sizeof(*vb));
  111058. return(0);
  111059. }
  111060. /* Analysis side code, but directly related to blocking. Thus it's
  111061. here and not in analysis.c (which is for analysis transforms only).
  111062. The init is here because some of it is shared */
  111063. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111064. int i;
  111065. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111066. private_state *b=NULL;
  111067. int hs;
  111068. if(ci==NULL) return 1;
  111069. hs=ci->halfrate_flag;
  111070. memset(v,0,sizeof(*v));
  111071. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111072. v->vi=vi;
  111073. b->modebits=ilog2(ci->modes);
  111074. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111075. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111076. /* MDCT is tranform 0 */
  111077. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111078. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111079. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111080. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111081. /* Vorbis I uses only window type 0 */
  111082. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111083. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111084. if(encp){ /* encode/decode differ here */
  111085. /* analysis always needs an fft */
  111086. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111087. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111088. /* finish the codebooks */
  111089. if(!ci->fullbooks){
  111090. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111091. for(i=0;i<ci->books;i++)
  111092. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111093. }
  111094. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111095. for(i=0;i<ci->psys;i++){
  111096. _vp_psy_init(b->psy+i,
  111097. ci->psy_param[i],
  111098. &ci->psy_g_param,
  111099. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111100. vi->rate);
  111101. }
  111102. v->analysisp=1;
  111103. }else{
  111104. /* finish the codebooks */
  111105. if(!ci->fullbooks){
  111106. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111107. for(i=0;i<ci->books;i++){
  111108. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111109. /* decode codebooks are now standalone after init */
  111110. vorbis_staticbook_destroy(ci->book_param[i]);
  111111. ci->book_param[i]=NULL;
  111112. }
  111113. }
  111114. }
  111115. /* initialize the storage vectors. blocksize[1] is small for encode,
  111116. but the correct size for decode */
  111117. v->pcm_storage=ci->blocksizes[1];
  111118. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111119. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111120. {
  111121. int i;
  111122. for(i=0;i<vi->channels;i++)
  111123. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111124. }
  111125. /* all 1 (large block) or 0 (small block) */
  111126. /* explicitly set for the sake of clarity */
  111127. v->lW=0; /* previous window size */
  111128. v->W=0; /* current window size */
  111129. /* all vector indexes */
  111130. v->centerW=ci->blocksizes[1]/2;
  111131. v->pcm_current=v->centerW;
  111132. /* initialize all the backend lookups */
  111133. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111134. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111135. for(i=0;i<ci->floors;i++)
  111136. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111137. look(v,ci->floor_param[i]);
  111138. for(i=0;i<ci->residues;i++)
  111139. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111140. look(v,ci->residue_param[i]);
  111141. return 0;
  111142. }
  111143. /* arbitrary settings and spec-mandated numbers get filled in here */
  111144. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111145. private_state *b=NULL;
  111146. if(_vds_shared_init(v,vi,1))return 1;
  111147. b=(private_state*)v->backend_state;
  111148. b->psy_g_look=_vp_global_look(vi);
  111149. /* Initialize the envelope state storage */
  111150. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111151. _ve_envelope_init(b->ve,vi);
  111152. vorbis_bitrate_init(vi,&b->bms);
  111153. /* compressed audio packets start after the headers
  111154. with sequence number 3 */
  111155. v->sequence=3;
  111156. return(0);
  111157. }
  111158. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111159. int i;
  111160. if(v){
  111161. vorbis_info *vi=v->vi;
  111162. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111163. private_state *b=(private_state*)v->backend_state;
  111164. if(b){
  111165. if(b->ve){
  111166. _ve_envelope_clear(b->ve);
  111167. _ogg_free(b->ve);
  111168. }
  111169. if(b->transform[0]){
  111170. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111171. _ogg_free(b->transform[0][0]);
  111172. _ogg_free(b->transform[0]);
  111173. }
  111174. if(b->transform[1]){
  111175. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111176. _ogg_free(b->transform[1][0]);
  111177. _ogg_free(b->transform[1]);
  111178. }
  111179. if(b->flr){
  111180. for(i=0;i<ci->floors;i++)
  111181. _floor_P[ci->floor_type[i]]->
  111182. free_look(b->flr[i]);
  111183. _ogg_free(b->flr);
  111184. }
  111185. if(b->residue){
  111186. for(i=0;i<ci->residues;i++)
  111187. _residue_P[ci->residue_type[i]]->
  111188. free_look(b->residue[i]);
  111189. _ogg_free(b->residue);
  111190. }
  111191. if(b->psy){
  111192. for(i=0;i<ci->psys;i++)
  111193. _vp_psy_clear(b->psy+i);
  111194. _ogg_free(b->psy);
  111195. }
  111196. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111197. vorbis_bitrate_clear(&b->bms);
  111198. drft_clear(&b->fft_look[0]);
  111199. drft_clear(&b->fft_look[1]);
  111200. }
  111201. if(v->pcm){
  111202. for(i=0;i<vi->channels;i++)
  111203. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111204. _ogg_free(v->pcm);
  111205. if(v->pcmret)_ogg_free(v->pcmret);
  111206. }
  111207. if(b){
  111208. /* free header, header1, header2 */
  111209. if(b->header)_ogg_free(b->header);
  111210. if(b->header1)_ogg_free(b->header1);
  111211. if(b->header2)_ogg_free(b->header2);
  111212. _ogg_free(b);
  111213. }
  111214. memset(v,0,sizeof(*v));
  111215. }
  111216. }
  111217. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111218. int i;
  111219. vorbis_info *vi=v->vi;
  111220. private_state *b=(private_state*)v->backend_state;
  111221. /* free header, header1, header2 */
  111222. if(b->header)_ogg_free(b->header);b->header=NULL;
  111223. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111224. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111225. /* Do we have enough storage space for the requested buffer? If not,
  111226. expand the PCM (and envelope) storage */
  111227. if(v->pcm_current+vals>=v->pcm_storage){
  111228. v->pcm_storage=v->pcm_current+vals*2;
  111229. for(i=0;i<vi->channels;i++){
  111230. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111231. }
  111232. }
  111233. for(i=0;i<vi->channels;i++)
  111234. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111235. return(v->pcmret);
  111236. }
  111237. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111238. int i;
  111239. int order=32;
  111240. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111241. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111242. long j;
  111243. v->preextrapolate=1;
  111244. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111245. for(i=0;i<v->vi->channels;i++){
  111246. /* need to run the extrapolation in reverse! */
  111247. for(j=0;j<v->pcm_current;j++)
  111248. work[j]=v->pcm[i][v->pcm_current-j-1];
  111249. /* prime as above */
  111250. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111251. /* run the predictor filter */
  111252. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111253. order,
  111254. work+v->pcm_current-v->centerW,
  111255. v->centerW);
  111256. for(j=0;j<v->pcm_current;j++)
  111257. v->pcm[i][v->pcm_current-j-1]=work[j];
  111258. }
  111259. }
  111260. }
  111261. /* call with val<=0 to set eof */
  111262. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111263. vorbis_info *vi=v->vi;
  111264. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111265. if(vals<=0){
  111266. int order=32;
  111267. int i;
  111268. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111269. /* if it wasn't done earlier (very short sample) */
  111270. if(!v->preextrapolate)
  111271. _preextrapolate_helper(v);
  111272. /* We're encoding the end of the stream. Just make sure we have
  111273. [at least] a few full blocks of zeroes at the end. */
  111274. /* actually, we don't want zeroes; that could drop a large
  111275. amplitude off a cliff, creating spread spectrum noise that will
  111276. suck to encode. Extrapolate for the sake of cleanliness. */
  111277. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111278. v->eofflag=v->pcm_current;
  111279. v->pcm_current+=ci->blocksizes[1]*3;
  111280. for(i=0;i<vi->channels;i++){
  111281. if(v->eofflag>order*2){
  111282. /* extrapolate with LPC to fill in */
  111283. long n;
  111284. /* make a predictor filter */
  111285. n=v->eofflag;
  111286. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111287. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111288. /* run the predictor filter */
  111289. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111290. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111291. }else{
  111292. /* not enough data to extrapolate (unlikely to happen due to
  111293. guarding the overlap, but bulletproof in case that
  111294. assumtion goes away). zeroes will do. */
  111295. memset(v->pcm[i]+v->eofflag,0,
  111296. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111297. }
  111298. }
  111299. }else{
  111300. if(v->pcm_current+vals>v->pcm_storage)
  111301. return(OV_EINVAL);
  111302. v->pcm_current+=vals;
  111303. /* we may want to reverse extrapolate the beginning of a stream
  111304. too... in case we're beginning on a cliff! */
  111305. /* clumsy, but simple. It only runs once, so simple is good. */
  111306. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111307. _preextrapolate_helper(v);
  111308. }
  111309. return(0);
  111310. }
  111311. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111312. the next block on which to continue analysis */
  111313. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111314. int i;
  111315. vorbis_info *vi=v->vi;
  111316. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111317. private_state *b=(private_state*)v->backend_state;
  111318. vorbis_look_psy_global *g=b->psy_g_look;
  111319. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111320. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111321. /* check to see if we're started... */
  111322. if(!v->preextrapolate)return(0);
  111323. /* check to see if we're done... */
  111324. if(v->eofflag==-1)return(0);
  111325. /* By our invariant, we have lW, W and centerW set. Search for
  111326. the next boundary so we can determine nW (the next window size)
  111327. which lets us compute the shape of the current block's window */
  111328. /* we do an envelope search even on a single blocksize; we may still
  111329. be throwing more bits at impulses, and envelope search handles
  111330. marking impulses too. */
  111331. {
  111332. long bp=_ve_envelope_search(v);
  111333. if(bp==-1){
  111334. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111335. full long block */
  111336. v->nW=0;
  111337. }else{
  111338. if(ci->blocksizes[0]==ci->blocksizes[1])
  111339. v->nW=0;
  111340. else
  111341. v->nW=bp;
  111342. }
  111343. }
  111344. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111345. {
  111346. /* center of next block + next block maximum right side. */
  111347. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111348. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111349. although this check is
  111350. less strict that the
  111351. _ve_envelope_search,
  111352. the search is not run
  111353. if we only use one
  111354. block size */
  111355. }
  111356. /* fill in the block. Note that for a short window, lW and nW are *short*
  111357. regardless of actual settings in the stream */
  111358. _vorbis_block_ripcord(vb);
  111359. vb->lW=v->lW;
  111360. vb->W=v->W;
  111361. vb->nW=v->nW;
  111362. if(v->W){
  111363. if(!v->lW || !v->nW){
  111364. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111365. /*fprintf(stderr,"-");*/
  111366. }else{
  111367. vbi->blocktype=BLOCKTYPE_LONG;
  111368. /*fprintf(stderr,"_");*/
  111369. }
  111370. }else{
  111371. if(_ve_envelope_mark(v)){
  111372. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111373. /*fprintf(stderr,"|");*/
  111374. }else{
  111375. vbi->blocktype=BLOCKTYPE_PADDING;
  111376. /*fprintf(stderr,".");*/
  111377. }
  111378. }
  111379. vb->vd=v;
  111380. vb->sequence=v->sequence++;
  111381. vb->granulepos=v->granulepos;
  111382. vb->pcmend=ci->blocksizes[v->W];
  111383. /* copy the vectors; this uses the local storage in vb */
  111384. /* this tracks 'strongest peak' for later psychoacoustics */
  111385. /* moved to the global psy state; clean this mess up */
  111386. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111387. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111388. vbi->ampmax=g->ampmax;
  111389. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111390. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111391. for(i=0;i<vi->channels;i++){
  111392. vbi->pcmdelay[i]=
  111393. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111394. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111395. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111396. /* before we added the delay
  111397. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111398. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111399. */
  111400. }
  111401. /* handle eof detection: eof==0 means that we've not yet received EOF
  111402. eof>0 marks the last 'real' sample in pcm[]
  111403. eof<0 'no more to do'; doesn't get here */
  111404. if(v->eofflag){
  111405. if(v->centerW>=v->eofflag){
  111406. v->eofflag=-1;
  111407. vb->eofflag=1;
  111408. return(1);
  111409. }
  111410. }
  111411. /* advance storage vectors and clean up */
  111412. {
  111413. int new_centerNext=ci->blocksizes[1]/2;
  111414. int movementW=centerNext-new_centerNext;
  111415. if(movementW>0){
  111416. _ve_envelope_shift(b->ve,movementW);
  111417. v->pcm_current-=movementW;
  111418. for(i=0;i<vi->channels;i++)
  111419. memmove(v->pcm[i],v->pcm[i]+movementW,
  111420. v->pcm_current*sizeof(*v->pcm[i]));
  111421. v->lW=v->W;
  111422. v->W=v->nW;
  111423. v->centerW=new_centerNext;
  111424. if(v->eofflag){
  111425. v->eofflag-=movementW;
  111426. if(v->eofflag<=0)v->eofflag=-1;
  111427. /* do not add padding to end of stream! */
  111428. if(v->centerW>=v->eofflag){
  111429. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111430. }else{
  111431. v->granulepos+=movementW;
  111432. }
  111433. }else{
  111434. v->granulepos+=movementW;
  111435. }
  111436. }
  111437. }
  111438. /* done */
  111439. return(1);
  111440. }
  111441. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111442. vorbis_info *vi=v->vi;
  111443. codec_setup_info *ci;
  111444. int hs;
  111445. if(!v->backend_state)return -1;
  111446. if(!vi)return -1;
  111447. ci=(codec_setup_info*) vi->codec_setup;
  111448. if(!ci)return -1;
  111449. hs=ci->halfrate_flag;
  111450. v->centerW=ci->blocksizes[1]>>(hs+1);
  111451. v->pcm_current=v->centerW>>hs;
  111452. v->pcm_returned=-1;
  111453. v->granulepos=-1;
  111454. v->sequence=-1;
  111455. v->eofflag=0;
  111456. ((private_state *)(v->backend_state))->sample_count=-1;
  111457. return(0);
  111458. }
  111459. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111460. if(_vds_shared_init(v,vi,0)) return 1;
  111461. vorbis_synthesis_restart(v);
  111462. return 0;
  111463. }
  111464. /* Unlike in analysis, the window is only partially applied for each
  111465. block. The time domain envelope is not yet handled at the point of
  111466. calling (as it relies on the previous block). */
  111467. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111468. vorbis_info *vi=v->vi;
  111469. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111470. private_state *b=(private_state*)v->backend_state;
  111471. int hs=ci->halfrate_flag;
  111472. int i,j;
  111473. if(!vb)return(OV_EINVAL);
  111474. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111475. v->lW=v->W;
  111476. v->W=vb->W;
  111477. v->nW=-1;
  111478. if((v->sequence==-1)||
  111479. (v->sequence+1 != vb->sequence)){
  111480. v->granulepos=-1; /* out of sequence; lose count */
  111481. b->sample_count=-1;
  111482. }
  111483. v->sequence=vb->sequence;
  111484. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111485. was called on block */
  111486. int n=ci->blocksizes[v->W]>>(hs+1);
  111487. int n0=ci->blocksizes[0]>>(hs+1);
  111488. int n1=ci->blocksizes[1]>>(hs+1);
  111489. int thisCenter;
  111490. int prevCenter;
  111491. v->glue_bits+=vb->glue_bits;
  111492. v->time_bits+=vb->time_bits;
  111493. v->floor_bits+=vb->floor_bits;
  111494. v->res_bits+=vb->res_bits;
  111495. if(v->centerW){
  111496. thisCenter=n1;
  111497. prevCenter=0;
  111498. }else{
  111499. thisCenter=0;
  111500. prevCenter=n1;
  111501. }
  111502. /* v->pcm is now used like a two-stage double buffer. We don't want
  111503. to have to constantly shift *or* adjust memory usage. Don't
  111504. accept a new block until the old is shifted out */
  111505. for(j=0;j<vi->channels;j++){
  111506. /* the overlap/add section */
  111507. if(v->lW){
  111508. if(v->W){
  111509. /* large/large */
  111510. float *w=_vorbis_window_get(b->window[1]-hs);
  111511. float *pcm=v->pcm[j]+prevCenter;
  111512. float *p=vb->pcm[j];
  111513. for(i=0;i<n1;i++)
  111514. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111515. }else{
  111516. /* large/small */
  111517. float *w=_vorbis_window_get(b->window[0]-hs);
  111518. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111519. float *p=vb->pcm[j];
  111520. for(i=0;i<n0;i++)
  111521. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111522. }
  111523. }else{
  111524. if(v->W){
  111525. /* small/large */
  111526. float *w=_vorbis_window_get(b->window[0]-hs);
  111527. float *pcm=v->pcm[j]+prevCenter;
  111528. float *p=vb->pcm[j]+n1/2-n0/2;
  111529. for(i=0;i<n0;i++)
  111530. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111531. for(;i<n1/2+n0/2;i++)
  111532. pcm[i]=p[i];
  111533. }else{
  111534. /* small/small */
  111535. float *w=_vorbis_window_get(b->window[0]-hs);
  111536. float *pcm=v->pcm[j]+prevCenter;
  111537. float *p=vb->pcm[j];
  111538. for(i=0;i<n0;i++)
  111539. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111540. }
  111541. }
  111542. /* the copy section */
  111543. {
  111544. float *pcm=v->pcm[j]+thisCenter;
  111545. float *p=vb->pcm[j]+n;
  111546. for(i=0;i<n;i++)
  111547. pcm[i]=p[i];
  111548. }
  111549. }
  111550. if(v->centerW)
  111551. v->centerW=0;
  111552. else
  111553. v->centerW=n1;
  111554. /* deal with initial packet state; we do this using the explicit
  111555. pcm_returned==-1 flag otherwise we're sensitive to first block
  111556. being short or long */
  111557. if(v->pcm_returned==-1){
  111558. v->pcm_returned=thisCenter;
  111559. v->pcm_current=thisCenter;
  111560. }else{
  111561. v->pcm_returned=prevCenter;
  111562. v->pcm_current=prevCenter+
  111563. ((ci->blocksizes[v->lW]/4+
  111564. ci->blocksizes[v->W]/4)>>hs);
  111565. }
  111566. }
  111567. /* track the frame number... This is for convenience, but also
  111568. making sure our last packet doesn't end with added padding. If
  111569. the last packet is partial, the number of samples we'll have to
  111570. return will be past the vb->granulepos.
  111571. This is not foolproof! It will be confused if we begin
  111572. decoding at the last page after a seek or hole. In that case,
  111573. we don't have a starting point to judge where the last frame
  111574. is. For this reason, vorbisfile will always try to make sure
  111575. it reads the last two marked pages in proper sequence */
  111576. if(b->sample_count==-1){
  111577. b->sample_count=0;
  111578. }else{
  111579. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111580. }
  111581. if(v->granulepos==-1){
  111582. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111583. v->granulepos=vb->granulepos;
  111584. /* is this a short page? */
  111585. if(b->sample_count>v->granulepos){
  111586. /* corner case; if this is both the first and last audio page,
  111587. then spec says the end is cut, not beginning */
  111588. if(vb->eofflag){
  111589. /* trim the end */
  111590. /* no preceeding granulepos; assume we started at zero (we'd
  111591. have to in a short single-page stream) */
  111592. /* granulepos could be -1 due to a seek, but that would result
  111593. in a long count, not short count */
  111594. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111595. }else{
  111596. /* trim the beginning */
  111597. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111598. if(v->pcm_returned>v->pcm_current)
  111599. v->pcm_returned=v->pcm_current;
  111600. }
  111601. }
  111602. }
  111603. }else{
  111604. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111605. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111606. if(v->granulepos>vb->granulepos){
  111607. long extra=v->granulepos-vb->granulepos;
  111608. if(extra)
  111609. if(vb->eofflag){
  111610. /* partial last frame. Strip the extra samples off */
  111611. v->pcm_current-=extra>>hs;
  111612. } /* else {Shouldn't happen *unless* the bitstream is out of
  111613. spec. Either way, believe the bitstream } */
  111614. } /* else {Shouldn't happen *unless* the bitstream is out of
  111615. spec. Either way, believe the bitstream } */
  111616. v->granulepos=vb->granulepos;
  111617. }
  111618. }
  111619. /* Update, cleanup */
  111620. if(vb->eofflag)v->eofflag=1;
  111621. return(0);
  111622. }
  111623. /* pcm==NULL indicates we just want the pending samples, no more */
  111624. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111625. vorbis_info *vi=v->vi;
  111626. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111627. if(pcm){
  111628. int i;
  111629. for(i=0;i<vi->channels;i++)
  111630. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111631. *pcm=v->pcmret;
  111632. }
  111633. return(v->pcm_current-v->pcm_returned);
  111634. }
  111635. return(0);
  111636. }
  111637. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111638. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111639. v->pcm_returned+=n;
  111640. return(0);
  111641. }
  111642. /* intended for use with a specific vorbisfile feature; we want access
  111643. to the [usually synthetic/postextrapolated] buffer and lapping at
  111644. the end of a decode cycle, specifically, a half-short-block worth.
  111645. This funtion works like pcmout above, except it will also expose
  111646. this implicit buffer data not normally decoded. */
  111647. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111648. vorbis_info *vi=v->vi;
  111649. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111650. int hs=ci->halfrate_flag;
  111651. int n=ci->blocksizes[v->W]>>(hs+1);
  111652. int n0=ci->blocksizes[0]>>(hs+1);
  111653. int n1=ci->blocksizes[1]>>(hs+1);
  111654. int i,j;
  111655. if(v->pcm_returned<0)return 0;
  111656. /* our returned data ends at pcm_returned; because the synthesis pcm
  111657. buffer is a two-fragment ring, that means our data block may be
  111658. fragmented by buffering, wrapping or a short block not filling
  111659. out a buffer. To simplify things, we unfragment if it's at all
  111660. possibly needed. Otherwise, we'd need to call lapout more than
  111661. once as well as hold additional dsp state. Opt for
  111662. simplicity. */
  111663. /* centerW was advanced by blockin; it would be the center of the
  111664. *next* block */
  111665. if(v->centerW==n1){
  111666. /* the data buffer wraps; swap the halves */
  111667. /* slow, sure, small */
  111668. for(j=0;j<vi->channels;j++){
  111669. float *p=v->pcm[j];
  111670. for(i=0;i<n1;i++){
  111671. float temp=p[i];
  111672. p[i]=p[i+n1];
  111673. p[i+n1]=temp;
  111674. }
  111675. }
  111676. v->pcm_current-=n1;
  111677. v->pcm_returned-=n1;
  111678. v->centerW=0;
  111679. }
  111680. /* solidify buffer into contiguous space */
  111681. if((v->lW^v->W)==1){
  111682. /* long/short or short/long */
  111683. for(j=0;j<vi->channels;j++){
  111684. float *s=v->pcm[j];
  111685. float *d=v->pcm[j]+(n1-n0)/2;
  111686. for(i=(n1+n0)/2-1;i>=0;--i)
  111687. d[i]=s[i];
  111688. }
  111689. v->pcm_returned+=(n1-n0)/2;
  111690. v->pcm_current+=(n1-n0)/2;
  111691. }else{
  111692. if(v->lW==0){
  111693. /* short/short */
  111694. for(j=0;j<vi->channels;j++){
  111695. float *s=v->pcm[j];
  111696. float *d=v->pcm[j]+n1-n0;
  111697. for(i=n0-1;i>=0;--i)
  111698. d[i]=s[i];
  111699. }
  111700. v->pcm_returned+=n1-n0;
  111701. v->pcm_current+=n1-n0;
  111702. }
  111703. }
  111704. if(pcm){
  111705. int i;
  111706. for(i=0;i<vi->channels;i++)
  111707. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111708. *pcm=v->pcmret;
  111709. }
  111710. return(n1+n-v->pcm_returned);
  111711. }
  111712. float *vorbis_window(vorbis_dsp_state *v,int W){
  111713. vorbis_info *vi=v->vi;
  111714. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111715. int hs=ci->halfrate_flag;
  111716. private_state *b=(private_state*)v->backend_state;
  111717. if(b->window[W]-1<0)return NULL;
  111718. return _vorbis_window_get(b->window[W]-hs);
  111719. }
  111720. #endif
  111721. /*** End of inlined file: block.c ***/
  111722. /*** Start of inlined file: codebook.c ***/
  111723. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111724. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111725. // tasks..
  111726. #if JUCE_MSVC
  111727. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111728. #endif
  111729. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111730. #if JUCE_USE_OGGVORBIS
  111731. #include <stdlib.h>
  111732. #include <string.h>
  111733. #include <math.h>
  111734. /* packs the given codebook into the bitstream **************************/
  111735. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111736. long i,j;
  111737. int ordered=0;
  111738. /* first the basic parameters */
  111739. oggpack_write(opb,0x564342,24);
  111740. oggpack_write(opb,c->dim,16);
  111741. oggpack_write(opb,c->entries,24);
  111742. /* pack the codewords. There are two packings; length ordered and
  111743. length random. Decide between the two now. */
  111744. for(i=1;i<c->entries;i++)
  111745. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111746. if(i==c->entries)ordered=1;
  111747. if(ordered){
  111748. /* length ordered. We only need to say how many codewords of
  111749. each length. The actual codewords are generated
  111750. deterministically */
  111751. long count=0;
  111752. oggpack_write(opb,1,1); /* ordered */
  111753. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111754. for(i=1;i<c->entries;i++){
  111755. long thisx=c->lengthlist[i];
  111756. long last=c->lengthlist[i-1];
  111757. if(thisx>last){
  111758. for(j=last;j<thisx;j++){
  111759. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111760. count=i;
  111761. }
  111762. }
  111763. }
  111764. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111765. }else{
  111766. /* length random. Again, we don't code the codeword itself, just
  111767. the length. This time, though, we have to encode each length */
  111768. oggpack_write(opb,0,1); /* unordered */
  111769. /* algortihmic mapping has use for 'unused entries', which we tag
  111770. here. The algorithmic mapping happens as usual, but the unused
  111771. entry has no codeword. */
  111772. for(i=0;i<c->entries;i++)
  111773. if(c->lengthlist[i]==0)break;
  111774. if(i==c->entries){
  111775. oggpack_write(opb,0,1); /* no unused entries */
  111776. for(i=0;i<c->entries;i++)
  111777. oggpack_write(opb,c->lengthlist[i]-1,5);
  111778. }else{
  111779. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111780. for(i=0;i<c->entries;i++){
  111781. if(c->lengthlist[i]==0){
  111782. oggpack_write(opb,0,1);
  111783. }else{
  111784. oggpack_write(opb,1,1);
  111785. oggpack_write(opb,c->lengthlist[i]-1,5);
  111786. }
  111787. }
  111788. }
  111789. }
  111790. /* is the entry number the desired return value, or do we have a
  111791. mapping? If we have a mapping, what type? */
  111792. oggpack_write(opb,c->maptype,4);
  111793. switch(c->maptype){
  111794. case 0:
  111795. /* no mapping */
  111796. break;
  111797. case 1:case 2:
  111798. /* implicitly populated value mapping */
  111799. /* explicitly populated value mapping */
  111800. if(!c->quantlist){
  111801. /* no quantlist? error */
  111802. return(-1);
  111803. }
  111804. /* values that define the dequantization */
  111805. oggpack_write(opb,c->q_min,32);
  111806. oggpack_write(opb,c->q_delta,32);
  111807. oggpack_write(opb,c->q_quant-1,4);
  111808. oggpack_write(opb,c->q_sequencep,1);
  111809. {
  111810. int quantvals;
  111811. switch(c->maptype){
  111812. case 1:
  111813. /* a single column of (c->entries/c->dim) quantized values for
  111814. building a full value list algorithmically (square lattice) */
  111815. quantvals=_book_maptype1_quantvals(c);
  111816. break;
  111817. case 2:
  111818. /* every value (c->entries*c->dim total) specified explicitly */
  111819. quantvals=c->entries*c->dim;
  111820. break;
  111821. default: /* NOT_REACHABLE */
  111822. quantvals=-1;
  111823. }
  111824. /* quantized values */
  111825. for(i=0;i<quantvals;i++)
  111826. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111827. }
  111828. break;
  111829. default:
  111830. /* error case; we don't have any other map types now */
  111831. return(-1);
  111832. }
  111833. return(0);
  111834. }
  111835. /* unpacks a codebook from the packet buffer into the codebook struct,
  111836. readies the codebook auxiliary structures for decode *************/
  111837. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111838. long i,j;
  111839. memset(s,0,sizeof(*s));
  111840. s->allocedp=1;
  111841. /* make sure alignment is correct */
  111842. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111843. /* first the basic parameters */
  111844. s->dim=oggpack_read(opb,16);
  111845. s->entries=oggpack_read(opb,24);
  111846. if(s->entries==-1)goto _eofout;
  111847. /* codeword ordering.... length ordered or unordered? */
  111848. switch((int)oggpack_read(opb,1)){
  111849. case 0:
  111850. /* unordered */
  111851. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111852. /* allocated but unused entries? */
  111853. if(oggpack_read(opb,1)){
  111854. /* yes, unused entries */
  111855. for(i=0;i<s->entries;i++){
  111856. if(oggpack_read(opb,1)){
  111857. long num=oggpack_read(opb,5);
  111858. if(num==-1)goto _eofout;
  111859. s->lengthlist[i]=num+1;
  111860. }else
  111861. s->lengthlist[i]=0;
  111862. }
  111863. }else{
  111864. /* all entries used; no tagging */
  111865. for(i=0;i<s->entries;i++){
  111866. long num=oggpack_read(opb,5);
  111867. if(num==-1)goto _eofout;
  111868. s->lengthlist[i]=num+1;
  111869. }
  111870. }
  111871. break;
  111872. case 1:
  111873. /* ordered */
  111874. {
  111875. long length=oggpack_read(opb,5)+1;
  111876. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111877. for(i=0;i<s->entries;){
  111878. long num=oggpack_read(opb,_ilog(s->entries-i));
  111879. if(num==-1)goto _eofout;
  111880. for(j=0;j<num && i<s->entries;j++,i++)
  111881. s->lengthlist[i]=length;
  111882. length++;
  111883. }
  111884. }
  111885. break;
  111886. default:
  111887. /* EOF */
  111888. return(-1);
  111889. }
  111890. /* Do we have a mapping to unpack? */
  111891. switch((s->maptype=oggpack_read(opb,4))){
  111892. case 0:
  111893. /* no mapping */
  111894. break;
  111895. case 1: case 2:
  111896. /* implicitly populated value mapping */
  111897. /* explicitly populated value mapping */
  111898. s->q_min=oggpack_read(opb,32);
  111899. s->q_delta=oggpack_read(opb,32);
  111900. s->q_quant=oggpack_read(opb,4)+1;
  111901. s->q_sequencep=oggpack_read(opb,1);
  111902. {
  111903. int quantvals=0;
  111904. switch(s->maptype){
  111905. case 1:
  111906. quantvals=_book_maptype1_quantvals(s);
  111907. break;
  111908. case 2:
  111909. quantvals=s->entries*s->dim;
  111910. break;
  111911. }
  111912. /* quantized values */
  111913. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111914. for(i=0;i<quantvals;i++)
  111915. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111916. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111917. }
  111918. break;
  111919. default:
  111920. goto _errout;
  111921. }
  111922. /* all set */
  111923. return(0);
  111924. _errout:
  111925. _eofout:
  111926. vorbis_staticbook_clear(s);
  111927. return(-1);
  111928. }
  111929. /* returns the number of bits ************************************************/
  111930. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111931. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111932. return(book->c->lengthlist[a]);
  111933. }
  111934. /* One the encode side, our vector writers are each designed for a
  111935. specific purpose, and the encoder is not flexible without modification:
  111936. The LSP vector coder uses a single stage nearest-match with no
  111937. interleave, so no step and no error return. This is specced by floor0
  111938. and doesn't change.
  111939. Residue0 encoding interleaves, uses multiple stages, and each stage
  111940. peels of a specific amount of resolution from a lattice (thus we want
  111941. to match by threshold, not nearest match). Residue doesn't *have* to
  111942. be encoded that way, but to change it, one will need to add more
  111943. infrastructure on the encode side (decode side is specced and simpler) */
  111944. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111945. /* returns entry number and *modifies a* to the quantization value *****/
  111946. int vorbis_book_errorv(codebook *book,float *a){
  111947. int dim=book->dim,k;
  111948. int best=_best(book,a,1);
  111949. for(k=0;k<dim;k++)
  111950. a[k]=(book->valuelist+best*dim)[k];
  111951. return(best);
  111952. }
  111953. /* returns the number of bits and *modifies a* to the quantization value *****/
  111954. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111955. int k,dim=book->dim;
  111956. for(k=0;k<dim;k++)
  111957. a[k]=(book->valuelist+best*dim)[k];
  111958. return(vorbis_book_encode(book,best,b));
  111959. }
  111960. /* the 'eliminate the decode tree' optimization actually requires the
  111961. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111962. (and one of the first places where carefully thought out design
  111963. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111964. to an MSb bitpacker), but not actually the huge hit it appears to
  111965. be. The first-stage decode table catches most words so that
  111966. bitreverse is not in the main execution path. */
  111967. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111968. int read=book->dec_maxlength;
  111969. long lo,hi;
  111970. long lok = oggpack_look(b,book->dec_firsttablen);
  111971. if (lok >= 0) {
  111972. long entry = book->dec_firsttable[lok];
  111973. if(entry&0x80000000UL){
  111974. lo=(entry>>15)&0x7fff;
  111975. hi=book->used_entries-(entry&0x7fff);
  111976. }else{
  111977. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111978. return(entry-1);
  111979. }
  111980. }else{
  111981. lo=0;
  111982. hi=book->used_entries;
  111983. }
  111984. lok = oggpack_look(b, read);
  111985. while(lok<0 && read>1)
  111986. lok = oggpack_look(b, --read);
  111987. if(lok<0)return -1;
  111988. /* bisect search for the codeword in the ordered list */
  111989. {
  111990. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111991. while(hi-lo>1){
  111992. long p=(hi-lo)>>1;
  111993. long test=book->codelist[lo+p]>testword;
  111994. lo+=p&(test-1);
  111995. hi-=p&(-test);
  111996. }
  111997. if(book->dec_codelengths[lo]<=read){
  111998. oggpack_adv(b, book->dec_codelengths[lo]);
  111999. return(lo);
  112000. }
  112001. }
  112002. oggpack_adv(b, read);
  112003. return(-1);
  112004. }
  112005. /* Decode side is specced and easier, because we don't need to find
  112006. matches using different criteria; we simply read and map. There are
  112007. two things we need to do 'depending':
  112008. We may need to support interleave. We don't really, but it's
  112009. convenient to do it here rather than rebuild the vector later.
  112010. Cascades may be additive or multiplicitive; this is not inherent in
  112011. the codebook, but set in the code using the codebook. Like
  112012. interleaving, it's easiest to do it here.
  112013. addmul==0 -> declarative (set the value)
  112014. addmul==1 -> additive
  112015. addmul==2 -> multiplicitive */
  112016. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112017. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112018. long packed_entry=decode_packed_entry_number(book,b);
  112019. if(packed_entry>=0)
  112020. return(book->dec_index[packed_entry]);
  112021. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112022. return(packed_entry);
  112023. }
  112024. /* returns 0 on OK or -1 on eof *************************************/
  112025. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112026. int step=n/book->dim;
  112027. long *entry = (long*)alloca(sizeof(*entry)*step);
  112028. float **t = (float**)alloca(sizeof(*t)*step);
  112029. int i,j,o;
  112030. for (i = 0; i < step; i++) {
  112031. entry[i]=decode_packed_entry_number(book,b);
  112032. if(entry[i]==-1)return(-1);
  112033. t[i] = book->valuelist+entry[i]*book->dim;
  112034. }
  112035. for(i=0,o=0;i<book->dim;i++,o+=step)
  112036. for (j=0;j<step;j++)
  112037. a[o+j]+=t[j][i];
  112038. return(0);
  112039. }
  112040. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112041. int i,j,entry;
  112042. float *t;
  112043. if(book->dim>8){
  112044. for(i=0;i<n;){
  112045. entry = decode_packed_entry_number(book,b);
  112046. if(entry==-1)return(-1);
  112047. t = book->valuelist+entry*book->dim;
  112048. for (j=0;j<book->dim;)
  112049. a[i++]+=t[j++];
  112050. }
  112051. }else{
  112052. for(i=0;i<n;){
  112053. entry = decode_packed_entry_number(book,b);
  112054. if(entry==-1)return(-1);
  112055. t = book->valuelist+entry*book->dim;
  112056. j=0;
  112057. switch((int)book->dim){
  112058. case 8:
  112059. a[i++]+=t[j++];
  112060. case 7:
  112061. a[i++]+=t[j++];
  112062. case 6:
  112063. a[i++]+=t[j++];
  112064. case 5:
  112065. a[i++]+=t[j++];
  112066. case 4:
  112067. a[i++]+=t[j++];
  112068. case 3:
  112069. a[i++]+=t[j++];
  112070. case 2:
  112071. a[i++]+=t[j++];
  112072. case 1:
  112073. a[i++]+=t[j++];
  112074. case 0:
  112075. break;
  112076. }
  112077. }
  112078. }
  112079. return(0);
  112080. }
  112081. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112082. int i,j,entry;
  112083. float *t;
  112084. for(i=0;i<n;){
  112085. entry = decode_packed_entry_number(book,b);
  112086. if(entry==-1)return(-1);
  112087. t = book->valuelist+entry*book->dim;
  112088. for (j=0;j<book->dim;)
  112089. a[i++]=t[j++];
  112090. }
  112091. return(0);
  112092. }
  112093. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112094. oggpack_buffer *b,int n){
  112095. long i,j,entry;
  112096. int chptr=0;
  112097. for(i=offset/ch;i<(offset+n)/ch;){
  112098. entry = decode_packed_entry_number(book,b);
  112099. if(entry==-1)return(-1);
  112100. {
  112101. const float *t = book->valuelist+entry*book->dim;
  112102. for (j=0;j<book->dim;j++){
  112103. a[chptr++][i]+=t[j];
  112104. if(chptr==ch){
  112105. chptr=0;
  112106. i++;
  112107. }
  112108. }
  112109. }
  112110. }
  112111. return(0);
  112112. }
  112113. #ifdef _V_SELFTEST
  112114. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112115. number of vectors through (keeping track of the quantized values),
  112116. and decode using the unpacked book. quantized version of in should
  112117. exactly equal out */
  112118. #include <stdio.h>
  112119. #include "vorbis/book/lsp20_0.vqh"
  112120. #include "vorbis/book/res0a_13.vqh"
  112121. #define TESTSIZE 40
  112122. float test1[TESTSIZE]={
  112123. 0.105939f,
  112124. 0.215373f,
  112125. 0.429117f,
  112126. 0.587974f,
  112127. 0.181173f,
  112128. 0.296583f,
  112129. 0.515707f,
  112130. 0.715261f,
  112131. 0.162327f,
  112132. 0.263834f,
  112133. 0.342876f,
  112134. 0.406025f,
  112135. 0.103571f,
  112136. 0.223561f,
  112137. 0.368513f,
  112138. 0.540313f,
  112139. 0.136672f,
  112140. 0.395882f,
  112141. 0.587183f,
  112142. 0.652476f,
  112143. 0.114338f,
  112144. 0.417300f,
  112145. 0.525486f,
  112146. 0.698679f,
  112147. 0.147492f,
  112148. 0.324481f,
  112149. 0.643089f,
  112150. 0.757582f,
  112151. 0.139556f,
  112152. 0.215795f,
  112153. 0.324559f,
  112154. 0.399387f,
  112155. 0.120236f,
  112156. 0.267420f,
  112157. 0.446940f,
  112158. 0.608760f,
  112159. 0.115587f,
  112160. 0.287234f,
  112161. 0.571081f,
  112162. 0.708603f,
  112163. };
  112164. float test3[TESTSIZE]={
  112165. 0,1,-2,3,4,-5,6,7,8,9,
  112166. 8,-2,7,-1,4,6,8,3,1,-9,
  112167. 10,11,12,13,14,15,26,17,18,19,
  112168. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112169. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112170. &_vq_book_res0a_13,NULL};
  112171. float *testvec[]={test1,test3};
  112172. int main(){
  112173. oggpack_buffer write;
  112174. oggpack_buffer read;
  112175. long ptr=0,i;
  112176. oggpack_writeinit(&write);
  112177. fprintf(stderr,"Testing codebook abstraction...:\n");
  112178. while(testlist[ptr]){
  112179. codebook c;
  112180. static_codebook s;
  112181. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112182. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112183. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112184. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112185. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112186. /* pack the codebook, write the testvector */
  112187. oggpack_reset(&write);
  112188. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112189. we can write */
  112190. vorbis_staticbook_pack(testlist[ptr],&write);
  112191. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112192. for(i=0;i<TESTSIZE;i+=c.dim){
  112193. int best=_best(&c,qv+i,1);
  112194. vorbis_book_encodev(&c,best,qv+i,&write);
  112195. }
  112196. vorbis_book_clear(&c);
  112197. fprintf(stderr,"OK.\n");
  112198. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112199. /* transfer the write data to a read buffer and unpack/read */
  112200. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112201. if(vorbis_staticbook_unpack(&read,&s)){
  112202. fprintf(stderr,"Error unpacking codebook.\n");
  112203. exit(1);
  112204. }
  112205. if(vorbis_book_init_decode(&c,&s)){
  112206. fprintf(stderr,"Error initializing codebook.\n");
  112207. exit(1);
  112208. }
  112209. for(i=0;i<TESTSIZE;i+=c.dim)
  112210. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112211. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112212. exit(1);
  112213. }
  112214. for(i=0;i<TESTSIZE;i++)
  112215. if(fabs(qv[i]-iv[i])>.000001){
  112216. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112217. iv[i],qv[i],i);
  112218. exit(1);
  112219. }
  112220. fprintf(stderr,"OK\n");
  112221. ptr++;
  112222. }
  112223. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112224. exit(0);
  112225. }
  112226. #endif
  112227. #endif
  112228. /*** End of inlined file: codebook.c ***/
  112229. /*** Start of inlined file: envelope.c ***/
  112230. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112231. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112232. // tasks..
  112233. #if JUCE_MSVC
  112234. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112235. #endif
  112236. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112237. #if JUCE_USE_OGGVORBIS
  112238. #include <stdlib.h>
  112239. #include <string.h>
  112240. #include <stdio.h>
  112241. #include <math.h>
  112242. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112243. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112244. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112245. int ch=vi->channels;
  112246. int i,j;
  112247. int n=e->winlength=128;
  112248. e->searchstep=64; /* not random */
  112249. e->minenergy=gi->preecho_minenergy;
  112250. e->ch=ch;
  112251. e->storage=128;
  112252. e->cursor=ci->blocksizes[1]/2;
  112253. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112254. mdct_init(&e->mdct,n);
  112255. for(i=0;i<n;i++){
  112256. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112257. e->mdct_win[i]*=e->mdct_win[i];
  112258. }
  112259. /* magic follows */
  112260. e->band[0].begin=2; e->band[0].end=4;
  112261. e->band[1].begin=4; e->band[1].end=5;
  112262. e->band[2].begin=6; e->band[2].end=6;
  112263. e->band[3].begin=9; e->band[3].end=8;
  112264. e->band[4].begin=13; e->band[4].end=8;
  112265. e->band[5].begin=17; e->band[5].end=8;
  112266. e->band[6].begin=22; e->band[6].end=8;
  112267. for(j=0;j<VE_BANDS;j++){
  112268. n=e->band[j].end;
  112269. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112270. for(i=0;i<n;i++){
  112271. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112272. e->band[j].total+=e->band[j].window[i];
  112273. }
  112274. e->band[j].total=1./e->band[j].total;
  112275. }
  112276. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112277. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112278. }
  112279. void _ve_envelope_clear(envelope_lookup *e){
  112280. int i;
  112281. mdct_clear(&e->mdct);
  112282. for(i=0;i<VE_BANDS;i++)
  112283. _ogg_free(e->band[i].window);
  112284. _ogg_free(e->mdct_win);
  112285. _ogg_free(e->filter);
  112286. _ogg_free(e->mark);
  112287. memset(e,0,sizeof(*e));
  112288. }
  112289. /* fairly straight threshhold-by-band based until we find something
  112290. that works better and isn't patented. */
  112291. static int _ve_amp(envelope_lookup *ve,
  112292. vorbis_info_psy_global *gi,
  112293. float *data,
  112294. envelope_band *bands,
  112295. envelope_filter_state *filters,
  112296. long pos){
  112297. long n=ve->winlength;
  112298. int ret=0;
  112299. long i,j;
  112300. float decay;
  112301. /* we want to have a 'minimum bar' for energy, else we're just
  112302. basing blocks on quantization noise that outweighs the signal
  112303. itself (for low power signals) */
  112304. float minV=ve->minenergy;
  112305. float *vec=(float*) alloca(n*sizeof(*vec));
  112306. /* stretch is used to gradually lengthen the number of windows
  112307. considered prevoius-to-potential-trigger */
  112308. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112309. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112310. if(penalty<0.f)penalty=0.f;
  112311. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112312. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112313. totalshift+pos*ve->searchstep);*/
  112314. /* window and transform */
  112315. for(i=0;i<n;i++)
  112316. vec[i]=data[i]*ve->mdct_win[i];
  112317. mdct_forward(&ve->mdct,vec,vec);
  112318. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112319. /* near-DC spreading function; this has nothing to do with
  112320. psychoacoustics, just sidelobe leakage and window size */
  112321. {
  112322. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112323. int ptr=filters->nearptr;
  112324. /* the accumulation is regularly refreshed from scratch to avoid
  112325. floating point creep */
  112326. if(ptr==0){
  112327. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112328. filters->nearDC_partialacc=temp;
  112329. }else{
  112330. decay=filters->nearDC_acc+=temp;
  112331. filters->nearDC_partialacc+=temp;
  112332. }
  112333. filters->nearDC_acc-=filters->nearDC[ptr];
  112334. filters->nearDC[ptr]=temp;
  112335. decay*=(1./(VE_NEARDC+1));
  112336. filters->nearptr++;
  112337. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112338. decay=todB(&decay)*.5-15.f;
  112339. }
  112340. /* perform spreading and limiting, also smooth the spectrum. yes,
  112341. the MDCT results in all real coefficients, but it still *behaves*
  112342. like real/imaginary pairs */
  112343. for(i=0;i<n/2;i+=2){
  112344. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112345. val=todB(&val)*.5f;
  112346. if(val<decay)val=decay;
  112347. if(val<minV)val=minV;
  112348. vec[i>>1]=val;
  112349. decay-=8.;
  112350. }
  112351. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112352. /* perform preecho/postecho triggering by band */
  112353. for(j=0;j<VE_BANDS;j++){
  112354. float acc=0.;
  112355. float valmax,valmin;
  112356. /* accumulate amplitude */
  112357. for(i=0;i<bands[j].end;i++)
  112358. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112359. acc*=bands[j].total;
  112360. /* convert amplitude to delta */
  112361. {
  112362. int p,thisx=filters[j].ampptr;
  112363. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112364. p=thisx;
  112365. p--;
  112366. if(p<0)p+=VE_AMP;
  112367. postmax=max(acc,filters[j].ampbuf[p]);
  112368. postmin=min(acc,filters[j].ampbuf[p]);
  112369. for(i=0;i<stretch;i++){
  112370. p--;
  112371. if(p<0)p+=VE_AMP;
  112372. premax=max(premax,filters[j].ampbuf[p]);
  112373. premin=min(premin,filters[j].ampbuf[p]);
  112374. }
  112375. valmin=postmin-premin;
  112376. valmax=postmax-premax;
  112377. /*filters[j].markers[pos]=valmax;*/
  112378. filters[j].ampbuf[thisx]=acc;
  112379. filters[j].ampptr++;
  112380. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112381. }
  112382. /* look at min/max, decide trigger */
  112383. if(valmax>gi->preecho_thresh[j]+penalty){
  112384. ret|=1;
  112385. ret|=4;
  112386. }
  112387. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112388. }
  112389. return(ret);
  112390. }
  112391. #if 0
  112392. static int seq=0;
  112393. static ogg_int64_t totalshift=-1024;
  112394. #endif
  112395. long _ve_envelope_search(vorbis_dsp_state *v){
  112396. vorbis_info *vi=v->vi;
  112397. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112398. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112399. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112400. long i,j;
  112401. int first=ve->current/ve->searchstep;
  112402. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112403. if(first<0)first=0;
  112404. /* make sure we have enough storage to match the PCM */
  112405. if(last+VE_WIN+VE_POST>ve->storage){
  112406. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112407. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112408. }
  112409. for(j=first;j<last;j++){
  112410. int ret=0;
  112411. ve->stretch++;
  112412. if(ve->stretch>VE_MAXSTRETCH*2)
  112413. ve->stretch=VE_MAXSTRETCH*2;
  112414. for(i=0;i<ve->ch;i++){
  112415. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112416. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112417. }
  112418. ve->mark[j+VE_POST]=0;
  112419. if(ret&1){
  112420. ve->mark[j]=1;
  112421. ve->mark[j+1]=1;
  112422. }
  112423. if(ret&2){
  112424. ve->mark[j]=1;
  112425. if(j>0)ve->mark[j-1]=1;
  112426. }
  112427. if(ret&4)ve->stretch=-1;
  112428. }
  112429. ve->current=last*ve->searchstep;
  112430. {
  112431. long centerW=v->centerW;
  112432. long testW=
  112433. centerW+
  112434. ci->blocksizes[v->W]/4+
  112435. ci->blocksizes[1]/2+
  112436. ci->blocksizes[0]/4;
  112437. j=ve->cursor;
  112438. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112439. working back one window */
  112440. if(j>=testW)return(1);
  112441. ve->cursor=j;
  112442. if(ve->mark[j/ve->searchstep]){
  112443. if(j>centerW){
  112444. #if 0
  112445. if(j>ve->curmark){
  112446. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112447. int l,m;
  112448. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112449. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112450. seq,
  112451. (totalshift+ve->cursor)/44100.,
  112452. (totalshift+j)/44100.);
  112453. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112454. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112455. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112456. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112457. for(m=0;m<VE_BANDS;m++){
  112458. char buf[80];
  112459. sprintf(buf,"delL%d",m);
  112460. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112461. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112462. }
  112463. for(m=0;m<VE_BANDS;m++){
  112464. char buf[80];
  112465. sprintf(buf,"delR%d",m);
  112466. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112467. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112468. }
  112469. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112470. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112471. seq++;
  112472. }
  112473. #endif
  112474. ve->curmark=j;
  112475. if(j>=testW)return(1);
  112476. return(0);
  112477. }
  112478. }
  112479. j+=ve->searchstep;
  112480. }
  112481. }
  112482. return(-1);
  112483. }
  112484. int _ve_envelope_mark(vorbis_dsp_state *v){
  112485. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112486. vorbis_info *vi=v->vi;
  112487. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112488. long centerW=v->centerW;
  112489. long beginW=centerW-ci->blocksizes[v->W]/4;
  112490. long endW=centerW+ci->blocksizes[v->W]/4;
  112491. if(v->W){
  112492. beginW-=ci->blocksizes[v->lW]/4;
  112493. endW+=ci->blocksizes[v->nW]/4;
  112494. }else{
  112495. beginW-=ci->blocksizes[0]/4;
  112496. endW+=ci->blocksizes[0]/4;
  112497. }
  112498. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112499. {
  112500. long first=beginW/ve->searchstep;
  112501. long last=endW/ve->searchstep;
  112502. long i;
  112503. for(i=first;i<last;i++)
  112504. if(ve->mark[i])return(1);
  112505. }
  112506. return(0);
  112507. }
  112508. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112509. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112510. ahead of ve->current */
  112511. int smallshift=shift/e->searchstep;
  112512. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112513. #if 0
  112514. for(i=0;i<VE_BANDS*e->ch;i++)
  112515. memmove(e->filter[i].markers,
  112516. e->filter[i].markers+smallshift,
  112517. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112518. totalshift+=shift;
  112519. #endif
  112520. e->current-=shift;
  112521. if(e->curmark>=0)
  112522. e->curmark-=shift;
  112523. e->cursor-=shift;
  112524. }
  112525. #endif
  112526. /*** End of inlined file: envelope.c ***/
  112527. /*** Start of inlined file: floor0.c ***/
  112528. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112529. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112530. // tasks..
  112531. #if JUCE_MSVC
  112532. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112533. #endif
  112534. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112535. #if JUCE_USE_OGGVORBIS
  112536. #include <stdlib.h>
  112537. #include <string.h>
  112538. #include <math.h>
  112539. /*** Start of inlined file: lsp.h ***/
  112540. #ifndef _V_LSP_H_
  112541. #define _V_LSP_H_
  112542. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112543. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112544. float *lsp,int m,
  112545. float amp,float ampoffset);
  112546. #endif
  112547. /*** End of inlined file: lsp.h ***/
  112548. #include <stdio.h>
  112549. typedef struct {
  112550. int ln;
  112551. int m;
  112552. int **linearmap;
  112553. int n[2];
  112554. vorbis_info_floor0 *vi;
  112555. long bits;
  112556. long frames;
  112557. } vorbis_look_floor0;
  112558. /***********************************************/
  112559. static void floor0_free_info(vorbis_info_floor *i){
  112560. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112561. if(info){
  112562. memset(info,0,sizeof(*info));
  112563. _ogg_free(info);
  112564. }
  112565. }
  112566. static void floor0_free_look(vorbis_look_floor *i){
  112567. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112568. if(look){
  112569. if(look->linearmap){
  112570. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112571. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112572. _ogg_free(look->linearmap);
  112573. }
  112574. memset(look,0,sizeof(*look));
  112575. _ogg_free(look);
  112576. }
  112577. }
  112578. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112579. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112580. int j;
  112581. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112582. info->order=oggpack_read(opb,8);
  112583. info->rate=oggpack_read(opb,16);
  112584. info->barkmap=oggpack_read(opb,16);
  112585. info->ampbits=oggpack_read(opb,6);
  112586. info->ampdB=oggpack_read(opb,8);
  112587. info->numbooks=oggpack_read(opb,4)+1;
  112588. if(info->order<1)goto err_out;
  112589. if(info->rate<1)goto err_out;
  112590. if(info->barkmap<1)goto err_out;
  112591. if(info->numbooks<1)goto err_out;
  112592. for(j=0;j<info->numbooks;j++){
  112593. info->books[j]=oggpack_read(opb,8);
  112594. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112595. }
  112596. return(info);
  112597. err_out:
  112598. floor0_free_info(info);
  112599. return(NULL);
  112600. }
  112601. /* initialize Bark scale and normalization lookups. We could do this
  112602. with static tables, but Vorbis allows a number of possible
  112603. combinations, so it's best to do it computationally.
  112604. The below is authoritative in terms of defining scale mapping.
  112605. Note that the scale depends on the sampling rate as well as the
  112606. linear block and mapping sizes */
  112607. static void floor0_map_lazy_init(vorbis_block *vb,
  112608. vorbis_info_floor *infoX,
  112609. vorbis_look_floor0 *look){
  112610. if(!look->linearmap[vb->W]){
  112611. vorbis_dsp_state *vd=vb->vd;
  112612. vorbis_info *vi=vd->vi;
  112613. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112614. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112615. int W=vb->W;
  112616. int n=ci->blocksizes[W]/2,j;
  112617. /* we choose a scaling constant so that:
  112618. floor(bark(rate/2-1)*C)=mapped-1
  112619. floor(bark(rate/2)*C)=mapped */
  112620. float scale=look->ln/toBARK(info->rate/2.f);
  112621. /* the mapping from a linear scale to a smaller bark scale is
  112622. straightforward. We do *not* make sure that the linear mapping
  112623. does not skip bark-scale bins; the decoder simply skips them and
  112624. the encoder may do what it wishes in filling them. They're
  112625. necessary in some mapping combinations to keep the scale spacing
  112626. accurate */
  112627. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112628. for(j=0;j<n;j++){
  112629. int val=floor( toBARK((info->rate/2.f)/n*j)
  112630. *scale); /* bark numbers represent band edges */
  112631. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112632. look->linearmap[W][j]=val;
  112633. }
  112634. look->linearmap[W][j]=-1;
  112635. look->n[W]=n;
  112636. }
  112637. }
  112638. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112639. vorbis_info_floor *i){
  112640. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112641. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112642. look->m=info->order;
  112643. look->ln=info->barkmap;
  112644. look->vi=info;
  112645. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112646. return look;
  112647. }
  112648. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112649. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112650. vorbis_info_floor0 *info=look->vi;
  112651. int j,k;
  112652. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112653. if(ampraw>0){ /* also handles the -1 out of data case */
  112654. long maxval=(1<<info->ampbits)-1;
  112655. float amp=(float)ampraw/maxval*info->ampdB;
  112656. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112657. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112658. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112659. codebook *b=ci->fullbooks+info->books[booknum];
  112660. float last=0.f;
  112661. /* the additional b->dim is a guard against any possible stack
  112662. smash; b->dim is provably more than we can overflow the
  112663. vector */
  112664. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112665. for(j=0;j<look->m;j+=b->dim)
  112666. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112667. for(j=0;j<look->m;){
  112668. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112669. last=lsp[j-1];
  112670. }
  112671. lsp[look->m]=amp;
  112672. return(lsp);
  112673. }
  112674. }
  112675. eop:
  112676. return(NULL);
  112677. }
  112678. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112679. void *memo,float *out){
  112680. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112681. vorbis_info_floor0 *info=look->vi;
  112682. floor0_map_lazy_init(vb,info,look);
  112683. if(memo){
  112684. float *lsp=(float *)memo;
  112685. float amp=lsp[look->m];
  112686. /* take the coefficients back to a spectral envelope curve */
  112687. vorbis_lsp_to_curve(out,
  112688. look->linearmap[vb->W],
  112689. look->n[vb->W],
  112690. look->ln,
  112691. lsp,look->m,amp,(float)info->ampdB);
  112692. return(1);
  112693. }
  112694. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112695. return(0);
  112696. }
  112697. /* export hooks */
  112698. vorbis_func_floor floor0_exportbundle={
  112699. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112700. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112701. };
  112702. #endif
  112703. /*** End of inlined file: floor0.c ***/
  112704. /*** Start of inlined file: floor1.c ***/
  112705. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112706. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112707. // tasks..
  112708. #if JUCE_MSVC
  112709. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112710. #endif
  112711. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112712. #if JUCE_USE_OGGVORBIS
  112713. #include <stdlib.h>
  112714. #include <string.h>
  112715. #include <math.h>
  112716. #include <stdio.h>
  112717. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112718. typedef struct {
  112719. int sorted_index[VIF_POSIT+2];
  112720. int forward_index[VIF_POSIT+2];
  112721. int reverse_index[VIF_POSIT+2];
  112722. int hineighbor[VIF_POSIT];
  112723. int loneighbor[VIF_POSIT];
  112724. int posts;
  112725. int n;
  112726. int quant_q;
  112727. vorbis_info_floor1 *vi;
  112728. long phrasebits;
  112729. long postbits;
  112730. long frames;
  112731. } vorbis_look_floor1;
  112732. typedef struct lsfit_acc{
  112733. long x0;
  112734. long x1;
  112735. long xa;
  112736. long ya;
  112737. long x2a;
  112738. long y2a;
  112739. long xya;
  112740. long an;
  112741. } lsfit_acc;
  112742. /***********************************************/
  112743. static void floor1_free_info(vorbis_info_floor *i){
  112744. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112745. if(info){
  112746. memset(info,0,sizeof(*info));
  112747. _ogg_free(info);
  112748. }
  112749. }
  112750. static void floor1_free_look(vorbis_look_floor *i){
  112751. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112752. if(look){
  112753. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112754. (float)look->phrasebits/look->frames,
  112755. (float)look->postbits/look->frames,
  112756. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112757. memset(look,0,sizeof(*look));
  112758. _ogg_free(look);
  112759. }
  112760. }
  112761. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112762. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112763. int j,k;
  112764. int count=0;
  112765. int rangebits;
  112766. int maxposit=info->postlist[1];
  112767. int maxclass=-1;
  112768. /* save out partitions */
  112769. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112770. for(j=0;j<info->partitions;j++){
  112771. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112772. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112773. }
  112774. /* save out partition classes */
  112775. for(j=0;j<maxclass+1;j++){
  112776. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112777. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112778. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112779. for(k=0;k<(1<<info->class_subs[j]);k++)
  112780. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112781. }
  112782. /* save out the post list */
  112783. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112784. oggpack_write(opb,ilog2(maxposit),4);
  112785. rangebits=ilog2(maxposit);
  112786. for(j=0,k=0;j<info->partitions;j++){
  112787. count+=info->class_dim[info->partitionclass[j]];
  112788. for(;k<count;k++)
  112789. oggpack_write(opb,info->postlist[k+2],rangebits);
  112790. }
  112791. }
  112792. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112793. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112794. int j,k,count=0,maxclass=-1,rangebits;
  112795. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112796. /* read partitions */
  112797. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112798. for(j=0;j<info->partitions;j++){
  112799. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112800. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112801. }
  112802. /* read partition classes */
  112803. for(j=0;j<maxclass+1;j++){
  112804. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112805. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112806. if(info->class_subs[j]<0)
  112807. goto err_out;
  112808. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112809. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112810. goto err_out;
  112811. for(k=0;k<(1<<info->class_subs[j]);k++){
  112812. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112813. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112814. goto err_out;
  112815. }
  112816. }
  112817. /* read the post list */
  112818. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112819. rangebits=oggpack_read(opb,4);
  112820. for(j=0,k=0;j<info->partitions;j++){
  112821. count+=info->class_dim[info->partitionclass[j]];
  112822. for(;k<count;k++){
  112823. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112824. if(t<0 || t>=(1<<rangebits))
  112825. goto err_out;
  112826. }
  112827. }
  112828. info->postlist[0]=0;
  112829. info->postlist[1]=1<<rangebits;
  112830. return(info);
  112831. err_out:
  112832. floor1_free_info(info);
  112833. return(NULL);
  112834. }
  112835. static int icomp(const void *a,const void *b){
  112836. return(**(int **)a-**(int **)b);
  112837. }
  112838. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112839. vorbis_info_floor *in){
  112840. int *sortpointer[VIF_POSIT+2];
  112841. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112842. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112843. int i,j,n=0;
  112844. look->vi=info;
  112845. look->n=info->postlist[1];
  112846. /* we drop each position value in-between already decoded values,
  112847. and use linear interpolation to predict each new value past the
  112848. edges. The positions are read in the order of the position
  112849. list... we precompute the bounding positions in the lookup. Of
  112850. course, the neighbors can change (if a position is declined), but
  112851. this is an initial mapping */
  112852. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112853. n+=2;
  112854. look->posts=n;
  112855. /* also store a sorted position index */
  112856. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112857. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112858. /* points from sort order back to range number */
  112859. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112860. /* points from range order to sorted position */
  112861. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112862. /* we actually need the post values too */
  112863. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112864. /* quantize values to multiplier spec */
  112865. switch(info->mult){
  112866. case 1: /* 1024 -> 256 */
  112867. look->quant_q=256;
  112868. break;
  112869. case 2: /* 1024 -> 128 */
  112870. look->quant_q=128;
  112871. break;
  112872. case 3: /* 1024 -> 86 */
  112873. look->quant_q=86;
  112874. break;
  112875. case 4: /* 1024 -> 64 */
  112876. look->quant_q=64;
  112877. break;
  112878. }
  112879. /* discover our neighbors for decode where we don't use fit flags
  112880. (that would push the neighbors outward) */
  112881. for(i=0;i<n-2;i++){
  112882. int lo=0;
  112883. int hi=1;
  112884. int lx=0;
  112885. int hx=look->n;
  112886. int currentx=info->postlist[i+2];
  112887. for(j=0;j<i+2;j++){
  112888. int x=info->postlist[j];
  112889. if(x>lx && x<currentx){
  112890. lo=j;
  112891. lx=x;
  112892. }
  112893. if(x<hx && x>currentx){
  112894. hi=j;
  112895. hx=x;
  112896. }
  112897. }
  112898. look->loneighbor[i]=lo;
  112899. look->hineighbor[i]=hi;
  112900. }
  112901. return(look);
  112902. }
  112903. static int render_point(int x0,int x1,int y0,int y1,int x){
  112904. y0&=0x7fff; /* mask off flag */
  112905. y1&=0x7fff;
  112906. {
  112907. int dy=y1-y0;
  112908. int adx=x1-x0;
  112909. int ady=abs(dy);
  112910. int err=ady*(x-x0);
  112911. int off=err/adx;
  112912. if(dy<0)return(y0-off);
  112913. return(y0+off);
  112914. }
  112915. }
  112916. static int vorbis_dBquant(const float *x){
  112917. int i= *x*7.3142857f+1023.5f;
  112918. if(i>1023)return(1023);
  112919. if(i<0)return(0);
  112920. return i;
  112921. }
  112922. static float FLOOR1_fromdB_LOOKUP[256]={
  112923. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112924. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112925. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112926. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112927. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112928. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112929. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112930. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112931. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112932. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112933. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112934. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112935. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112936. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112937. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112938. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112939. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112940. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112941. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112942. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112943. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112944. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112945. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112946. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112947. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112948. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112949. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112950. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112951. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112952. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112953. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112954. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112955. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112956. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112957. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112958. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112959. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112960. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112961. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112962. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112963. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112964. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112965. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112966. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112967. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112968. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112969. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112970. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112971. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112972. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112973. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112974. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112975. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112976. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112977. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112978. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112979. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112980. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112981. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112982. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112983. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112984. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112985. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112986. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112987. };
  112988. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112989. int dy=y1-y0;
  112990. int adx=x1-x0;
  112991. int ady=abs(dy);
  112992. int base=dy/adx;
  112993. int sy=(dy<0?base-1:base+1);
  112994. int x=x0;
  112995. int y=y0;
  112996. int err=0;
  112997. ady-=abs(base*adx);
  112998. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112999. while(++x<x1){
  113000. err=err+ady;
  113001. if(err>=adx){
  113002. err-=adx;
  113003. y+=sy;
  113004. }else{
  113005. y+=base;
  113006. }
  113007. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113008. }
  113009. }
  113010. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113011. int dy=y1-y0;
  113012. int adx=x1-x0;
  113013. int ady=abs(dy);
  113014. int base=dy/adx;
  113015. int sy=(dy<0?base-1:base+1);
  113016. int x=x0;
  113017. int y=y0;
  113018. int err=0;
  113019. ady-=abs(base*adx);
  113020. d[x]=y;
  113021. while(++x<x1){
  113022. err=err+ady;
  113023. if(err>=adx){
  113024. err-=adx;
  113025. y+=sy;
  113026. }else{
  113027. y+=base;
  113028. }
  113029. d[x]=y;
  113030. }
  113031. }
  113032. /* the floor has already been filtered to only include relevant sections */
  113033. static int accumulate_fit(const float *flr,const float *mdct,
  113034. int x0, int x1,lsfit_acc *a,
  113035. int n,vorbis_info_floor1 *info){
  113036. long i;
  113037. 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;
  113038. memset(a,0,sizeof(*a));
  113039. a->x0=x0;
  113040. a->x1=x1;
  113041. if(x1>=n)x1=n-1;
  113042. for(i=x0;i<=x1;i++){
  113043. int quantized=vorbis_dBquant(flr+i);
  113044. if(quantized){
  113045. if(mdct[i]+info->twofitatten>=flr[i]){
  113046. xa += i;
  113047. ya += quantized;
  113048. x2a += i*i;
  113049. y2a += quantized*quantized;
  113050. xya += i*quantized;
  113051. na++;
  113052. }else{
  113053. xb += i;
  113054. yb += quantized;
  113055. x2b += i*i;
  113056. y2b += quantized*quantized;
  113057. xyb += i*quantized;
  113058. nb++;
  113059. }
  113060. }
  113061. }
  113062. xb+=xa;
  113063. yb+=ya;
  113064. x2b+=x2a;
  113065. y2b+=y2a;
  113066. xyb+=xya;
  113067. nb+=na;
  113068. /* weight toward the actually used frequencies if we meet the threshhold */
  113069. {
  113070. int weight=nb*info->twofitweight/(na+1);
  113071. a->xa=xa*weight+xb;
  113072. a->ya=ya*weight+yb;
  113073. a->x2a=x2a*weight+x2b;
  113074. a->y2a=y2a*weight+y2b;
  113075. a->xya=xya*weight+xyb;
  113076. a->an=na*weight+nb;
  113077. }
  113078. return(na);
  113079. }
  113080. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113081. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113082. long x0=a[0].x0;
  113083. long x1=a[fits-1].x1;
  113084. for(i=0;i<fits;i++){
  113085. x+=a[i].xa;
  113086. y+=a[i].ya;
  113087. x2+=a[i].x2a;
  113088. y2+=a[i].y2a;
  113089. xy+=a[i].xya;
  113090. an+=a[i].an;
  113091. }
  113092. if(*y0>=0){
  113093. x+= x0;
  113094. y+= *y0;
  113095. x2+= x0 * x0;
  113096. y2+= *y0 * *y0;
  113097. xy+= *y0 * x0;
  113098. an++;
  113099. }
  113100. if(*y1>=0){
  113101. x+= x1;
  113102. y+= *y1;
  113103. x2+= x1 * x1;
  113104. y2+= *y1 * *y1;
  113105. xy+= *y1 * x1;
  113106. an++;
  113107. }
  113108. if(an){
  113109. /* need 64 bit multiplies, which C doesn't give portably as int */
  113110. double fx=x;
  113111. double fy=y;
  113112. double fx2=x2;
  113113. double fxy=xy;
  113114. double denom=1./(an*fx2-fx*fx);
  113115. double a=(fy*fx2-fxy*fx)*denom;
  113116. double b=(an*fxy-fx*fy)*denom;
  113117. *y0=rint(a+b*x0);
  113118. *y1=rint(a+b*x1);
  113119. /* limit to our range! */
  113120. if(*y0>1023)*y0=1023;
  113121. if(*y1>1023)*y1=1023;
  113122. if(*y0<0)*y0=0;
  113123. if(*y1<0)*y1=0;
  113124. }else{
  113125. *y0=0;
  113126. *y1=0;
  113127. }
  113128. }
  113129. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113130. long y=0;
  113131. int i;
  113132. for(i=0;i<fits && y==0;i++)
  113133. y+=a[i].ya;
  113134. *y0=*y1=y;
  113135. }*/
  113136. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113137. const float *mdct,
  113138. vorbis_info_floor1 *info){
  113139. int dy=y1-y0;
  113140. int adx=x1-x0;
  113141. int ady=abs(dy);
  113142. int base=dy/adx;
  113143. int sy=(dy<0?base-1:base+1);
  113144. int x=x0;
  113145. int y=y0;
  113146. int err=0;
  113147. int val=vorbis_dBquant(mask+x);
  113148. int mse=0;
  113149. int n=0;
  113150. ady-=abs(base*adx);
  113151. mse=(y-val);
  113152. mse*=mse;
  113153. n++;
  113154. if(mdct[x]+info->twofitatten>=mask[x]){
  113155. if(y+info->maxover<val)return(1);
  113156. if(y-info->maxunder>val)return(1);
  113157. }
  113158. while(++x<x1){
  113159. err=err+ady;
  113160. if(err>=adx){
  113161. err-=adx;
  113162. y+=sy;
  113163. }else{
  113164. y+=base;
  113165. }
  113166. val=vorbis_dBquant(mask+x);
  113167. mse+=((y-val)*(y-val));
  113168. n++;
  113169. if(mdct[x]+info->twofitatten>=mask[x]){
  113170. if(val){
  113171. if(y+info->maxover<val)return(1);
  113172. if(y-info->maxunder>val)return(1);
  113173. }
  113174. }
  113175. }
  113176. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113177. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113178. if(mse/n>info->maxerr)return(1);
  113179. return(0);
  113180. }
  113181. static int post_Y(int *A,int *B,int pos){
  113182. if(A[pos]<0)
  113183. return B[pos];
  113184. if(B[pos]<0)
  113185. return A[pos];
  113186. return (A[pos]+B[pos])>>1;
  113187. }
  113188. int *floor1_fit(vorbis_block *vb,void *look_,
  113189. const float *logmdct, /* in */
  113190. const float *logmask){
  113191. long i,j;
  113192. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113193. vorbis_info_floor1 *info=look->vi;
  113194. long n=look->n;
  113195. long posts=look->posts;
  113196. long nonzero=0;
  113197. lsfit_acc fits[VIF_POSIT+1];
  113198. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113199. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113200. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113201. int hineighbor[VIF_POSIT+2];
  113202. int *output=NULL;
  113203. int memo[VIF_POSIT+2];
  113204. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113205. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113206. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113207. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113208. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113209. /* quantize the relevant floor points and collect them into line fit
  113210. structures (one per minimal division) at the same time */
  113211. if(posts==0){
  113212. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113213. }else{
  113214. for(i=0;i<posts-1;i++)
  113215. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113216. look->sorted_index[i+1],fits+i,
  113217. n,info);
  113218. }
  113219. if(nonzero){
  113220. /* start by fitting the implicit base case.... */
  113221. int y0=-200;
  113222. int y1=-200;
  113223. fit_line(fits,posts-1,&y0,&y1);
  113224. fit_valueA[0]=y0;
  113225. fit_valueB[0]=y0;
  113226. fit_valueB[1]=y1;
  113227. fit_valueA[1]=y1;
  113228. /* Non degenerate case */
  113229. /* start progressive splitting. This is a greedy, non-optimal
  113230. algorithm, but simple and close enough to the best
  113231. answer. */
  113232. for(i=2;i<posts;i++){
  113233. int sortpos=look->reverse_index[i];
  113234. int ln=loneighbor[sortpos];
  113235. int hn=hineighbor[sortpos];
  113236. /* eliminate repeat searches of a particular range with a memo */
  113237. if(memo[ln]!=hn){
  113238. /* haven't performed this error search yet */
  113239. int lsortpos=look->reverse_index[ln];
  113240. int hsortpos=look->reverse_index[hn];
  113241. memo[ln]=hn;
  113242. {
  113243. /* A note: we want to bound/minimize *local*, not global, error */
  113244. int lx=info->postlist[ln];
  113245. int hx=info->postlist[hn];
  113246. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113247. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113248. if(ly==-1 || hy==-1){
  113249. exit(1);
  113250. }
  113251. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113252. /* outside error bounds/begin search area. Split it. */
  113253. int ly0=-200;
  113254. int ly1=-200;
  113255. int hy0=-200;
  113256. int hy1=-200;
  113257. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113258. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113259. /* store new edge values */
  113260. fit_valueB[ln]=ly0;
  113261. if(ln==0)fit_valueA[ln]=ly0;
  113262. fit_valueA[i]=ly1;
  113263. fit_valueB[i]=hy0;
  113264. fit_valueA[hn]=hy1;
  113265. if(hn==1)fit_valueB[hn]=hy1;
  113266. if(ly1>=0 || hy0>=0){
  113267. /* store new neighbor values */
  113268. for(j=sortpos-1;j>=0;j--)
  113269. if(hineighbor[j]==hn)
  113270. hineighbor[j]=i;
  113271. else
  113272. break;
  113273. for(j=sortpos+1;j<posts;j++)
  113274. if(loneighbor[j]==ln)
  113275. loneighbor[j]=i;
  113276. else
  113277. break;
  113278. }
  113279. }else{
  113280. fit_valueA[i]=-200;
  113281. fit_valueB[i]=-200;
  113282. }
  113283. }
  113284. }
  113285. }
  113286. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113287. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113288. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113289. /* fill in posts marked as not using a fit; we will zero
  113290. back out to 'unused' when encoding them so long as curve
  113291. interpolation doesn't force them into use */
  113292. for(i=2;i<posts;i++){
  113293. int ln=look->loneighbor[i-2];
  113294. int hn=look->hineighbor[i-2];
  113295. int x0=info->postlist[ln];
  113296. int x1=info->postlist[hn];
  113297. int y0=output[ln];
  113298. int y1=output[hn];
  113299. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113300. int vx=post_Y(fit_valueA,fit_valueB,i);
  113301. if(vx>=0 && predicted!=vx){
  113302. output[i]=vx;
  113303. }else{
  113304. output[i]= predicted|0x8000;
  113305. }
  113306. }
  113307. }
  113308. return(output);
  113309. }
  113310. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113311. int *A,int *B,
  113312. int del){
  113313. long i;
  113314. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113315. long posts=look->posts;
  113316. int *output=NULL;
  113317. if(A && B){
  113318. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113319. for(i=0;i<posts;i++){
  113320. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113321. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113322. }
  113323. }
  113324. return(output);
  113325. }
  113326. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113327. void*look_,
  113328. int *post,int *ilogmask){
  113329. long i,j;
  113330. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113331. vorbis_info_floor1 *info=look->vi;
  113332. long posts=look->posts;
  113333. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113334. int out[VIF_POSIT+2];
  113335. static_codebook **sbooks=ci->book_param;
  113336. codebook *books=ci->fullbooks;
  113337. static long seq=0;
  113338. /* quantize values to multiplier spec */
  113339. if(post){
  113340. for(i=0;i<posts;i++){
  113341. int val=post[i]&0x7fff;
  113342. switch(info->mult){
  113343. case 1: /* 1024 -> 256 */
  113344. val>>=2;
  113345. break;
  113346. case 2: /* 1024 -> 128 */
  113347. val>>=3;
  113348. break;
  113349. case 3: /* 1024 -> 86 */
  113350. val/=12;
  113351. break;
  113352. case 4: /* 1024 -> 64 */
  113353. val>>=4;
  113354. break;
  113355. }
  113356. post[i]=val | (post[i]&0x8000);
  113357. }
  113358. out[0]=post[0];
  113359. out[1]=post[1];
  113360. /* find prediction values for each post and subtract them */
  113361. for(i=2;i<posts;i++){
  113362. int ln=look->loneighbor[i-2];
  113363. int hn=look->hineighbor[i-2];
  113364. int x0=info->postlist[ln];
  113365. int x1=info->postlist[hn];
  113366. int y0=post[ln];
  113367. int y1=post[hn];
  113368. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113369. if((post[i]&0x8000) || (predicted==post[i])){
  113370. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113371. in interpolation */
  113372. out[i]=0;
  113373. }else{
  113374. int headroom=(look->quant_q-predicted<predicted?
  113375. look->quant_q-predicted:predicted);
  113376. int val=post[i]-predicted;
  113377. /* at this point the 'deviation' value is in the range +/- max
  113378. range, but the real, unique range can always be mapped to
  113379. only [0-maxrange). So we want to wrap the deviation into
  113380. this limited range, but do it in the way that least screws
  113381. an essentially gaussian probability distribution. */
  113382. if(val<0)
  113383. if(val<-headroom)
  113384. val=headroom-val-1;
  113385. else
  113386. val=-1-(val<<1);
  113387. else
  113388. if(val>=headroom)
  113389. val= val+headroom;
  113390. else
  113391. val<<=1;
  113392. out[i]=val;
  113393. post[ln]&=0x7fff;
  113394. post[hn]&=0x7fff;
  113395. }
  113396. }
  113397. /* we have everything we need. pack it out */
  113398. /* mark nontrivial floor */
  113399. oggpack_write(opb,1,1);
  113400. /* beginning/end post */
  113401. look->frames++;
  113402. look->postbits+=ilog(look->quant_q-1)*2;
  113403. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113404. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113405. /* partition by partition */
  113406. for(i=0,j=2;i<info->partitions;i++){
  113407. int classx=info->partitionclass[i];
  113408. int cdim=info->class_dim[classx];
  113409. int csubbits=info->class_subs[classx];
  113410. int csub=1<<csubbits;
  113411. int bookas[8]={0,0,0,0,0,0,0,0};
  113412. int cval=0;
  113413. int cshift=0;
  113414. int k,l;
  113415. /* generate the partition's first stage cascade value */
  113416. if(csubbits){
  113417. int maxval[8];
  113418. for(k=0;k<csub;k++){
  113419. int booknum=info->class_subbook[classx][k];
  113420. if(booknum<0){
  113421. maxval[k]=1;
  113422. }else{
  113423. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113424. }
  113425. }
  113426. for(k=0;k<cdim;k++){
  113427. for(l=0;l<csub;l++){
  113428. int val=out[j+k];
  113429. if(val<maxval[l]){
  113430. bookas[k]=l;
  113431. break;
  113432. }
  113433. }
  113434. cval|= bookas[k]<<cshift;
  113435. cshift+=csubbits;
  113436. }
  113437. /* write it */
  113438. look->phrasebits+=
  113439. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113440. #ifdef TRAIN_FLOOR1
  113441. {
  113442. FILE *of;
  113443. char buffer[80];
  113444. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113445. vb->pcmend/2,posts-2,class);
  113446. of=fopen(buffer,"a");
  113447. fprintf(of,"%d\n",cval);
  113448. fclose(of);
  113449. }
  113450. #endif
  113451. }
  113452. /* write post values */
  113453. for(k=0;k<cdim;k++){
  113454. int book=info->class_subbook[classx][bookas[k]];
  113455. if(book>=0){
  113456. /* hack to allow training with 'bad' books */
  113457. if(out[j+k]<(books+book)->entries)
  113458. look->postbits+=vorbis_book_encode(books+book,
  113459. out[j+k],opb);
  113460. /*else
  113461. fprintf(stderr,"+!");*/
  113462. #ifdef TRAIN_FLOOR1
  113463. {
  113464. FILE *of;
  113465. char buffer[80];
  113466. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113467. vb->pcmend/2,posts-2,class,bookas[k]);
  113468. of=fopen(buffer,"a");
  113469. fprintf(of,"%d\n",out[j+k]);
  113470. fclose(of);
  113471. }
  113472. #endif
  113473. }
  113474. }
  113475. j+=cdim;
  113476. }
  113477. {
  113478. /* generate quantized floor equivalent to what we'd unpack in decode */
  113479. /* render the lines */
  113480. int hx=0;
  113481. int lx=0;
  113482. int ly=post[0]*info->mult;
  113483. for(j=1;j<look->posts;j++){
  113484. int current=look->forward_index[j];
  113485. int hy=post[current]&0x7fff;
  113486. if(hy==post[current]){
  113487. hy*=info->mult;
  113488. hx=info->postlist[current];
  113489. render_line0(lx,hx,ly,hy,ilogmask);
  113490. lx=hx;
  113491. ly=hy;
  113492. }
  113493. }
  113494. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113495. seq++;
  113496. return(1);
  113497. }
  113498. }else{
  113499. oggpack_write(opb,0,1);
  113500. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113501. seq++;
  113502. return(0);
  113503. }
  113504. }
  113505. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113506. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113507. vorbis_info_floor1 *info=look->vi;
  113508. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113509. int i,j,k;
  113510. codebook *books=ci->fullbooks;
  113511. /* unpack wrapped/predicted values from stream */
  113512. if(oggpack_read(&vb->opb,1)==1){
  113513. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113514. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113515. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113516. /* partition by partition */
  113517. for(i=0,j=2;i<info->partitions;i++){
  113518. int classx=info->partitionclass[i];
  113519. int cdim=info->class_dim[classx];
  113520. int csubbits=info->class_subs[classx];
  113521. int csub=1<<csubbits;
  113522. int cval=0;
  113523. /* decode the partition's first stage cascade value */
  113524. if(csubbits){
  113525. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113526. if(cval==-1)goto eop;
  113527. }
  113528. for(k=0;k<cdim;k++){
  113529. int book=info->class_subbook[classx][cval&(csub-1)];
  113530. cval>>=csubbits;
  113531. if(book>=0){
  113532. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113533. goto eop;
  113534. }else{
  113535. fit_value[j+k]=0;
  113536. }
  113537. }
  113538. j+=cdim;
  113539. }
  113540. /* unwrap positive values and reconsitute via linear interpolation */
  113541. for(i=2;i<look->posts;i++){
  113542. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113543. info->postlist[look->hineighbor[i-2]],
  113544. fit_value[look->loneighbor[i-2]],
  113545. fit_value[look->hineighbor[i-2]],
  113546. info->postlist[i]);
  113547. int hiroom=look->quant_q-predicted;
  113548. int loroom=predicted;
  113549. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113550. int val=fit_value[i];
  113551. if(val){
  113552. if(val>=room){
  113553. if(hiroom>loroom){
  113554. val = val-loroom;
  113555. }else{
  113556. val = -1-(val-hiroom);
  113557. }
  113558. }else{
  113559. if(val&1){
  113560. val= -((val+1)>>1);
  113561. }else{
  113562. val>>=1;
  113563. }
  113564. }
  113565. fit_value[i]=val+predicted;
  113566. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113567. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113568. }else{
  113569. fit_value[i]=predicted|0x8000;
  113570. }
  113571. }
  113572. return(fit_value);
  113573. }
  113574. eop:
  113575. return(NULL);
  113576. }
  113577. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113578. float *out){
  113579. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113580. vorbis_info_floor1 *info=look->vi;
  113581. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113582. int n=ci->blocksizes[vb->W]/2;
  113583. int j;
  113584. if(memo){
  113585. /* render the lines */
  113586. int *fit_value=(int *)memo;
  113587. int hx=0;
  113588. int lx=0;
  113589. int ly=fit_value[0]*info->mult;
  113590. for(j=1;j<look->posts;j++){
  113591. int current=look->forward_index[j];
  113592. int hy=fit_value[current]&0x7fff;
  113593. if(hy==fit_value[current]){
  113594. hy*=info->mult;
  113595. hx=info->postlist[current];
  113596. render_line(lx,hx,ly,hy,out);
  113597. lx=hx;
  113598. ly=hy;
  113599. }
  113600. }
  113601. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113602. return(1);
  113603. }
  113604. memset(out,0,sizeof(*out)*n);
  113605. return(0);
  113606. }
  113607. /* export hooks */
  113608. vorbis_func_floor floor1_exportbundle={
  113609. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113610. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113611. };
  113612. #endif
  113613. /*** End of inlined file: floor1.c ***/
  113614. /*** Start of inlined file: info.c ***/
  113615. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113616. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113617. // tasks..
  113618. #if JUCE_MSVC
  113619. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113620. #endif
  113621. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113622. #if JUCE_USE_OGGVORBIS
  113623. /* general handling of the header and the vorbis_info structure (and
  113624. substructures) */
  113625. #include <stdlib.h>
  113626. #include <string.h>
  113627. #include <ctype.h>
  113628. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113629. while(bytes--){
  113630. oggpack_write(o,*s++,8);
  113631. }
  113632. }
  113633. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113634. while(bytes--){
  113635. *buf++=oggpack_read(o,8);
  113636. }
  113637. }
  113638. void vorbis_comment_init(vorbis_comment *vc){
  113639. memset(vc,0,sizeof(*vc));
  113640. }
  113641. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113642. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113643. (vc->comments+2)*sizeof(*vc->user_comments));
  113644. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113645. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113646. vc->comment_lengths[vc->comments]=strlen(comment);
  113647. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113648. strcpy(vc->user_comments[vc->comments], comment);
  113649. vc->comments++;
  113650. vc->user_comments[vc->comments]=NULL;
  113651. }
  113652. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113653. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113654. strcpy(comment, tag);
  113655. strcat(comment, "=");
  113656. strcat(comment, contents);
  113657. vorbis_comment_add(vc, comment);
  113658. }
  113659. /* This is more or less the same as strncasecmp - but that doesn't exist
  113660. * everywhere, and this is a fairly trivial function, so we include it */
  113661. static int tagcompare(const char *s1, const char *s2, int n){
  113662. int c=0;
  113663. while(c < n){
  113664. if(toupper(s1[c]) != toupper(s2[c]))
  113665. return !0;
  113666. c++;
  113667. }
  113668. return 0;
  113669. }
  113670. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113671. long i;
  113672. int found = 0;
  113673. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113674. char *fulltag = (char*)alloca(taglen+ 1);
  113675. strcpy(fulltag, tag);
  113676. strcat(fulltag, "=");
  113677. for(i=0;i<vc->comments;i++){
  113678. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113679. if(count == found)
  113680. /* We return a pointer to the data, not a copy */
  113681. return vc->user_comments[i] + taglen;
  113682. else
  113683. found++;
  113684. }
  113685. }
  113686. return NULL; /* didn't find anything */
  113687. }
  113688. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113689. int i,count=0;
  113690. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113691. char *fulltag = (char*)alloca(taglen+1);
  113692. strcpy(fulltag,tag);
  113693. strcat(fulltag, "=");
  113694. for(i=0;i<vc->comments;i++){
  113695. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113696. count++;
  113697. }
  113698. return count;
  113699. }
  113700. void vorbis_comment_clear(vorbis_comment *vc){
  113701. if(vc){
  113702. long i;
  113703. for(i=0;i<vc->comments;i++)
  113704. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113705. if(vc->user_comments)_ogg_free(vc->user_comments);
  113706. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113707. if(vc->vendor)_ogg_free(vc->vendor);
  113708. }
  113709. memset(vc,0,sizeof(*vc));
  113710. }
  113711. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113712. They may be equal, but short will never ge greater than long */
  113713. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113714. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113715. return ci ? ci->blocksizes[zo] : -1;
  113716. }
  113717. /* used by synthesis, which has a full, alloced vi */
  113718. void vorbis_info_init(vorbis_info *vi){
  113719. memset(vi,0,sizeof(*vi));
  113720. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113721. }
  113722. void vorbis_info_clear(vorbis_info *vi){
  113723. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113724. int i;
  113725. if(ci){
  113726. for(i=0;i<ci->modes;i++)
  113727. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113728. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113729. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113730. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113731. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113732. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113733. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113734. for(i=0;i<ci->books;i++){
  113735. if(ci->book_param[i]){
  113736. /* knows if the book was not alloced */
  113737. vorbis_staticbook_destroy(ci->book_param[i]);
  113738. }
  113739. if(ci->fullbooks)
  113740. vorbis_book_clear(ci->fullbooks+i);
  113741. }
  113742. if(ci->fullbooks)
  113743. _ogg_free(ci->fullbooks);
  113744. for(i=0;i<ci->psys;i++)
  113745. _vi_psy_free(ci->psy_param[i]);
  113746. _ogg_free(ci);
  113747. }
  113748. memset(vi,0,sizeof(*vi));
  113749. }
  113750. /* Header packing/unpacking ********************************************/
  113751. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113752. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113753. if(!ci)return(OV_EFAULT);
  113754. vi->version=oggpack_read(opb,32);
  113755. if(vi->version!=0)return(OV_EVERSION);
  113756. vi->channels=oggpack_read(opb,8);
  113757. vi->rate=oggpack_read(opb,32);
  113758. vi->bitrate_upper=oggpack_read(opb,32);
  113759. vi->bitrate_nominal=oggpack_read(opb,32);
  113760. vi->bitrate_lower=oggpack_read(opb,32);
  113761. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113762. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113763. if(vi->rate<1)goto err_out;
  113764. if(vi->channels<1)goto err_out;
  113765. if(ci->blocksizes[0]<8)goto err_out;
  113766. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113767. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113768. return(0);
  113769. err_out:
  113770. vorbis_info_clear(vi);
  113771. return(OV_EBADHEADER);
  113772. }
  113773. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113774. int i;
  113775. int vendorlen=oggpack_read(opb,32);
  113776. if(vendorlen<0)goto err_out;
  113777. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113778. _v_readstring(opb,vc->vendor,vendorlen);
  113779. vc->comments=oggpack_read(opb,32);
  113780. if(vc->comments<0)goto err_out;
  113781. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113782. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113783. for(i=0;i<vc->comments;i++){
  113784. int len=oggpack_read(opb,32);
  113785. if(len<0)goto err_out;
  113786. vc->comment_lengths[i]=len;
  113787. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113788. _v_readstring(opb,vc->user_comments[i],len);
  113789. }
  113790. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113791. return(0);
  113792. err_out:
  113793. vorbis_comment_clear(vc);
  113794. return(OV_EBADHEADER);
  113795. }
  113796. /* all of the real encoding details are here. The modes, books,
  113797. everything */
  113798. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113799. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113800. int i;
  113801. if(!ci)return(OV_EFAULT);
  113802. /* codebooks */
  113803. ci->books=oggpack_read(opb,8)+1;
  113804. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113805. for(i=0;i<ci->books;i++){
  113806. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113807. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113808. }
  113809. /* time backend settings; hooks are unused */
  113810. {
  113811. int times=oggpack_read(opb,6)+1;
  113812. for(i=0;i<times;i++){
  113813. int test=oggpack_read(opb,16);
  113814. if(test<0 || test>=VI_TIMEB)goto err_out;
  113815. }
  113816. }
  113817. /* floor backend settings */
  113818. ci->floors=oggpack_read(opb,6)+1;
  113819. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113820. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113821. for(i=0;i<ci->floors;i++){
  113822. ci->floor_type[i]=oggpack_read(opb,16);
  113823. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113824. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113825. if(!ci->floor_param[i])goto err_out;
  113826. }
  113827. /* residue backend settings */
  113828. ci->residues=oggpack_read(opb,6)+1;
  113829. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113830. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113831. for(i=0;i<ci->residues;i++){
  113832. ci->residue_type[i]=oggpack_read(opb,16);
  113833. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113834. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113835. if(!ci->residue_param[i])goto err_out;
  113836. }
  113837. /* map backend settings */
  113838. ci->maps=oggpack_read(opb,6)+1;
  113839. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113840. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113841. for(i=0;i<ci->maps;i++){
  113842. ci->map_type[i]=oggpack_read(opb,16);
  113843. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113844. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113845. if(!ci->map_param[i])goto err_out;
  113846. }
  113847. /* mode settings */
  113848. ci->modes=oggpack_read(opb,6)+1;
  113849. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113850. for(i=0;i<ci->modes;i++){
  113851. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113852. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113853. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113854. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113855. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113856. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113857. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113858. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113859. }
  113860. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113861. return(0);
  113862. err_out:
  113863. vorbis_info_clear(vi);
  113864. return(OV_EBADHEADER);
  113865. }
  113866. /* The Vorbis header is in three packets; the initial small packet in
  113867. the first page that identifies basic parameters, a second packet
  113868. with bitstream comments and a third packet that holds the
  113869. codebook. */
  113870. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113871. oggpack_buffer opb;
  113872. if(op){
  113873. oggpack_readinit(&opb,op->packet,op->bytes);
  113874. /* Which of the three types of header is this? */
  113875. /* Also verify header-ness, vorbis */
  113876. {
  113877. char buffer[6];
  113878. int packtype=oggpack_read(&opb,8);
  113879. memset(buffer,0,6);
  113880. _v_readstring(&opb,buffer,6);
  113881. if(memcmp(buffer,"vorbis",6)){
  113882. /* not a vorbis header */
  113883. return(OV_ENOTVORBIS);
  113884. }
  113885. switch(packtype){
  113886. case 0x01: /* least significant *bit* is read first */
  113887. if(!op->b_o_s){
  113888. /* Not the initial packet */
  113889. return(OV_EBADHEADER);
  113890. }
  113891. if(vi->rate!=0){
  113892. /* previously initialized info header */
  113893. return(OV_EBADHEADER);
  113894. }
  113895. return(_vorbis_unpack_info(vi,&opb));
  113896. case 0x03: /* least significant *bit* is read first */
  113897. if(vi->rate==0){
  113898. /* um... we didn't get the initial header */
  113899. return(OV_EBADHEADER);
  113900. }
  113901. return(_vorbis_unpack_comment(vc,&opb));
  113902. case 0x05: /* least significant *bit* is read first */
  113903. if(vi->rate==0 || vc->vendor==NULL){
  113904. /* um... we didn;t get the initial header or comments yet */
  113905. return(OV_EBADHEADER);
  113906. }
  113907. return(_vorbis_unpack_books(vi,&opb));
  113908. default:
  113909. /* Not a valid vorbis header type */
  113910. return(OV_EBADHEADER);
  113911. break;
  113912. }
  113913. }
  113914. }
  113915. return(OV_EBADHEADER);
  113916. }
  113917. /* pack side **********************************************************/
  113918. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113919. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113920. if(!ci)return(OV_EFAULT);
  113921. /* preamble */
  113922. oggpack_write(opb,0x01,8);
  113923. _v_writestring(opb,"vorbis", 6);
  113924. /* basic information about the stream */
  113925. oggpack_write(opb,0x00,32);
  113926. oggpack_write(opb,vi->channels,8);
  113927. oggpack_write(opb,vi->rate,32);
  113928. oggpack_write(opb,vi->bitrate_upper,32);
  113929. oggpack_write(opb,vi->bitrate_nominal,32);
  113930. oggpack_write(opb,vi->bitrate_lower,32);
  113931. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113932. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113933. oggpack_write(opb,1,1);
  113934. return(0);
  113935. }
  113936. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113937. char temp[]="Xiph.Org libVorbis I 20050304";
  113938. int bytes = strlen(temp);
  113939. /* preamble */
  113940. oggpack_write(opb,0x03,8);
  113941. _v_writestring(opb,"vorbis", 6);
  113942. /* vendor */
  113943. oggpack_write(opb,bytes,32);
  113944. _v_writestring(opb,temp, bytes);
  113945. /* comments */
  113946. oggpack_write(opb,vc->comments,32);
  113947. if(vc->comments){
  113948. int i;
  113949. for(i=0;i<vc->comments;i++){
  113950. if(vc->user_comments[i]){
  113951. oggpack_write(opb,vc->comment_lengths[i],32);
  113952. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113953. }else{
  113954. oggpack_write(opb,0,32);
  113955. }
  113956. }
  113957. }
  113958. oggpack_write(opb,1,1);
  113959. return(0);
  113960. }
  113961. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113962. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113963. int i;
  113964. if(!ci)return(OV_EFAULT);
  113965. oggpack_write(opb,0x05,8);
  113966. _v_writestring(opb,"vorbis", 6);
  113967. /* books */
  113968. oggpack_write(opb,ci->books-1,8);
  113969. for(i=0;i<ci->books;i++)
  113970. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113971. /* times; hook placeholders */
  113972. oggpack_write(opb,0,6);
  113973. oggpack_write(opb,0,16);
  113974. /* floors */
  113975. oggpack_write(opb,ci->floors-1,6);
  113976. for(i=0;i<ci->floors;i++){
  113977. oggpack_write(opb,ci->floor_type[i],16);
  113978. if(_floor_P[ci->floor_type[i]]->pack)
  113979. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113980. else
  113981. goto err_out;
  113982. }
  113983. /* residues */
  113984. oggpack_write(opb,ci->residues-1,6);
  113985. for(i=0;i<ci->residues;i++){
  113986. oggpack_write(opb,ci->residue_type[i],16);
  113987. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113988. }
  113989. /* maps */
  113990. oggpack_write(opb,ci->maps-1,6);
  113991. for(i=0;i<ci->maps;i++){
  113992. oggpack_write(opb,ci->map_type[i],16);
  113993. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113994. }
  113995. /* modes */
  113996. oggpack_write(opb,ci->modes-1,6);
  113997. for(i=0;i<ci->modes;i++){
  113998. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113999. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114000. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114001. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114002. }
  114003. oggpack_write(opb,1,1);
  114004. return(0);
  114005. err_out:
  114006. return(-1);
  114007. }
  114008. int vorbis_commentheader_out(vorbis_comment *vc,
  114009. ogg_packet *op){
  114010. oggpack_buffer opb;
  114011. oggpack_writeinit(&opb);
  114012. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114013. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114014. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114015. op->bytes=oggpack_bytes(&opb);
  114016. op->b_o_s=0;
  114017. op->e_o_s=0;
  114018. op->granulepos=0;
  114019. op->packetno=1;
  114020. return 0;
  114021. }
  114022. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114023. vorbis_comment *vc,
  114024. ogg_packet *op,
  114025. ogg_packet *op_comm,
  114026. ogg_packet *op_code){
  114027. int ret=OV_EIMPL;
  114028. vorbis_info *vi=v->vi;
  114029. oggpack_buffer opb;
  114030. private_state *b=(private_state*)v->backend_state;
  114031. if(!b){
  114032. ret=OV_EFAULT;
  114033. goto err_out;
  114034. }
  114035. /* first header packet **********************************************/
  114036. oggpack_writeinit(&opb);
  114037. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114038. /* build the packet */
  114039. if(b->header)_ogg_free(b->header);
  114040. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114041. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114042. op->packet=b->header;
  114043. op->bytes=oggpack_bytes(&opb);
  114044. op->b_o_s=1;
  114045. op->e_o_s=0;
  114046. op->granulepos=0;
  114047. op->packetno=0;
  114048. /* second header packet (comments) **********************************/
  114049. oggpack_reset(&opb);
  114050. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114051. if(b->header1)_ogg_free(b->header1);
  114052. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114053. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114054. op_comm->packet=b->header1;
  114055. op_comm->bytes=oggpack_bytes(&opb);
  114056. op_comm->b_o_s=0;
  114057. op_comm->e_o_s=0;
  114058. op_comm->granulepos=0;
  114059. op_comm->packetno=1;
  114060. /* third header packet (modes/codebooks) ****************************/
  114061. oggpack_reset(&opb);
  114062. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114063. if(b->header2)_ogg_free(b->header2);
  114064. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114065. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114066. op_code->packet=b->header2;
  114067. op_code->bytes=oggpack_bytes(&opb);
  114068. op_code->b_o_s=0;
  114069. op_code->e_o_s=0;
  114070. op_code->granulepos=0;
  114071. op_code->packetno=2;
  114072. oggpack_writeclear(&opb);
  114073. return(0);
  114074. err_out:
  114075. oggpack_writeclear(&opb);
  114076. memset(op,0,sizeof(*op));
  114077. memset(op_comm,0,sizeof(*op_comm));
  114078. memset(op_code,0,sizeof(*op_code));
  114079. if(b->header)_ogg_free(b->header);
  114080. if(b->header1)_ogg_free(b->header1);
  114081. if(b->header2)_ogg_free(b->header2);
  114082. b->header=NULL;
  114083. b->header1=NULL;
  114084. b->header2=NULL;
  114085. return(ret);
  114086. }
  114087. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114088. if(granulepos>=0)
  114089. return((double)granulepos/v->vi->rate);
  114090. return(-1);
  114091. }
  114092. #endif
  114093. /*** End of inlined file: info.c ***/
  114094. /*** Start of inlined file: lpc.c ***/
  114095. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114096. are derived from code written by Jutta Degener and Carsten Bormann;
  114097. thus we include their copyright below. The entirety of this file
  114098. is freely redistributable on the condition that both of these
  114099. copyright notices are preserved without modification. */
  114100. /* Preserved Copyright: *********************************************/
  114101. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114102. Technische Universita"t Berlin
  114103. Any use of this software is permitted provided that this notice is not
  114104. removed and that neither the authors nor the Technische Universita"t
  114105. Berlin are deemed to have made any representations as to the
  114106. suitability of this software for any purpose nor are held responsible
  114107. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114108. THIS SOFTWARE.
  114109. As a matter of courtesy, the authors request to be informed about uses
  114110. this software has found, about bugs in this software, and about any
  114111. improvements that may be of general interest.
  114112. Berlin, 28.11.1994
  114113. Jutta Degener
  114114. Carsten Bormann
  114115. *********************************************************************/
  114116. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114117. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114118. // tasks..
  114119. #if JUCE_MSVC
  114120. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114121. #endif
  114122. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114123. #if JUCE_USE_OGGVORBIS
  114124. #include <stdlib.h>
  114125. #include <string.h>
  114126. #include <math.h>
  114127. /* Autocorrelation LPC coeff generation algorithm invented by
  114128. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114129. /* Input : n elements of time doamin data
  114130. Output: m lpc coefficients, excitation energy */
  114131. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114132. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114133. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114134. double error;
  114135. int i,j;
  114136. /* autocorrelation, p+1 lag coefficients */
  114137. j=m+1;
  114138. while(j--){
  114139. double d=0; /* double needed for accumulator depth */
  114140. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114141. aut[j]=d;
  114142. }
  114143. /* Generate lpc coefficients from autocorr values */
  114144. error=aut[0];
  114145. for(i=0;i<m;i++){
  114146. double r= -aut[i+1];
  114147. if(error==0){
  114148. memset(lpci,0,m*sizeof(*lpci));
  114149. return 0;
  114150. }
  114151. /* Sum up this iteration's reflection coefficient; note that in
  114152. Vorbis we don't save it. If anyone wants to recycle this code
  114153. and needs reflection coefficients, save the results of 'r' from
  114154. each iteration. */
  114155. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114156. r/=error;
  114157. /* Update LPC coefficients and total error */
  114158. lpc[i]=r;
  114159. for(j=0;j<i/2;j++){
  114160. double tmp=lpc[j];
  114161. lpc[j]+=r*lpc[i-1-j];
  114162. lpc[i-1-j]+=r*tmp;
  114163. }
  114164. if(i%2)lpc[j]+=lpc[j]*r;
  114165. error*=1.f-r*r;
  114166. }
  114167. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114168. /* we need the error value to know how big an impulse to hit the
  114169. filter with later */
  114170. return error;
  114171. }
  114172. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114173. float *data,long n){
  114174. /* in: coeff[0...m-1] LPC coefficients
  114175. prime[0...m-1] initial values (allocated size of n+m-1)
  114176. out: data[0...n-1] data samples */
  114177. long i,j,o,p;
  114178. float y;
  114179. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114180. if(!prime)
  114181. for(i=0;i<m;i++)
  114182. work[i]=0.f;
  114183. else
  114184. for(i=0;i<m;i++)
  114185. work[i]=prime[i];
  114186. for(i=0;i<n;i++){
  114187. y=0;
  114188. o=i;
  114189. p=m;
  114190. for(j=0;j<m;j++)
  114191. y-=work[o++]*coeff[--p];
  114192. data[i]=work[o]=y;
  114193. }
  114194. }
  114195. #endif
  114196. /*** End of inlined file: lpc.c ***/
  114197. /*** Start of inlined file: lsp.c ***/
  114198. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114199. an iterative root polisher (CACM algorithm 283). It *is* possible
  114200. to confuse this algorithm into not converging; that should only
  114201. happen with absurdly closely spaced roots (very sharp peaks in the
  114202. LPC f response) which in turn should be impossible in our use of
  114203. the code. If this *does* happen anyway, it's a bug in the floor
  114204. finder; find the cause of the confusion (probably a single bin
  114205. spike or accidental near-float-limit resolution problems) and
  114206. correct it. */
  114207. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114208. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114209. // tasks..
  114210. #if JUCE_MSVC
  114211. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114212. #endif
  114213. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114214. #if JUCE_USE_OGGVORBIS
  114215. #include <math.h>
  114216. #include <string.h>
  114217. #include <stdlib.h>
  114218. /*** Start of inlined file: lookup.h ***/
  114219. #ifndef _V_LOOKUP_H_
  114220. #ifdef FLOAT_LOOKUP
  114221. extern float vorbis_coslook(float a);
  114222. extern float vorbis_invsqlook(float a);
  114223. extern float vorbis_invsq2explook(int a);
  114224. extern float vorbis_fromdBlook(float a);
  114225. #endif
  114226. #ifdef INT_LOOKUP
  114227. extern long vorbis_invsqlook_i(long a,long e);
  114228. extern long vorbis_coslook_i(long a);
  114229. extern float vorbis_fromdBlook_i(long a);
  114230. #endif
  114231. #endif
  114232. /*** End of inlined file: lookup.h ***/
  114233. /* three possible LSP to f curve functions; the exact computation
  114234. (float), a lookup based float implementation, and an integer
  114235. implementation. The float lookup is likely the optimal choice on
  114236. any machine with an FPU. The integer implementation is *not* fixed
  114237. point (due to the need for a large dynamic range and thus a
  114238. seperately tracked exponent) and thus much more complex than the
  114239. relatively simple float implementations. It's mostly for future
  114240. work on a fully fixed point implementation for processors like the
  114241. ARM family. */
  114242. /* undefine both for the 'old' but more precise implementation */
  114243. #define FLOAT_LOOKUP
  114244. #undef INT_LOOKUP
  114245. #ifdef FLOAT_LOOKUP
  114246. /*** Start of inlined file: lookup.c ***/
  114247. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114248. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114249. // tasks..
  114250. #if JUCE_MSVC
  114251. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114252. #endif
  114253. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114254. #if JUCE_USE_OGGVORBIS
  114255. #include <math.h>
  114256. /*** Start of inlined file: lookup.h ***/
  114257. #ifndef _V_LOOKUP_H_
  114258. #ifdef FLOAT_LOOKUP
  114259. extern float vorbis_coslook(float a);
  114260. extern float vorbis_invsqlook(float a);
  114261. extern float vorbis_invsq2explook(int a);
  114262. extern float vorbis_fromdBlook(float a);
  114263. #endif
  114264. #ifdef INT_LOOKUP
  114265. extern long vorbis_invsqlook_i(long a,long e);
  114266. extern long vorbis_coslook_i(long a);
  114267. extern float vorbis_fromdBlook_i(long a);
  114268. #endif
  114269. #endif
  114270. /*** End of inlined file: lookup.h ***/
  114271. /*** Start of inlined file: lookup_data.h ***/
  114272. #ifndef _V_LOOKUP_DATA_H_
  114273. #ifdef FLOAT_LOOKUP
  114274. #define COS_LOOKUP_SZ 128
  114275. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114276. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114277. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114278. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114279. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114280. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114281. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114282. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114283. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114284. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114285. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114286. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114287. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114288. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114289. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114290. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114291. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114292. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114293. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114294. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114295. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114296. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114297. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114298. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114299. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114300. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114301. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114302. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114303. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114304. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114305. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114306. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114307. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114308. -1.0000000000000f,
  114309. };
  114310. #define INVSQ_LOOKUP_SZ 32
  114311. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114312. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114313. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114314. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114315. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114316. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114317. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114318. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114319. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114320. 1.000000000000f,
  114321. };
  114322. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114323. #define INVSQ2EXP_LOOKUP_MAX 32
  114324. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114325. INVSQ2EXP_LOOKUP_MIN+1]={
  114326. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114327. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114328. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114329. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114330. 256.f, 181.019336f, 128.f, 90.50966799f,
  114331. 64.f, 45.254834f, 32.f, 22.627417f,
  114332. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114333. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114334. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114335. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114336. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114337. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114338. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114339. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114340. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114341. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114342. 1.525878906e-05f,
  114343. };
  114344. #endif
  114345. #define FROMdB_LOOKUP_SZ 35
  114346. #define FROMdB2_LOOKUP_SZ 32
  114347. #define FROMdB_SHIFT 5
  114348. #define FROMdB2_SHIFT 3
  114349. #define FROMdB2_MASK 31
  114350. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114351. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114352. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114353. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114354. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114355. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114356. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114357. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114358. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114359. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114360. };
  114361. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114362. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114363. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114364. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114365. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114366. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114367. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114368. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114369. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114370. };
  114371. #ifdef INT_LOOKUP
  114372. #define INVSQ_LOOKUP_I_SHIFT 10
  114373. #define INVSQ_LOOKUP_I_MASK 1023
  114374. static long INVSQ_LOOKUP_I[64+1]={
  114375. 92682l, 91966l, 91267l, 90583l,
  114376. 89915l, 89261l, 88621l, 87995l,
  114377. 87381l, 86781l, 86192l, 85616l,
  114378. 85051l, 84497l, 83953l, 83420l,
  114379. 82897l, 82384l, 81880l, 81385l,
  114380. 80899l, 80422l, 79953l, 79492l,
  114381. 79039l, 78594l, 78156l, 77726l,
  114382. 77302l, 76885l, 76475l, 76072l,
  114383. 75674l, 75283l, 74898l, 74519l,
  114384. 74146l, 73778l, 73415l, 73058l,
  114385. 72706l, 72359l, 72016l, 71679l,
  114386. 71347l, 71019l, 70695l, 70376l,
  114387. 70061l, 69750l, 69444l, 69141l,
  114388. 68842l, 68548l, 68256l, 67969l,
  114389. 67685l, 67405l, 67128l, 66855l,
  114390. 66585l, 66318l, 66054l, 65794l,
  114391. 65536l,
  114392. };
  114393. #define COS_LOOKUP_I_SHIFT 9
  114394. #define COS_LOOKUP_I_MASK 511
  114395. #define COS_LOOKUP_I_SZ 128
  114396. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114397. 16384l, 16379l, 16364l, 16340l,
  114398. 16305l, 16261l, 16207l, 16143l,
  114399. 16069l, 15986l, 15893l, 15791l,
  114400. 15679l, 15557l, 15426l, 15286l,
  114401. 15137l, 14978l, 14811l, 14635l,
  114402. 14449l, 14256l, 14053l, 13842l,
  114403. 13623l, 13395l, 13160l, 12916l,
  114404. 12665l, 12406l, 12140l, 11866l,
  114405. 11585l, 11297l, 11003l, 10702l,
  114406. 10394l, 10080l, 9760l, 9434l,
  114407. 9102l, 8765l, 8423l, 8076l,
  114408. 7723l, 7366l, 7005l, 6639l,
  114409. 6270l, 5897l, 5520l, 5139l,
  114410. 4756l, 4370l, 3981l, 3590l,
  114411. 3196l, 2801l, 2404l, 2006l,
  114412. 1606l, 1205l, 804l, 402l,
  114413. 0l, -401l, -803l, -1204l,
  114414. -1605l, -2005l, -2403l, -2800l,
  114415. -3195l, -3589l, -3980l, -4369l,
  114416. -4755l, -5138l, -5519l, -5896l,
  114417. -6269l, -6638l, -7004l, -7365l,
  114418. -7722l, -8075l, -8422l, -8764l,
  114419. -9101l, -9433l, -9759l, -10079l,
  114420. -10393l, -10701l, -11002l, -11296l,
  114421. -11584l, -11865l, -12139l, -12405l,
  114422. -12664l, -12915l, -13159l, -13394l,
  114423. -13622l, -13841l, -14052l, -14255l,
  114424. -14448l, -14634l, -14810l, -14977l,
  114425. -15136l, -15285l, -15425l, -15556l,
  114426. -15678l, -15790l, -15892l, -15985l,
  114427. -16068l, -16142l, -16206l, -16260l,
  114428. -16304l, -16339l, -16363l, -16378l,
  114429. -16383l,
  114430. };
  114431. #endif
  114432. #endif
  114433. /*** End of inlined file: lookup_data.h ***/
  114434. #ifdef FLOAT_LOOKUP
  114435. /* interpolated lookup based cos function, domain 0 to PI only */
  114436. float vorbis_coslook(float a){
  114437. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114438. int i=vorbis_ftoi(d-.5);
  114439. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114440. }
  114441. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114442. float vorbis_invsqlook(float a){
  114443. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114444. int i=vorbis_ftoi(d-.5f);
  114445. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114446. }
  114447. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114448. float vorbis_invsq2explook(int a){
  114449. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114450. }
  114451. #include <stdio.h>
  114452. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114453. float vorbis_fromdBlook(float a){
  114454. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114455. return (i<0)?1.f:
  114456. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114457. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114458. }
  114459. #endif
  114460. #ifdef INT_LOOKUP
  114461. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114462. 16.16 format
  114463. returns in m.8 format */
  114464. long vorbis_invsqlook_i(long a,long e){
  114465. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114466. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114467. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114468. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114469. d)>>16); /* result 1.16 */
  114470. e+=32;
  114471. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114472. e=(e>>1)-8;
  114473. return(val>>e);
  114474. }
  114475. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114476. /* a is in n.12 format */
  114477. float vorbis_fromdBlook_i(long a){
  114478. int i=(-a)>>(12-FROMdB2_SHIFT);
  114479. return (i<0)?1.f:
  114480. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114481. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114482. }
  114483. /* interpolated lookup based cos function, domain 0 to PI only */
  114484. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114485. long vorbis_coslook_i(long a){
  114486. int i=a>>COS_LOOKUP_I_SHIFT;
  114487. int d=a&COS_LOOKUP_I_MASK;
  114488. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114489. COS_LOOKUP_I_SHIFT);
  114490. }
  114491. #endif
  114492. #endif
  114493. /*** End of inlined file: lookup.c ***/
  114494. /* catch this in the build system; we #include for
  114495. compilers (like gcc) that can't inline across
  114496. modules */
  114497. /* side effect: changes *lsp to cosines of lsp */
  114498. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114499. float amp,float ampoffset){
  114500. int i;
  114501. float wdel=M_PI/ln;
  114502. vorbis_fpu_control fpu;
  114503. (void) fpu; // to avoid an unused variable warning
  114504. vorbis_fpu_setround(&fpu);
  114505. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114506. i=0;
  114507. while(i<n){
  114508. int k=map[i];
  114509. int qexp;
  114510. float p=.7071067812f;
  114511. float q=.7071067812f;
  114512. float w=vorbis_coslook(wdel*k);
  114513. float *ftmp=lsp;
  114514. int c=m>>1;
  114515. do{
  114516. q*=ftmp[0]-w;
  114517. p*=ftmp[1]-w;
  114518. ftmp+=2;
  114519. }while(--c);
  114520. if(m&1){
  114521. /* odd order filter; slightly assymetric */
  114522. /* the last coefficient */
  114523. q*=ftmp[0]-w;
  114524. q*=q;
  114525. p*=p*(1.f-w*w);
  114526. }else{
  114527. /* even order filter; still symmetric */
  114528. q*=q*(1.f+w);
  114529. p*=p*(1.f-w);
  114530. }
  114531. q=frexp(p+q,&qexp);
  114532. q=vorbis_fromdBlook(amp*
  114533. vorbis_invsqlook(q)*
  114534. vorbis_invsq2explook(qexp+m)-
  114535. ampoffset);
  114536. do{
  114537. curve[i++]*=q;
  114538. }while(map[i]==k);
  114539. }
  114540. vorbis_fpu_restore(fpu);
  114541. }
  114542. #else
  114543. #ifdef INT_LOOKUP
  114544. /*** Start of inlined file: lookup.c ***/
  114545. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114546. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114547. // tasks..
  114548. #if JUCE_MSVC
  114549. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114550. #endif
  114551. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114552. #if JUCE_USE_OGGVORBIS
  114553. #include <math.h>
  114554. /*** Start of inlined file: lookup.h ***/
  114555. #ifndef _V_LOOKUP_H_
  114556. #ifdef FLOAT_LOOKUP
  114557. extern float vorbis_coslook(float a);
  114558. extern float vorbis_invsqlook(float a);
  114559. extern float vorbis_invsq2explook(int a);
  114560. extern float vorbis_fromdBlook(float a);
  114561. #endif
  114562. #ifdef INT_LOOKUP
  114563. extern long vorbis_invsqlook_i(long a,long e);
  114564. extern long vorbis_coslook_i(long a);
  114565. extern float vorbis_fromdBlook_i(long a);
  114566. #endif
  114567. #endif
  114568. /*** End of inlined file: lookup.h ***/
  114569. /*** Start of inlined file: lookup_data.h ***/
  114570. #ifndef _V_LOOKUP_DATA_H_
  114571. #ifdef FLOAT_LOOKUP
  114572. #define COS_LOOKUP_SZ 128
  114573. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114574. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114575. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114576. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114577. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114578. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114579. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114580. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114581. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114582. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114583. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114584. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114585. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114586. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114587. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114588. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114589. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114590. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114591. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114592. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114593. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114594. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114595. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114596. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114597. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114598. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114599. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114600. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114601. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114602. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114603. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114604. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114605. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114606. -1.0000000000000f,
  114607. };
  114608. #define INVSQ_LOOKUP_SZ 32
  114609. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114610. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114611. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114612. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114613. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114614. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114615. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114616. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114617. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114618. 1.000000000000f,
  114619. };
  114620. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114621. #define INVSQ2EXP_LOOKUP_MAX 32
  114622. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114623. INVSQ2EXP_LOOKUP_MIN+1]={
  114624. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114625. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114626. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114627. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114628. 256.f, 181.019336f, 128.f, 90.50966799f,
  114629. 64.f, 45.254834f, 32.f, 22.627417f,
  114630. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114631. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114632. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114633. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114634. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114635. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114636. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114637. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114638. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114639. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114640. 1.525878906e-05f,
  114641. };
  114642. #endif
  114643. #define FROMdB_LOOKUP_SZ 35
  114644. #define FROMdB2_LOOKUP_SZ 32
  114645. #define FROMdB_SHIFT 5
  114646. #define FROMdB2_SHIFT 3
  114647. #define FROMdB2_MASK 31
  114648. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114649. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114650. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114651. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114652. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114653. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114654. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114655. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114656. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114657. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114658. };
  114659. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114660. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114661. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114662. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114663. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114664. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114665. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114666. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114667. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114668. };
  114669. #ifdef INT_LOOKUP
  114670. #define INVSQ_LOOKUP_I_SHIFT 10
  114671. #define INVSQ_LOOKUP_I_MASK 1023
  114672. static long INVSQ_LOOKUP_I[64+1]={
  114673. 92682l, 91966l, 91267l, 90583l,
  114674. 89915l, 89261l, 88621l, 87995l,
  114675. 87381l, 86781l, 86192l, 85616l,
  114676. 85051l, 84497l, 83953l, 83420l,
  114677. 82897l, 82384l, 81880l, 81385l,
  114678. 80899l, 80422l, 79953l, 79492l,
  114679. 79039l, 78594l, 78156l, 77726l,
  114680. 77302l, 76885l, 76475l, 76072l,
  114681. 75674l, 75283l, 74898l, 74519l,
  114682. 74146l, 73778l, 73415l, 73058l,
  114683. 72706l, 72359l, 72016l, 71679l,
  114684. 71347l, 71019l, 70695l, 70376l,
  114685. 70061l, 69750l, 69444l, 69141l,
  114686. 68842l, 68548l, 68256l, 67969l,
  114687. 67685l, 67405l, 67128l, 66855l,
  114688. 66585l, 66318l, 66054l, 65794l,
  114689. 65536l,
  114690. };
  114691. #define COS_LOOKUP_I_SHIFT 9
  114692. #define COS_LOOKUP_I_MASK 511
  114693. #define COS_LOOKUP_I_SZ 128
  114694. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114695. 16384l, 16379l, 16364l, 16340l,
  114696. 16305l, 16261l, 16207l, 16143l,
  114697. 16069l, 15986l, 15893l, 15791l,
  114698. 15679l, 15557l, 15426l, 15286l,
  114699. 15137l, 14978l, 14811l, 14635l,
  114700. 14449l, 14256l, 14053l, 13842l,
  114701. 13623l, 13395l, 13160l, 12916l,
  114702. 12665l, 12406l, 12140l, 11866l,
  114703. 11585l, 11297l, 11003l, 10702l,
  114704. 10394l, 10080l, 9760l, 9434l,
  114705. 9102l, 8765l, 8423l, 8076l,
  114706. 7723l, 7366l, 7005l, 6639l,
  114707. 6270l, 5897l, 5520l, 5139l,
  114708. 4756l, 4370l, 3981l, 3590l,
  114709. 3196l, 2801l, 2404l, 2006l,
  114710. 1606l, 1205l, 804l, 402l,
  114711. 0l, -401l, -803l, -1204l,
  114712. -1605l, -2005l, -2403l, -2800l,
  114713. -3195l, -3589l, -3980l, -4369l,
  114714. -4755l, -5138l, -5519l, -5896l,
  114715. -6269l, -6638l, -7004l, -7365l,
  114716. -7722l, -8075l, -8422l, -8764l,
  114717. -9101l, -9433l, -9759l, -10079l,
  114718. -10393l, -10701l, -11002l, -11296l,
  114719. -11584l, -11865l, -12139l, -12405l,
  114720. -12664l, -12915l, -13159l, -13394l,
  114721. -13622l, -13841l, -14052l, -14255l,
  114722. -14448l, -14634l, -14810l, -14977l,
  114723. -15136l, -15285l, -15425l, -15556l,
  114724. -15678l, -15790l, -15892l, -15985l,
  114725. -16068l, -16142l, -16206l, -16260l,
  114726. -16304l, -16339l, -16363l, -16378l,
  114727. -16383l,
  114728. };
  114729. #endif
  114730. #endif
  114731. /*** End of inlined file: lookup_data.h ***/
  114732. #ifdef FLOAT_LOOKUP
  114733. /* interpolated lookup based cos function, domain 0 to PI only */
  114734. float vorbis_coslook(float a){
  114735. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114736. int i=vorbis_ftoi(d-.5);
  114737. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114738. }
  114739. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114740. float vorbis_invsqlook(float a){
  114741. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114742. int i=vorbis_ftoi(d-.5f);
  114743. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114744. }
  114745. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114746. float vorbis_invsq2explook(int a){
  114747. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114748. }
  114749. #include <stdio.h>
  114750. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114751. float vorbis_fromdBlook(float a){
  114752. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114753. return (i<0)?1.f:
  114754. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114755. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114756. }
  114757. #endif
  114758. #ifdef INT_LOOKUP
  114759. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114760. 16.16 format
  114761. returns in m.8 format */
  114762. long vorbis_invsqlook_i(long a,long e){
  114763. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114764. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114765. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114766. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114767. d)>>16); /* result 1.16 */
  114768. e+=32;
  114769. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114770. e=(e>>1)-8;
  114771. return(val>>e);
  114772. }
  114773. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114774. /* a is in n.12 format */
  114775. float vorbis_fromdBlook_i(long a){
  114776. int i=(-a)>>(12-FROMdB2_SHIFT);
  114777. return (i<0)?1.f:
  114778. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114779. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114780. }
  114781. /* interpolated lookup based cos function, domain 0 to PI only */
  114782. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114783. long vorbis_coslook_i(long a){
  114784. int i=a>>COS_LOOKUP_I_SHIFT;
  114785. int d=a&COS_LOOKUP_I_MASK;
  114786. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114787. COS_LOOKUP_I_SHIFT);
  114788. }
  114789. #endif
  114790. #endif
  114791. /*** End of inlined file: lookup.c ***/
  114792. /* catch this in the build system; we #include for
  114793. compilers (like gcc) that can't inline across
  114794. modules */
  114795. static int MLOOP_1[64]={
  114796. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114797. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114798. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114799. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114800. };
  114801. static int MLOOP_2[64]={
  114802. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114803. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114804. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114805. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114806. };
  114807. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114808. /* side effect: changes *lsp to cosines of lsp */
  114809. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114810. float amp,float ampoffset){
  114811. /* 0 <= m < 256 */
  114812. /* set up for using all int later */
  114813. int i;
  114814. int ampoffseti=rint(ampoffset*4096.f);
  114815. int ampi=rint(amp*16.f);
  114816. long *ilsp=alloca(m*sizeof(*ilsp));
  114817. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114818. i=0;
  114819. while(i<n){
  114820. int j,k=map[i];
  114821. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114822. unsigned long qi=46341;
  114823. int qexp=0,shift;
  114824. long wi=vorbis_coslook_i(k*65536/ln);
  114825. qi*=labs(ilsp[0]-wi);
  114826. pi*=labs(ilsp[1]-wi);
  114827. for(j=3;j<m;j+=2){
  114828. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114829. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114830. shift=MLOOP_3[(pi|qi)>>16];
  114831. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114832. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114833. qexp+=shift;
  114834. }
  114835. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114836. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114837. shift=MLOOP_3[(pi|qi)>>16];
  114838. /* pi,qi normalized collectively, both tracked using qexp */
  114839. if(m&1){
  114840. /* odd order filter; slightly assymetric */
  114841. /* the last coefficient */
  114842. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114843. pi=(pi>>shift)<<14;
  114844. qexp+=shift;
  114845. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114846. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114847. shift=MLOOP_3[(pi|qi)>>16];
  114848. pi>>=shift;
  114849. qi>>=shift;
  114850. qexp+=shift-14*((m+1)>>1);
  114851. pi=((pi*pi)>>16);
  114852. qi=((qi*qi)>>16);
  114853. qexp=qexp*2+m;
  114854. pi*=(1<<14)-((wi*wi)>>14);
  114855. qi+=pi>>14;
  114856. }else{
  114857. /* even order filter; still symmetric */
  114858. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114859. worth tracking step by step */
  114860. pi>>=shift;
  114861. qi>>=shift;
  114862. qexp+=shift-7*m;
  114863. pi=((pi*pi)>>16);
  114864. qi=((qi*qi)>>16);
  114865. qexp=qexp*2+m;
  114866. pi*=(1<<14)-wi;
  114867. qi*=(1<<14)+wi;
  114868. qi=(qi+pi)>>14;
  114869. }
  114870. /* we've let the normalization drift because it wasn't important;
  114871. however, for the lookup, things must be normalized again. We
  114872. need at most one right shift or a number of left shifts */
  114873. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114874. qi>>=1; qexp++;
  114875. }else
  114876. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114877. qi<<=1; qexp--;
  114878. }
  114879. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114880. vorbis_invsqlook_i(qi,qexp)-
  114881. /* m.8, m+n<=8 */
  114882. ampoffseti); /* 8.12[0] */
  114883. curve[i]*=amp;
  114884. while(map[++i]==k)curve[i]*=amp;
  114885. }
  114886. }
  114887. #else
  114888. /* old, nonoptimized but simple version for any poor sap who needs to
  114889. figure out what the hell this code does, or wants the other
  114890. fraction of a dB precision */
  114891. /* side effect: changes *lsp to cosines of lsp */
  114892. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114893. float amp,float ampoffset){
  114894. int i;
  114895. float wdel=M_PI/ln;
  114896. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114897. i=0;
  114898. while(i<n){
  114899. int j,k=map[i];
  114900. float p=.5f;
  114901. float q=.5f;
  114902. float w=2.f*cos(wdel*k);
  114903. for(j=1;j<m;j+=2){
  114904. q *= w-lsp[j-1];
  114905. p *= w-lsp[j];
  114906. }
  114907. if(j==m){
  114908. /* odd order filter; slightly assymetric */
  114909. /* the last coefficient */
  114910. q*=w-lsp[j-1];
  114911. p*=p*(4.f-w*w);
  114912. q*=q;
  114913. }else{
  114914. /* even order filter; still symmetric */
  114915. p*=p*(2.f-w);
  114916. q*=q*(2.f+w);
  114917. }
  114918. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114919. curve[i]*=q;
  114920. while(map[++i]==k)curve[i]*=q;
  114921. }
  114922. }
  114923. #endif
  114924. #endif
  114925. static void cheby(float *g, int ord) {
  114926. int i, j;
  114927. g[0] *= .5f;
  114928. for(i=2; i<= ord; i++) {
  114929. for(j=ord; j >= i; j--) {
  114930. g[j-2] -= g[j];
  114931. g[j] += g[j];
  114932. }
  114933. }
  114934. }
  114935. static int comp(const void *a,const void *b){
  114936. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114937. }
  114938. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114939. but there are root sets for which it gets into limit cycles
  114940. (exacerbated by zero suppression) and fails. We can't afford to
  114941. fail, even if the failure is 1 in 100,000,000, so we now use
  114942. Laguerre and later polish with Newton-Raphson (which can then
  114943. afford to fail) */
  114944. #define EPSILON 10e-7
  114945. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114946. int i,m;
  114947. double lastdelta=0.f;
  114948. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114949. for(i=0;i<=ord;i++)defl[i]=a[i];
  114950. for(m=ord;m>0;m--){
  114951. double newx=0.f,delta;
  114952. /* iterate a root */
  114953. while(1){
  114954. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114955. /* eval the polynomial and its first two derivatives */
  114956. for(i=m;i>0;i--){
  114957. ppp = newx*ppp + pp;
  114958. pp = newx*pp + p;
  114959. p = newx*p + defl[i-1];
  114960. }
  114961. /* Laguerre's method */
  114962. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114963. if(denom<0)
  114964. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114965. if(pp>0){
  114966. denom = pp + sqrt(denom);
  114967. if(denom<EPSILON)denom=EPSILON;
  114968. }else{
  114969. denom = pp - sqrt(denom);
  114970. if(denom>-(EPSILON))denom=-(EPSILON);
  114971. }
  114972. delta = m*p/denom;
  114973. newx -= delta;
  114974. if(delta<0.f)delta*=-1;
  114975. if(fabs(delta/newx)<10e-12)break;
  114976. lastdelta=delta;
  114977. }
  114978. r[m-1]=newx;
  114979. /* forward deflation */
  114980. for(i=m;i>0;i--)
  114981. defl[i-1]+=newx*defl[i];
  114982. defl++;
  114983. }
  114984. return(0);
  114985. }
  114986. /* for spit-and-polish only */
  114987. static int Newton_Raphson(float *a,int ord,float *r){
  114988. int i, k, count=0;
  114989. double error=1.f;
  114990. double *root=(double*)alloca(ord*sizeof(*root));
  114991. for(i=0; i<ord;i++) root[i] = r[i];
  114992. while(error>1e-20){
  114993. error=0;
  114994. for(i=0; i<ord; i++) { /* Update each point. */
  114995. double pp=0.,delta;
  114996. double rooti=root[i];
  114997. double p=a[ord];
  114998. for(k=ord-1; k>= 0; k--) {
  114999. pp= pp* rooti + p;
  115000. p = p * rooti + a[k];
  115001. }
  115002. delta = p/pp;
  115003. root[i] -= delta;
  115004. error+= delta*delta;
  115005. }
  115006. if(count>40)return(-1);
  115007. count++;
  115008. }
  115009. /* Replaced the original bubble sort with a real sort. With your
  115010. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115011. for(i=0; i<ord;i++) r[i] = root[i];
  115012. return(0);
  115013. }
  115014. /* Convert lpc coefficients to lsp coefficients */
  115015. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115016. int order2=(m+1)>>1;
  115017. int g1_order,g2_order;
  115018. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115019. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115020. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115021. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115022. int i;
  115023. /* even and odd are slightly different base cases */
  115024. g1_order=(m+1)>>1;
  115025. g2_order=(m) >>1;
  115026. /* Compute the lengths of the x polynomials. */
  115027. /* Compute the first half of K & R F1 & F2 polynomials. */
  115028. /* Compute half of the symmetric and antisymmetric polynomials. */
  115029. /* Remove the roots at +1 and -1. */
  115030. g1[g1_order] = 1.f;
  115031. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115032. g2[g2_order] = 1.f;
  115033. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115034. if(g1_order>g2_order){
  115035. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115036. }else{
  115037. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115038. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115039. }
  115040. /* Convert into polynomials in cos(alpha) */
  115041. cheby(g1,g1_order);
  115042. cheby(g2,g2_order);
  115043. /* Find the roots of the 2 even polynomials.*/
  115044. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115045. Laguerre_With_Deflation(g2,g2_order,g2r))
  115046. return(-1);
  115047. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115048. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115049. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115050. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115051. for(i=0;i<g1_order;i++)
  115052. lsp[i*2] = acos(g1r[i]);
  115053. for(i=0;i<g2_order;i++)
  115054. lsp[i*2+1] = acos(g2r[i]);
  115055. return(0);
  115056. }
  115057. #endif
  115058. /*** End of inlined file: lsp.c ***/
  115059. /*** Start of inlined file: mapping0.c ***/
  115060. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115061. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115062. // tasks..
  115063. #if JUCE_MSVC
  115064. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115065. #endif
  115066. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115067. #if JUCE_USE_OGGVORBIS
  115068. #include <stdlib.h>
  115069. #include <stdio.h>
  115070. #include <string.h>
  115071. #include <math.h>
  115072. /* simplistic, wasteful way of doing this (unique lookup for each
  115073. mode/submapping); there should be a central repository for
  115074. identical lookups. That will require minor work, so I'm putting it
  115075. off as low priority.
  115076. Why a lookup for each backend in a given mode? Because the
  115077. blocksize is set by the mode, and low backend lookups may require
  115078. parameters from other areas of the mode/mapping */
  115079. static void mapping0_free_info(vorbis_info_mapping *i){
  115080. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115081. if(info){
  115082. memset(info,0,sizeof(*info));
  115083. _ogg_free(info);
  115084. }
  115085. }
  115086. static int ilog3(unsigned int v){
  115087. int ret=0;
  115088. if(v)--v;
  115089. while(v){
  115090. ret++;
  115091. v>>=1;
  115092. }
  115093. return(ret);
  115094. }
  115095. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115096. oggpack_buffer *opb){
  115097. int i;
  115098. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115099. /* another 'we meant to do it this way' hack... up to beta 4, we
  115100. packed 4 binary zeros here to signify one submapping in use. We
  115101. now redefine that to mean four bitflags that indicate use of
  115102. deeper features; bit0:submappings, bit1:coupling,
  115103. bit2,3:reserved. This is backward compatable with all actual uses
  115104. of the beta code. */
  115105. if(info->submaps>1){
  115106. oggpack_write(opb,1,1);
  115107. oggpack_write(opb,info->submaps-1,4);
  115108. }else
  115109. oggpack_write(opb,0,1);
  115110. if(info->coupling_steps>0){
  115111. oggpack_write(opb,1,1);
  115112. oggpack_write(opb,info->coupling_steps-1,8);
  115113. for(i=0;i<info->coupling_steps;i++){
  115114. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115115. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115116. }
  115117. }else
  115118. oggpack_write(opb,0,1);
  115119. oggpack_write(opb,0,2); /* 2,3:reserved */
  115120. /* we don't write the channel submappings if we only have one... */
  115121. if(info->submaps>1){
  115122. for(i=0;i<vi->channels;i++)
  115123. oggpack_write(opb,info->chmuxlist[i],4);
  115124. }
  115125. for(i=0;i<info->submaps;i++){
  115126. oggpack_write(opb,0,8); /* time submap unused */
  115127. oggpack_write(opb,info->floorsubmap[i],8);
  115128. oggpack_write(opb,info->residuesubmap[i],8);
  115129. }
  115130. }
  115131. /* also responsible for range checking */
  115132. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115133. int i;
  115134. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115135. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115136. memset(info,0,sizeof(*info));
  115137. if(oggpack_read(opb,1))
  115138. info->submaps=oggpack_read(opb,4)+1;
  115139. else
  115140. info->submaps=1;
  115141. if(oggpack_read(opb,1)){
  115142. info->coupling_steps=oggpack_read(opb,8)+1;
  115143. for(i=0;i<info->coupling_steps;i++){
  115144. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115145. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115146. if(testM<0 ||
  115147. testA<0 ||
  115148. testM==testA ||
  115149. testM>=vi->channels ||
  115150. testA>=vi->channels) goto err_out;
  115151. }
  115152. }
  115153. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115154. if(info->submaps>1){
  115155. for(i=0;i<vi->channels;i++){
  115156. info->chmuxlist[i]=oggpack_read(opb,4);
  115157. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115158. }
  115159. }
  115160. for(i=0;i<info->submaps;i++){
  115161. oggpack_read(opb,8); /* time submap unused */
  115162. info->floorsubmap[i]=oggpack_read(opb,8);
  115163. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115164. info->residuesubmap[i]=oggpack_read(opb,8);
  115165. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115166. }
  115167. return info;
  115168. err_out:
  115169. mapping0_free_info(info);
  115170. return(NULL);
  115171. }
  115172. #if 0
  115173. static long seq=0;
  115174. static ogg_int64_t total=0;
  115175. static float FLOOR1_fromdB_LOOKUP[256]={
  115176. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115177. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115178. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115179. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115180. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115181. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115182. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115183. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115184. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115185. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115186. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115187. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115188. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115189. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115190. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115191. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115192. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115193. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115194. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115195. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115196. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115197. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115198. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115199. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115200. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115201. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115202. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115203. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115204. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115205. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115206. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115207. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115208. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115209. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115210. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115211. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115212. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115213. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115214. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115215. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115216. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115217. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115218. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115219. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115220. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115221. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115222. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115223. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115224. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115225. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115226. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115227. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115228. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115229. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115230. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115231. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115232. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115233. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115234. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115235. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115236. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115237. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115238. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115239. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115240. };
  115241. #endif
  115242. extern int *floor1_fit(vorbis_block *vb,void *look,
  115243. const float *logmdct, /* in */
  115244. const float *logmask);
  115245. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115246. int *A,int *B,
  115247. int del);
  115248. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115249. void*look,
  115250. int *post,int *ilogmask);
  115251. static int mapping0_forward(vorbis_block *vb){
  115252. vorbis_dsp_state *vd=vb->vd;
  115253. vorbis_info *vi=vd->vi;
  115254. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115255. private_state *b=(private_state*)vb->vd->backend_state;
  115256. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115257. int n=vb->pcmend;
  115258. int i,j,k;
  115259. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115260. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115261. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115262. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115263. float global_ampmax=vbi->ampmax;
  115264. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115265. int blocktype=vbi->blocktype;
  115266. int modenumber=vb->W;
  115267. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115268. vorbis_look_psy *psy_look=
  115269. b->psy+blocktype+(vb->W?2:0);
  115270. vb->mode=modenumber;
  115271. for(i=0;i<vi->channels;i++){
  115272. float scale=4.f/n;
  115273. float scale_dB;
  115274. float *pcm =vb->pcm[i];
  115275. float *logfft =pcm;
  115276. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115277. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115278. todB estimation used on IEEE 754
  115279. compliant machines had a bug that
  115280. returned dB values about a third
  115281. of a decibel too high. The bug
  115282. was harmless because tunings
  115283. implicitly took that into
  115284. account. However, fixing the bug
  115285. in the estimator requires
  115286. changing all the tunings as well.
  115287. For now, it's easier to sync
  115288. things back up here, and
  115289. recalibrate the tunings in the
  115290. next major model upgrade. */
  115291. #if 0
  115292. if(vi->channels==2)
  115293. if(i==0)
  115294. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115295. else
  115296. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115297. #endif
  115298. /* window the PCM data */
  115299. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115300. #if 0
  115301. if(vi->channels==2)
  115302. if(i==0)
  115303. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115304. else
  115305. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115306. #endif
  115307. /* transform the PCM data */
  115308. /* only MDCT right now.... */
  115309. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115310. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115311. drft_forward(&b->fft_look[vb->W],pcm);
  115312. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115313. original todB estimation used on
  115314. IEEE 754 compliant machines had a
  115315. bug that returned dB values about
  115316. a third of a decibel too high.
  115317. The bug was harmless because
  115318. tunings implicitly took that into
  115319. account. However, fixing the bug
  115320. in the estimator requires
  115321. changing all the tunings as well.
  115322. For now, it's easier to sync
  115323. things back up here, and
  115324. recalibrate the tunings in the
  115325. next major model upgrade. */
  115326. local_ampmax[i]=logfft[0];
  115327. for(j=1;j<n-1;j+=2){
  115328. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115329. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115330. .345 is a hack; the original todB
  115331. estimation used on IEEE 754
  115332. compliant machines had a bug that
  115333. returned dB values about a third
  115334. of a decibel too high. The bug
  115335. was harmless because tunings
  115336. implicitly took that into
  115337. account. However, fixing the bug
  115338. in the estimator requires
  115339. changing all the tunings as well.
  115340. For now, it's easier to sync
  115341. things back up here, and
  115342. recalibrate the tunings in the
  115343. next major model upgrade. */
  115344. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115345. }
  115346. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115347. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115348. #if 0
  115349. if(vi->channels==2){
  115350. if(i==0){
  115351. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115352. }else{
  115353. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115354. }
  115355. }
  115356. #endif
  115357. }
  115358. {
  115359. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115360. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115361. for(i=0;i<vi->channels;i++){
  115362. /* the encoder setup assumes that all the modes used by any
  115363. specific bitrate tweaking use the same floor */
  115364. int submap=info->chmuxlist[i];
  115365. /* the following makes things clearer to *me* anyway */
  115366. float *mdct =gmdct[i];
  115367. float *logfft =vb->pcm[i];
  115368. float *logmdct =logfft+n/2;
  115369. float *logmask =logfft;
  115370. vb->mode=modenumber;
  115371. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115372. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115373. for(j=0;j<n/2;j++)
  115374. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115375. todB estimation used on IEEE 754
  115376. compliant machines had a bug that
  115377. returned dB values about a third
  115378. of a decibel too high. The bug
  115379. was harmless because tunings
  115380. implicitly took that into
  115381. account. However, fixing the bug
  115382. in the estimator requires
  115383. changing all the tunings as well.
  115384. For now, it's easier to sync
  115385. things back up here, and
  115386. recalibrate the tunings in the
  115387. next major model upgrade. */
  115388. #if 0
  115389. if(vi->channels==2){
  115390. if(i==0)
  115391. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115392. else
  115393. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115394. }else{
  115395. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115396. }
  115397. #endif
  115398. /* first step; noise masking. Not only does 'noise masking'
  115399. give us curves from which we can decide how much resolution
  115400. to give noise parts of the spectrum, it also implicitly hands
  115401. us a tonality estimate (the larger the value in the
  115402. 'noise_depth' vector, the more tonal that area is) */
  115403. _vp_noisemask(psy_look,
  115404. logmdct,
  115405. noise); /* noise does not have by-frequency offset
  115406. bias applied yet */
  115407. #if 0
  115408. if(vi->channels==2){
  115409. if(i==0)
  115410. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115411. else
  115412. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115413. }
  115414. #endif
  115415. /* second step: 'all the other crap'; all the stuff that isn't
  115416. computed/fit for bitrate management goes in the second psy
  115417. vector. This includes tone masking, peak limiting and ATH */
  115418. _vp_tonemask(psy_look,
  115419. logfft,
  115420. tone,
  115421. global_ampmax,
  115422. local_ampmax[i]);
  115423. #if 0
  115424. if(vi->channels==2){
  115425. if(i==0)
  115426. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115427. else
  115428. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115429. }
  115430. #endif
  115431. /* third step; we offset the noise vectors, overlay tone
  115432. masking. We then do a floor1-specific line fit. If we're
  115433. performing bitrate management, the line fit is performed
  115434. multiple times for up/down tweakage on demand. */
  115435. #if 0
  115436. {
  115437. float aotuv[psy_look->n];
  115438. #endif
  115439. _vp_offset_and_mix(psy_look,
  115440. noise,
  115441. tone,
  115442. 1,
  115443. logmask,
  115444. mdct,
  115445. logmdct);
  115446. #if 0
  115447. if(vi->channels==2){
  115448. if(i==0)
  115449. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115450. else
  115451. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115452. }
  115453. }
  115454. #endif
  115455. #if 0
  115456. if(vi->channels==2){
  115457. if(i==0)
  115458. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115459. else
  115460. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115461. }
  115462. #endif
  115463. /* this algorithm is hardwired to floor 1 for now; abort out if
  115464. we're *not* floor1. This won't happen unless someone has
  115465. broken the encode setup lib. Guard it anyway. */
  115466. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115467. floor_posts[i][PACKETBLOBS/2]=
  115468. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115469. logmdct,
  115470. logmask);
  115471. /* are we managing bitrate? If so, perform two more fits for
  115472. later rate tweaking (fits represent hi/lo) */
  115473. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115474. /* higher rate by way of lower noise curve */
  115475. _vp_offset_and_mix(psy_look,
  115476. noise,
  115477. tone,
  115478. 2,
  115479. logmask,
  115480. mdct,
  115481. logmdct);
  115482. #if 0
  115483. if(vi->channels==2){
  115484. if(i==0)
  115485. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115486. else
  115487. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115488. }
  115489. #endif
  115490. floor_posts[i][PACKETBLOBS-1]=
  115491. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115492. logmdct,
  115493. logmask);
  115494. /* lower rate by way of higher noise curve */
  115495. _vp_offset_and_mix(psy_look,
  115496. noise,
  115497. tone,
  115498. 0,
  115499. logmask,
  115500. mdct,
  115501. logmdct);
  115502. #if 0
  115503. if(vi->channels==2)
  115504. if(i==0)
  115505. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115506. else
  115507. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115508. #endif
  115509. floor_posts[i][0]=
  115510. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115511. logmdct,
  115512. logmask);
  115513. /* we also interpolate a range of intermediate curves for
  115514. intermediate rates */
  115515. for(k=1;k<PACKETBLOBS/2;k++)
  115516. floor_posts[i][k]=
  115517. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115518. floor_posts[i][0],
  115519. floor_posts[i][PACKETBLOBS/2],
  115520. k*65536/(PACKETBLOBS/2));
  115521. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115522. floor_posts[i][k]=
  115523. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115524. floor_posts[i][PACKETBLOBS/2],
  115525. floor_posts[i][PACKETBLOBS-1],
  115526. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115527. }
  115528. }
  115529. }
  115530. vbi->ampmax=global_ampmax;
  115531. /*
  115532. the next phases are performed once for vbr-only and PACKETBLOB
  115533. times for bitrate managed modes.
  115534. 1) encode actual mode being used
  115535. 2) encode the floor for each channel, compute coded mask curve/res
  115536. 3) normalize and couple.
  115537. 4) encode residue
  115538. 5) save packet bytes to the packetblob vector
  115539. */
  115540. /* iterate over the many masking curve fits we've created */
  115541. {
  115542. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115543. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115544. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115545. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115546. float **mag_memo;
  115547. int **mag_sort;
  115548. if(info->coupling_steps){
  115549. mag_memo=_vp_quantize_couple_memo(vb,
  115550. &ci->psy_g_param,
  115551. psy_look,
  115552. info,
  115553. gmdct);
  115554. mag_sort=_vp_quantize_couple_sort(vb,
  115555. psy_look,
  115556. info,
  115557. mag_memo);
  115558. hf_reduction(&ci->psy_g_param,
  115559. psy_look,
  115560. info,
  115561. mag_memo);
  115562. }
  115563. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115564. if(psy_look->vi->normal_channel_p){
  115565. for(i=0;i<vi->channels;i++){
  115566. float *mdct =gmdct[i];
  115567. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115568. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115569. }
  115570. }
  115571. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115572. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115573. k++){
  115574. oggpack_buffer *opb=vbi->packetblob[k];
  115575. /* start out our new packet blob with packet type and mode */
  115576. /* Encode the packet type */
  115577. oggpack_write(opb,0,1);
  115578. /* Encode the modenumber */
  115579. /* Encode frame mode, pre,post windowsize, then dispatch */
  115580. oggpack_write(opb,modenumber,b->modebits);
  115581. if(vb->W){
  115582. oggpack_write(opb,vb->lW,1);
  115583. oggpack_write(opb,vb->nW,1);
  115584. }
  115585. /* encode floor, compute masking curve, sep out residue */
  115586. for(i=0;i<vi->channels;i++){
  115587. int submap=info->chmuxlist[i];
  115588. float *mdct =gmdct[i];
  115589. float *res =vb->pcm[i];
  115590. int *ilogmask=ilogmaskch[i]=
  115591. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115592. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115593. floor_posts[i][k],
  115594. ilogmask);
  115595. #if 0
  115596. {
  115597. char buf[80];
  115598. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115599. float work[n/2];
  115600. for(j=0;j<n/2;j++)
  115601. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115602. _analysis_output(buf,seq,work,n/2,1,1,0);
  115603. }
  115604. #endif
  115605. _vp_remove_floor(psy_look,
  115606. mdct,
  115607. ilogmask,
  115608. res,
  115609. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115610. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115611. #if 0
  115612. {
  115613. char buf[80];
  115614. float work[n/2];
  115615. for(j=0;j<n/2;j++)
  115616. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115617. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115618. _analysis_output(buf,seq,work,n/2,1,1,0);
  115619. }
  115620. #endif
  115621. }
  115622. /* our iteration is now based on masking curve, not prequant and
  115623. coupling. Only one prequant/coupling step */
  115624. /* quantize/couple */
  115625. /* incomplete implementation that assumes the tree is all depth
  115626. one, or no tree at all */
  115627. if(info->coupling_steps){
  115628. _vp_couple(k,
  115629. &ci->psy_g_param,
  115630. psy_look,
  115631. info,
  115632. vb->pcm,
  115633. mag_memo,
  115634. mag_sort,
  115635. ilogmaskch,
  115636. nonzero,
  115637. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115638. }
  115639. /* classify and encode by submap */
  115640. for(i=0;i<info->submaps;i++){
  115641. int ch_in_bundle=0;
  115642. long **classifications;
  115643. int resnum=info->residuesubmap[i];
  115644. for(j=0;j<vi->channels;j++){
  115645. if(info->chmuxlist[j]==i){
  115646. zerobundle[ch_in_bundle]=0;
  115647. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115648. res_bundle[ch_in_bundle]=vb->pcm[j];
  115649. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115650. }
  115651. }
  115652. classifications=_residue_P[ci->residue_type[resnum]]->
  115653. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115654. _residue_P[ci->residue_type[resnum]]->
  115655. forward(opb,vb,b->residue[resnum],
  115656. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115657. }
  115658. /* ok, done encoding. Next protopacket. */
  115659. }
  115660. }
  115661. #if 0
  115662. seq++;
  115663. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115664. #endif
  115665. return(0);
  115666. }
  115667. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115668. vorbis_dsp_state *vd=vb->vd;
  115669. vorbis_info *vi=vd->vi;
  115670. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115671. private_state *b=(private_state*)vd->backend_state;
  115672. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115673. int i,j;
  115674. long n=vb->pcmend=ci->blocksizes[vb->W];
  115675. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115676. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115677. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115678. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115679. /* recover the spectral envelope; store it in the PCM vector for now */
  115680. for(i=0;i<vi->channels;i++){
  115681. int submap=info->chmuxlist[i];
  115682. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115683. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115684. if(floormemo[i])
  115685. nonzero[i]=1;
  115686. else
  115687. nonzero[i]=0;
  115688. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115689. }
  115690. /* channel coupling can 'dirty' the nonzero listing */
  115691. for(i=0;i<info->coupling_steps;i++){
  115692. if(nonzero[info->coupling_mag[i]] ||
  115693. nonzero[info->coupling_ang[i]]){
  115694. nonzero[info->coupling_mag[i]]=1;
  115695. nonzero[info->coupling_ang[i]]=1;
  115696. }
  115697. }
  115698. /* recover the residue into our working vectors */
  115699. for(i=0;i<info->submaps;i++){
  115700. int ch_in_bundle=0;
  115701. for(j=0;j<vi->channels;j++){
  115702. if(info->chmuxlist[j]==i){
  115703. if(nonzero[j])
  115704. zerobundle[ch_in_bundle]=1;
  115705. else
  115706. zerobundle[ch_in_bundle]=0;
  115707. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115708. }
  115709. }
  115710. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115711. inverse(vb,b->residue[info->residuesubmap[i]],
  115712. pcmbundle,zerobundle,ch_in_bundle);
  115713. }
  115714. /* channel coupling */
  115715. for(i=info->coupling_steps-1;i>=0;i--){
  115716. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115717. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115718. for(j=0;j<n/2;j++){
  115719. float mag=pcmM[j];
  115720. float ang=pcmA[j];
  115721. if(mag>0)
  115722. if(ang>0){
  115723. pcmM[j]=mag;
  115724. pcmA[j]=mag-ang;
  115725. }else{
  115726. pcmA[j]=mag;
  115727. pcmM[j]=mag+ang;
  115728. }
  115729. else
  115730. if(ang>0){
  115731. pcmM[j]=mag;
  115732. pcmA[j]=mag+ang;
  115733. }else{
  115734. pcmA[j]=mag;
  115735. pcmM[j]=mag-ang;
  115736. }
  115737. }
  115738. }
  115739. /* compute and apply spectral envelope */
  115740. for(i=0;i<vi->channels;i++){
  115741. float *pcm=vb->pcm[i];
  115742. int submap=info->chmuxlist[i];
  115743. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115744. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115745. floormemo[i],pcm);
  115746. }
  115747. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115748. /* only MDCT right now.... */
  115749. for(i=0;i<vi->channels;i++){
  115750. float *pcm=vb->pcm[i];
  115751. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115752. }
  115753. /* all done! */
  115754. return(0);
  115755. }
  115756. /* export hooks */
  115757. vorbis_func_mapping mapping0_exportbundle={
  115758. &mapping0_pack,
  115759. &mapping0_unpack,
  115760. &mapping0_free_info,
  115761. &mapping0_forward,
  115762. &mapping0_inverse
  115763. };
  115764. #endif
  115765. /*** End of inlined file: mapping0.c ***/
  115766. /*** Start of inlined file: mdct.c ***/
  115767. /* this can also be run as an integer transform by uncommenting a
  115768. define in mdct.h; the integerization is a first pass and although
  115769. it's likely stable for Vorbis, the dynamic range is constrained and
  115770. roundoff isn't done (so it's noisy). Consider it functional, but
  115771. only a starting point. There's no point on a machine with an FPU */
  115772. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115773. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115774. // tasks..
  115775. #if JUCE_MSVC
  115776. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115777. #endif
  115778. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115779. #if JUCE_USE_OGGVORBIS
  115780. #include <stdio.h>
  115781. #include <stdlib.h>
  115782. #include <string.h>
  115783. #include <math.h>
  115784. /* build lookups for trig functions; also pre-figure scaling and
  115785. some window function algebra. */
  115786. void mdct_init(mdct_lookup *lookup,int n){
  115787. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115788. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115789. int i;
  115790. int n2=n>>1;
  115791. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115792. lookup->n=n;
  115793. lookup->trig=T;
  115794. lookup->bitrev=bitrev;
  115795. /* trig lookups... */
  115796. for(i=0;i<n/4;i++){
  115797. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115798. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115799. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115800. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115801. }
  115802. for(i=0;i<n/8;i++){
  115803. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115804. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115805. }
  115806. /* bitreverse lookup... */
  115807. {
  115808. int mask=(1<<(log2n-1))-1,i,j;
  115809. int msb=1<<(log2n-2);
  115810. for(i=0;i<n/8;i++){
  115811. int acc=0;
  115812. for(j=0;msb>>j;j++)
  115813. if((msb>>j)&i)acc|=1<<j;
  115814. bitrev[i*2]=((~acc)&mask)-1;
  115815. bitrev[i*2+1]=acc;
  115816. }
  115817. }
  115818. lookup->scale=FLOAT_CONV(4.f/n);
  115819. }
  115820. /* 8 point butterfly (in place, 4 register) */
  115821. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115822. REG_TYPE r0 = x[6] + x[2];
  115823. REG_TYPE r1 = x[6] - x[2];
  115824. REG_TYPE r2 = x[4] + x[0];
  115825. REG_TYPE r3 = x[4] - x[0];
  115826. x[6] = r0 + r2;
  115827. x[4] = r0 - r2;
  115828. r0 = x[5] - x[1];
  115829. r2 = x[7] - x[3];
  115830. x[0] = r1 + r0;
  115831. x[2] = r1 - r0;
  115832. r0 = x[5] + x[1];
  115833. r1 = x[7] + x[3];
  115834. x[3] = r2 + r3;
  115835. x[1] = r2 - r3;
  115836. x[7] = r1 + r0;
  115837. x[5] = r1 - r0;
  115838. }
  115839. /* 16 point butterfly (in place, 4 register) */
  115840. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115841. REG_TYPE r0 = x[1] - x[9];
  115842. REG_TYPE r1 = x[0] - x[8];
  115843. x[8] += x[0];
  115844. x[9] += x[1];
  115845. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115846. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115847. r0 = x[3] - x[11];
  115848. r1 = x[10] - x[2];
  115849. x[10] += x[2];
  115850. x[11] += x[3];
  115851. x[2] = r0;
  115852. x[3] = r1;
  115853. r0 = x[12] - x[4];
  115854. r1 = x[13] - x[5];
  115855. x[12] += x[4];
  115856. x[13] += x[5];
  115857. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115858. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115859. r0 = x[14] - x[6];
  115860. r1 = x[15] - x[7];
  115861. x[14] += x[6];
  115862. x[15] += x[7];
  115863. x[6] = r0;
  115864. x[7] = r1;
  115865. mdct_butterfly_8(x);
  115866. mdct_butterfly_8(x+8);
  115867. }
  115868. /* 32 point butterfly (in place, 4 register) */
  115869. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115870. REG_TYPE r0 = x[30] - x[14];
  115871. REG_TYPE r1 = x[31] - x[15];
  115872. x[30] += x[14];
  115873. x[31] += x[15];
  115874. x[14] = r0;
  115875. x[15] = r1;
  115876. r0 = x[28] - x[12];
  115877. r1 = x[29] - x[13];
  115878. x[28] += x[12];
  115879. x[29] += x[13];
  115880. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115881. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115882. r0 = x[26] - x[10];
  115883. r1 = x[27] - x[11];
  115884. x[26] += x[10];
  115885. x[27] += x[11];
  115886. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115887. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115888. r0 = x[24] - x[8];
  115889. r1 = x[25] - x[9];
  115890. x[24] += x[8];
  115891. x[25] += x[9];
  115892. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115893. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115894. r0 = x[22] - x[6];
  115895. r1 = x[7] - x[23];
  115896. x[22] += x[6];
  115897. x[23] += x[7];
  115898. x[6] = r1;
  115899. x[7] = r0;
  115900. r0 = x[4] - x[20];
  115901. r1 = x[5] - x[21];
  115902. x[20] += x[4];
  115903. x[21] += x[5];
  115904. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115905. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115906. r0 = x[2] - x[18];
  115907. r1 = x[3] - x[19];
  115908. x[18] += x[2];
  115909. x[19] += x[3];
  115910. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115911. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115912. r0 = x[0] - x[16];
  115913. r1 = x[1] - x[17];
  115914. x[16] += x[0];
  115915. x[17] += x[1];
  115916. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115917. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115918. mdct_butterfly_16(x);
  115919. mdct_butterfly_16(x+16);
  115920. }
  115921. /* N point first stage butterfly (in place, 2 register) */
  115922. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115923. DATA_TYPE *x,
  115924. int points){
  115925. DATA_TYPE *x1 = x + points - 8;
  115926. DATA_TYPE *x2 = x + (points>>1) - 8;
  115927. REG_TYPE r0;
  115928. REG_TYPE r1;
  115929. do{
  115930. r0 = x1[6] - x2[6];
  115931. r1 = x1[7] - x2[7];
  115932. x1[6] += x2[6];
  115933. x1[7] += x2[7];
  115934. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115935. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115936. r0 = x1[4] - x2[4];
  115937. r1 = x1[5] - x2[5];
  115938. x1[4] += x2[4];
  115939. x1[5] += x2[5];
  115940. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115941. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115942. r0 = x1[2] - x2[2];
  115943. r1 = x1[3] - x2[3];
  115944. x1[2] += x2[2];
  115945. x1[3] += x2[3];
  115946. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115947. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115948. r0 = x1[0] - x2[0];
  115949. r1 = x1[1] - x2[1];
  115950. x1[0] += x2[0];
  115951. x1[1] += x2[1];
  115952. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115953. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115954. x1-=8;
  115955. x2-=8;
  115956. T+=16;
  115957. }while(x2>=x);
  115958. }
  115959. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115960. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115961. DATA_TYPE *x,
  115962. int points,
  115963. int trigint){
  115964. DATA_TYPE *x1 = x + points - 8;
  115965. DATA_TYPE *x2 = x + (points>>1) - 8;
  115966. REG_TYPE r0;
  115967. REG_TYPE r1;
  115968. do{
  115969. r0 = x1[6] - x2[6];
  115970. r1 = x1[7] - x2[7];
  115971. x1[6] += x2[6];
  115972. x1[7] += x2[7];
  115973. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115974. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115975. T+=trigint;
  115976. r0 = x1[4] - x2[4];
  115977. r1 = x1[5] - x2[5];
  115978. x1[4] += x2[4];
  115979. x1[5] += x2[5];
  115980. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115981. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115982. T+=trigint;
  115983. r0 = x1[2] - x2[2];
  115984. r1 = x1[3] - x2[3];
  115985. x1[2] += x2[2];
  115986. x1[3] += x2[3];
  115987. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115988. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115989. T+=trigint;
  115990. r0 = x1[0] - x2[0];
  115991. r1 = x1[1] - x2[1];
  115992. x1[0] += x2[0];
  115993. x1[1] += x2[1];
  115994. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115995. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115996. T+=trigint;
  115997. x1-=8;
  115998. x2-=8;
  115999. }while(x2>=x);
  116000. }
  116001. STIN void mdct_butterflies(mdct_lookup *init,
  116002. DATA_TYPE *x,
  116003. int points){
  116004. DATA_TYPE *T=init->trig;
  116005. int stages=init->log2n-5;
  116006. int i,j;
  116007. if(--stages>0){
  116008. mdct_butterfly_first(T,x,points);
  116009. }
  116010. for(i=1;--stages>0;i++){
  116011. for(j=0;j<(1<<i);j++)
  116012. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116013. }
  116014. for(j=0;j<points;j+=32)
  116015. mdct_butterfly_32(x+j);
  116016. }
  116017. void mdct_clear(mdct_lookup *l){
  116018. if(l){
  116019. if(l->trig)_ogg_free(l->trig);
  116020. if(l->bitrev)_ogg_free(l->bitrev);
  116021. memset(l,0,sizeof(*l));
  116022. }
  116023. }
  116024. STIN void mdct_bitreverse(mdct_lookup *init,
  116025. DATA_TYPE *x){
  116026. int n = init->n;
  116027. int *bit = init->bitrev;
  116028. DATA_TYPE *w0 = x;
  116029. DATA_TYPE *w1 = x = w0+(n>>1);
  116030. DATA_TYPE *T = init->trig+n;
  116031. do{
  116032. DATA_TYPE *x0 = x+bit[0];
  116033. DATA_TYPE *x1 = x+bit[1];
  116034. REG_TYPE r0 = x0[1] - x1[1];
  116035. REG_TYPE r1 = x0[0] + x1[0];
  116036. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116037. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116038. w1 -= 4;
  116039. r0 = HALVE(x0[1] + x1[1]);
  116040. r1 = HALVE(x0[0] - x1[0]);
  116041. w0[0] = r0 + r2;
  116042. w1[2] = r0 - r2;
  116043. w0[1] = r1 + r3;
  116044. w1[3] = r3 - r1;
  116045. x0 = x+bit[2];
  116046. x1 = x+bit[3];
  116047. r0 = x0[1] - x1[1];
  116048. r1 = x0[0] + x1[0];
  116049. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116050. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116051. r0 = HALVE(x0[1] + x1[1]);
  116052. r1 = HALVE(x0[0] - x1[0]);
  116053. w0[2] = r0 + r2;
  116054. w1[0] = r0 - r2;
  116055. w0[3] = r1 + r3;
  116056. w1[1] = r3 - r1;
  116057. T += 4;
  116058. bit += 4;
  116059. w0 += 4;
  116060. }while(w0<w1);
  116061. }
  116062. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116063. int n=init->n;
  116064. int n2=n>>1;
  116065. int n4=n>>2;
  116066. /* rotate */
  116067. DATA_TYPE *iX = in+n2-7;
  116068. DATA_TYPE *oX = out+n2+n4;
  116069. DATA_TYPE *T = init->trig+n4;
  116070. do{
  116071. oX -= 4;
  116072. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116073. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116074. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116075. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116076. iX -= 8;
  116077. T += 4;
  116078. }while(iX>=in);
  116079. iX = in+n2-8;
  116080. oX = out+n2+n4;
  116081. T = init->trig+n4;
  116082. do{
  116083. T -= 4;
  116084. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116085. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116086. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116087. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116088. iX -= 8;
  116089. oX += 4;
  116090. }while(iX>=in);
  116091. mdct_butterflies(init,out+n2,n2);
  116092. mdct_bitreverse(init,out);
  116093. /* roatate + window */
  116094. {
  116095. DATA_TYPE *oX1=out+n2+n4;
  116096. DATA_TYPE *oX2=out+n2+n4;
  116097. DATA_TYPE *iX =out;
  116098. T =init->trig+n2;
  116099. do{
  116100. oX1-=4;
  116101. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116102. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116103. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116104. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116105. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116106. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116107. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116108. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116109. oX2+=4;
  116110. iX += 8;
  116111. T += 8;
  116112. }while(iX<oX1);
  116113. iX=out+n2+n4;
  116114. oX1=out+n4;
  116115. oX2=oX1;
  116116. do{
  116117. oX1-=4;
  116118. iX-=4;
  116119. oX2[0] = -(oX1[3] = iX[3]);
  116120. oX2[1] = -(oX1[2] = iX[2]);
  116121. oX2[2] = -(oX1[1] = iX[1]);
  116122. oX2[3] = -(oX1[0] = iX[0]);
  116123. oX2+=4;
  116124. }while(oX2<iX);
  116125. iX=out+n2+n4;
  116126. oX1=out+n2+n4;
  116127. oX2=out+n2;
  116128. do{
  116129. oX1-=4;
  116130. oX1[0]= iX[3];
  116131. oX1[1]= iX[2];
  116132. oX1[2]= iX[1];
  116133. oX1[3]= iX[0];
  116134. iX+=4;
  116135. }while(oX1>oX2);
  116136. }
  116137. }
  116138. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116139. int n=init->n;
  116140. int n2=n>>1;
  116141. int n4=n>>2;
  116142. int n8=n>>3;
  116143. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116144. DATA_TYPE *w2=w+n2;
  116145. /* rotate */
  116146. /* window + rotate + step 1 */
  116147. REG_TYPE r0;
  116148. REG_TYPE r1;
  116149. DATA_TYPE *x0=in+n2+n4;
  116150. DATA_TYPE *x1=x0+1;
  116151. DATA_TYPE *T=init->trig+n2;
  116152. int i=0;
  116153. for(i=0;i<n8;i+=2){
  116154. x0 -=4;
  116155. T-=2;
  116156. r0= x0[2] + x1[0];
  116157. r1= x0[0] + x1[2];
  116158. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116159. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116160. x1 +=4;
  116161. }
  116162. x1=in+1;
  116163. for(;i<n2-n8;i+=2){
  116164. T-=2;
  116165. x0 -=4;
  116166. r0= x0[2] - x1[0];
  116167. r1= x0[0] - x1[2];
  116168. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116169. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116170. x1 +=4;
  116171. }
  116172. x0=in+n;
  116173. for(;i<n2;i+=2){
  116174. T-=2;
  116175. x0 -=4;
  116176. r0= -x0[2] - x1[0];
  116177. r1= -x0[0] - x1[2];
  116178. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116179. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116180. x1 +=4;
  116181. }
  116182. mdct_butterflies(init,w+n2,n2);
  116183. mdct_bitreverse(init,w);
  116184. /* roatate + window */
  116185. T=init->trig+n2;
  116186. x0=out+n2;
  116187. for(i=0;i<n4;i++){
  116188. x0--;
  116189. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116190. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116191. w+=2;
  116192. T+=2;
  116193. }
  116194. }
  116195. #endif
  116196. /*** End of inlined file: mdct.c ***/
  116197. /*** Start of inlined file: psy.c ***/
  116198. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116199. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116200. // tasks..
  116201. #if JUCE_MSVC
  116202. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116203. #endif
  116204. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116205. #if JUCE_USE_OGGVORBIS
  116206. #include <stdlib.h>
  116207. #include <math.h>
  116208. #include <string.h>
  116209. /*** Start of inlined file: masking.h ***/
  116210. #ifndef _V_MASKING_H_
  116211. #define _V_MASKING_H_
  116212. /* more detailed ATH; the bass if flat to save stressing the floor
  116213. overly for only a bin or two of savings. */
  116214. #define MAX_ATH 88
  116215. static float ATH[]={
  116216. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116217. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116218. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116219. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116220. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116221. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116222. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116223. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116224. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116225. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116226. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116227. };
  116228. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116229. replaced by an empirically collected data set. The previously
  116230. published values were, far too often, simply on crack. */
  116231. #define EHMER_OFFSET 16
  116232. #define EHMER_MAX 56
  116233. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116234. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116235. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116236. for collection of these curves) */
  116237. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116238. /* 62.5 Hz */
  116239. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116240. -60, -60, -60, -60, -62, -62, -65, -73,
  116241. -69, -68, -68, -67, -70, -70, -72, -74,
  116242. -75, -79, -79, -80, -83, -88, -93, -100,
  116243. -110, -999, -999, -999, -999, -999, -999, -999,
  116244. -999, -999, -999, -999, -999, -999, -999, -999,
  116245. -999, -999, -999, -999, -999, -999, -999, -999},
  116246. { -48, -48, -48, -48, -48, -48, -48, -48,
  116247. -48, -48, -48, -48, -48, -53, -61, -66,
  116248. -66, -68, -67, -70, -76, -76, -72, -73,
  116249. -75, -76, -78, -79, -83, -88, -93, -100,
  116250. -110, -999, -999, -999, -999, -999, -999, -999,
  116251. -999, -999, -999, -999, -999, -999, -999, -999,
  116252. -999, -999, -999, -999, -999, -999, -999, -999},
  116253. { -37, -37, -37, -37, -37, -37, -37, -37,
  116254. -38, -40, -42, -46, -48, -53, -55, -62,
  116255. -65, -58, -56, -56, -61, -60, -65, -67,
  116256. -69, -71, -77, -77, -78, -80, -82, -84,
  116257. -88, -93, -98, -106, -112, -999, -999, -999,
  116258. -999, -999, -999, -999, -999, -999, -999, -999,
  116259. -999, -999, -999, -999, -999, -999, -999, -999},
  116260. { -25, -25, -25, -25, -25, -25, -25, -25,
  116261. -25, -26, -27, -29, -32, -38, -48, -52,
  116262. -52, -50, -48, -48, -51, -52, -54, -60,
  116263. -67, -67, -66, -68, -69, -73, -73, -76,
  116264. -80, -81, -81, -85, -85, -86, -88, -93,
  116265. -100, -110, -999, -999, -999, -999, -999, -999,
  116266. -999, -999, -999, -999, -999, -999, -999, -999},
  116267. { -16, -16, -16, -16, -16, -16, -16, -16,
  116268. -17, -19, -20, -22, -26, -28, -31, -40,
  116269. -47, -39, -39, -40, -42, -43, -47, -51,
  116270. -57, -52, -55, -55, -60, -58, -62, -63,
  116271. -70, -67, -69, -72, -73, -77, -80, -82,
  116272. -83, -87, -90, -94, -98, -104, -115, -999,
  116273. -999, -999, -999, -999, -999, -999, -999, -999},
  116274. { -8, -8, -8, -8, -8, -8, -8, -8,
  116275. -8, -8, -10, -11, -15, -19, -25, -30,
  116276. -34, -31, -30, -31, -29, -32, -35, -42,
  116277. -48, -42, -44, -46, -50, -50, -51, -52,
  116278. -59, -54, -55, -55, -58, -62, -63, -66,
  116279. -72, -73, -76, -75, -78, -80, -80, -81,
  116280. -84, -88, -90, -94, -98, -101, -106, -110}},
  116281. /* 88Hz */
  116282. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116283. -66, -66, -66, -66, -66, -67, -67, -67,
  116284. -76, -72, -71, -74, -76, -76, -75, -78,
  116285. -79, -79, -81, -83, -86, -89, -93, -97,
  116286. -100, -105, -110, -999, -999, -999, -999, -999,
  116287. -999, -999, -999, -999, -999, -999, -999, -999,
  116288. -999, -999, -999, -999, -999, -999, -999, -999},
  116289. { -47, -47, -47, -47, -47, -47, -47, -47,
  116290. -47, -47, -47, -48, -51, -55, -59, -66,
  116291. -66, -66, -67, -66, -68, -69, -70, -74,
  116292. -79, -77, -77, -78, -80, -81, -82, -84,
  116293. -86, -88, -91, -95, -100, -108, -116, -999,
  116294. -999, -999, -999, -999, -999, -999, -999, -999,
  116295. -999, -999, -999, -999, -999, -999, -999, -999},
  116296. { -36, -36, -36, -36, -36, -36, -36, -36,
  116297. -36, -37, -37, -41, -44, -48, -51, -58,
  116298. -62, -60, -57, -59, -59, -60, -63, -65,
  116299. -72, -71, -70, -72, -74, -77, -76, -78,
  116300. -81, -81, -80, -83, -86, -91, -96, -100,
  116301. -105, -110, -999, -999, -999, -999, -999, -999,
  116302. -999, -999, -999, -999, -999, -999, -999, -999},
  116303. { -28, -28, -28, -28, -28, -28, -28, -28,
  116304. -28, -30, -32, -32, -33, -35, -41, -49,
  116305. -50, -49, -47, -48, -48, -52, -51, -57,
  116306. -65, -61, -59, -61, -64, -69, -70, -74,
  116307. -77, -77, -78, -81, -84, -85, -87, -90,
  116308. -92, -96, -100, -107, -112, -999, -999, -999,
  116309. -999, -999, -999, -999, -999, -999, -999, -999},
  116310. { -19, -19, -19, -19, -19, -19, -19, -19,
  116311. -20, -21, -23, -27, -30, -35, -36, -41,
  116312. -46, -44, -42, -40, -41, -41, -43, -48,
  116313. -55, -53, -52, -53, -56, -59, -58, -60,
  116314. -67, -66, -69, -71, -72, -75, -79, -81,
  116315. -84, -87, -90, -93, -97, -101, -107, -114,
  116316. -999, -999, -999, -999, -999, -999, -999, -999},
  116317. { -9, -9, -9, -9, -9, -9, -9, -9,
  116318. -11, -12, -12, -15, -16, -20, -23, -30,
  116319. -37, -34, -33, -34, -31, -32, -32, -38,
  116320. -47, -44, -41, -40, -47, -49, -46, -46,
  116321. -58, -50, -50, -54, -58, -62, -64, -67,
  116322. -67, -70, -72, -76, -79, -83, -87, -91,
  116323. -96, -100, -104, -110, -999, -999, -999, -999}},
  116324. /* 125 Hz */
  116325. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116326. -62, -62, -63, -64, -66, -67, -66, -68,
  116327. -75, -72, -76, -75, -76, -78, -79, -82,
  116328. -84, -85, -90, -94, -101, -110, -999, -999,
  116329. -999, -999, -999, -999, -999, -999, -999, -999,
  116330. -999, -999, -999, -999, -999, -999, -999, -999,
  116331. -999, -999, -999, -999, -999, -999, -999, -999},
  116332. { -59, -59, -59, -59, -59, -59, -59, -59,
  116333. -59, -59, -59, -60, -60, -61, -63, -66,
  116334. -71, -68, -70, -70, -71, -72, -72, -75,
  116335. -81, -78, -79, -82, -83, -86, -90, -97,
  116336. -103, -113, -999, -999, -999, -999, -999, -999,
  116337. -999, -999, -999, -999, -999, -999, -999, -999,
  116338. -999, -999, -999, -999, -999, -999, -999, -999},
  116339. { -53, -53, -53, -53, -53, -53, -53, -53,
  116340. -53, -54, -55, -57, -56, -57, -55, -61,
  116341. -65, -60, -60, -62, -63, -63, -66, -68,
  116342. -74, -73, -75, -75, -78, -80, -80, -82,
  116343. -85, -90, -96, -101, -108, -999, -999, -999,
  116344. -999, -999, -999, -999, -999, -999, -999, -999,
  116345. -999, -999, -999, -999, -999, -999, -999, -999},
  116346. { -46, -46, -46, -46, -46, -46, -46, -46,
  116347. -46, -46, -47, -47, -47, -47, -48, -51,
  116348. -57, -51, -49, -50, -51, -53, -54, -59,
  116349. -66, -60, -62, -67, -67, -70, -72, -75,
  116350. -76, -78, -81, -85, -88, -94, -97, -104,
  116351. -112, -999, -999, -999, -999, -999, -999, -999,
  116352. -999, -999, -999, -999, -999, -999, -999, -999},
  116353. { -36, -36, -36, -36, -36, -36, -36, -36,
  116354. -39, -41, -42, -42, -39, -38, -41, -43,
  116355. -52, -44, -40, -39, -37, -37, -40, -47,
  116356. -54, -50, -48, -50, -55, -61, -59, -62,
  116357. -66, -66, -66, -69, -69, -73, -74, -74,
  116358. -75, -77, -79, -82, -87, -91, -95, -100,
  116359. -108, -115, -999, -999, -999, -999, -999, -999},
  116360. { -28, -26, -24, -22, -20, -20, -23, -29,
  116361. -30, -31, -28, -27, -28, -28, -28, -35,
  116362. -40, -33, -32, -29, -30, -30, -30, -37,
  116363. -45, -41, -37, -38, -45, -47, -47, -48,
  116364. -53, -49, -48, -50, -49, -49, -51, -52,
  116365. -58, -56, -57, -56, -60, -61, -62, -70,
  116366. -72, -74, -78, -83, -88, -93, -100, -106}},
  116367. /* 177 Hz */
  116368. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -110, -105, -100, -95, -91, -87, -83,
  116370. -80, -78, -76, -78, -78, -81, -83, -85,
  116371. -86, -85, -86, -87, -90, -97, -107, -999,
  116372. -999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -999, -999, -999, -999, -999, -999,
  116374. -999, -999, -999, -999, -999, -999, -999, -999},
  116375. {-999, -999, -999, -110, -105, -100, -95, -90,
  116376. -85, -81, -77, -73, -70, -67, -67, -68,
  116377. -75, -73, -70, -69, -70, -72, -75, -79,
  116378. -84, -83, -84, -86, -88, -89, -89, -93,
  116379. -98, -105, -112, -999, -999, -999, -999, -999,
  116380. -999, -999, -999, -999, -999, -999, -999, -999,
  116381. -999, -999, -999, -999, -999, -999, -999, -999},
  116382. {-105, -100, -95, -90, -85, -80, -76, -71,
  116383. -68, -68, -65, -63, -63, -62, -62, -64,
  116384. -65, -64, -61, -62, -63, -64, -66, -68,
  116385. -73, -73, -74, -75, -76, -81, -83, -85,
  116386. -88, -89, -92, -95, -100, -108, -999, -999,
  116387. -999, -999, -999, -999, -999, -999, -999, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999},
  116389. { -80, -75, -71, -68, -65, -63, -62, -61,
  116390. -61, -61, -61, -59, -56, -57, -53, -50,
  116391. -58, -52, -50, -50, -52, -53, -54, -58,
  116392. -67, -63, -67, -68, -72, -75, -78, -80,
  116393. -81, -81, -82, -85, -89, -90, -93, -97,
  116394. -101, -107, -114, -999, -999, -999, -999, -999,
  116395. -999, -999, -999, -999, -999, -999, -999, -999},
  116396. { -65, -61, -59, -57, -56, -55, -55, -56,
  116397. -56, -57, -55, -53, -52, -47, -44, -44,
  116398. -50, -44, -41, -39, -39, -42, -40, -46,
  116399. -51, -49, -50, -53, -54, -63, -60, -61,
  116400. -62, -66, -66, -66, -70, -73, -74, -75,
  116401. -76, -75, -79, -85, -89, -91, -96, -102,
  116402. -110, -999, -999, -999, -999, -999, -999, -999},
  116403. { -52, -50, -49, -49, -48, -48, -48, -49,
  116404. -50, -50, -49, -46, -43, -39, -35, -33,
  116405. -38, -36, -32, -29, -32, -32, -32, -35,
  116406. -44, -39, -38, -38, -46, -50, -45, -46,
  116407. -53, -50, -50, -50, -54, -54, -53, -53,
  116408. -56, -57, -59, -66, -70, -72, -74, -79,
  116409. -83, -85, -90, -97, -114, -999, -999, -999}},
  116410. /* 250 Hz */
  116411. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116412. -100, -95, -90, -86, -80, -75, -75, -79,
  116413. -80, -79, -80, -81, -82, -88, -95, -103,
  116414. -110, -999, -999, -999, -999, -999, -999, -999,
  116415. -999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -999, -999, -999,
  116417. -999, -999, -999, -999, -999, -999, -999, -999},
  116418. {-999, -999, -999, -999, -108, -103, -98, -93,
  116419. -88, -83, -79, -78, -75, -71, -67, -68,
  116420. -73, -73, -72, -73, -75, -77, -80, -82,
  116421. -88, -93, -100, -107, -114, -999, -999, -999,
  116422. -999, -999, -999, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -999, -999, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999},
  116425. {-999, -999, -999, -110, -105, -101, -96, -90,
  116426. -86, -81, -77, -73, -69, -66, -61, -62,
  116427. -66, -64, -62, -65, -66, -70, -72, -76,
  116428. -81, -80, -84, -90, -95, -102, -110, -999,
  116429. -999, -999, -999, -999, -999, -999, -999, -999,
  116430. -999, -999, -999, -999, -999, -999, -999, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999},
  116432. {-999, -999, -999, -107, -103, -97, -92, -88,
  116433. -83, -79, -74, -70, -66, -59, -53, -58,
  116434. -62, -55, -54, -54, -54, -58, -61, -62,
  116435. -72, -70, -72, -75, -78, -80, -81, -80,
  116436. -83, -83, -88, -93, -100, -107, -115, -999,
  116437. -999, -999, -999, -999, -999, -999, -999, -999,
  116438. -999, -999, -999, -999, -999, -999, -999, -999},
  116439. {-999, -999, -999, -105, -100, -95, -90, -85,
  116440. -80, -75, -70, -66, -62, -56, -48, -44,
  116441. -48, -46, -46, -43, -46, -48, -48, -51,
  116442. -58, -58, -59, -60, -62, -62, -61, -61,
  116443. -65, -64, -65, -68, -70, -74, -75, -78,
  116444. -81, -86, -95, -110, -999, -999, -999, -999,
  116445. -999, -999, -999, -999, -999, -999, -999, -999},
  116446. {-999, -999, -105, -100, -95, -90, -85, -80,
  116447. -75, -70, -65, -61, -55, -49, -39, -33,
  116448. -40, -35, -32, -38, -40, -33, -35, -37,
  116449. -46, -41, -45, -44, -46, -42, -45, -46,
  116450. -52, -50, -50, -50, -54, -54, -55, -57,
  116451. -62, -64, -66, -68, -70, -76, -81, -90,
  116452. -100, -110, -999, -999, -999, -999, -999, -999}},
  116453. /* 354 hz */
  116454. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116455. -105, -98, -90, -85, -82, -83, -80, -78,
  116456. -84, -79, -80, -83, -87, -89, -91, -93,
  116457. -99, -106, -117, -999, -999, -999, -999, -999,
  116458. -999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999,
  116460. -999, -999, -999, -999, -999, -999, -999, -999},
  116461. {-999, -999, -999, -999, -999, -999, -999, -999,
  116462. -105, -98, -90, -85, -80, -75, -70, -68,
  116463. -74, -72, -74, -77, -80, -82, -85, -87,
  116464. -92, -89, -91, -95, -100, -106, -112, -999,
  116465. -999, -999, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999},
  116468. {-999, -999, -999, -999, -999, -999, -999, -999,
  116469. -105, -98, -90, -83, -75, -71, -63, -64,
  116470. -67, -62, -64, -67, -70, -73, -77, -81,
  116471. -84, -83, -85, -89, -90, -93, -98, -104,
  116472. -109, -114, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999},
  116475. {-999, -999, -999, -999, -999, -999, -999, -999,
  116476. -103, -96, -88, -81, -75, -68, -58, -54,
  116477. -56, -54, -56, -56, -58, -60, -63, -66,
  116478. -74, -69, -72, -72, -75, -74, -77, -81,
  116479. -81, -82, -84, -87, -93, -96, -99, -104,
  116480. -110, -999, -999, -999, -999, -999, -999, -999,
  116481. -999, -999, -999, -999, -999, -999, -999, -999},
  116482. {-999, -999, -999, -999, -999, -108, -102, -96,
  116483. -91, -85, -80, -74, -68, -60, -51, -46,
  116484. -48, -46, -43, -45, -47, -47, -49, -48,
  116485. -56, -53, -55, -58, -57, -63, -58, -60,
  116486. -66, -64, -67, -70, -70, -74, -77, -84,
  116487. -86, -89, -91, -93, -94, -101, -109, -118,
  116488. -999, -999, -999, -999, -999, -999, -999, -999},
  116489. {-999, -999, -999, -108, -103, -98, -93, -88,
  116490. -83, -78, -73, -68, -60, -53, -44, -35,
  116491. -38, -38, -34, -34, -36, -40, -41, -44,
  116492. -51, -45, -46, -47, -46, -54, -50, -49,
  116493. -50, -50, -50, -51, -54, -57, -58, -60,
  116494. -66, -66, -66, -64, -65, -68, -77, -82,
  116495. -87, -95, -110, -999, -999, -999, -999, -999}},
  116496. /* 500 Hz */
  116497. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116498. -107, -102, -97, -92, -87, -83, -78, -75,
  116499. -82, -79, -83, -85, -89, -92, -95, -98,
  116500. -101, -105, -109, -113, -999, -999, -999, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -999, -999, -999, -999, -999, -999,
  116503. -999, -999, -999, -999, -999, -999, -999, -999},
  116504. {-999, -999, -999, -999, -999, -999, -999, -106,
  116505. -100, -95, -90, -86, -81, -78, -74, -69,
  116506. -74, -74, -76, -79, -83, -84, -86, -89,
  116507. -92, -97, -93, -100, -103, -107, -110, -999,
  116508. -999, -999, -999, -999, -999, -999, -999, -999,
  116509. -999, -999, -999, -999, -999, -999, -999, -999,
  116510. -999, -999, -999, -999, -999, -999, -999, -999},
  116511. {-999, -999, -999, -999, -999, -999, -106, -100,
  116512. -95, -90, -87, -83, -80, -75, -69, -60,
  116513. -66, -66, -68, -70, -74, -78, -79, -81,
  116514. -81, -83, -84, -87, -93, -96, -99, -103,
  116515. -107, -110, -999, -999, -999, -999, -999, -999,
  116516. -999, -999, -999, -999, -999, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999},
  116518. {-999, -999, -999, -999, -999, -108, -103, -98,
  116519. -93, -89, -85, -82, -78, -71, -62, -55,
  116520. -58, -58, -54, -54, -55, -59, -61, -62,
  116521. -70, -66, -66, -67, -70, -72, -75, -78,
  116522. -84, -84, -84, -88, -91, -90, -95, -98,
  116523. -102, -103, -106, -110, -999, -999, -999, -999,
  116524. -999, -999, -999, -999, -999, -999, -999, -999},
  116525. {-999, -999, -999, -999, -108, -103, -98, -94,
  116526. -90, -87, -82, -79, -73, -67, -58, -47,
  116527. -50, -45, -41, -45, -48, -44, -44, -49,
  116528. -54, -51, -48, -47, -49, -50, -51, -57,
  116529. -58, -60, -63, -69, -70, -69, -71, -74,
  116530. -78, -82, -90, -95, -101, -105, -110, -999,
  116531. -999, -999, -999, -999, -999, -999, -999, -999},
  116532. {-999, -999, -999, -105, -101, -97, -93, -90,
  116533. -85, -80, -77, -72, -65, -56, -48, -37,
  116534. -40, -36, -34, -40, -50, -47, -38, -41,
  116535. -47, -38, -35, -39, -38, -43, -40, -45,
  116536. -50, -45, -44, -47, -50, -55, -48, -48,
  116537. -52, -66, -70, -76, -82, -90, -97, -105,
  116538. -110, -999, -999, -999, -999, -999, -999, -999}},
  116539. /* 707 Hz */
  116540. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116541. -999, -108, -103, -98, -93, -86, -79, -76,
  116542. -83, -81, -85, -87, -89, -93, -98, -102,
  116543. -107, -112, -999, -999, -999, -999, -999, -999,
  116544. -999, -999, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -999, -999, -999, -999, -999,
  116546. -999, -999, -999, -999, -999, -999, -999, -999},
  116547. {-999, -999, -999, -999, -999, -999, -999, -999,
  116548. -999, -108, -103, -98, -93, -86, -79, -71,
  116549. -77, -74, -77, -79, -81, -84, -85, -90,
  116550. -92, -93, -92, -98, -101, -108, -112, -999,
  116551. -999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -999, -999, -999, -999, -999,
  116553. -999, -999, -999, -999, -999, -999, -999, -999},
  116554. {-999, -999, -999, -999, -999, -999, -999, -999,
  116555. -108, -103, -98, -93, -87, -78, -68, -65,
  116556. -66, -62, -65, -67, -70, -73, -75, -78,
  116557. -82, -82, -83, -84, -91, -93, -98, -102,
  116558. -106, -110, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999,
  116560. -999, -999, -999, -999, -999, -999, -999, -999},
  116561. {-999, -999, -999, -999, -999, -999, -999, -999,
  116562. -105, -100, -95, -90, -82, -74, -62, -57,
  116563. -58, -56, -51, -52, -52, -54, -54, -58,
  116564. -66, -59, -60, -63, -66, -69, -73, -79,
  116565. -83, -84, -80, -81, -81, -82, -88, -92,
  116566. -98, -105, -113, -999, -999, -999, -999, -999,
  116567. -999, -999, -999, -999, -999, -999, -999, -999},
  116568. {-999, -999, -999, -999, -999, -999, -999, -107,
  116569. -102, -97, -92, -84, -79, -69, -57, -47,
  116570. -52, -47, -44, -45, -50, -52, -42, -42,
  116571. -53, -43, -43, -48, -51, -56, -55, -52,
  116572. -57, -59, -61, -62, -67, -71, -78, -83,
  116573. -86, -94, -98, -103, -110, -999, -999, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999},
  116575. {-999, -999, -999, -999, -999, -999, -105, -100,
  116576. -95, -90, -84, -78, -70, -61, -51, -41,
  116577. -40, -38, -40, -46, -52, -51, -41, -40,
  116578. -46, -40, -38, -38, -41, -46, -41, -46,
  116579. -47, -43, -43, -45, -41, -45, -56, -67,
  116580. -68, -83, -87, -90, -95, -102, -107, -113,
  116581. -999, -999, -999, -999, -999, -999, -999, -999}},
  116582. /* 1000 Hz */
  116583. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116584. -999, -109, -105, -101, -96, -91, -84, -77,
  116585. -82, -82, -85, -89, -94, -100, -106, -110,
  116586. -999, -999, -999, -999, -999, -999, -999, -999,
  116587. -999, -999, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -999, -999, -999,
  116589. -999, -999, -999, -999, -999, -999, -999, -999},
  116590. {-999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -106, -103, -98, -92, -85, -80, -71,
  116592. -75, -72, -76, -80, -84, -86, -89, -93,
  116593. -100, -107, -113, -999, -999, -999, -999, -999,
  116594. -999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999,
  116596. -999, -999, -999, -999, -999, -999, -999, -999},
  116597. {-999, -999, -999, -999, -999, -999, -999, -107,
  116598. -104, -101, -97, -92, -88, -84, -80, -64,
  116599. -66, -63, -64, -66, -69, -73, -77, -83,
  116600. -83, -86, -91, -98, -104, -111, -999, -999,
  116601. -999, -999, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -999, -999, -999, -999, -999,
  116603. -999, -999, -999, -999, -999, -999, -999, -999},
  116604. {-999, -999, -999, -999, -999, -999, -999, -107,
  116605. -104, -101, -97, -92, -90, -84, -74, -57,
  116606. -58, -52, -55, -54, -50, -52, -50, -52,
  116607. -63, -62, -69, -76, -77, -78, -78, -79,
  116608. -82, -88, -94, -100, -106, -111, -999, -999,
  116609. -999, -999, -999, -999, -999, -999, -999, -999,
  116610. -999, -999, -999, -999, -999, -999, -999, -999},
  116611. {-999, -999, -999, -999, -999, -999, -106, -102,
  116612. -98, -95, -90, -85, -83, -78, -70, -50,
  116613. -50, -41, -44, -49, -47, -50, -50, -44,
  116614. -55, -46, -47, -48, -48, -54, -49, -49,
  116615. -58, -62, -71, -81, -87, -92, -97, -102,
  116616. -108, -114, -999, -999, -999, -999, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999},
  116618. {-999, -999, -999, -999, -999, -999, -106, -102,
  116619. -98, -95, -90, -85, -83, -78, -70, -45,
  116620. -43, -41, -47, -50, -51, -50, -49, -45,
  116621. -47, -41, -44, -41, -39, -43, -38, -37,
  116622. -40, -41, -44, -50, -58, -65, -73, -79,
  116623. -85, -92, -97, -101, -105, -109, -113, -999,
  116624. -999, -999, -999, -999, -999, -999, -999, -999}},
  116625. /* 1414 Hz */
  116626. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116627. -999, -999, -999, -107, -100, -95, -87, -81,
  116628. -85, -83, -88, -93, -100, -107, -114, -999,
  116629. -999, -999, -999, -999, -999, -999, -999, -999,
  116630. -999, -999, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -999, -999, -999, -999, -999, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999},
  116633. {-999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -107, -101, -95, -88, -83, -76,
  116635. -73, -72, -79, -84, -90, -95, -100, -105,
  116636. -110, -115, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -999, -999, -999, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999},
  116640. {-999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -104, -98, -92, -87, -81, -70,
  116642. -65, -62, -67, -71, -74, -80, -85, -91,
  116643. -95, -99, -103, -108, -111, -114, -999, -999,
  116644. -999, -999, -999, -999, -999, -999, -999, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -999,
  116646. -999, -999, -999, -999, -999, -999, -999, -999},
  116647. {-999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -103, -97, -90, -85, -76, -60,
  116649. -56, -54, -60, -62, -61, -56, -63, -65,
  116650. -73, -74, -77, -75, -78, -81, -86, -87,
  116651. -88, -91, -94, -98, -103, -110, -999, -999,
  116652. -999, -999, -999, -999, -999, -999, -999, -999,
  116653. -999, -999, -999, -999, -999, -999, -999, -999},
  116654. {-999, -999, -999, -999, -999, -999, -999, -105,
  116655. -100, -97, -92, -86, -81, -79, -70, -57,
  116656. -51, -47, -51, -58, -60, -56, -53, -50,
  116657. -58, -52, -50, -50, -53, -55, -64, -69,
  116658. -71, -85, -82, -78, -81, -85, -95, -102,
  116659. -112, -999, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999},
  116661. {-999, -999, -999, -999, -999, -999, -999, -105,
  116662. -100, -97, -92, -85, -83, -79, -72, -49,
  116663. -40, -43, -43, -54, -56, -51, -50, -40,
  116664. -43, -38, -36, -35, -37, -38, -37, -44,
  116665. -54, -60, -57, -60, -70, -75, -84, -92,
  116666. -103, -112, -999, -999, -999, -999, -999, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999}},
  116668. /* 2000 Hz */
  116669. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116670. -999, -999, -999, -110, -102, -95, -89, -82,
  116671. -83, -84, -90, -92, -99, -107, -113, -999,
  116672. -999, -999, -999, -999, -999, -999, -999, -999,
  116673. -999, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999,
  116675. -999, -999, -999, -999, -999, -999, -999, -999},
  116676. {-999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -107, -101, -95, -89, -83, -72,
  116678. -74, -78, -85, -88, -88, -90, -92, -98,
  116679. -105, -111, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999},
  116683. {-999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -109, -103, -97, -93, -87, -81, -70,
  116685. -70, -67, -75, -73, -76, -79, -81, -83,
  116686. -88, -89, -97, -103, -110, -999, -999, -999,
  116687. -999, -999, -999, -999, -999, -999, -999, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999},
  116690. {-999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -107, -100, -94, -88, -83, -75, -63,
  116692. -59, -59, -63, -66, -60, -62, -67, -67,
  116693. -77, -76, -81, -88, -86, -92, -96, -102,
  116694. -109, -116, -999, -999, -999, -999, -999, -999,
  116695. -999, -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, -105, -98, -92, -86, -81, -73, -56,
  116699. -52, -47, -55, -60, -58, -52, -51, -45,
  116700. -49, -50, -53, -54, -61, -71, -70, -69,
  116701. -78, -79, -87, -90, -96, -104, -112, -999,
  116702. -999, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999},
  116704. {-999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -103, -96, -90, -86, -78, -70, -51,
  116706. -42, -47, -48, -55, -54, -54, -53, -42,
  116707. -35, -28, -33, -38, -37, -44, -47, -49,
  116708. -54, -63, -68, -78, -82, -89, -94, -99,
  116709. -104, -109, -114, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999}},
  116711. /* 2828 Hz */
  116712. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -110, -100, -90, -79,
  116714. -85, -81, -82, -82, -89, -94, -99, -103,
  116715. -109, -115, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -999, -999, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999},
  116719. {-999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -105, -97, -85, -72,
  116721. -74, -70, -70, -70, -76, -85, -91, -93,
  116722. -97, -103, -109, -115, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999},
  116726. {-999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -112, -93, -81, -68,
  116728. -62, -60, -60, -57, -63, -70, -77, -82,
  116729. -90, -93, -98, -104, -109, -113, -999, -999,
  116730. -999, -999, -999, -999, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999},
  116733. {-999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -113, -100, -93, -84, -63,
  116735. -58, -48, -53, -54, -52, -52, -57, -64,
  116736. -66, -76, -83, -81, -85, -85, -90, -95,
  116737. -98, -101, -103, -106, -108, -111, -999, -999,
  116738. -999, -999, -999, -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, -105, -95, -86, -74, -53,
  116742. -50, -38, -43, -49, -43, -42, -39, -39,
  116743. -46, -52, -57, -56, -72, -69, -74, -81,
  116744. -87, -92, -94, -97, -99, -102, -105, -108,
  116745. -999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999},
  116747. {-999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -108, -99, -90, -76, -66, -45,
  116749. -43, -41, -44, -47, -43, -47, -40, -30,
  116750. -31, -31, -39, -33, -40, -41, -43, -53,
  116751. -59, -70, -73, -77, -79, -82, -84, -87,
  116752. -999, -999, -999, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999}},
  116754. /* 4000 Hz */
  116755. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -999, -999, -999, -110, -91, -76,
  116757. -75, -85, -93, -98, -104, -110, -999, -999,
  116758. -999, -999, -999, -999, -999, -999, -999, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999},
  116762. {-999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -999, -110, -91, -70,
  116764. -70, -75, -86, -89, -94, -98, -101, -106,
  116765. -110, -999, -999, -999, -999, -999, -999, -999,
  116766. -999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999},
  116769. {-999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -110, -95, -80, -60,
  116771. -65, -64, -74, -83, -88, -91, -95, -99,
  116772. -103, -107, -110, -999, -999, -999, -999, -999,
  116773. -999, -999, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999},
  116776. {-999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -110, -95, -80, -58,
  116778. -55, -49, -66, -68, -71, -78, -78, -80,
  116779. -88, -85, -89, -97, -100, -105, -110, -999,
  116780. -999, -999, -999, -999, -999, -999, -999, -999,
  116781. -999, -999, -999, -999, -999, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999},
  116783. {-999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -110, -95, -80, -53,
  116785. -52, -41, -59, -59, -49, -58, -56, -63,
  116786. -86, -79, -90, -93, -98, -103, -107, -112,
  116787. -999, -999, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999},
  116790. {-999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -110, -97, -91, -73, -45,
  116792. -40, -33, -53, -61, -49, -54, -50, -50,
  116793. -60, -52, -67, -74, -81, -92, -96, -100,
  116794. -105, -110, -999, -999, -999, -999, -999, -999,
  116795. -999, -999, -999, -999, -999, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999}},
  116797. /* 5657 Hz */
  116798. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -113, -106, -99, -92, -77,
  116800. -80, -88, -97, -106, -115, -999, -999, -999,
  116801. -999, -999, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999},
  116805. {-999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -116, -109, -102, -95, -89, -74,
  116807. -72, -88, -87, -95, -102, -109, -116, -999,
  116808. -999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -999, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999},
  116812. {-999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -116, -109, -102, -95, -89, -75,
  116814. -66, -74, -77, -78, -86, -87, -90, -96,
  116815. -105, -115, -999, -999, -999, -999, -999, -999,
  116816. -999, -999, -999, -999, -999, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999},
  116819. {-999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -115, -108, -101, -94, -88, -66,
  116821. -56, -61, -70, -65, -78, -72, -83, -84,
  116822. -93, -98, -105, -110, -999, -999, -999, -999,
  116823. -999, -999, -999, -999, -999, -999, -999, -999,
  116824. -999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999},
  116826. {-999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -110, -105, -95, -89, -82, -57,
  116828. -52, -52, -59, -56, -59, -58, -69, -67,
  116829. -88, -82, -82, -89, -94, -100, -108, -999,
  116830. -999, -999, -999, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999},
  116833. {-999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -110, -101, -96, -90, -83, -77, -54,
  116835. -43, -38, -50, -48, -52, -48, -42, -42,
  116836. -51, -52, -53, -59, -65, -71, -78, -85,
  116837. -95, -999, -999, -999, -999, -999, -999, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999}},
  116840. /* 8000 Hz */
  116841. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -120, -105, -86, -68,
  116843. -78, -79, -90, -100, -110, -999, -999, -999,
  116844. -999, -999, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999},
  116848. {-999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -120, -105, -86, -66,
  116850. -73, -77, -88, -96, -105, -115, -999, -999,
  116851. -999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999},
  116855. {-999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -120, -105, -92, -80, -61,
  116857. -64, -68, -80, -87, -92, -100, -110, -999,
  116858. -999, -999, -999, -999, -999, -999, -999, -999,
  116859. -999, -999, -999, -999, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999},
  116862. {-999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -120, -104, -91, -79, -52,
  116864. -60, -54, -64, -69, -77, -80, -82, -84,
  116865. -85, -87, -88, -90, -999, -999, -999, -999,
  116866. -999, -999, -999, -999, -999, -999, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999},
  116869. {-999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -118, -100, -87, -77, -49,
  116871. -50, -44, -58, -61, -61, -67, -65, -62,
  116872. -62, -62, -65, -68, -999, -999, -999, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999},
  116876. {-999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -115, -98, -84, -62, -49,
  116878. -44, -38, -46, -49, -49, -46, -39, -37,
  116879. -39, -40, -42, -43, -999, -999, -999, -999,
  116880. -999, -999, -999, -999, -999, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999}},
  116883. /* 11314 Hz */
  116884. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116885. -999, -999, -999, -999, -999, -110, -88, -74,
  116886. -77, -82, -82, -85, -90, -94, -99, -104,
  116887. -999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999},
  116891. {-999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -999, -999, -999, -110, -88, -66,
  116893. -70, -81, -80, -81, -84, -88, -91, -93,
  116894. -999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999},
  116898. {-999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -999, -999, -999, -110, -88, -61,
  116900. -63, -70, -71, -74, -77, -80, -83, -85,
  116901. -999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999},
  116905. {-999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -110, -86, -62,
  116907. -63, -62, -62, -58, -52, -50, -50, -52,
  116908. -54, -999, -999, -999, -999, -999, -999, -999,
  116909. -999, -999, -999, -999, -999, -999, -999, -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, -118, -108, -84, -53,
  116914. -50, -50, -50, -55, -47, -45, -40, -40,
  116915. -40, -999, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999},
  116919. {-999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -999, -118, -100, -73, -43,
  116921. -37, -42, -43, -53, -38, -37, -35, -35,
  116922. -38, -999, -999, -999, -999, -999, -999, -999,
  116923. -999, -999, -999, -999, -999, -999, -999, -999,
  116924. -999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999}},
  116926. /* 16000 Hz */
  116927. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -110, -100, -91, -84, -74,
  116929. -80, -80, -80, -80, -80, -999, -999, -999,
  116930. -999, -999, -999, -999, -999, -999, -999, -999,
  116931. -999, -999, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999},
  116934. {-999, -999, -999, -999, -999, -999, -999, -999,
  116935. -999, -999, -999, -110, -100, -91, -84, -74,
  116936. -68, -68, -68, -68, -68, -999, -999, -999,
  116937. -999, -999, -999, -999, -999, -999, -999, -999,
  116938. -999, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999},
  116941. {-999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -110, -100, -86, -78, -70,
  116943. -60, -45, -30, -21, -999, -999, -999, -999,
  116944. -999, -999, -999, -999, -999, -999, -999, -999,
  116945. -999, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999},
  116948. {-999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -110, -100, -87, -78, -67,
  116950. -48, -38, -29, -21, -999, -999, -999, -999,
  116951. -999, -999, -999, -999, -999, -999, -999, -999,
  116952. -999, -999, -999, -999, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999},
  116955. {-999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -110, -100, -86, -69, -56,
  116957. -45, -35, -33, -29, -999, -999, -999, -999,
  116958. -999, -999, -999, -999, -999, -999, -999, -999,
  116959. -999, -999, -999, -999, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999},
  116962. {-999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -110, -100, -83, -71, -48,
  116964. -27, -38, -37, -34, -999, -999, -999, -999,
  116965. -999, -999, -999, -999, -999, -999, -999, -999,
  116966. -999, -999, -999, -999, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999}}
  116969. };
  116970. #endif
  116971. /*** End of inlined file: masking.h ***/
  116972. #define NEGINF -9999.f
  116973. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116974. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116975. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116976. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116977. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116978. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116979. look->channels=vi->channels;
  116980. look->ampmax=-9999.;
  116981. look->gi=gi;
  116982. return(look);
  116983. }
  116984. void _vp_global_free(vorbis_look_psy_global *look){
  116985. if(look){
  116986. memset(look,0,sizeof(*look));
  116987. _ogg_free(look);
  116988. }
  116989. }
  116990. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116991. if(i){
  116992. memset(i,0,sizeof(*i));
  116993. _ogg_free(i);
  116994. }
  116995. }
  116996. void _vi_psy_free(vorbis_info_psy *i){
  116997. if(i){
  116998. memset(i,0,sizeof(*i));
  116999. _ogg_free(i);
  117000. }
  117001. }
  117002. static void min_curve(float *c,
  117003. float *c2){
  117004. int i;
  117005. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117006. }
  117007. static void max_curve(float *c,
  117008. float *c2){
  117009. int i;
  117010. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117011. }
  117012. static void attenuate_curve(float *c,float att){
  117013. int i;
  117014. for(i=0;i<EHMER_MAX;i++)
  117015. c[i]+=att;
  117016. }
  117017. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117018. float center_boost, float center_decay_rate){
  117019. int i,j,k,m;
  117020. float ath[EHMER_MAX];
  117021. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117022. float athc[P_LEVELS][EHMER_MAX];
  117023. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117024. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117025. memset(workc,0,sizeof(workc));
  117026. for(i=0;i<P_BANDS;i++){
  117027. /* we add back in the ATH to avoid low level curves falling off to
  117028. -infinity and unnecessarily cutting off high level curves in the
  117029. curve limiting (last step). */
  117030. /* A half-band's settings must be valid over the whole band, and
  117031. it's better to mask too little than too much */
  117032. int ath_offset=i*4;
  117033. for(j=0;j<EHMER_MAX;j++){
  117034. float min=999.;
  117035. for(k=0;k<4;k++)
  117036. if(j+k+ath_offset<MAX_ATH){
  117037. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117038. }else{
  117039. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117040. }
  117041. ath[j]=min;
  117042. }
  117043. /* copy curves into working space, replicate the 50dB curve to 30
  117044. and 40, replicate the 100dB curve to 110 */
  117045. for(j=0;j<6;j++)
  117046. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117047. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117048. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117049. /* apply centered curve boost/decay */
  117050. for(j=0;j<P_LEVELS;j++){
  117051. for(k=0;k<EHMER_MAX;k++){
  117052. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117053. if(adj<0. && center_boost>0)adj=0.;
  117054. if(adj>0. && center_boost<0)adj=0.;
  117055. workc[i][j][k]+=adj;
  117056. }
  117057. }
  117058. /* normalize curves so the driving amplitude is 0dB */
  117059. /* make temp curves with the ATH overlayed */
  117060. for(j=0;j<P_LEVELS;j++){
  117061. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117062. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117063. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117064. max_curve(athc[j],workc[i][j]);
  117065. }
  117066. /* Now limit the louder curves.
  117067. the idea is this: We don't know what the playback attenuation
  117068. will be; 0dB SL moves every time the user twiddles the volume
  117069. knob. So that means we have to use a single 'most pessimal' curve
  117070. for all masking amplitudes, right? Wrong. The *loudest* sound
  117071. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117072. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117073. etc... */
  117074. for(j=1;j<P_LEVELS;j++){
  117075. min_curve(athc[j],athc[j-1]);
  117076. min_curve(workc[i][j],athc[j]);
  117077. }
  117078. }
  117079. for(i=0;i<P_BANDS;i++){
  117080. int hi_curve,lo_curve,bin;
  117081. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117082. /* low frequency curves are measured with greater resolution than
  117083. the MDCT/FFT will actually give us; we want the curve applied
  117084. to the tone data to be pessimistic and thus apply the minimum
  117085. masking possible for a given bin. That means that a single bin
  117086. could span more than one octave and that the curve will be a
  117087. composite of multiple octaves. It also may mean that a single
  117088. bin may span > an eighth of an octave and that the eighth
  117089. octave values may also be composited. */
  117090. /* which octave curves will we be compositing? */
  117091. bin=floor(fromOC(i*.5)/binHz);
  117092. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117093. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117094. if(lo_curve>i)lo_curve=i;
  117095. if(lo_curve<0)lo_curve=0;
  117096. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117097. for(m=0;m<P_LEVELS;m++){
  117098. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117099. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117100. /* render the curve into bins, then pull values back into curve.
  117101. The point is that any inherent subsampling aliasing results in
  117102. a safe minimum */
  117103. for(k=lo_curve;k<=hi_curve;k++){
  117104. int l=0;
  117105. for(j=0;j<EHMER_MAX;j++){
  117106. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117107. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117108. if(lo_bin<0)lo_bin=0;
  117109. if(lo_bin>n)lo_bin=n;
  117110. if(lo_bin<l)l=lo_bin;
  117111. if(hi_bin<0)hi_bin=0;
  117112. if(hi_bin>n)hi_bin=n;
  117113. for(;l<hi_bin && l<n;l++)
  117114. if(brute_buffer[l]>workc[k][m][j])
  117115. brute_buffer[l]=workc[k][m][j];
  117116. }
  117117. for(;l<n;l++)
  117118. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117119. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117120. }
  117121. /* be equally paranoid about being valid up to next half ocatve */
  117122. if(i+1<P_BANDS){
  117123. int l=0;
  117124. k=i+1;
  117125. for(j=0;j<EHMER_MAX;j++){
  117126. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117127. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117128. if(lo_bin<0)lo_bin=0;
  117129. if(lo_bin>n)lo_bin=n;
  117130. if(lo_bin<l)l=lo_bin;
  117131. if(hi_bin<0)hi_bin=0;
  117132. if(hi_bin>n)hi_bin=n;
  117133. for(;l<hi_bin && l<n;l++)
  117134. if(brute_buffer[l]>workc[k][m][j])
  117135. brute_buffer[l]=workc[k][m][j];
  117136. }
  117137. for(;l<n;l++)
  117138. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117139. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117140. }
  117141. for(j=0;j<EHMER_MAX;j++){
  117142. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117143. if(bin<0){
  117144. ret[i][m][j+2]=-999.;
  117145. }else{
  117146. if(bin>=n){
  117147. ret[i][m][j+2]=-999.;
  117148. }else{
  117149. ret[i][m][j+2]=brute_buffer[bin];
  117150. }
  117151. }
  117152. }
  117153. /* add fenceposts */
  117154. for(j=0;j<EHMER_OFFSET;j++)
  117155. if(ret[i][m][j+2]>-200.f)break;
  117156. ret[i][m][0]=j;
  117157. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117158. if(ret[i][m][j+2]>-200.f)
  117159. break;
  117160. ret[i][m][1]=j;
  117161. }
  117162. }
  117163. return(ret);
  117164. }
  117165. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117166. vorbis_info_psy_global *gi,int n,long rate){
  117167. long i,j,lo=-99,hi=1;
  117168. long maxoc;
  117169. memset(p,0,sizeof(*p));
  117170. p->eighth_octave_lines=gi->eighth_octave_lines;
  117171. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117172. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117173. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117174. p->total_octave_lines=maxoc-p->firstoc+1;
  117175. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117176. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117177. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117178. p->vi=vi;
  117179. p->n=n;
  117180. p->rate=rate;
  117181. /* AoTuV HF weighting */
  117182. p->m_val = 1.;
  117183. if(rate < 26000) p->m_val = 0;
  117184. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117185. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117186. /* set up the lookups for a given blocksize and sample rate */
  117187. for(i=0,j=0;i<MAX_ATH-1;i++){
  117188. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117189. float base=ATH[i];
  117190. if(j<endpos){
  117191. float delta=(ATH[i+1]-base)/(endpos-j);
  117192. for(;j<endpos && j<n;j++){
  117193. p->ath[j]=base+100.;
  117194. base+=delta;
  117195. }
  117196. }
  117197. }
  117198. for(i=0;i<n;i++){
  117199. float bark=toBARK(rate/(2*n)*i);
  117200. for(;lo+vi->noisewindowlomin<i &&
  117201. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117202. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117203. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117204. p->bark[i]=((lo-1)<<16)+(hi-1);
  117205. }
  117206. for(i=0;i<n;i++)
  117207. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117208. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117209. vi->tone_centerboost,vi->tone_decay);
  117210. /* set up rolling noise median */
  117211. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117212. for(i=0;i<P_NOISECURVES;i++)
  117213. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117214. for(i=0;i<n;i++){
  117215. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117216. int inthalfoc;
  117217. float del;
  117218. if(halfoc<0)halfoc=0;
  117219. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117220. inthalfoc=(int)halfoc;
  117221. del=halfoc-inthalfoc;
  117222. for(j=0;j<P_NOISECURVES;j++)
  117223. p->noiseoffset[j][i]=
  117224. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117225. p->vi->noiseoff[j][inthalfoc+1]*del;
  117226. }
  117227. #if 0
  117228. {
  117229. static int ls=0;
  117230. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117231. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117232. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117233. }
  117234. #endif
  117235. }
  117236. void _vp_psy_clear(vorbis_look_psy *p){
  117237. int i,j;
  117238. if(p){
  117239. if(p->ath)_ogg_free(p->ath);
  117240. if(p->octave)_ogg_free(p->octave);
  117241. if(p->bark)_ogg_free(p->bark);
  117242. if(p->tonecurves){
  117243. for(i=0;i<P_BANDS;i++){
  117244. for(j=0;j<P_LEVELS;j++){
  117245. _ogg_free(p->tonecurves[i][j]);
  117246. }
  117247. _ogg_free(p->tonecurves[i]);
  117248. }
  117249. _ogg_free(p->tonecurves);
  117250. }
  117251. if(p->noiseoffset){
  117252. for(i=0;i<P_NOISECURVES;i++){
  117253. _ogg_free(p->noiseoffset[i]);
  117254. }
  117255. _ogg_free(p->noiseoffset);
  117256. }
  117257. memset(p,0,sizeof(*p));
  117258. }
  117259. }
  117260. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117261. static void seed_curve(float *seed,
  117262. const float **curves,
  117263. float amp,
  117264. int oc, int n,
  117265. int linesper,float dBoffset){
  117266. int i,post1;
  117267. int seedptr;
  117268. const float *posts,*curve;
  117269. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117270. choice=max(choice,0);
  117271. choice=min(choice,P_LEVELS-1);
  117272. posts=curves[choice];
  117273. curve=posts+2;
  117274. post1=(int)posts[1];
  117275. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117276. for(i=posts[0];i<post1;i++){
  117277. if(seedptr>0){
  117278. float lin=amp+curve[i];
  117279. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117280. }
  117281. seedptr+=linesper;
  117282. if(seedptr>=n)break;
  117283. }
  117284. }
  117285. static void seed_loop(vorbis_look_psy *p,
  117286. const float ***curves,
  117287. const float *f,
  117288. const float *flr,
  117289. float *seed,
  117290. float specmax){
  117291. vorbis_info_psy *vi=p->vi;
  117292. long n=p->n,i;
  117293. float dBoffset=vi->max_curve_dB-specmax;
  117294. /* prime the working vector with peak values */
  117295. for(i=0;i<n;i++){
  117296. float max=f[i];
  117297. long oc=p->octave[i];
  117298. while(i+1<n && p->octave[i+1]==oc){
  117299. i++;
  117300. if(f[i]>max)max=f[i];
  117301. }
  117302. if(max+6.f>flr[i]){
  117303. oc=oc>>p->shiftoc;
  117304. if(oc>=P_BANDS)oc=P_BANDS-1;
  117305. if(oc<0)oc=0;
  117306. seed_curve(seed,
  117307. curves[oc],
  117308. max,
  117309. p->octave[i]-p->firstoc,
  117310. p->total_octave_lines,
  117311. p->eighth_octave_lines,
  117312. dBoffset);
  117313. }
  117314. }
  117315. }
  117316. static void seed_chase(float *seeds, int linesper, long n){
  117317. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117318. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117319. long stack=0;
  117320. long pos=0;
  117321. long i;
  117322. for(i=0;i<n;i++){
  117323. if(stack<2){
  117324. posstack[stack]=i;
  117325. ampstack[stack++]=seeds[i];
  117326. }else{
  117327. while(1){
  117328. if(seeds[i]<ampstack[stack-1]){
  117329. posstack[stack]=i;
  117330. ampstack[stack++]=seeds[i];
  117331. break;
  117332. }else{
  117333. if(i<posstack[stack-1]+linesper){
  117334. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117335. i<posstack[stack-2]+linesper){
  117336. /* we completely overlap, making stack-1 irrelevant. pop it */
  117337. stack--;
  117338. continue;
  117339. }
  117340. }
  117341. posstack[stack]=i;
  117342. ampstack[stack++]=seeds[i];
  117343. break;
  117344. }
  117345. }
  117346. }
  117347. }
  117348. /* the stack now contains only the positions that are relevant. Scan
  117349. 'em straight through */
  117350. for(i=0;i<stack;i++){
  117351. long endpos;
  117352. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117353. endpos=posstack[i+1];
  117354. }else{
  117355. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117356. discarded in short frames */
  117357. }
  117358. if(endpos>n)endpos=n;
  117359. for(;pos<endpos;pos++)
  117360. seeds[pos]=ampstack[i];
  117361. }
  117362. /* there. Linear time. I now remember this was on a problem set I
  117363. had in Grad Skool... I didn't solve it at the time ;-) */
  117364. }
  117365. /* bleaugh, this is more complicated than it needs to be */
  117366. #include<stdio.h>
  117367. static void max_seeds(vorbis_look_psy *p,
  117368. float *seed,
  117369. float *flr){
  117370. long n=p->total_octave_lines;
  117371. int linesper=p->eighth_octave_lines;
  117372. long linpos=0;
  117373. long pos;
  117374. seed_chase(seed,linesper,n); /* for masking */
  117375. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117376. while(linpos+1<p->n){
  117377. float minV=seed[pos];
  117378. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117379. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117380. while(pos+1<=end){
  117381. pos++;
  117382. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117383. minV=seed[pos];
  117384. }
  117385. end=pos+p->firstoc;
  117386. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117387. if(flr[linpos]<minV)flr[linpos]=minV;
  117388. }
  117389. {
  117390. float minV=seed[p->total_octave_lines-1];
  117391. for(;linpos<p->n;linpos++)
  117392. if(flr[linpos]<minV)flr[linpos]=minV;
  117393. }
  117394. }
  117395. static void bark_noise_hybridmp(int n,const long *b,
  117396. const float *f,
  117397. float *noise,
  117398. const float offset,
  117399. const int fixed){
  117400. float *N=(float*) alloca(n*sizeof(*N));
  117401. float *X=(float*) alloca(n*sizeof(*N));
  117402. float *XX=(float*) alloca(n*sizeof(*N));
  117403. float *Y=(float*) alloca(n*sizeof(*N));
  117404. float *XY=(float*) alloca(n*sizeof(*N));
  117405. float tN, tX, tXX, tY, tXY;
  117406. int i;
  117407. int lo, hi;
  117408. float R, A, B, D;
  117409. float w, x, y;
  117410. tN = tX = tXX = tY = tXY = 0.f;
  117411. y = f[0] + offset;
  117412. if (y < 1.f) y = 1.f;
  117413. w = y * y * .5;
  117414. tN += w;
  117415. tX += w;
  117416. tY += w * y;
  117417. N[0] = tN;
  117418. X[0] = tX;
  117419. XX[0] = tXX;
  117420. Y[0] = tY;
  117421. XY[0] = tXY;
  117422. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117423. y = f[i] + offset;
  117424. if (y < 1.f) y = 1.f;
  117425. w = y * y;
  117426. tN += w;
  117427. tX += w * x;
  117428. tXX += w * x * x;
  117429. tY += w * y;
  117430. tXY += w * x * y;
  117431. N[i] = tN;
  117432. X[i] = tX;
  117433. XX[i] = tXX;
  117434. Y[i] = tY;
  117435. XY[i] = tXY;
  117436. }
  117437. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117438. lo = b[i] >> 16;
  117439. if( lo>=0 ) break;
  117440. hi = b[i] & 0xffff;
  117441. tN = N[hi] + N[-lo];
  117442. tX = X[hi] - X[-lo];
  117443. tXX = XX[hi] + XX[-lo];
  117444. tY = Y[hi] + Y[-lo];
  117445. tXY = XY[hi] - XY[-lo];
  117446. A = tY * tXX - tX * tXY;
  117447. B = tN * tXY - tX * tY;
  117448. D = tN * tXX - tX * tX;
  117449. R = (A + x * B) / D;
  117450. if (R < 0.f)
  117451. R = 0.f;
  117452. noise[i] = R - offset;
  117453. }
  117454. for ( ;; i++, x += 1.f) {
  117455. lo = b[i] >> 16;
  117456. hi = b[i] & 0xffff;
  117457. if(hi>=n)break;
  117458. tN = N[hi] - N[lo];
  117459. tX = X[hi] - X[lo];
  117460. tXX = XX[hi] - XX[lo];
  117461. tY = Y[hi] - Y[lo];
  117462. tXY = XY[hi] - XY[lo];
  117463. A = tY * tXX - tX * tXY;
  117464. B = tN * tXY - tX * tY;
  117465. D = tN * tXX - tX * tX;
  117466. R = (A + x * B) / D;
  117467. if (R < 0.f) R = 0.f;
  117468. noise[i] = R - offset;
  117469. }
  117470. for ( ; i < n; i++, x += 1.f) {
  117471. R = (A + x * B) / D;
  117472. if (R < 0.f) R = 0.f;
  117473. noise[i] = R - offset;
  117474. }
  117475. if (fixed <= 0) return;
  117476. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117477. hi = i + fixed / 2;
  117478. lo = hi - fixed;
  117479. if(lo>=0)break;
  117480. tN = N[hi] + N[-lo];
  117481. tX = X[hi] - X[-lo];
  117482. tXX = XX[hi] + XX[-lo];
  117483. tY = Y[hi] + Y[-lo];
  117484. tXY = XY[hi] - XY[-lo];
  117485. A = tY * tXX - tX * tXY;
  117486. B = tN * tXY - tX * tY;
  117487. D = tN * tXX - tX * tX;
  117488. R = (A + x * B) / D;
  117489. if (R - offset < noise[i]) noise[i] = R - offset;
  117490. }
  117491. for ( ;; i++, x += 1.f) {
  117492. hi = i + fixed / 2;
  117493. lo = hi - fixed;
  117494. if(hi>=n)break;
  117495. tN = N[hi] - N[lo];
  117496. tX = X[hi] - X[lo];
  117497. tXX = XX[hi] - XX[lo];
  117498. tY = Y[hi] - Y[lo];
  117499. tXY = XY[hi] - XY[lo];
  117500. A = tY * tXX - tX * tXY;
  117501. B = tN * tXY - tX * tY;
  117502. D = tN * tXX - tX * tX;
  117503. R = (A + x * B) / D;
  117504. if (R - offset < noise[i]) noise[i] = R - offset;
  117505. }
  117506. for ( ; i < n; i++, x += 1.f) {
  117507. R = (A + x * B) / D;
  117508. if (R - offset < noise[i]) noise[i] = R - offset;
  117509. }
  117510. }
  117511. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117512. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117513. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117514. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117515. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117516. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117517. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117518. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117519. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117520. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117521. 973377.F, 913981.F, 858210.F, 805842.F,
  117522. 756669.F, 710497.F, 667142.F, 626433.F,
  117523. 588208.F, 552316.F, 518613.F, 486967.F,
  117524. 457252.F, 429351.F, 403152.F, 378551.F,
  117525. 355452.F, 333762.F, 313396.F, 294273.F,
  117526. 276316.F, 259455.F, 243623.F, 228757.F,
  117527. 214798.F, 201691.F, 189384.F, 177828.F,
  117528. 166977.F, 156788.F, 147221.F, 138237.F,
  117529. 129802.F, 121881.F, 114444.F, 107461.F,
  117530. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117531. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117532. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117533. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117534. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117535. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117536. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117537. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117538. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117539. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117540. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117541. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117542. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117543. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117544. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117545. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117546. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117547. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117548. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117549. 842.910F, 791.475F, 743.179F, 697.830F,
  117550. 655.249F, 615.265F, 577.722F, 542.469F,
  117551. 509.367F, 478.286F, 449.101F, 421.696F,
  117552. 395.964F, 371.803F, 349.115F, 327.812F,
  117553. 307.809F, 289.026F, 271.390F, 254.830F,
  117554. 239.280F, 224.679F, 210.969F, 198.096F,
  117555. 186.008F, 174.658F, 164.000F, 153.993F,
  117556. 144.596F, 135.773F, 127.488F, 119.708F,
  117557. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117558. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117559. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117560. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117561. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117562. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117563. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117564. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117565. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117566. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117567. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117568. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117569. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117570. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117571. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117572. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117573. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117574. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117575. 1.20790F, 1.13419F, 1.06499F, 1.F
  117576. };
  117577. void _vp_remove_floor(vorbis_look_psy *p,
  117578. float *mdct,
  117579. int *codedflr,
  117580. float *residue,
  117581. int sliding_lowpass){
  117582. int i,n=p->n;
  117583. if(sliding_lowpass>n)sliding_lowpass=n;
  117584. for(i=0;i<sliding_lowpass;i++){
  117585. residue[i]=
  117586. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117587. }
  117588. for(;i<n;i++)
  117589. residue[i]=0.;
  117590. }
  117591. void _vp_noisemask(vorbis_look_psy *p,
  117592. float *logmdct,
  117593. float *logmask){
  117594. int i,n=p->n;
  117595. float *work=(float*) alloca(n*sizeof(*work));
  117596. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117597. 140.,-1);
  117598. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117599. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117600. p->vi->noisewindowfixed);
  117601. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117602. #if 0
  117603. {
  117604. static int seq=0;
  117605. float work2[n];
  117606. for(i=0;i<n;i++){
  117607. work2[i]=logmask[i]+work[i];
  117608. }
  117609. if(seq&1)
  117610. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117611. else
  117612. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117613. if(seq&1)
  117614. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117615. else
  117616. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117617. seq++;
  117618. }
  117619. #endif
  117620. for(i=0;i<n;i++){
  117621. int dB=logmask[i]+.5;
  117622. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117623. if(dB<0)dB=0;
  117624. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117625. }
  117626. }
  117627. void _vp_tonemask(vorbis_look_psy *p,
  117628. float *logfft,
  117629. float *logmask,
  117630. float global_specmax,
  117631. float local_specmax){
  117632. int i,n=p->n;
  117633. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117634. float att=local_specmax+p->vi->ath_adjatt;
  117635. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117636. /* set the ATH (floating below localmax, not global max by a
  117637. specified att) */
  117638. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117639. for(i=0;i<n;i++)
  117640. logmask[i]=p->ath[i]+att;
  117641. /* tone masking */
  117642. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117643. max_seeds(p,seed,logmask);
  117644. }
  117645. void _vp_offset_and_mix(vorbis_look_psy *p,
  117646. float *noise,
  117647. float *tone,
  117648. int offset_select,
  117649. float *logmask,
  117650. float *mdct,
  117651. float *logmdct){
  117652. int i,n=p->n;
  117653. float de, coeffi, cx;/* AoTuV */
  117654. float toneatt=p->vi->tone_masteratt[offset_select];
  117655. cx = p->m_val;
  117656. for(i=0;i<n;i++){
  117657. float val= noise[i]+p->noiseoffset[offset_select][i];
  117658. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117659. logmask[i]=max(val,tone[i]+toneatt);
  117660. /* AoTuV */
  117661. /** @ M1 **
  117662. The following codes improve a noise problem.
  117663. A fundamental idea uses the value of masking and carries out
  117664. the relative compensation of the MDCT.
  117665. However, this code is not perfect and all noise problems cannot be solved.
  117666. by Aoyumi @ 2004/04/18
  117667. */
  117668. if(offset_select == 1) {
  117669. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117670. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117671. if(val > coeffi){
  117672. /* mdct value is > -17.2 dB below floor */
  117673. de = 1.0-((val-coeffi)*0.005*cx);
  117674. /* pro-rated attenuation:
  117675. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117676. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117677. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117678. etc... */
  117679. if(de < 0) de = 0.0001;
  117680. }else
  117681. /* mdct value is <= -17.2 dB below floor */
  117682. de = 1.0-((val-coeffi)*0.0003*cx);
  117683. /* pro-rated attenuation:
  117684. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117685. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117686. etc... */
  117687. mdct[i] *= de;
  117688. }
  117689. }
  117690. }
  117691. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117692. vorbis_info *vi=vd->vi;
  117693. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117694. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117695. int n=ci->blocksizes[vd->W]/2;
  117696. float secs=(float)n/vi->rate;
  117697. amp+=secs*gi->ampmax_att_per_sec;
  117698. if(amp<-9999)amp=-9999;
  117699. return(amp);
  117700. }
  117701. static void couple_lossless(float A, float B,
  117702. float *qA, float *qB){
  117703. int test1=fabs(*qA)>fabs(*qB);
  117704. test1-= fabs(*qA)<fabs(*qB);
  117705. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117706. if(test1==1){
  117707. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117708. }else{
  117709. float temp=*qB;
  117710. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117711. *qA=temp;
  117712. }
  117713. if(*qB>fabs(*qA)*1.9999f){
  117714. *qB= -fabs(*qA)*2.f;
  117715. *qA= -*qA;
  117716. }
  117717. }
  117718. static float hypot_lookup[32]={
  117719. -0.009935, -0.011245, -0.012726, -0.014397,
  117720. -0.016282, -0.018407, -0.020800, -0.023494,
  117721. -0.026522, -0.029923, -0.033737, -0.038010,
  117722. -0.042787, -0.048121, -0.054064, -0.060671,
  117723. -0.068000, -0.076109, -0.085054, -0.094892,
  117724. -0.105675, -0.117451, -0.130260, -0.144134,
  117725. -0.159093, -0.175146, -0.192286, -0.210490,
  117726. -0.229718, -0.249913, -0.271001, -0.292893};
  117727. static void precomputed_couple_point(float premag,
  117728. int floorA,int floorB,
  117729. float *mag, float *ang){
  117730. int test=(floorA>floorB)-1;
  117731. int offset=31-abs(floorA-floorB);
  117732. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117733. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117734. *mag=premag*floormag;
  117735. *ang=0.f;
  117736. }
  117737. /* just like below, this is currently set up to only do
  117738. single-step-depth coupling. Otherwise, we'd have to do more
  117739. copying (which will be inevitable later) */
  117740. /* doing the real circular magnitude calculation is audibly superior
  117741. to (A+B)/sqrt(2) */
  117742. static float dipole_hypot(float a, float b){
  117743. if(a>0.){
  117744. if(b>0.)return sqrt(a*a+b*b);
  117745. if(a>-b)return sqrt(a*a-b*b);
  117746. return -sqrt(b*b-a*a);
  117747. }
  117748. if(b<0.)return -sqrt(a*a+b*b);
  117749. if(-a>b)return -sqrt(a*a-b*b);
  117750. return sqrt(b*b-a*a);
  117751. }
  117752. static float round_hypot(float a, float b){
  117753. if(a>0.){
  117754. if(b>0.)return sqrt(a*a+b*b);
  117755. if(a>-b)return sqrt(a*a+b*b);
  117756. return -sqrt(b*b+a*a);
  117757. }
  117758. if(b<0.)return -sqrt(a*a+b*b);
  117759. if(-a>b)return -sqrt(a*a+b*b);
  117760. return sqrt(b*b+a*a);
  117761. }
  117762. /* revert to round hypot for now */
  117763. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117764. vorbis_info_psy_global *g,
  117765. vorbis_look_psy *p,
  117766. vorbis_info_mapping0 *vi,
  117767. float **mdct){
  117768. int i,j,n=p->n;
  117769. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117770. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117771. for(i=0;i<vi->coupling_steps;i++){
  117772. float *mdctM=mdct[vi->coupling_mag[i]];
  117773. float *mdctA=mdct[vi->coupling_ang[i]];
  117774. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117775. for(j=0;j<limit;j++)
  117776. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117777. for(;j<n;j++)
  117778. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117779. }
  117780. return(ret);
  117781. }
  117782. /* this is for per-channel noise normalization */
  117783. static int apsort(const void *a, const void *b){
  117784. float f1=fabs(**(float**)a);
  117785. float f2=fabs(**(float**)b);
  117786. return (f1<f2)-(f1>f2);
  117787. }
  117788. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117789. vorbis_look_psy *p,
  117790. vorbis_info_mapping0 *vi,
  117791. float **mags){
  117792. if(p->vi->normal_point_p){
  117793. int i,j,k,n=p->n;
  117794. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117795. int partition=p->vi->normal_partition;
  117796. float **work=(float**) alloca(sizeof(*work)*partition);
  117797. for(i=0;i<vi->coupling_steps;i++){
  117798. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117799. for(j=0;j<n;j+=partition){
  117800. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117801. qsort(work,partition,sizeof(*work),apsort);
  117802. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117803. }
  117804. }
  117805. return(ret);
  117806. }
  117807. return(NULL);
  117808. }
  117809. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117810. float *magnitudes,int *sortedindex){
  117811. int i,j,n=p->n;
  117812. vorbis_info_psy *vi=p->vi;
  117813. int partition=vi->normal_partition;
  117814. float **work=(float**) alloca(sizeof(*work)*partition);
  117815. int start=vi->normal_start;
  117816. for(j=start;j<n;j+=partition){
  117817. if(j+partition>n)partition=n-j;
  117818. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117819. qsort(work,partition,sizeof(*work),apsort);
  117820. for(i=0;i<partition;i++){
  117821. sortedindex[i+j-start]=work[i]-magnitudes;
  117822. }
  117823. }
  117824. }
  117825. void _vp_noise_normalize(vorbis_look_psy *p,
  117826. float *in,float *out,int *sortedindex){
  117827. int flag=0,i,j=0,n=p->n;
  117828. vorbis_info_psy *vi=p->vi;
  117829. int partition=vi->normal_partition;
  117830. int start=vi->normal_start;
  117831. if(start>n)start=n;
  117832. if(vi->normal_channel_p){
  117833. for(;j<start;j++)
  117834. out[j]=rint(in[j]);
  117835. for(;j+partition<=n;j+=partition){
  117836. float acc=0.;
  117837. int k;
  117838. for(i=j;i<j+partition;i++)
  117839. acc+=in[i]*in[i];
  117840. for(i=0;i<partition;i++){
  117841. k=sortedindex[i+j-start];
  117842. if(in[k]*in[k]>=.25f){
  117843. out[k]=rint(in[k]);
  117844. acc-=in[k]*in[k];
  117845. flag=1;
  117846. }else{
  117847. if(acc<vi->normal_thresh)break;
  117848. out[k]=unitnorm(in[k]);
  117849. acc-=1.;
  117850. }
  117851. }
  117852. for(;i<partition;i++){
  117853. k=sortedindex[i+j-start];
  117854. out[k]=0.;
  117855. }
  117856. }
  117857. }
  117858. for(;j<n;j++)
  117859. out[j]=rint(in[j]);
  117860. }
  117861. void _vp_couple(int blobno,
  117862. vorbis_info_psy_global *g,
  117863. vorbis_look_psy *p,
  117864. vorbis_info_mapping0 *vi,
  117865. float **res,
  117866. float **mag_memo,
  117867. int **mag_sort,
  117868. int **ifloor,
  117869. int *nonzero,
  117870. int sliding_lowpass){
  117871. int i,j,k,n=p->n;
  117872. /* perform any requested channel coupling */
  117873. /* point stereo can only be used in a first stage (in this encoder)
  117874. because of the dependency on floor lookups */
  117875. for(i=0;i<vi->coupling_steps;i++){
  117876. /* once we're doing multistage coupling in which a channel goes
  117877. through more than one coupling step, the floor vector
  117878. magnitudes will also have to be recalculated an propogated
  117879. along with PCM. Right now, we're not (that will wait until 5.1
  117880. most likely), so the code isn't here yet. The memory management
  117881. here is all assuming single depth couplings anyway. */
  117882. /* make sure coupling a zero and a nonzero channel results in two
  117883. nonzero channels. */
  117884. if(nonzero[vi->coupling_mag[i]] ||
  117885. nonzero[vi->coupling_ang[i]]){
  117886. float *rM=res[vi->coupling_mag[i]];
  117887. float *rA=res[vi->coupling_ang[i]];
  117888. float *qM=rM+n;
  117889. float *qA=rA+n;
  117890. int *floorM=ifloor[vi->coupling_mag[i]];
  117891. int *floorA=ifloor[vi->coupling_ang[i]];
  117892. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117893. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117894. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117895. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117896. int pointlimit=limit;
  117897. nonzero[vi->coupling_mag[i]]=1;
  117898. nonzero[vi->coupling_ang[i]]=1;
  117899. /* The threshold of a stereo is changed with the size of n */
  117900. if(n > 1000)
  117901. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117902. for(j=0;j<p->n;j+=partition){
  117903. float acc=0.f;
  117904. for(k=0;k<partition;k++){
  117905. int l=k+j;
  117906. if(l<sliding_lowpass){
  117907. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117908. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117909. precomputed_couple_point(mag_memo[i][l],
  117910. floorM[l],floorA[l],
  117911. qM+l,qA+l);
  117912. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117913. }else{
  117914. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117915. }
  117916. }else{
  117917. qM[l]=0.;
  117918. qA[l]=0.;
  117919. }
  117920. }
  117921. if(p->vi->normal_point_p){
  117922. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117923. int l=mag_sort[i][j+k];
  117924. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117925. qM[l]=unitnorm(qM[l]);
  117926. acc-=1.f;
  117927. }
  117928. }
  117929. }
  117930. }
  117931. }
  117932. }
  117933. }
  117934. /* AoTuV */
  117935. /** @ M2 **
  117936. The boost problem by the combination of noise normalization and point stereo is eased.
  117937. However, this is a temporary patch.
  117938. by Aoyumi @ 2004/04/18
  117939. */
  117940. void hf_reduction(vorbis_info_psy_global *g,
  117941. vorbis_look_psy *p,
  117942. vorbis_info_mapping0 *vi,
  117943. float **mdct){
  117944. int i,j,n=p->n, de=0.3*p->m_val;
  117945. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117946. for(i=0; i<vi->coupling_steps; i++){
  117947. /* for(j=start; j<limit; j++){} // ???*/
  117948. for(j=limit; j<n; j++)
  117949. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117950. }
  117951. }
  117952. #endif
  117953. /*** End of inlined file: psy.c ***/
  117954. /*** Start of inlined file: registry.c ***/
  117955. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117956. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117957. // tasks..
  117958. #if JUCE_MSVC
  117959. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117960. #endif
  117961. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117962. #if JUCE_USE_OGGVORBIS
  117963. /* seems like major overkill now; the backend numbers will grow into
  117964. the infrastructure soon enough */
  117965. extern vorbis_func_floor floor0_exportbundle;
  117966. extern vorbis_func_floor floor1_exportbundle;
  117967. extern vorbis_func_residue residue0_exportbundle;
  117968. extern vorbis_func_residue residue1_exportbundle;
  117969. extern vorbis_func_residue residue2_exportbundle;
  117970. extern vorbis_func_mapping mapping0_exportbundle;
  117971. vorbis_func_floor *_floor_P[]={
  117972. &floor0_exportbundle,
  117973. &floor1_exportbundle,
  117974. };
  117975. vorbis_func_residue *_residue_P[]={
  117976. &residue0_exportbundle,
  117977. &residue1_exportbundle,
  117978. &residue2_exportbundle,
  117979. };
  117980. vorbis_func_mapping *_mapping_P[]={
  117981. &mapping0_exportbundle,
  117982. };
  117983. #endif
  117984. /*** End of inlined file: registry.c ***/
  117985. /*** Start of inlined file: res0.c ***/
  117986. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117987. encode/decode loops are coded for clarity and performance is not
  117988. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117989. it's slow. */
  117990. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117991. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117992. // tasks..
  117993. #if JUCE_MSVC
  117994. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117995. #endif
  117996. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117997. #if JUCE_USE_OGGVORBIS
  117998. #include <stdlib.h>
  117999. #include <string.h>
  118000. #include <math.h>
  118001. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118002. #include <stdio.h>
  118003. #endif
  118004. typedef struct {
  118005. vorbis_info_residue0 *info;
  118006. int parts;
  118007. int stages;
  118008. codebook *fullbooks;
  118009. codebook *phrasebook;
  118010. codebook ***partbooks;
  118011. int partvals;
  118012. int **decodemap;
  118013. long postbits;
  118014. long phrasebits;
  118015. long frames;
  118016. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118017. int train_seq;
  118018. long *training_data[8][64];
  118019. float training_max[8][64];
  118020. float training_min[8][64];
  118021. float tmin;
  118022. float tmax;
  118023. #endif
  118024. } vorbis_look_residue0;
  118025. void res0_free_info(vorbis_info_residue *i){
  118026. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118027. if(info){
  118028. memset(info,0,sizeof(*info));
  118029. _ogg_free(info);
  118030. }
  118031. }
  118032. void res0_free_look(vorbis_look_residue *i){
  118033. int j;
  118034. if(i){
  118035. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118036. #ifdef TRAIN_RES
  118037. {
  118038. int j,k,l;
  118039. for(j=0;j<look->parts;j++){
  118040. /*fprintf(stderr,"partition %d: ",j);*/
  118041. for(k=0;k<8;k++)
  118042. if(look->training_data[k][j]){
  118043. char buffer[80];
  118044. FILE *of;
  118045. codebook *statebook=look->partbooks[j][k];
  118046. /* long and short into the same bucket by current convention */
  118047. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118048. of=fopen(buffer,"a");
  118049. for(l=0;l<statebook->entries;l++)
  118050. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118051. fclose(of);
  118052. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118053. look->training_min[k][j],look->training_max[k][j]);*/
  118054. _ogg_free(look->training_data[k][j]);
  118055. look->training_data[k][j]=NULL;
  118056. }
  118057. /*fprintf(stderr,"\n");*/
  118058. }
  118059. }
  118060. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118061. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118062. (float)look->phrasebits/look->frames,
  118063. (float)look->postbits/look->frames,
  118064. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118065. #endif
  118066. /*vorbis_info_residue0 *info=look->info;
  118067. fprintf(stderr,
  118068. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118069. "(%g/frame) \n",look->frames,look->phrasebits,
  118070. look->resbitsflat,
  118071. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118072. for(j=0;j<look->parts;j++){
  118073. long acc=0;
  118074. fprintf(stderr,"\t[%d] == ",j);
  118075. for(k=0;k<look->stages;k++)
  118076. if((info->secondstages[j]>>k)&1){
  118077. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118078. acc+=look->resbits[j][k];
  118079. }
  118080. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118081. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118082. }
  118083. fprintf(stderr,"\n");*/
  118084. for(j=0;j<look->parts;j++)
  118085. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118086. _ogg_free(look->partbooks);
  118087. for(j=0;j<look->partvals;j++)
  118088. _ogg_free(look->decodemap[j]);
  118089. _ogg_free(look->decodemap);
  118090. memset(look,0,sizeof(*look));
  118091. _ogg_free(look);
  118092. }
  118093. }
  118094. static int icount(unsigned int v){
  118095. int ret=0;
  118096. while(v){
  118097. ret+=v&1;
  118098. v>>=1;
  118099. }
  118100. return(ret);
  118101. }
  118102. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118103. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118104. int j,acc=0;
  118105. oggpack_write(opb,info->begin,24);
  118106. oggpack_write(opb,info->end,24);
  118107. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118108. code with a partitioned book */
  118109. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118110. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118111. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118112. bitmask of one indicates this partition class has bits to write
  118113. this pass */
  118114. for(j=0;j<info->partitions;j++){
  118115. if(ilog(info->secondstages[j])>3){
  118116. /* yes, this is a minor hack due to not thinking ahead */
  118117. oggpack_write(opb,info->secondstages[j],3);
  118118. oggpack_write(opb,1,1);
  118119. oggpack_write(opb,info->secondstages[j]>>3,5);
  118120. }else
  118121. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118122. acc+=icount(info->secondstages[j]);
  118123. }
  118124. for(j=0;j<acc;j++)
  118125. oggpack_write(opb,info->booklist[j],8);
  118126. }
  118127. /* vorbis_info is for range checking */
  118128. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118129. int j,acc=0;
  118130. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118131. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118132. info->begin=oggpack_read(opb,24);
  118133. info->end=oggpack_read(opb,24);
  118134. info->grouping=oggpack_read(opb,24)+1;
  118135. info->partitions=oggpack_read(opb,6)+1;
  118136. info->groupbook=oggpack_read(opb,8);
  118137. for(j=0;j<info->partitions;j++){
  118138. int cascade=oggpack_read(opb,3);
  118139. if(oggpack_read(opb,1))
  118140. cascade|=(oggpack_read(opb,5)<<3);
  118141. info->secondstages[j]=cascade;
  118142. acc+=icount(cascade);
  118143. }
  118144. for(j=0;j<acc;j++)
  118145. info->booklist[j]=oggpack_read(opb,8);
  118146. if(info->groupbook>=ci->books)goto errout;
  118147. for(j=0;j<acc;j++)
  118148. if(info->booklist[j]>=ci->books)goto errout;
  118149. return(info);
  118150. errout:
  118151. res0_free_info(info);
  118152. return(NULL);
  118153. }
  118154. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118155. vorbis_info_residue *vr){
  118156. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118157. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118158. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118159. int j,k,acc=0;
  118160. int dim;
  118161. int maxstage=0;
  118162. look->info=info;
  118163. look->parts=info->partitions;
  118164. look->fullbooks=ci->fullbooks;
  118165. look->phrasebook=ci->fullbooks+info->groupbook;
  118166. dim=look->phrasebook->dim;
  118167. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118168. for(j=0;j<look->parts;j++){
  118169. int stages=ilog(info->secondstages[j]);
  118170. if(stages){
  118171. if(stages>maxstage)maxstage=stages;
  118172. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118173. for(k=0;k<stages;k++)
  118174. if(info->secondstages[j]&(1<<k)){
  118175. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118176. #ifdef TRAIN_RES
  118177. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118178. sizeof(***look->training_data));
  118179. #endif
  118180. }
  118181. }
  118182. }
  118183. look->partvals=rint(pow((float)look->parts,(float)dim));
  118184. look->stages=maxstage;
  118185. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118186. for(j=0;j<look->partvals;j++){
  118187. long val=j;
  118188. long mult=look->partvals/look->parts;
  118189. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118190. for(k=0;k<dim;k++){
  118191. long deco=val/mult;
  118192. val-=deco*mult;
  118193. mult/=look->parts;
  118194. look->decodemap[j][k]=deco;
  118195. }
  118196. }
  118197. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118198. {
  118199. static int train_seq=0;
  118200. look->train_seq=train_seq++;
  118201. }
  118202. #endif
  118203. return(look);
  118204. }
  118205. /* break an abstraction and copy some code for performance purposes */
  118206. static int local_book_besterror(codebook *book,float *a){
  118207. int dim=book->dim,i,k,o;
  118208. int best=0;
  118209. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118210. /* find the quant val of each scalar */
  118211. for(k=0,o=dim;k<dim;++k){
  118212. float val=a[--o];
  118213. i=tt->threshvals>>1;
  118214. if(val<tt->quantthresh[i]){
  118215. if(val<tt->quantthresh[i-1]){
  118216. for(--i;i>0;--i)
  118217. if(val>=tt->quantthresh[i-1])
  118218. break;
  118219. }
  118220. }else{
  118221. for(++i;i<tt->threshvals-1;++i)
  118222. if(val<tt->quantthresh[i])break;
  118223. }
  118224. best=(best*tt->quantvals)+tt->quantmap[i];
  118225. }
  118226. /* regular lattices are easy :-) */
  118227. if(book->c->lengthlist[best]<=0){
  118228. const static_codebook *c=book->c;
  118229. int i,j;
  118230. float bestf=0.f;
  118231. float *e=book->valuelist;
  118232. best=-1;
  118233. for(i=0;i<book->entries;i++){
  118234. if(c->lengthlist[i]>0){
  118235. float thisx=0.f;
  118236. for(j=0;j<dim;j++){
  118237. float val=(e[j]-a[j]);
  118238. thisx+=val*val;
  118239. }
  118240. if(best==-1 || thisx<bestf){
  118241. bestf=thisx;
  118242. best=i;
  118243. }
  118244. }
  118245. e+=dim;
  118246. }
  118247. }
  118248. {
  118249. float *ptr=book->valuelist+best*dim;
  118250. for(i=0;i<dim;i++)
  118251. *a++ -= *ptr++;
  118252. }
  118253. return(best);
  118254. }
  118255. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118256. codebook *book,long *acc){
  118257. int i,bits=0;
  118258. int dim=book->dim;
  118259. int step=n/dim;
  118260. for(i=0;i<step;i++){
  118261. int entry=local_book_besterror(book,vec+i*dim);
  118262. #ifdef TRAIN_RES
  118263. acc[entry]++;
  118264. #endif
  118265. bits+=vorbis_book_encode(book,entry,opb);
  118266. }
  118267. return(bits);
  118268. }
  118269. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118270. float **in,int ch){
  118271. long i,j,k;
  118272. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118273. vorbis_info_residue0 *info=look->info;
  118274. /* move all this setup out later */
  118275. int samples_per_partition=info->grouping;
  118276. int possible_partitions=info->partitions;
  118277. int n=info->end-info->begin;
  118278. int partvals=n/samples_per_partition;
  118279. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118280. float scale=100./samples_per_partition;
  118281. /* we find the partition type for each partition of each
  118282. channel. We'll go back and do the interleaved encoding in a
  118283. bit. For now, clarity */
  118284. for(i=0;i<ch;i++){
  118285. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118286. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118287. }
  118288. for(i=0;i<partvals;i++){
  118289. int offset=i*samples_per_partition+info->begin;
  118290. for(j=0;j<ch;j++){
  118291. float max=0.;
  118292. float ent=0.;
  118293. for(k=0;k<samples_per_partition;k++){
  118294. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118295. ent+=fabs(rint(in[j][offset+k]));
  118296. }
  118297. ent*=scale;
  118298. for(k=0;k<possible_partitions-1;k++)
  118299. if(max<=info->classmetric1[k] &&
  118300. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118301. break;
  118302. partword[j][i]=k;
  118303. }
  118304. }
  118305. #ifdef TRAIN_RESAUX
  118306. {
  118307. FILE *of;
  118308. char buffer[80];
  118309. for(i=0;i<ch;i++){
  118310. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118311. of=fopen(buffer,"a");
  118312. for(j=0;j<partvals;j++)
  118313. fprintf(of,"%ld, ",partword[i][j]);
  118314. fprintf(of,"\n");
  118315. fclose(of);
  118316. }
  118317. }
  118318. #endif
  118319. look->frames++;
  118320. return(partword);
  118321. }
  118322. /* designed for stereo or other modes where the partition size is an
  118323. integer multiple of the number of channels encoded in the current
  118324. submap */
  118325. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118326. int ch){
  118327. long i,j,k,l;
  118328. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118329. vorbis_info_residue0 *info=look->info;
  118330. /* move all this setup out later */
  118331. int samples_per_partition=info->grouping;
  118332. int possible_partitions=info->partitions;
  118333. int n=info->end-info->begin;
  118334. int partvals=n/samples_per_partition;
  118335. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118336. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118337. FILE *of;
  118338. char buffer[80];
  118339. #endif
  118340. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118341. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118342. for(i=0,l=info->begin/ch;i<partvals;i++){
  118343. float magmax=0.f;
  118344. float angmax=0.f;
  118345. for(j=0;j<samples_per_partition;j+=ch){
  118346. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118347. for(k=1;k<ch;k++)
  118348. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118349. l++;
  118350. }
  118351. for(j=0;j<possible_partitions-1;j++)
  118352. if(magmax<=info->classmetric1[j] &&
  118353. angmax<=info->classmetric2[j])
  118354. break;
  118355. partword[0][i]=j;
  118356. }
  118357. #ifdef TRAIN_RESAUX
  118358. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118359. of=fopen(buffer,"a");
  118360. for(i=0;i<partvals;i++)
  118361. fprintf(of,"%ld, ",partword[0][i]);
  118362. fprintf(of,"\n");
  118363. fclose(of);
  118364. #endif
  118365. look->frames++;
  118366. return(partword);
  118367. }
  118368. static int _01forward(oggpack_buffer *opb,
  118369. vorbis_block *vb,vorbis_look_residue *vl,
  118370. float **in,int ch,
  118371. long **partword,
  118372. int (*encode)(oggpack_buffer *,float *,int,
  118373. codebook *,long *)){
  118374. long i,j,k,s;
  118375. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118376. vorbis_info_residue0 *info=look->info;
  118377. /* move all this setup out later */
  118378. int samples_per_partition=info->grouping;
  118379. int possible_partitions=info->partitions;
  118380. int partitions_per_word=look->phrasebook->dim;
  118381. int n=info->end-info->begin;
  118382. int partvals=n/samples_per_partition;
  118383. long resbits[128];
  118384. long resvals[128];
  118385. #ifdef TRAIN_RES
  118386. for(i=0;i<ch;i++)
  118387. for(j=info->begin;j<info->end;j++){
  118388. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118389. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118390. }
  118391. #endif
  118392. memset(resbits,0,sizeof(resbits));
  118393. memset(resvals,0,sizeof(resvals));
  118394. /* we code the partition words for each channel, then the residual
  118395. words for a partition per channel until we've written all the
  118396. residual words for that partition word. Then write the next
  118397. partition channel words... */
  118398. for(s=0;s<look->stages;s++){
  118399. for(i=0;i<partvals;){
  118400. /* first we encode a partition codeword for each channel */
  118401. if(s==0){
  118402. for(j=0;j<ch;j++){
  118403. long val=partword[j][i];
  118404. for(k=1;k<partitions_per_word;k++){
  118405. val*=possible_partitions;
  118406. if(i+k<partvals)
  118407. val+=partword[j][i+k];
  118408. }
  118409. /* training hack */
  118410. if(val<look->phrasebook->entries)
  118411. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118412. #if 0 /*def TRAIN_RES*/
  118413. else
  118414. fprintf(stderr,"!");
  118415. #endif
  118416. }
  118417. }
  118418. /* now we encode interleaved residual values for the partitions */
  118419. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118420. long offset=i*samples_per_partition+info->begin;
  118421. for(j=0;j<ch;j++){
  118422. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118423. if(info->secondstages[partword[j][i]]&(1<<s)){
  118424. codebook *statebook=look->partbooks[partword[j][i]][s];
  118425. if(statebook){
  118426. int ret;
  118427. long *accumulator=NULL;
  118428. #ifdef TRAIN_RES
  118429. accumulator=look->training_data[s][partword[j][i]];
  118430. {
  118431. int l;
  118432. float *samples=in[j]+offset;
  118433. for(l=0;l<samples_per_partition;l++){
  118434. if(samples[l]<look->training_min[s][partword[j][i]])
  118435. look->training_min[s][partword[j][i]]=samples[l];
  118436. if(samples[l]>look->training_max[s][partword[j][i]])
  118437. look->training_max[s][partword[j][i]]=samples[l];
  118438. }
  118439. }
  118440. #endif
  118441. ret=encode(opb,in[j]+offset,samples_per_partition,
  118442. statebook,accumulator);
  118443. look->postbits+=ret;
  118444. resbits[partword[j][i]]+=ret;
  118445. }
  118446. }
  118447. }
  118448. }
  118449. }
  118450. }
  118451. /*{
  118452. long total=0;
  118453. long totalbits=0;
  118454. fprintf(stderr,"%d :: ",vb->mode);
  118455. for(k=0;k<possible_partitions;k++){
  118456. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118457. total+=resvals[k];
  118458. totalbits+=resbits[k];
  118459. }
  118460. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118461. }*/
  118462. return(0);
  118463. }
  118464. /* a truncated packet here just means 'stop working'; it's not an error */
  118465. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118466. float **in,int ch,
  118467. long (*decodepart)(codebook *, float *,
  118468. oggpack_buffer *,int)){
  118469. long i,j,k,l,s;
  118470. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118471. vorbis_info_residue0 *info=look->info;
  118472. /* move all this setup out later */
  118473. int samples_per_partition=info->grouping;
  118474. int partitions_per_word=look->phrasebook->dim;
  118475. int n=info->end-info->begin;
  118476. int partvals=n/samples_per_partition;
  118477. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118478. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118479. for(j=0;j<ch;j++)
  118480. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118481. for(s=0;s<look->stages;s++){
  118482. /* each loop decodes on partition codeword containing
  118483. partitions_pre_word partitions */
  118484. for(i=0,l=0;i<partvals;l++){
  118485. if(s==0){
  118486. /* fetch the partition word for each channel */
  118487. for(j=0;j<ch;j++){
  118488. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118489. if(temp==-1)goto eopbreak;
  118490. partword[j][l]=look->decodemap[temp];
  118491. if(partword[j][l]==NULL)goto errout;
  118492. }
  118493. }
  118494. /* now we decode residual values for the partitions */
  118495. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118496. for(j=0;j<ch;j++){
  118497. long offset=info->begin+i*samples_per_partition;
  118498. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118499. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118500. if(stagebook){
  118501. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118502. samples_per_partition)==-1)goto eopbreak;
  118503. }
  118504. }
  118505. }
  118506. }
  118507. }
  118508. errout:
  118509. eopbreak:
  118510. return(0);
  118511. }
  118512. #if 0
  118513. /* residue 0 and 1 are just slight variants of one another. 0 is
  118514. interleaved, 1 is not */
  118515. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118516. float **in,int *nonzero,int ch){
  118517. /* we encode only the nonzero parts of a bundle */
  118518. int i,used=0;
  118519. for(i=0;i<ch;i++)
  118520. if(nonzero[i])
  118521. in[used++]=in[i];
  118522. if(used)
  118523. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118524. return(_01class(vb,vl,in,used));
  118525. else
  118526. return(0);
  118527. }
  118528. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118529. float **in,float **out,int *nonzero,int ch,
  118530. long **partword){
  118531. /* we encode only the nonzero parts of a bundle */
  118532. int i,j,used=0,n=vb->pcmend/2;
  118533. for(i=0;i<ch;i++)
  118534. if(nonzero[i]){
  118535. if(out)
  118536. for(j=0;j<n;j++)
  118537. out[i][j]+=in[i][j];
  118538. in[used++]=in[i];
  118539. }
  118540. if(used){
  118541. int ret=_01forward(vb,vl,in,used,partword,
  118542. _interleaved_encodepart);
  118543. if(out){
  118544. used=0;
  118545. for(i=0;i<ch;i++)
  118546. if(nonzero[i]){
  118547. for(j=0;j<n;j++)
  118548. out[i][j]-=in[used][j];
  118549. used++;
  118550. }
  118551. }
  118552. return(ret);
  118553. }else{
  118554. return(0);
  118555. }
  118556. }
  118557. #endif
  118558. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118559. float **in,int *nonzero,int ch){
  118560. int i,used=0;
  118561. for(i=0;i<ch;i++)
  118562. if(nonzero[i])
  118563. in[used++]=in[i];
  118564. if(used)
  118565. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118566. else
  118567. return(0);
  118568. }
  118569. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118570. float **in,float **out,int *nonzero,int ch,
  118571. long **partword){
  118572. int i,j,used=0,n=vb->pcmend/2;
  118573. for(i=0;i<ch;i++)
  118574. if(nonzero[i]){
  118575. if(out)
  118576. for(j=0;j<n;j++)
  118577. out[i][j]+=in[i][j];
  118578. in[used++]=in[i];
  118579. }
  118580. if(used){
  118581. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118582. if(out){
  118583. used=0;
  118584. for(i=0;i<ch;i++)
  118585. if(nonzero[i]){
  118586. for(j=0;j<n;j++)
  118587. out[i][j]-=in[used][j];
  118588. used++;
  118589. }
  118590. }
  118591. return(ret);
  118592. }else{
  118593. return(0);
  118594. }
  118595. }
  118596. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118597. float **in,int *nonzero,int ch){
  118598. int i,used=0;
  118599. for(i=0;i<ch;i++)
  118600. if(nonzero[i])
  118601. in[used++]=in[i];
  118602. if(used)
  118603. return(_01class(vb,vl,in,used));
  118604. else
  118605. return(0);
  118606. }
  118607. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118608. float **in,int *nonzero,int ch){
  118609. int i,used=0;
  118610. for(i=0;i<ch;i++)
  118611. if(nonzero[i])
  118612. in[used++]=in[i];
  118613. if(used)
  118614. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118615. else
  118616. return(0);
  118617. }
  118618. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118619. float **in,int *nonzero,int ch){
  118620. int i,used=0;
  118621. for(i=0;i<ch;i++)
  118622. if(nonzero[i])used++;
  118623. if(used)
  118624. return(_2class(vb,vl,in,ch));
  118625. else
  118626. return(0);
  118627. }
  118628. /* res2 is slightly more different; all the channels are interleaved
  118629. into a single vector and encoded. */
  118630. int res2_forward(oggpack_buffer *opb,
  118631. vorbis_block *vb,vorbis_look_residue *vl,
  118632. float **in,float **out,int *nonzero,int ch,
  118633. long **partword){
  118634. long i,j,k,n=vb->pcmend/2,used=0;
  118635. /* don't duplicate the code; use a working vector hack for now and
  118636. reshape ourselves into a single channel res1 */
  118637. /* ugly; reallocs for each coupling pass :-( */
  118638. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118639. for(i=0;i<ch;i++){
  118640. float *pcm=in[i];
  118641. if(nonzero[i])used++;
  118642. for(j=0,k=i;j<n;j++,k+=ch)
  118643. work[k]=pcm[j];
  118644. }
  118645. if(used){
  118646. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118647. /* update the sofar vector */
  118648. if(out){
  118649. for(i=0;i<ch;i++){
  118650. float *pcm=in[i];
  118651. float *sofar=out[i];
  118652. for(j=0,k=i;j<n;j++,k+=ch)
  118653. sofar[j]+=pcm[j]-work[k];
  118654. }
  118655. }
  118656. return(ret);
  118657. }else{
  118658. return(0);
  118659. }
  118660. }
  118661. /* duplicate code here as speed is somewhat more important */
  118662. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118663. float **in,int *nonzero,int ch){
  118664. long i,k,l,s;
  118665. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118666. vorbis_info_residue0 *info=look->info;
  118667. /* move all this setup out later */
  118668. int samples_per_partition=info->grouping;
  118669. int partitions_per_word=look->phrasebook->dim;
  118670. int n=info->end-info->begin;
  118671. int partvals=n/samples_per_partition;
  118672. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118673. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118674. for(i=0;i<ch;i++)if(nonzero[i])break;
  118675. if(i==ch)return(0); /* no nonzero vectors */
  118676. for(s=0;s<look->stages;s++){
  118677. for(i=0,l=0;i<partvals;l++){
  118678. if(s==0){
  118679. /* fetch the partition word */
  118680. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118681. if(temp==-1)goto eopbreak;
  118682. partword[l]=look->decodemap[temp];
  118683. if(partword[l]==NULL)goto errout;
  118684. }
  118685. /* now we decode residual values for the partitions */
  118686. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118687. if(info->secondstages[partword[l][k]]&(1<<s)){
  118688. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118689. if(stagebook){
  118690. if(vorbis_book_decodevv_add(stagebook,in,
  118691. i*samples_per_partition+info->begin,ch,
  118692. &vb->opb,samples_per_partition)==-1)
  118693. goto eopbreak;
  118694. }
  118695. }
  118696. }
  118697. }
  118698. errout:
  118699. eopbreak:
  118700. return(0);
  118701. }
  118702. vorbis_func_residue residue0_exportbundle={
  118703. NULL,
  118704. &res0_unpack,
  118705. &res0_look,
  118706. &res0_free_info,
  118707. &res0_free_look,
  118708. NULL,
  118709. NULL,
  118710. &res0_inverse
  118711. };
  118712. vorbis_func_residue residue1_exportbundle={
  118713. &res0_pack,
  118714. &res0_unpack,
  118715. &res0_look,
  118716. &res0_free_info,
  118717. &res0_free_look,
  118718. &res1_class,
  118719. &res1_forward,
  118720. &res1_inverse
  118721. };
  118722. vorbis_func_residue residue2_exportbundle={
  118723. &res0_pack,
  118724. &res0_unpack,
  118725. &res0_look,
  118726. &res0_free_info,
  118727. &res0_free_look,
  118728. &res2_class,
  118729. &res2_forward,
  118730. &res2_inverse
  118731. };
  118732. #endif
  118733. /*** End of inlined file: res0.c ***/
  118734. /*** Start of inlined file: sharedbook.c ***/
  118735. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118736. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118737. // tasks..
  118738. #if JUCE_MSVC
  118739. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118740. #endif
  118741. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118742. #if JUCE_USE_OGGVORBIS
  118743. #include <stdlib.h>
  118744. #include <math.h>
  118745. #include <string.h>
  118746. /**** pack/unpack helpers ******************************************/
  118747. int _ilog(unsigned int v){
  118748. int ret=0;
  118749. while(v){
  118750. ret++;
  118751. v>>=1;
  118752. }
  118753. return(ret);
  118754. }
  118755. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118756. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118757. Why not IEEE? It's just not that important here. */
  118758. #define VQ_FEXP 10
  118759. #define VQ_FMAN 21
  118760. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118761. /* doesn't currently guard under/overflow */
  118762. long _float32_pack(float val){
  118763. int sign=0;
  118764. long exp;
  118765. long mant;
  118766. if(val<0){
  118767. sign=0x80000000;
  118768. val= -val;
  118769. }
  118770. exp= floor(log(val)/log(2.f));
  118771. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118772. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118773. return(sign|exp|mant);
  118774. }
  118775. float _float32_unpack(long val){
  118776. double mant=val&0x1fffff;
  118777. int sign=val&0x80000000;
  118778. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118779. if(sign)mant= -mant;
  118780. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118781. }
  118782. /* given a list of word lengths, generate a list of codewords. Works
  118783. for length ordered or unordered, always assigns the lowest valued
  118784. codewords first. Extended to handle unused entries (length 0) */
  118785. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118786. long i,j,count=0;
  118787. ogg_uint32_t marker[33];
  118788. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118789. memset(marker,0,sizeof(marker));
  118790. for(i=0;i<n;i++){
  118791. long length=l[i];
  118792. if(length>0){
  118793. ogg_uint32_t entry=marker[length];
  118794. /* when we claim a node for an entry, we also claim the nodes
  118795. below it (pruning off the imagined tree that may have dangled
  118796. from it) as well as blocking the use of any nodes directly
  118797. above for leaves */
  118798. /* update ourself */
  118799. if(length<32 && (entry>>length)){
  118800. /* error condition; the lengths must specify an overpopulated tree */
  118801. _ogg_free(r);
  118802. return(NULL);
  118803. }
  118804. r[count++]=entry;
  118805. /* Look to see if the next shorter marker points to the node
  118806. above. if so, update it and repeat. */
  118807. {
  118808. for(j=length;j>0;j--){
  118809. if(marker[j]&1){
  118810. /* have to jump branches */
  118811. if(j==1)
  118812. marker[1]++;
  118813. else
  118814. marker[j]=marker[j-1]<<1;
  118815. break; /* invariant says next upper marker would already
  118816. have been moved if it was on the same path */
  118817. }
  118818. marker[j]++;
  118819. }
  118820. }
  118821. /* prune the tree; the implicit invariant says all the longer
  118822. markers were dangling from our just-taken node. Dangle them
  118823. from our *new* node. */
  118824. for(j=length+1;j<33;j++)
  118825. if((marker[j]>>1) == entry){
  118826. entry=marker[j];
  118827. marker[j]=marker[j-1]<<1;
  118828. }else
  118829. break;
  118830. }else
  118831. if(sparsecount==0)count++;
  118832. }
  118833. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118834. endian */
  118835. for(i=0,count=0;i<n;i++){
  118836. ogg_uint32_t temp=0;
  118837. for(j=0;j<l[i];j++){
  118838. temp<<=1;
  118839. temp|=(r[count]>>j)&1;
  118840. }
  118841. if(sparsecount){
  118842. if(l[i])
  118843. r[count++]=temp;
  118844. }else
  118845. r[count++]=temp;
  118846. }
  118847. return(r);
  118848. }
  118849. /* there might be a straightforward one-line way to do the below
  118850. that's portable and totally safe against roundoff, but I haven't
  118851. thought of it. Therefore, we opt on the side of caution */
  118852. long _book_maptype1_quantvals(const static_codebook *b){
  118853. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118854. /* the above *should* be reliable, but we'll not assume that FP is
  118855. ever reliable when bitstream sync is at stake; verify via integer
  118856. means that vals really is the greatest value of dim for which
  118857. vals^b->bim <= b->entries */
  118858. /* treat the above as an initial guess */
  118859. while(1){
  118860. long acc=1;
  118861. long acc1=1;
  118862. int i;
  118863. for(i=0;i<b->dim;i++){
  118864. acc*=vals;
  118865. acc1*=vals+1;
  118866. }
  118867. if(acc<=b->entries && acc1>b->entries){
  118868. return(vals);
  118869. }else{
  118870. if(acc>b->entries){
  118871. vals--;
  118872. }else{
  118873. vals++;
  118874. }
  118875. }
  118876. }
  118877. }
  118878. /* unpack the quantized list of values for encode/decode ***********/
  118879. /* we need to deal with two map types: in map type 1, the values are
  118880. generated algorithmically (each column of the vector counts through
  118881. the values in the quant vector). in map type 2, all the values came
  118882. in in an explicit list. Both value lists must be unpacked */
  118883. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118884. long j,k,count=0;
  118885. if(b->maptype==1 || b->maptype==2){
  118886. int quantvals;
  118887. float mindel=_float32_unpack(b->q_min);
  118888. float delta=_float32_unpack(b->q_delta);
  118889. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118890. /* maptype 1 and 2 both use a quantized value vector, but
  118891. different sizes */
  118892. switch(b->maptype){
  118893. case 1:
  118894. /* most of the time, entries%dimensions == 0, but we need to be
  118895. well defined. We define that the possible vales at each
  118896. scalar is values == entries/dim. If entries%dim != 0, we'll
  118897. have 'too few' values (values*dim<entries), which means that
  118898. we'll have 'left over' entries; left over entries use zeroed
  118899. values (and are wasted). So don't generate codebooks like
  118900. that */
  118901. quantvals=_book_maptype1_quantvals(b);
  118902. for(j=0;j<b->entries;j++){
  118903. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118904. float last=0.f;
  118905. int indexdiv=1;
  118906. for(k=0;k<b->dim;k++){
  118907. int index= (j/indexdiv)%quantvals;
  118908. float val=b->quantlist[index];
  118909. val=fabs(val)*delta+mindel+last;
  118910. if(b->q_sequencep)last=val;
  118911. if(sparsemap)
  118912. r[sparsemap[count]*b->dim+k]=val;
  118913. else
  118914. r[count*b->dim+k]=val;
  118915. indexdiv*=quantvals;
  118916. }
  118917. count++;
  118918. }
  118919. }
  118920. break;
  118921. case 2:
  118922. for(j=0;j<b->entries;j++){
  118923. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118924. float last=0.f;
  118925. for(k=0;k<b->dim;k++){
  118926. float val=b->quantlist[j*b->dim+k];
  118927. val=fabs(val)*delta+mindel+last;
  118928. if(b->q_sequencep)last=val;
  118929. if(sparsemap)
  118930. r[sparsemap[count]*b->dim+k]=val;
  118931. else
  118932. r[count*b->dim+k]=val;
  118933. }
  118934. count++;
  118935. }
  118936. }
  118937. break;
  118938. }
  118939. return(r);
  118940. }
  118941. return(NULL);
  118942. }
  118943. void vorbis_staticbook_clear(static_codebook *b){
  118944. if(b->allocedp){
  118945. if(b->quantlist)_ogg_free(b->quantlist);
  118946. if(b->lengthlist)_ogg_free(b->lengthlist);
  118947. if(b->nearest_tree){
  118948. _ogg_free(b->nearest_tree->ptr0);
  118949. _ogg_free(b->nearest_tree->ptr1);
  118950. _ogg_free(b->nearest_tree->p);
  118951. _ogg_free(b->nearest_tree->q);
  118952. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118953. _ogg_free(b->nearest_tree);
  118954. }
  118955. if(b->thresh_tree){
  118956. _ogg_free(b->thresh_tree->quantthresh);
  118957. _ogg_free(b->thresh_tree->quantmap);
  118958. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118959. _ogg_free(b->thresh_tree);
  118960. }
  118961. memset(b,0,sizeof(*b));
  118962. }
  118963. }
  118964. void vorbis_staticbook_destroy(static_codebook *b){
  118965. if(b->allocedp){
  118966. vorbis_staticbook_clear(b);
  118967. _ogg_free(b);
  118968. }
  118969. }
  118970. void vorbis_book_clear(codebook *b){
  118971. /* static book is not cleared; we're likely called on the lookup and
  118972. the static codebook belongs to the info struct */
  118973. if(b->valuelist)_ogg_free(b->valuelist);
  118974. if(b->codelist)_ogg_free(b->codelist);
  118975. if(b->dec_index)_ogg_free(b->dec_index);
  118976. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118977. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118978. memset(b,0,sizeof(*b));
  118979. }
  118980. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118981. memset(c,0,sizeof(*c));
  118982. c->c=s;
  118983. c->entries=s->entries;
  118984. c->used_entries=s->entries;
  118985. c->dim=s->dim;
  118986. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118987. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118988. return(0);
  118989. }
  118990. static int sort32a(const void *a,const void *b){
  118991. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118992. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118993. }
  118994. /* decode codebook arrangement is more heavily optimized than encode */
  118995. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118996. int i,j,n=0,tabn;
  118997. int *sortindex;
  118998. memset(c,0,sizeof(*c));
  118999. /* count actually used entries */
  119000. for(i=0;i<s->entries;i++)
  119001. if(s->lengthlist[i]>0)
  119002. n++;
  119003. c->entries=s->entries;
  119004. c->used_entries=n;
  119005. c->dim=s->dim;
  119006. /* two different remappings go on here.
  119007. First, we collapse the likely sparse codebook down only to
  119008. actually represented values/words. This collapsing needs to be
  119009. indexed as map-valueless books are used to encode original entry
  119010. positions as integers.
  119011. Second, we reorder all vectors, including the entry index above,
  119012. by sorted bitreversed codeword to allow treeless decode. */
  119013. {
  119014. /* perform sort */
  119015. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119016. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119017. if(codes==NULL)goto err_out;
  119018. for(i=0;i<n;i++){
  119019. codes[i]=ogg_bitreverse(codes[i]);
  119020. codep[i]=codes+i;
  119021. }
  119022. qsort(codep,n,sizeof(*codep),sort32a);
  119023. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119024. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119025. /* the index is a reverse index */
  119026. for(i=0;i<n;i++){
  119027. int position=codep[i]-codes;
  119028. sortindex[position]=i;
  119029. }
  119030. for(i=0;i<n;i++)
  119031. c->codelist[sortindex[i]]=codes[i];
  119032. _ogg_free(codes);
  119033. }
  119034. c->valuelist=_book_unquantize(s,n,sortindex);
  119035. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119036. for(n=0,i=0;i<s->entries;i++)
  119037. if(s->lengthlist[i]>0)
  119038. c->dec_index[sortindex[n++]]=i;
  119039. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119040. for(n=0,i=0;i<s->entries;i++)
  119041. if(s->lengthlist[i]>0)
  119042. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119043. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119044. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119045. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119046. tabn=1<<c->dec_firsttablen;
  119047. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119048. c->dec_maxlength=0;
  119049. for(i=0;i<n;i++){
  119050. if(c->dec_maxlength<c->dec_codelengths[i])
  119051. c->dec_maxlength=c->dec_codelengths[i];
  119052. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119053. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119054. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119055. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119056. }
  119057. }
  119058. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119059. hints for the non-direct-hits */
  119060. {
  119061. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119062. long lo=0,hi=0;
  119063. for(i=0;i<tabn;i++){
  119064. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119065. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119066. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119067. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119068. /* we only actually have 15 bits per hint to play with here.
  119069. In order to overflow gracefully (nothing breaks, efficiency
  119070. just drops), encode as the difference from the extremes. */
  119071. {
  119072. unsigned long loval=lo;
  119073. unsigned long hival=n-hi;
  119074. if(loval>0x7fff)loval=0x7fff;
  119075. if(hival>0x7fff)hival=0x7fff;
  119076. c->dec_firsttable[ogg_bitreverse(word)]=
  119077. 0x80000000UL | (loval<<15) | hival;
  119078. }
  119079. }
  119080. }
  119081. }
  119082. return(0);
  119083. err_out:
  119084. vorbis_book_clear(c);
  119085. return(-1);
  119086. }
  119087. static float _dist(int el,float *ref, float *b,int step){
  119088. int i;
  119089. float acc=0.f;
  119090. for(i=0;i<el;i++){
  119091. float val=(ref[i]-b[i*step]);
  119092. acc+=val*val;
  119093. }
  119094. return(acc);
  119095. }
  119096. int _best(codebook *book, float *a, int step){
  119097. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119098. #if 0
  119099. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119100. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119101. #endif
  119102. int dim=book->dim;
  119103. int k,o;
  119104. /*int savebest=-1;
  119105. float saverr;*/
  119106. /* do we have a threshhold encode hint? */
  119107. if(tt){
  119108. int index=0,i;
  119109. /* find the quant val of each scalar */
  119110. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119111. i=tt->threshvals>>1;
  119112. if(a[o]<tt->quantthresh[i]){
  119113. for(;i>0;i--)
  119114. if(a[o]>=tt->quantthresh[i-1])
  119115. break;
  119116. }else{
  119117. for(i++;i<tt->threshvals-1;i++)
  119118. if(a[o]<tt->quantthresh[i])break;
  119119. }
  119120. index=(index*tt->quantvals)+tt->quantmap[i];
  119121. }
  119122. /* regular lattices are easy :-) */
  119123. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119124. use a decision tree after all
  119125. and fall through*/
  119126. return(index);
  119127. }
  119128. #if 0
  119129. /* do we have a pigeonhole encode hint? */
  119130. if(pt){
  119131. const static_codebook *c=book->c;
  119132. int i,besti=-1;
  119133. float best=0.f;
  119134. int entry=0;
  119135. /* dealing with sequentialness is a pain in the ass */
  119136. if(c->q_sequencep){
  119137. int pv;
  119138. long mul=1;
  119139. float qlast=0;
  119140. for(k=0,o=0;k<dim;k++,o+=step){
  119141. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119142. if(pv<0 || pv>=pt->mapentries)break;
  119143. entry+=pt->pigeonmap[pv]*mul;
  119144. mul*=pt->quantvals;
  119145. qlast+=pv*pt->del+pt->min;
  119146. }
  119147. }else{
  119148. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119149. int pv=(int)((a[o]-pt->min)/pt->del);
  119150. if(pv<0 || pv>=pt->mapentries)break;
  119151. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119152. }
  119153. }
  119154. /* must be within the pigeonholable range; if we quant outside (or
  119155. in an entry that we define no list for), brute force it */
  119156. if(k==dim && pt->fitlength[entry]){
  119157. /* search the abbreviated list */
  119158. long *list=pt->fitlist+pt->fitmap[entry];
  119159. for(i=0;i<pt->fitlength[entry];i++){
  119160. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119161. if(besti==-1 || this<best){
  119162. best=this;
  119163. besti=list[i];
  119164. }
  119165. }
  119166. return(besti);
  119167. }
  119168. }
  119169. if(nt){
  119170. /* optimized using the decision tree */
  119171. while(1){
  119172. float c=0.f;
  119173. float *p=book->valuelist+nt->p[ptr];
  119174. float *q=book->valuelist+nt->q[ptr];
  119175. for(k=0,o=0;k<dim;k++,o+=step)
  119176. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119177. if(c>0.f) /* in A */
  119178. ptr= -nt->ptr0[ptr];
  119179. else /* in B */
  119180. ptr= -nt->ptr1[ptr];
  119181. if(ptr<=0)break;
  119182. }
  119183. return(-ptr);
  119184. }
  119185. #endif
  119186. /* brute force it! */
  119187. {
  119188. const static_codebook *c=book->c;
  119189. int i,besti=-1;
  119190. float best=0.f;
  119191. float *e=book->valuelist;
  119192. for(i=0;i<book->entries;i++){
  119193. if(c->lengthlist[i]>0){
  119194. float thisx=_dist(dim,e,a,step);
  119195. if(besti==-1 || thisx<best){
  119196. best=thisx;
  119197. besti=i;
  119198. }
  119199. }
  119200. e+=dim;
  119201. }
  119202. /*if(savebest!=-1 && savebest!=besti){
  119203. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119204. "original:");
  119205. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119206. fprintf(stderr,"\n"
  119207. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119208. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119209. (book->valuelist+savebest*dim)[i]);
  119210. fprintf(stderr,"\n"
  119211. "bruteforce (entry %d, err %g):",besti,best);
  119212. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119213. (book->valuelist+besti*dim)[i]);
  119214. fprintf(stderr,"\n");
  119215. }*/
  119216. return(besti);
  119217. }
  119218. }
  119219. long vorbis_book_codeword(codebook *book,int entry){
  119220. if(book->c) /* only use with encode; decode optimizations are
  119221. allowed to break this */
  119222. return book->codelist[entry];
  119223. return -1;
  119224. }
  119225. long vorbis_book_codelen(codebook *book,int entry){
  119226. if(book->c) /* only use with encode; decode optimizations are
  119227. allowed to break this */
  119228. return book->c->lengthlist[entry];
  119229. return -1;
  119230. }
  119231. #ifdef _V_SELFTEST
  119232. /* Unit tests of the dequantizer; this stuff will be OK
  119233. cross-platform, I simply want to be sure that special mapping cases
  119234. actually work properly; a bug could go unnoticed for a while */
  119235. #include <stdio.h>
  119236. /* cases:
  119237. no mapping
  119238. full, explicit mapping
  119239. algorithmic mapping
  119240. nonsequential
  119241. sequential
  119242. */
  119243. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119244. static long partial_quantlist1[]={0,7,2};
  119245. /* no mapping */
  119246. static_codebook test1={
  119247. 4,16,
  119248. NULL,
  119249. 0,
  119250. 0,0,0,0,
  119251. NULL,
  119252. NULL,NULL
  119253. };
  119254. static float *test1_result=NULL;
  119255. /* linear, full mapping, nonsequential */
  119256. static_codebook test2={
  119257. 4,3,
  119258. NULL,
  119259. 2,
  119260. -533200896,1611661312,4,0,
  119261. full_quantlist1,
  119262. NULL,NULL
  119263. };
  119264. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119265. /* linear, full mapping, sequential */
  119266. static_codebook test3={
  119267. 4,3,
  119268. NULL,
  119269. 2,
  119270. -533200896,1611661312,4,1,
  119271. full_quantlist1,
  119272. NULL,NULL
  119273. };
  119274. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119275. /* linear, algorithmic mapping, nonsequential */
  119276. static_codebook test4={
  119277. 3,27,
  119278. NULL,
  119279. 1,
  119280. -533200896,1611661312,4,0,
  119281. partial_quantlist1,
  119282. NULL,NULL
  119283. };
  119284. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119285. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119286. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119287. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119288. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119289. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119290. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119291. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119292. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119293. /* linear, algorithmic mapping, sequential */
  119294. static_codebook test5={
  119295. 3,27,
  119296. NULL,
  119297. 1,
  119298. -533200896,1611661312,4,1,
  119299. partial_quantlist1,
  119300. NULL,NULL
  119301. };
  119302. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119303. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119304. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119305. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119306. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119307. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119308. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119309. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119310. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119311. void run_test(static_codebook *b,float *comp){
  119312. float *out=_book_unquantize(b,b->entries,NULL);
  119313. int i;
  119314. if(comp){
  119315. if(!out){
  119316. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119317. exit(1);
  119318. }
  119319. for(i=0;i<b->entries*b->dim;i++)
  119320. if(fabs(out[i]-comp[i])>.0001){
  119321. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119322. "position %d, %g != %g\n",i,out[i],comp[i]);
  119323. exit(1);
  119324. }
  119325. }else{
  119326. if(out){
  119327. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119328. " correct result should have been NULL\n");
  119329. exit(1);
  119330. }
  119331. }
  119332. }
  119333. int main(){
  119334. /* run the nine dequant tests, and compare to the hand-rolled results */
  119335. fprintf(stderr,"Dequant test 1... ");
  119336. run_test(&test1,test1_result);
  119337. fprintf(stderr,"OK\nDequant test 2... ");
  119338. run_test(&test2,test2_result);
  119339. fprintf(stderr,"OK\nDequant test 3... ");
  119340. run_test(&test3,test3_result);
  119341. fprintf(stderr,"OK\nDequant test 4... ");
  119342. run_test(&test4,test4_result);
  119343. fprintf(stderr,"OK\nDequant test 5... ");
  119344. run_test(&test5,test5_result);
  119345. fprintf(stderr,"OK\n\n");
  119346. return(0);
  119347. }
  119348. #endif
  119349. #endif
  119350. /*** End of inlined file: sharedbook.c ***/
  119351. /*** Start of inlined file: smallft.c ***/
  119352. /* FFT implementation from OggSquish, minus cosine transforms,
  119353. * minus all but radix 2/4 case. In Vorbis we only need this
  119354. * cut-down version.
  119355. *
  119356. * To do more than just power-of-two sized vectors, see the full
  119357. * version I wrote for NetLib.
  119358. *
  119359. * Note that the packing is a little strange; rather than the FFT r/i
  119360. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119361. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119362. * FORTRAN version
  119363. */
  119364. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119365. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119366. // tasks..
  119367. #if JUCE_MSVC
  119368. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119369. #endif
  119370. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119371. #if JUCE_USE_OGGVORBIS
  119372. #include <stdlib.h>
  119373. #include <string.h>
  119374. #include <math.h>
  119375. static void drfti1(int n, float *wa, int *ifac){
  119376. static int ntryh[4] = { 4,2,3,5 };
  119377. static float tpi = 6.28318530717958648f;
  119378. float arg,argh,argld,fi;
  119379. int ntry=0,i,j=-1;
  119380. int k1, l1, l2, ib;
  119381. int ld, ii, ip, is, nq, nr;
  119382. int ido, ipm, nfm1;
  119383. int nl=n;
  119384. int nf=0;
  119385. L101:
  119386. j++;
  119387. if (j < 4)
  119388. ntry=ntryh[j];
  119389. else
  119390. ntry+=2;
  119391. L104:
  119392. nq=nl/ntry;
  119393. nr=nl-ntry*nq;
  119394. if (nr!=0) goto L101;
  119395. nf++;
  119396. ifac[nf+1]=ntry;
  119397. nl=nq;
  119398. if(ntry!=2)goto L107;
  119399. if(nf==1)goto L107;
  119400. for (i=1;i<nf;i++){
  119401. ib=nf-i+1;
  119402. ifac[ib+1]=ifac[ib];
  119403. }
  119404. ifac[2] = 2;
  119405. L107:
  119406. if(nl!=1)goto L104;
  119407. ifac[0]=n;
  119408. ifac[1]=nf;
  119409. argh=tpi/n;
  119410. is=0;
  119411. nfm1=nf-1;
  119412. l1=1;
  119413. if(nfm1==0)return;
  119414. for (k1=0;k1<nfm1;k1++){
  119415. ip=ifac[k1+2];
  119416. ld=0;
  119417. l2=l1*ip;
  119418. ido=n/l2;
  119419. ipm=ip-1;
  119420. for (j=0;j<ipm;j++){
  119421. ld+=l1;
  119422. i=is;
  119423. argld=(float)ld*argh;
  119424. fi=0.f;
  119425. for (ii=2;ii<ido;ii+=2){
  119426. fi+=1.f;
  119427. arg=fi*argld;
  119428. wa[i++]=cos(arg);
  119429. wa[i++]=sin(arg);
  119430. }
  119431. is+=ido;
  119432. }
  119433. l1=l2;
  119434. }
  119435. }
  119436. static void fdrffti(int n, float *wsave, int *ifac){
  119437. if (n == 1) return;
  119438. drfti1(n, wsave+n, ifac);
  119439. }
  119440. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119441. int i,k;
  119442. float ti2,tr2;
  119443. int t0,t1,t2,t3,t4,t5,t6;
  119444. t1=0;
  119445. t0=(t2=l1*ido);
  119446. t3=ido<<1;
  119447. for(k=0;k<l1;k++){
  119448. ch[t1<<1]=cc[t1]+cc[t2];
  119449. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119450. t1+=ido;
  119451. t2+=ido;
  119452. }
  119453. if(ido<2)return;
  119454. if(ido==2)goto L105;
  119455. t1=0;
  119456. t2=t0;
  119457. for(k=0;k<l1;k++){
  119458. t3=t2;
  119459. t4=(t1<<1)+(ido<<1);
  119460. t5=t1;
  119461. t6=t1+t1;
  119462. for(i=2;i<ido;i+=2){
  119463. t3+=2;
  119464. t4-=2;
  119465. t5+=2;
  119466. t6+=2;
  119467. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119468. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119469. ch[t6]=cc[t5]+ti2;
  119470. ch[t4]=ti2-cc[t5];
  119471. ch[t6-1]=cc[t5-1]+tr2;
  119472. ch[t4-1]=cc[t5-1]-tr2;
  119473. }
  119474. t1+=ido;
  119475. t2+=ido;
  119476. }
  119477. if(ido%2==1)return;
  119478. L105:
  119479. t3=(t2=(t1=ido)-1);
  119480. t2+=t0;
  119481. for(k=0;k<l1;k++){
  119482. ch[t1]=-cc[t2];
  119483. ch[t1-1]=cc[t3];
  119484. t1+=ido<<1;
  119485. t2+=ido;
  119486. t3+=ido;
  119487. }
  119488. }
  119489. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119490. float *wa2,float *wa3){
  119491. static float hsqt2 = .70710678118654752f;
  119492. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119493. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119494. t0=l1*ido;
  119495. t1=t0;
  119496. t4=t1<<1;
  119497. t2=t1+(t1<<1);
  119498. t3=0;
  119499. for(k=0;k<l1;k++){
  119500. tr1=cc[t1]+cc[t2];
  119501. tr2=cc[t3]+cc[t4];
  119502. ch[t5=t3<<2]=tr1+tr2;
  119503. ch[(ido<<2)+t5-1]=tr2-tr1;
  119504. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119505. ch[t5]=cc[t2]-cc[t1];
  119506. t1+=ido;
  119507. t2+=ido;
  119508. t3+=ido;
  119509. t4+=ido;
  119510. }
  119511. if(ido<2)return;
  119512. if(ido==2)goto L105;
  119513. t1=0;
  119514. for(k=0;k<l1;k++){
  119515. t2=t1;
  119516. t4=t1<<2;
  119517. t5=(t6=ido<<1)+t4;
  119518. for(i=2;i<ido;i+=2){
  119519. t3=(t2+=2);
  119520. t4+=2;
  119521. t5-=2;
  119522. t3+=t0;
  119523. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119524. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119525. t3+=t0;
  119526. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119527. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119528. t3+=t0;
  119529. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119530. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119531. tr1=cr2+cr4;
  119532. tr4=cr4-cr2;
  119533. ti1=ci2+ci4;
  119534. ti4=ci2-ci4;
  119535. ti2=cc[t2]+ci3;
  119536. ti3=cc[t2]-ci3;
  119537. tr2=cc[t2-1]+cr3;
  119538. tr3=cc[t2-1]-cr3;
  119539. ch[t4-1]=tr1+tr2;
  119540. ch[t4]=ti1+ti2;
  119541. ch[t5-1]=tr3-ti4;
  119542. ch[t5]=tr4-ti3;
  119543. ch[t4+t6-1]=ti4+tr3;
  119544. ch[t4+t6]=tr4+ti3;
  119545. ch[t5+t6-1]=tr2-tr1;
  119546. ch[t5+t6]=ti1-ti2;
  119547. }
  119548. t1+=ido;
  119549. }
  119550. if(ido&1)return;
  119551. L105:
  119552. t2=(t1=t0+ido-1)+(t0<<1);
  119553. t3=ido<<2;
  119554. t4=ido;
  119555. t5=ido<<1;
  119556. t6=ido;
  119557. for(k=0;k<l1;k++){
  119558. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119559. tr1=hsqt2*(cc[t1]-cc[t2]);
  119560. ch[t4-1]=tr1+cc[t6-1];
  119561. ch[t4+t5-1]=cc[t6-1]-tr1;
  119562. ch[t4]=ti1-cc[t1+t0];
  119563. ch[t4+t5]=ti1+cc[t1+t0];
  119564. t1+=ido;
  119565. t2+=ido;
  119566. t4+=t3;
  119567. t6+=ido;
  119568. }
  119569. }
  119570. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119571. float *c2,float *ch,float *ch2,float *wa){
  119572. static float tpi=6.283185307179586f;
  119573. int idij,ipph,i,j,k,l,ic,ik,is;
  119574. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119575. float dc2,ai1,ai2,ar1,ar2,ds2;
  119576. int nbd;
  119577. float dcp,arg,dsp,ar1h,ar2h;
  119578. int idp2,ipp2;
  119579. arg=tpi/(float)ip;
  119580. dcp=cos(arg);
  119581. dsp=sin(arg);
  119582. ipph=(ip+1)>>1;
  119583. ipp2=ip;
  119584. idp2=ido;
  119585. nbd=(ido-1)>>1;
  119586. t0=l1*ido;
  119587. t10=ip*ido;
  119588. if(ido==1)goto L119;
  119589. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119590. t1=0;
  119591. for(j=1;j<ip;j++){
  119592. t1+=t0;
  119593. t2=t1;
  119594. for(k=0;k<l1;k++){
  119595. ch[t2]=c1[t2];
  119596. t2+=ido;
  119597. }
  119598. }
  119599. is=-ido;
  119600. t1=0;
  119601. if(nbd>l1){
  119602. for(j=1;j<ip;j++){
  119603. t1+=t0;
  119604. is+=ido;
  119605. t2= -ido+t1;
  119606. for(k=0;k<l1;k++){
  119607. idij=is-1;
  119608. t2+=ido;
  119609. t3=t2;
  119610. for(i=2;i<ido;i+=2){
  119611. idij+=2;
  119612. t3+=2;
  119613. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119614. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119615. }
  119616. }
  119617. }
  119618. }else{
  119619. for(j=1;j<ip;j++){
  119620. is+=ido;
  119621. idij=is-1;
  119622. t1+=t0;
  119623. t2=t1;
  119624. for(i=2;i<ido;i+=2){
  119625. idij+=2;
  119626. t2+=2;
  119627. t3=t2;
  119628. for(k=0;k<l1;k++){
  119629. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119630. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119631. t3+=ido;
  119632. }
  119633. }
  119634. }
  119635. }
  119636. t1=0;
  119637. t2=ipp2*t0;
  119638. if(nbd<l1){
  119639. for(j=1;j<ipph;j++){
  119640. t1+=t0;
  119641. t2-=t0;
  119642. t3=t1;
  119643. t4=t2;
  119644. for(i=2;i<ido;i+=2){
  119645. t3+=2;
  119646. t4+=2;
  119647. t5=t3-ido;
  119648. t6=t4-ido;
  119649. for(k=0;k<l1;k++){
  119650. t5+=ido;
  119651. t6+=ido;
  119652. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119653. c1[t6-1]=ch[t5]-ch[t6];
  119654. c1[t5]=ch[t5]+ch[t6];
  119655. c1[t6]=ch[t6-1]-ch[t5-1];
  119656. }
  119657. }
  119658. }
  119659. }else{
  119660. for(j=1;j<ipph;j++){
  119661. t1+=t0;
  119662. t2-=t0;
  119663. t3=t1;
  119664. t4=t2;
  119665. for(k=0;k<l1;k++){
  119666. t5=t3;
  119667. t6=t4;
  119668. for(i=2;i<ido;i+=2){
  119669. t5+=2;
  119670. t6+=2;
  119671. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119672. c1[t6-1]=ch[t5]-ch[t6];
  119673. c1[t5]=ch[t5]+ch[t6];
  119674. c1[t6]=ch[t6-1]-ch[t5-1];
  119675. }
  119676. t3+=ido;
  119677. t4+=ido;
  119678. }
  119679. }
  119680. }
  119681. L119:
  119682. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119683. t1=0;
  119684. t2=ipp2*idl1;
  119685. for(j=1;j<ipph;j++){
  119686. t1+=t0;
  119687. t2-=t0;
  119688. t3=t1-ido;
  119689. t4=t2-ido;
  119690. for(k=0;k<l1;k++){
  119691. t3+=ido;
  119692. t4+=ido;
  119693. c1[t3]=ch[t3]+ch[t4];
  119694. c1[t4]=ch[t4]-ch[t3];
  119695. }
  119696. }
  119697. ar1=1.f;
  119698. ai1=0.f;
  119699. t1=0;
  119700. t2=ipp2*idl1;
  119701. t3=(ip-1)*idl1;
  119702. for(l=1;l<ipph;l++){
  119703. t1+=idl1;
  119704. t2-=idl1;
  119705. ar1h=dcp*ar1-dsp*ai1;
  119706. ai1=dcp*ai1+dsp*ar1;
  119707. ar1=ar1h;
  119708. t4=t1;
  119709. t5=t2;
  119710. t6=t3;
  119711. t7=idl1;
  119712. for(ik=0;ik<idl1;ik++){
  119713. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119714. ch2[t5++]=ai1*c2[t6++];
  119715. }
  119716. dc2=ar1;
  119717. ds2=ai1;
  119718. ar2=ar1;
  119719. ai2=ai1;
  119720. t4=idl1;
  119721. t5=(ipp2-1)*idl1;
  119722. for(j=2;j<ipph;j++){
  119723. t4+=idl1;
  119724. t5-=idl1;
  119725. ar2h=dc2*ar2-ds2*ai2;
  119726. ai2=dc2*ai2+ds2*ar2;
  119727. ar2=ar2h;
  119728. t6=t1;
  119729. t7=t2;
  119730. t8=t4;
  119731. t9=t5;
  119732. for(ik=0;ik<idl1;ik++){
  119733. ch2[t6++]+=ar2*c2[t8++];
  119734. ch2[t7++]+=ai2*c2[t9++];
  119735. }
  119736. }
  119737. }
  119738. t1=0;
  119739. for(j=1;j<ipph;j++){
  119740. t1+=idl1;
  119741. t2=t1;
  119742. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119743. }
  119744. if(ido<l1)goto L132;
  119745. t1=0;
  119746. t2=0;
  119747. for(k=0;k<l1;k++){
  119748. t3=t1;
  119749. t4=t2;
  119750. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119751. t1+=ido;
  119752. t2+=t10;
  119753. }
  119754. goto L135;
  119755. L132:
  119756. for(i=0;i<ido;i++){
  119757. t1=i;
  119758. t2=i;
  119759. for(k=0;k<l1;k++){
  119760. cc[t2]=ch[t1];
  119761. t1+=ido;
  119762. t2+=t10;
  119763. }
  119764. }
  119765. L135:
  119766. t1=0;
  119767. t2=ido<<1;
  119768. t3=0;
  119769. t4=ipp2*t0;
  119770. for(j=1;j<ipph;j++){
  119771. t1+=t2;
  119772. t3+=t0;
  119773. t4-=t0;
  119774. t5=t1;
  119775. t6=t3;
  119776. t7=t4;
  119777. for(k=0;k<l1;k++){
  119778. cc[t5-1]=ch[t6];
  119779. cc[t5]=ch[t7];
  119780. t5+=t10;
  119781. t6+=ido;
  119782. t7+=ido;
  119783. }
  119784. }
  119785. if(ido==1)return;
  119786. if(nbd<l1)goto L141;
  119787. t1=-ido;
  119788. t3=0;
  119789. t4=0;
  119790. t5=ipp2*t0;
  119791. for(j=1;j<ipph;j++){
  119792. t1+=t2;
  119793. t3+=t2;
  119794. t4+=t0;
  119795. t5-=t0;
  119796. t6=t1;
  119797. t7=t3;
  119798. t8=t4;
  119799. t9=t5;
  119800. for(k=0;k<l1;k++){
  119801. for(i=2;i<ido;i+=2){
  119802. ic=idp2-i;
  119803. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119804. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119805. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119806. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119807. }
  119808. t6+=t10;
  119809. t7+=t10;
  119810. t8+=ido;
  119811. t9+=ido;
  119812. }
  119813. }
  119814. return;
  119815. L141:
  119816. t1=-ido;
  119817. t3=0;
  119818. t4=0;
  119819. t5=ipp2*t0;
  119820. for(j=1;j<ipph;j++){
  119821. t1+=t2;
  119822. t3+=t2;
  119823. t4+=t0;
  119824. t5-=t0;
  119825. for(i=2;i<ido;i+=2){
  119826. t6=idp2+t1-i;
  119827. t7=i+t3;
  119828. t8=i+t4;
  119829. t9=i+t5;
  119830. for(k=0;k<l1;k++){
  119831. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119832. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119833. cc[t7]=ch[t8]+ch[t9];
  119834. cc[t6]=ch[t9]-ch[t8];
  119835. t6+=t10;
  119836. t7+=t10;
  119837. t8+=ido;
  119838. t9+=ido;
  119839. }
  119840. }
  119841. }
  119842. }
  119843. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119844. int i,k1,l1,l2;
  119845. int na,kh,nf;
  119846. int ip,iw,ido,idl1,ix2,ix3;
  119847. nf=ifac[1];
  119848. na=1;
  119849. l2=n;
  119850. iw=n;
  119851. for(k1=0;k1<nf;k1++){
  119852. kh=nf-k1;
  119853. ip=ifac[kh+1];
  119854. l1=l2/ip;
  119855. ido=n/l2;
  119856. idl1=ido*l1;
  119857. iw-=(ip-1)*ido;
  119858. na=1-na;
  119859. if(ip!=4)goto L102;
  119860. ix2=iw+ido;
  119861. ix3=ix2+ido;
  119862. if(na!=0)
  119863. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119864. else
  119865. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119866. goto L110;
  119867. L102:
  119868. if(ip!=2)goto L104;
  119869. if(na!=0)goto L103;
  119870. dradf2(ido,l1,c,ch,wa+iw-1);
  119871. goto L110;
  119872. L103:
  119873. dradf2(ido,l1,ch,c,wa+iw-1);
  119874. goto L110;
  119875. L104:
  119876. if(ido==1)na=1-na;
  119877. if(na!=0)goto L109;
  119878. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119879. na=1;
  119880. goto L110;
  119881. L109:
  119882. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119883. na=0;
  119884. L110:
  119885. l2=l1;
  119886. }
  119887. if(na==1)return;
  119888. for(i=0;i<n;i++)c[i]=ch[i];
  119889. }
  119890. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119891. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119892. float ti2,tr2;
  119893. t0=l1*ido;
  119894. t1=0;
  119895. t2=0;
  119896. t3=(ido<<1)-1;
  119897. for(k=0;k<l1;k++){
  119898. ch[t1]=cc[t2]+cc[t3+t2];
  119899. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119900. t2=(t1+=ido)<<1;
  119901. }
  119902. if(ido<2)return;
  119903. if(ido==2)goto L105;
  119904. t1=0;
  119905. t2=0;
  119906. for(k=0;k<l1;k++){
  119907. t3=t1;
  119908. t5=(t4=t2)+(ido<<1);
  119909. t6=t0+t1;
  119910. for(i=2;i<ido;i+=2){
  119911. t3+=2;
  119912. t4+=2;
  119913. t5-=2;
  119914. t6+=2;
  119915. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119916. tr2=cc[t4-1]-cc[t5-1];
  119917. ch[t3]=cc[t4]-cc[t5];
  119918. ti2=cc[t4]+cc[t5];
  119919. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119920. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119921. }
  119922. t2=(t1+=ido)<<1;
  119923. }
  119924. if(ido%2==1)return;
  119925. L105:
  119926. t1=ido-1;
  119927. t2=ido-1;
  119928. for(k=0;k<l1;k++){
  119929. ch[t1]=cc[t2]+cc[t2];
  119930. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119931. t1+=ido;
  119932. t2+=ido<<1;
  119933. }
  119934. }
  119935. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119936. float *wa2){
  119937. static float taur = -.5f;
  119938. static float taui = .8660254037844386f;
  119939. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119940. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119941. t0=l1*ido;
  119942. t1=0;
  119943. t2=t0<<1;
  119944. t3=ido<<1;
  119945. t4=ido+(ido<<1);
  119946. t5=0;
  119947. for(k=0;k<l1;k++){
  119948. tr2=cc[t3-1]+cc[t3-1];
  119949. cr2=cc[t5]+(taur*tr2);
  119950. ch[t1]=cc[t5]+tr2;
  119951. ci3=taui*(cc[t3]+cc[t3]);
  119952. ch[t1+t0]=cr2-ci3;
  119953. ch[t1+t2]=cr2+ci3;
  119954. t1+=ido;
  119955. t3+=t4;
  119956. t5+=t4;
  119957. }
  119958. if(ido==1)return;
  119959. t1=0;
  119960. t3=ido<<1;
  119961. for(k=0;k<l1;k++){
  119962. t7=t1+(t1<<1);
  119963. t6=(t5=t7+t3);
  119964. t8=t1;
  119965. t10=(t9=t1+t0)+t0;
  119966. for(i=2;i<ido;i+=2){
  119967. t5+=2;
  119968. t6-=2;
  119969. t7+=2;
  119970. t8+=2;
  119971. t9+=2;
  119972. t10+=2;
  119973. tr2=cc[t5-1]+cc[t6-1];
  119974. cr2=cc[t7-1]+(taur*tr2);
  119975. ch[t8-1]=cc[t7-1]+tr2;
  119976. ti2=cc[t5]-cc[t6];
  119977. ci2=cc[t7]+(taur*ti2);
  119978. ch[t8]=cc[t7]+ti2;
  119979. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119980. ci3=taui*(cc[t5]+cc[t6]);
  119981. dr2=cr2-ci3;
  119982. dr3=cr2+ci3;
  119983. di2=ci2+cr3;
  119984. di3=ci2-cr3;
  119985. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119986. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119987. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119988. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119989. }
  119990. t1+=ido;
  119991. }
  119992. }
  119993. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119994. float *wa2,float *wa3){
  119995. static float sqrt2=1.414213562373095f;
  119996. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119997. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119998. t0=l1*ido;
  119999. t1=0;
  120000. t2=ido<<2;
  120001. t3=0;
  120002. t6=ido<<1;
  120003. for(k=0;k<l1;k++){
  120004. t4=t3+t6;
  120005. t5=t1;
  120006. tr3=cc[t4-1]+cc[t4-1];
  120007. tr4=cc[t4]+cc[t4];
  120008. tr1=cc[t3]-cc[(t4+=t6)-1];
  120009. tr2=cc[t3]+cc[t4-1];
  120010. ch[t5]=tr2+tr3;
  120011. ch[t5+=t0]=tr1-tr4;
  120012. ch[t5+=t0]=tr2-tr3;
  120013. ch[t5+=t0]=tr1+tr4;
  120014. t1+=ido;
  120015. t3+=t2;
  120016. }
  120017. if(ido<2)return;
  120018. if(ido==2)goto L105;
  120019. t1=0;
  120020. for(k=0;k<l1;k++){
  120021. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120022. t7=t1;
  120023. for(i=2;i<ido;i+=2){
  120024. t2+=2;
  120025. t3+=2;
  120026. t4-=2;
  120027. t5-=2;
  120028. t7+=2;
  120029. ti1=cc[t2]+cc[t5];
  120030. ti2=cc[t2]-cc[t5];
  120031. ti3=cc[t3]-cc[t4];
  120032. tr4=cc[t3]+cc[t4];
  120033. tr1=cc[t2-1]-cc[t5-1];
  120034. tr2=cc[t2-1]+cc[t5-1];
  120035. ti4=cc[t3-1]-cc[t4-1];
  120036. tr3=cc[t3-1]+cc[t4-1];
  120037. ch[t7-1]=tr2+tr3;
  120038. cr3=tr2-tr3;
  120039. ch[t7]=ti2+ti3;
  120040. ci3=ti2-ti3;
  120041. cr2=tr1-tr4;
  120042. cr4=tr1+tr4;
  120043. ci2=ti1+ti4;
  120044. ci4=ti1-ti4;
  120045. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120046. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120047. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120048. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120049. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120050. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120051. }
  120052. t1+=ido;
  120053. }
  120054. if(ido%2 == 1)return;
  120055. L105:
  120056. t1=ido;
  120057. t2=ido<<2;
  120058. t3=ido-1;
  120059. t4=ido+(ido<<1);
  120060. for(k=0;k<l1;k++){
  120061. t5=t3;
  120062. ti1=cc[t1]+cc[t4];
  120063. ti2=cc[t4]-cc[t1];
  120064. tr1=cc[t1-1]-cc[t4-1];
  120065. tr2=cc[t1-1]+cc[t4-1];
  120066. ch[t5]=tr2+tr2;
  120067. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120068. ch[t5+=t0]=ti2+ti2;
  120069. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120070. t3+=ido;
  120071. t1+=t2;
  120072. t4+=t2;
  120073. }
  120074. }
  120075. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120076. float *c2,float *ch,float *ch2,float *wa){
  120077. static float tpi=6.283185307179586f;
  120078. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120079. t11,t12;
  120080. float dc2,ai1,ai2,ar1,ar2,ds2;
  120081. int nbd;
  120082. float dcp,arg,dsp,ar1h,ar2h;
  120083. int ipp2;
  120084. t10=ip*ido;
  120085. t0=l1*ido;
  120086. arg=tpi/(float)ip;
  120087. dcp=cos(arg);
  120088. dsp=sin(arg);
  120089. nbd=(ido-1)>>1;
  120090. ipp2=ip;
  120091. ipph=(ip+1)>>1;
  120092. if(ido<l1)goto L103;
  120093. t1=0;
  120094. t2=0;
  120095. for(k=0;k<l1;k++){
  120096. t3=t1;
  120097. t4=t2;
  120098. for(i=0;i<ido;i++){
  120099. ch[t3]=cc[t4];
  120100. t3++;
  120101. t4++;
  120102. }
  120103. t1+=ido;
  120104. t2+=t10;
  120105. }
  120106. goto L106;
  120107. L103:
  120108. t1=0;
  120109. for(i=0;i<ido;i++){
  120110. t2=t1;
  120111. t3=t1;
  120112. for(k=0;k<l1;k++){
  120113. ch[t2]=cc[t3];
  120114. t2+=ido;
  120115. t3+=t10;
  120116. }
  120117. t1++;
  120118. }
  120119. L106:
  120120. t1=0;
  120121. t2=ipp2*t0;
  120122. t7=(t5=ido<<1);
  120123. for(j=1;j<ipph;j++){
  120124. t1+=t0;
  120125. t2-=t0;
  120126. t3=t1;
  120127. t4=t2;
  120128. t6=t5;
  120129. for(k=0;k<l1;k++){
  120130. ch[t3]=cc[t6-1]+cc[t6-1];
  120131. ch[t4]=cc[t6]+cc[t6];
  120132. t3+=ido;
  120133. t4+=ido;
  120134. t6+=t10;
  120135. }
  120136. t5+=t7;
  120137. }
  120138. if (ido == 1)goto L116;
  120139. if(nbd<l1)goto L112;
  120140. t1=0;
  120141. t2=ipp2*t0;
  120142. t7=0;
  120143. for(j=1;j<ipph;j++){
  120144. t1+=t0;
  120145. t2-=t0;
  120146. t3=t1;
  120147. t4=t2;
  120148. t7+=(ido<<1);
  120149. t8=t7;
  120150. for(k=0;k<l1;k++){
  120151. t5=t3;
  120152. t6=t4;
  120153. t9=t8;
  120154. t11=t8;
  120155. for(i=2;i<ido;i+=2){
  120156. t5+=2;
  120157. t6+=2;
  120158. t9+=2;
  120159. t11-=2;
  120160. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120161. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120162. ch[t5]=cc[t9]-cc[t11];
  120163. ch[t6]=cc[t9]+cc[t11];
  120164. }
  120165. t3+=ido;
  120166. t4+=ido;
  120167. t8+=t10;
  120168. }
  120169. }
  120170. goto L116;
  120171. L112:
  120172. t1=0;
  120173. t2=ipp2*t0;
  120174. t7=0;
  120175. for(j=1;j<ipph;j++){
  120176. t1+=t0;
  120177. t2-=t0;
  120178. t3=t1;
  120179. t4=t2;
  120180. t7+=(ido<<1);
  120181. t8=t7;
  120182. t9=t7;
  120183. for(i=2;i<ido;i+=2){
  120184. t3+=2;
  120185. t4+=2;
  120186. t8+=2;
  120187. t9-=2;
  120188. t5=t3;
  120189. t6=t4;
  120190. t11=t8;
  120191. t12=t9;
  120192. for(k=0;k<l1;k++){
  120193. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120194. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120195. ch[t5]=cc[t11]-cc[t12];
  120196. ch[t6]=cc[t11]+cc[t12];
  120197. t5+=ido;
  120198. t6+=ido;
  120199. t11+=t10;
  120200. t12+=t10;
  120201. }
  120202. }
  120203. }
  120204. L116:
  120205. ar1=1.f;
  120206. ai1=0.f;
  120207. t1=0;
  120208. t9=(t2=ipp2*idl1);
  120209. t3=(ip-1)*idl1;
  120210. for(l=1;l<ipph;l++){
  120211. t1+=idl1;
  120212. t2-=idl1;
  120213. ar1h=dcp*ar1-dsp*ai1;
  120214. ai1=dcp*ai1+dsp*ar1;
  120215. ar1=ar1h;
  120216. t4=t1;
  120217. t5=t2;
  120218. t6=0;
  120219. t7=idl1;
  120220. t8=t3;
  120221. for(ik=0;ik<idl1;ik++){
  120222. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120223. c2[t5++]=ai1*ch2[t8++];
  120224. }
  120225. dc2=ar1;
  120226. ds2=ai1;
  120227. ar2=ar1;
  120228. ai2=ai1;
  120229. t6=idl1;
  120230. t7=t9-idl1;
  120231. for(j=2;j<ipph;j++){
  120232. t6+=idl1;
  120233. t7-=idl1;
  120234. ar2h=dc2*ar2-ds2*ai2;
  120235. ai2=dc2*ai2+ds2*ar2;
  120236. ar2=ar2h;
  120237. t4=t1;
  120238. t5=t2;
  120239. t11=t6;
  120240. t12=t7;
  120241. for(ik=0;ik<idl1;ik++){
  120242. c2[t4++]+=ar2*ch2[t11++];
  120243. c2[t5++]+=ai2*ch2[t12++];
  120244. }
  120245. }
  120246. }
  120247. t1=0;
  120248. for(j=1;j<ipph;j++){
  120249. t1+=idl1;
  120250. t2=t1;
  120251. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120252. }
  120253. t1=0;
  120254. t2=ipp2*t0;
  120255. for(j=1;j<ipph;j++){
  120256. t1+=t0;
  120257. t2-=t0;
  120258. t3=t1;
  120259. t4=t2;
  120260. for(k=0;k<l1;k++){
  120261. ch[t3]=c1[t3]-c1[t4];
  120262. ch[t4]=c1[t3]+c1[t4];
  120263. t3+=ido;
  120264. t4+=ido;
  120265. }
  120266. }
  120267. if(ido==1)goto L132;
  120268. if(nbd<l1)goto L128;
  120269. t1=0;
  120270. t2=ipp2*t0;
  120271. for(j=1;j<ipph;j++){
  120272. t1+=t0;
  120273. t2-=t0;
  120274. t3=t1;
  120275. t4=t2;
  120276. for(k=0;k<l1;k++){
  120277. t5=t3;
  120278. t6=t4;
  120279. for(i=2;i<ido;i+=2){
  120280. t5+=2;
  120281. t6+=2;
  120282. ch[t5-1]=c1[t5-1]-c1[t6];
  120283. ch[t6-1]=c1[t5-1]+c1[t6];
  120284. ch[t5]=c1[t5]+c1[t6-1];
  120285. ch[t6]=c1[t5]-c1[t6-1];
  120286. }
  120287. t3+=ido;
  120288. t4+=ido;
  120289. }
  120290. }
  120291. goto L132;
  120292. L128:
  120293. t1=0;
  120294. t2=ipp2*t0;
  120295. for(j=1;j<ipph;j++){
  120296. t1+=t0;
  120297. t2-=t0;
  120298. t3=t1;
  120299. t4=t2;
  120300. for(i=2;i<ido;i+=2){
  120301. t3+=2;
  120302. t4+=2;
  120303. t5=t3;
  120304. t6=t4;
  120305. for(k=0;k<l1;k++){
  120306. ch[t5-1]=c1[t5-1]-c1[t6];
  120307. ch[t6-1]=c1[t5-1]+c1[t6];
  120308. ch[t5]=c1[t5]+c1[t6-1];
  120309. ch[t6]=c1[t5]-c1[t6-1];
  120310. t5+=ido;
  120311. t6+=ido;
  120312. }
  120313. }
  120314. }
  120315. L132:
  120316. if(ido==1)return;
  120317. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120318. t1=0;
  120319. for(j=1;j<ip;j++){
  120320. t2=(t1+=t0);
  120321. for(k=0;k<l1;k++){
  120322. c1[t2]=ch[t2];
  120323. t2+=ido;
  120324. }
  120325. }
  120326. if(nbd>l1)goto L139;
  120327. is= -ido-1;
  120328. t1=0;
  120329. for(j=1;j<ip;j++){
  120330. is+=ido;
  120331. t1+=t0;
  120332. idij=is;
  120333. t2=t1;
  120334. for(i=2;i<ido;i+=2){
  120335. t2+=2;
  120336. idij+=2;
  120337. t3=t2;
  120338. for(k=0;k<l1;k++){
  120339. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120340. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120341. t3+=ido;
  120342. }
  120343. }
  120344. }
  120345. return;
  120346. L139:
  120347. is= -ido-1;
  120348. t1=0;
  120349. for(j=1;j<ip;j++){
  120350. is+=ido;
  120351. t1+=t0;
  120352. t2=t1;
  120353. for(k=0;k<l1;k++){
  120354. idij=is;
  120355. t3=t2;
  120356. for(i=2;i<ido;i+=2){
  120357. idij+=2;
  120358. t3+=2;
  120359. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120360. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120361. }
  120362. t2+=ido;
  120363. }
  120364. }
  120365. }
  120366. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120367. int i,k1,l1,l2;
  120368. int na;
  120369. int nf,ip,iw,ix2,ix3,ido,idl1;
  120370. nf=ifac[1];
  120371. na=0;
  120372. l1=1;
  120373. iw=1;
  120374. for(k1=0;k1<nf;k1++){
  120375. ip=ifac[k1 + 2];
  120376. l2=ip*l1;
  120377. ido=n/l2;
  120378. idl1=ido*l1;
  120379. if(ip!=4)goto L103;
  120380. ix2=iw+ido;
  120381. ix3=ix2+ido;
  120382. if(na!=0)
  120383. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120384. else
  120385. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120386. na=1-na;
  120387. goto L115;
  120388. L103:
  120389. if(ip!=2)goto L106;
  120390. if(na!=0)
  120391. dradb2(ido,l1,ch,c,wa+iw-1);
  120392. else
  120393. dradb2(ido,l1,c,ch,wa+iw-1);
  120394. na=1-na;
  120395. goto L115;
  120396. L106:
  120397. if(ip!=3)goto L109;
  120398. ix2=iw+ido;
  120399. if(na!=0)
  120400. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120401. else
  120402. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120403. na=1-na;
  120404. goto L115;
  120405. L109:
  120406. /* The radix five case can be translated later..... */
  120407. /* if(ip!=5)goto L112;
  120408. ix2=iw+ido;
  120409. ix3=ix2+ido;
  120410. ix4=ix3+ido;
  120411. if(na!=0)
  120412. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120413. else
  120414. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120415. na=1-na;
  120416. goto L115;
  120417. L112:*/
  120418. if(na!=0)
  120419. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120420. else
  120421. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120422. if(ido==1)na=1-na;
  120423. L115:
  120424. l1=l2;
  120425. iw+=(ip-1)*ido;
  120426. }
  120427. if(na==0)return;
  120428. for(i=0;i<n;i++)c[i]=ch[i];
  120429. }
  120430. void drft_forward(drft_lookup *l,float *data){
  120431. if(l->n==1)return;
  120432. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120433. }
  120434. void drft_backward(drft_lookup *l,float *data){
  120435. if (l->n==1)return;
  120436. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120437. }
  120438. void drft_init(drft_lookup *l,int n){
  120439. l->n=n;
  120440. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120441. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120442. fdrffti(n, l->trigcache, l->splitcache);
  120443. }
  120444. void drft_clear(drft_lookup *l){
  120445. if(l){
  120446. if(l->trigcache)_ogg_free(l->trigcache);
  120447. if(l->splitcache)_ogg_free(l->splitcache);
  120448. memset(l,0,sizeof(*l));
  120449. }
  120450. }
  120451. #endif
  120452. /*** End of inlined file: smallft.c ***/
  120453. /*** Start of inlined file: synthesis.c ***/
  120454. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120455. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120456. // tasks..
  120457. #if JUCE_MSVC
  120458. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120459. #endif
  120460. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120461. #if JUCE_USE_OGGVORBIS
  120462. #include <stdio.h>
  120463. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120464. vorbis_dsp_state *vd=vb->vd;
  120465. private_state *b=(private_state*)vd->backend_state;
  120466. vorbis_info *vi=vd->vi;
  120467. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120468. oggpack_buffer *opb=&vb->opb;
  120469. int type,mode,i;
  120470. /* first things first. Make sure decode is ready */
  120471. _vorbis_block_ripcord(vb);
  120472. oggpack_readinit(opb,op->packet,op->bytes);
  120473. /* Check the packet type */
  120474. if(oggpack_read(opb,1)!=0){
  120475. /* Oops. This is not an audio data packet */
  120476. return(OV_ENOTAUDIO);
  120477. }
  120478. /* read our mode and pre/post windowsize */
  120479. mode=oggpack_read(opb,b->modebits);
  120480. if(mode==-1)return(OV_EBADPACKET);
  120481. vb->mode=mode;
  120482. vb->W=ci->mode_param[mode]->blockflag;
  120483. if(vb->W){
  120484. /* this doesn;t get mapped through mode selection as it's used
  120485. only for window selection */
  120486. vb->lW=oggpack_read(opb,1);
  120487. vb->nW=oggpack_read(opb,1);
  120488. if(vb->nW==-1) return(OV_EBADPACKET);
  120489. }else{
  120490. vb->lW=0;
  120491. vb->nW=0;
  120492. }
  120493. /* more setup */
  120494. vb->granulepos=op->granulepos;
  120495. vb->sequence=op->packetno;
  120496. vb->eofflag=op->e_o_s;
  120497. /* alloc pcm passback storage */
  120498. vb->pcmend=ci->blocksizes[vb->W];
  120499. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120500. for(i=0;i<vi->channels;i++)
  120501. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120502. /* unpack_header enforces range checking */
  120503. type=ci->map_type[ci->mode_param[mode]->mapping];
  120504. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120505. mapping]));
  120506. }
  120507. /* used to track pcm position without actually performing decode.
  120508. Useful for sequential 'fast forward' */
  120509. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120510. vorbis_dsp_state *vd=vb->vd;
  120511. private_state *b=(private_state*)vd->backend_state;
  120512. vorbis_info *vi=vd->vi;
  120513. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120514. oggpack_buffer *opb=&vb->opb;
  120515. int mode;
  120516. /* first things first. Make sure decode is ready */
  120517. _vorbis_block_ripcord(vb);
  120518. oggpack_readinit(opb,op->packet,op->bytes);
  120519. /* Check the packet type */
  120520. if(oggpack_read(opb,1)!=0){
  120521. /* Oops. This is not an audio data packet */
  120522. return(OV_ENOTAUDIO);
  120523. }
  120524. /* read our mode and pre/post windowsize */
  120525. mode=oggpack_read(opb,b->modebits);
  120526. if(mode==-1)return(OV_EBADPACKET);
  120527. vb->mode=mode;
  120528. vb->W=ci->mode_param[mode]->blockflag;
  120529. if(vb->W){
  120530. vb->lW=oggpack_read(opb,1);
  120531. vb->nW=oggpack_read(opb,1);
  120532. if(vb->nW==-1) return(OV_EBADPACKET);
  120533. }else{
  120534. vb->lW=0;
  120535. vb->nW=0;
  120536. }
  120537. /* more setup */
  120538. vb->granulepos=op->granulepos;
  120539. vb->sequence=op->packetno;
  120540. vb->eofflag=op->e_o_s;
  120541. /* no pcm */
  120542. vb->pcmend=0;
  120543. vb->pcm=NULL;
  120544. return(0);
  120545. }
  120546. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120547. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120548. oggpack_buffer opb;
  120549. int mode;
  120550. oggpack_readinit(&opb,op->packet,op->bytes);
  120551. /* Check the packet type */
  120552. if(oggpack_read(&opb,1)!=0){
  120553. /* Oops. This is not an audio data packet */
  120554. return(OV_ENOTAUDIO);
  120555. }
  120556. {
  120557. int modebits=0;
  120558. int v=ci->modes;
  120559. while(v>1){
  120560. modebits++;
  120561. v>>=1;
  120562. }
  120563. /* read our mode and pre/post windowsize */
  120564. mode=oggpack_read(&opb,modebits);
  120565. }
  120566. if(mode==-1)return(OV_EBADPACKET);
  120567. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120568. }
  120569. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120570. /* set / clear half-sample-rate mode */
  120571. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120572. /* right now, our MDCT can't handle < 64 sample windows. */
  120573. if(ci->blocksizes[0]<=64 && flag)return -1;
  120574. ci->halfrate_flag=(flag?1:0);
  120575. return 0;
  120576. }
  120577. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120578. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120579. return ci->halfrate_flag;
  120580. }
  120581. #endif
  120582. /*** End of inlined file: synthesis.c ***/
  120583. /*** Start of inlined file: vorbisenc.c ***/
  120584. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120585. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120586. // tasks..
  120587. #if JUCE_MSVC
  120588. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120589. #endif
  120590. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120591. #if JUCE_USE_OGGVORBIS
  120592. #include <stdlib.h>
  120593. #include <string.h>
  120594. #include <math.h>
  120595. /* careful with this; it's using static array sizing to make managing
  120596. all the modes a little less annoying. If we use a residue backend
  120597. with > 12 partition types, or a different division of iteration,
  120598. this needs to be updated. */
  120599. typedef struct {
  120600. static_codebook *books[12][3];
  120601. } static_bookblock;
  120602. typedef struct {
  120603. int res_type;
  120604. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120605. vorbis_info_residue0 *res;
  120606. static_codebook *book_aux;
  120607. static_codebook *book_aux_managed;
  120608. static_bookblock *books_base;
  120609. static_bookblock *books_base_managed;
  120610. } vorbis_residue_template;
  120611. typedef struct {
  120612. vorbis_info_mapping0 *map;
  120613. vorbis_residue_template *res;
  120614. } vorbis_mapping_template;
  120615. typedef struct vp_adjblock{
  120616. int block[P_BANDS];
  120617. } vp_adjblock;
  120618. typedef struct {
  120619. int data[NOISE_COMPAND_LEVELS];
  120620. } compandblock;
  120621. /* high level configuration information for setting things up
  120622. step-by-step with the detailed vorbis_encode_ctl interface.
  120623. There's a fair amount of redundancy such that interactive setup
  120624. does not directly deal with any vorbis_info or codec_setup_info
  120625. initialization; it's all stored (until full init) in this highlevel
  120626. setup, then flushed out to the real codec setup structs later. */
  120627. typedef struct {
  120628. int att[P_NOISECURVES];
  120629. float boost;
  120630. float decay;
  120631. } att3;
  120632. typedef struct { int data[P_NOISECURVES]; } adj3;
  120633. typedef struct {
  120634. int pre[PACKETBLOBS];
  120635. int post[PACKETBLOBS];
  120636. float kHz[PACKETBLOBS];
  120637. float lowpasskHz[PACKETBLOBS];
  120638. } adj_stereo;
  120639. typedef struct {
  120640. int lo;
  120641. int hi;
  120642. int fixed;
  120643. } noiseguard;
  120644. typedef struct {
  120645. int data[P_NOISECURVES][17];
  120646. } noise3;
  120647. typedef struct {
  120648. int mappings;
  120649. double *rate_mapping;
  120650. double *quality_mapping;
  120651. int coupling_restriction;
  120652. long samplerate_min_restriction;
  120653. long samplerate_max_restriction;
  120654. int *blocksize_short;
  120655. int *blocksize_long;
  120656. att3 *psy_tone_masteratt;
  120657. int *psy_tone_0dB;
  120658. int *psy_tone_dBsuppress;
  120659. vp_adjblock *psy_tone_adj_impulse;
  120660. vp_adjblock *psy_tone_adj_long;
  120661. vp_adjblock *psy_tone_adj_other;
  120662. noiseguard *psy_noiseguards;
  120663. noise3 *psy_noise_bias_impulse;
  120664. noise3 *psy_noise_bias_padding;
  120665. noise3 *psy_noise_bias_trans;
  120666. noise3 *psy_noise_bias_long;
  120667. int *psy_noise_dBsuppress;
  120668. compandblock *psy_noise_compand;
  120669. double *psy_noise_compand_short_mapping;
  120670. double *psy_noise_compand_long_mapping;
  120671. int *psy_noise_normal_start[2];
  120672. int *psy_noise_normal_partition[2];
  120673. double *psy_noise_normal_thresh;
  120674. int *psy_ath_float;
  120675. int *psy_ath_abs;
  120676. double *psy_lowpass;
  120677. vorbis_info_psy_global *global_params;
  120678. double *global_mapping;
  120679. adj_stereo *stereo_modes;
  120680. static_codebook ***floor_books;
  120681. vorbis_info_floor1 *floor_params;
  120682. int *floor_short_mapping;
  120683. int *floor_long_mapping;
  120684. vorbis_mapping_template *maps;
  120685. } ve_setup_data_template;
  120686. /* a few static coder conventions */
  120687. static vorbis_info_mode _mode_template[2]={
  120688. {0,0,0,0},
  120689. {1,0,0,1}
  120690. };
  120691. static vorbis_info_mapping0 _map_nominal[2]={
  120692. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120693. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120694. };
  120695. /*** Start of inlined file: setup_44.h ***/
  120696. /*** Start of inlined file: floor_all.h ***/
  120697. /*** Start of inlined file: floor_books.h ***/
  120698. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120699. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120700. };
  120701. static static_codebook _huff_book_line_256x7_0sub1 = {
  120702. 1, 9,
  120703. _huff_lengthlist_line_256x7_0sub1,
  120704. 0, 0, 0, 0, 0,
  120705. NULL,
  120706. NULL,
  120707. NULL,
  120708. NULL,
  120709. 0
  120710. };
  120711. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120713. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120714. };
  120715. static static_codebook _huff_book_line_256x7_0sub2 = {
  120716. 1, 25,
  120717. _huff_lengthlist_line_256x7_0sub2,
  120718. 0, 0, 0, 0, 0,
  120719. NULL,
  120720. NULL,
  120721. NULL,
  120722. NULL,
  120723. 0
  120724. };
  120725. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120728. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120729. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120730. };
  120731. static static_codebook _huff_book_line_256x7_0sub3 = {
  120732. 1, 64,
  120733. _huff_lengthlist_line_256x7_0sub3,
  120734. 0, 0, 0, 0, 0,
  120735. NULL,
  120736. NULL,
  120737. NULL,
  120738. NULL,
  120739. 0
  120740. };
  120741. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120742. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120743. };
  120744. static static_codebook _huff_book_line_256x7_1sub1 = {
  120745. 1, 9,
  120746. _huff_lengthlist_line_256x7_1sub1,
  120747. 0, 0, 0, 0, 0,
  120748. NULL,
  120749. NULL,
  120750. NULL,
  120751. NULL,
  120752. 0
  120753. };
  120754. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120756. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120757. };
  120758. static static_codebook _huff_book_line_256x7_1sub2 = {
  120759. 1, 25,
  120760. _huff_lengthlist_line_256x7_1sub2,
  120761. 0, 0, 0, 0, 0,
  120762. NULL,
  120763. NULL,
  120764. NULL,
  120765. NULL,
  120766. 0
  120767. };
  120768. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120771. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120772. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120773. };
  120774. static static_codebook _huff_book_line_256x7_1sub3 = {
  120775. 1, 64,
  120776. _huff_lengthlist_line_256x7_1sub3,
  120777. 0, 0, 0, 0, 0,
  120778. NULL,
  120779. NULL,
  120780. NULL,
  120781. NULL,
  120782. 0
  120783. };
  120784. static long _huff_lengthlist_line_256x7_class0[] = {
  120785. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120786. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120787. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120788. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120789. };
  120790. static static_codebook _huff_book_line_256x7_class0 = {
  120791. 1, 64,
  120792. _huff_lengthlist_line_256x7_class0,
  120793. 0, 0, 0, 0, 0,
  120794. NULL,
  120795. NULL,
  120796. NULL,
  120797. NULL,
  120798. 0
  120799. };
  120800. static long _huff_lengthlist_line_256x7_class1[] = {
  120801. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120802. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120803. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120804. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120805. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120806. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120807. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120808. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120809. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120810. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120811. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120812. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120813. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120814. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120815. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120816. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120817. };
  120818. static static_codebook _huff_book_line_256x7_class1 = {
  120819. 1, 256,
  120820. _huff_lengthlist_line_256x7_class1,
  120821. 0, 0, 0, 0, 0,
  120822. NULL,
  120823. NULL,
  120824. NULL,
  120825. NULL,
  120826. 0
  120827. };
  120828. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120829. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120830. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120831. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120832. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120833. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120834. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120835. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120836. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120837. };
  120838. static static_codebook _huff_book_line_512x17_0sub0 = {
  120839. 1, 128,
  120840. _huff_lengthlist_line_512x17_0sub0,
  120841. 0, 0, 0, 0, 0,
  120842. NULL,
  120843. NULL,
  120844. NULL,
  120845. NULL,
  120846. 0
  120847. };
  120848. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120849. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120850. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120851. };
  120852. static static_codebook _huff_book_line_512x17_1sub0 = {
  120853. 1, 32,
  120854. _huff_lengthlist_line_512x17_1sub0,
  120855. 0, 0, 0, 0, 0,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. 0
  120861. };
  120862. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120866. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120867. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120868. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120869. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120870. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120871. };
  120872. static static_codebook _huff_book_line_512x17_1sub1 = {
  120873. 1, 128,
  120874. _huff_lengthlist_line_512x17_1sub1,
  120875. 0, 0, 0, 0, 0,
  120876. NULL,
  120877. NULL,
  120878. NULL,
  120879. NULL,
  120880. 0
  120881. };
  120882. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120883. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120884. 5, 3,
  120885. };
  120886. static static_codebook _huff_book_line_512x17_2sub1 = {
  120887. 1, 18,
  120888. _huff_lengthlist_line_512x17_2sub1,
  120889. 0, 0, 0, 0, 0,
  120890. NULL,
  120891. NULL,
  120892. NULL,
  120893. NULL,
  120894. 0
  120895. };
  120896. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120899. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120900. 9, 8,
  120901. };
  120902. static static_codebook _huff_book_line_512x17_2sub2 = {
  120903. 1, 50,
  120904. _huff_lengthlist_line_512x17_2sub2,
  120905. 0, 0, 0, 0, 0,
  120906. NULL,
  120907. NULL,
  120908. NULL,
  120909. NULL,
  120910. 0
  120911. };
  120912. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120917. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120918. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120919. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120920. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120921. };
  120922. static static_codebook _huff_book_line_512x17_2sub3 = {
  120923. 1, 128,
  120924. _huff_lengthlist_line_512x17_2sub3,
  120925. 0, 0, 0, 0, 0,
  120926. NULL,
  120927. NULL,
  120928. NULL,
  120929. NULL,
  120930. 0
  120931. };
  120932. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120933. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120934. 5, 5,
  120935. };
  120936. static static_codebook _huff_book_line_512x17_3sub1 = {
  120937. 1, 18,
  120938. _huff_lengthlist_line_512x17_3sub1,
  120939. 0, 0, 0, 0, 0,
  120940. NULL,
  120941. NULL,
  120942. NULL,
  120943. NULL,
  120944. 0
  120945. };
  120946. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120949. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120950. 11,14,
  120951. };
  120952. static static_codebook _huff_book_line_512x17_3sub2 = {
  120953. 1, 50,
  120954. _huff_lengthlist_line_512x17_3sub2,
  120955. 0, 0, 0, 0, 0,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. 0
  120961. };
  120962. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120966. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120967. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120968. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120969. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120970. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120971. };
  120972. static static_codebook _huff_book_line_512x17_3sub3 = {
  120973. 1, 128,
  120974. _huff_lengthlist_line_512x17_3sub3,
  120975. 0, 0, 0, 0, 0,
  120976. NULL,
  120977. NULL,
  120978. NULL,
  120979. NULL,
  120980. 0
  120981. };
  120982. static long _huff_lengthlist_line_512x17_class1[] = {
  120983. 1, 2, 3, 6, 5, 4, 7, 7,
  120984. };
  120985. static static_codebook _huff_book_line_512x17_class1 = {
  120986. 1, 8,
  120987. _huff_lengthlist_line_512x17_class1,
  120988. 0, 0, 0, 0, 0,
  120989. NULL,
  120990. NULL,
  120991. NULL,
  120992. NULL,
  120993. 0
  120994. };
  120995. static long _huff_lengthlist_line_512x17_class2[] = {
  120996. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120997. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120998. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120999. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121000. };
  121001. static static_codebook _huff_book_line_512x17_class2 = {
  121002. 1, 64,
  121003. _huff_lengthlist_line_512x17_class2,
  121004. 0, 0, 0, 0, 0,
  121005. NULL,
  121006. NULL,
  121007. NULL,
  121008. NULL,
  121009. 0
  121010. };
  121011. static long _huff_lengthlist_line_512x17_class3[] = {
  121012. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121013. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121014. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121015. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121016. };
  121017. static static_codebook _huff_book_line_512x17_class3 = {
  121018. 1, 64,
  121019. _huff_lengthlist_line_512x17_class3,
  121020. 0, 0, 0, 0, 0,
  121021. NULL,
  121022. NULL,
  121023. NULL,
  121024. NULL,
  121025. 0
  121026. };
  121027. static long _huff_lengthlist_line_128x4_class0[] = {
  121028. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121029. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121030. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121031. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121032. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121033. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121034. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121035. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121036. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121037. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121038. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121039. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121040. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121041. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121042. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121043. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121044. };
  121045. static static_codebook _huff_book_line_128x4_class0 = {
  121046. 1, 256,
  121047. _huff_lengthlist_line_128x4_class0,
  121048. 0, 0, 0, 0, 0,
  121049. NULL,
  121050. NULL,
  121051. NULL,
  121052. NULL,
  121053. 0
  121054. };
  121055. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121056. 2, 2, 2, 2,
  121057. };
  121058. static static_codebook _huff_book_line_128x4_0sub0 = {
  121059. 1, 4,
  121060. _huff_lengthlist_line_128x4_0sub0,
  121061. 0, 0, 0, 0, 0,
  121062. NULL,
  121063. NULL,
  121064. NULL,
  121065. NULL,
  121066. 0
  121067. };
  121068. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121069. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121070. };
  121071. static static_codebook _huff_book_line_128x4_0sub1 = {
  121072. 1, 10,
  121073. _huff_lengthlist_line_128x4_0sub1,
  121074. 0, 0, 0, 0, 0,
  121075. NULL,
  121076. NULL,
  121077. NULL,
  121078. NULL,
  121079. 0
  121080. };
  121081. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121083. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121084. };
  121085. static static_codebook _huff_book_line_128x4_0sub2 = {
  121086. 1, 25,
  121087. _huff_lengthlist_line_128x4_0sub2,
  121088. 0, 0, 0, 0, 0,
  121089. NULL,
  121090. NULL,
  121091. NULL,
  121092. NULL,
  121093. 0
  121094. };
  121095. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121098. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121099. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121100. };
  121101. static static_codebook _huff_book_line_128x4_0sub3 = {
  121102. 1, 64,
  121103. _huff_lengthlist_line_128x4_0sub3,
  121104. 0, 0, 0, 0, 0,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. 0
  121110. };
  121111. static long _huff_lengthlist_line_256x4_class0[] = {
  121112. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121113. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121114. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121115. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121116. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121117. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121118. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121119. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121120. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121121. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121122. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121123. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121124. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121125. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121126. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121127. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121128. };
  121129. static static_codebook _huff_book_line_256x4_class0 = {
  121130. 1, 256,
  121131. _huff_lengthlist_line_256x4_class0,
  121132. 0, 0, 0, 0, 0,
  121133. NULL,
  121134. NULL,
  121135. NULL,
  121136. NULL,
  121137. 0
  121138. };
  121139. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121140. 2, 2, 2, 2,
  121141. };
  121142. static static_codebook _huff_book_line_256x4_0sub0 = {
  121143. 1, 4,
  121144. _huff_lengthlist_line_256x4_0sub0,
  121145. 0, 0, 0, 0, 0,
  121146. NULL,
  121147. NULL,
  121148. NULL,
  121149. NULL,
  121150. 0
  121151. };
  121152. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121153. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121154. };
  121155. static static_codebook _huff_book_line_256x4_0sub1 = {
  121156. 1, 10,
  121157. _huff_lengthlist_line_256x4_0sub1,
  121158. 0, 0, 0, 0, 0,
  121159. NULL,
  121160. NULL,
  121161. NULL,
  121162. NULL,
  121163. 0
  121164. };
  121165. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121167. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121168. };
  121169. static static_codebook _huff_book_line_256x4_0sub2 = {
  121170. 1, 25,
  121171. _huff_lengthlist_line_256x4_0sub2,
  121172. 0, 0, 0, 0, 0,
  121173. NULL,
  121174. NULL,
  121175. NULL,
  121176. NULL,
  121177. 0
  121178. };
  121179. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121182. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121183. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121184. };
  121185. static static_codebook _huff_book_line_256x4_0sub3 = {
  121186. 1, 64,
  121187. _huff_lengthlist_line_256x4_0sub3,
  121188. 0, 0, 0, 0, 0,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. NULL,
  121193. 0
  121194. };
  121195. static long _huff_lengthlist_line_128x7_class0[] = {
  121196. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121197. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121198. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121199. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121200. };
  121201. static static_codebook _huff_book_line_128x7_class0 = {
  121202. 1, 64,
  121203. _huff_lengthlist_line_128x7_class0,
  121204. 0, 0, 0, 0, 0,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. NULL,
  121209. 0
  121210. };
  121211. static long _huff_lengthlist_line_128x7_class1[] = {
  121212. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121213. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121214. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121215. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121216. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121217. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121218. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121219. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121220. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121221. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121222. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121223. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121224. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121225. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121226. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121227. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121228. };
  121229. static static_codebook _huff_book_line_128x7_class1 = {
  121230. 1, 256,
  121231. _huff_lengthlist_line_128x7_class1,
  121232. 0, 0, 0, 0, 0,
  121233. NULL,
  121234. NULL,
  121235. NULL,
  121236. NULL,
  121237. 0
  121238. };
  121239. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121240. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121241. };
  121242. static static_codebook _huff_book_line_128x7_0sub1 = {
  121243. 1, 9,
  121244. _huff_lengthlist_line_128x7_0sub1,
  121245. 0, 0, 0, 0, 0,
  121246. NULL,
  121247. NULL,
  121248. NULL,
  121249. NULL,
  121250. 0
  121251. };
  121252. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121254. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121255. };
  121256. static static_codebook _huff_book_line_128x7_0sub2 = {
  121257. 1, 25,
  121258. _huff_lengthlist_line_128x7_0sub2,
  121259. 0, 0, 0, 0, 0,
  121260. NULL,
  121261. NULL,
  121262. NULL,
  121263. NULL,
  121264. 0
  121265. };
  121266. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121269. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121270. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121271. };
  121272. static static_codebook _huff_book_line_128x7_0sub3 = {
  121273. 1, 64,
  121274. _huff_lengthlist_line_128x7_0sub3,
  121275. 0, 0, 0, 0, 0,
  121276. NULL,
  121277. NULL,
  121278. NULL,
  121279. NULL,
  121280. 0
  121281. };
  121282. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121283. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121284. };
  121285. static static_codebook _huff_book_line_128x7_1sub1 = {
  121286. 1, 9,
  121287. _huff_lengthlist_line_128x7_1sub1,
  121288. 0, 0, 0, 0, 0,
  121289. NULL,
  121290. NULL,
  121291. NULL,
  121292. NULL,
  121293. 0
  121294. };
  121295. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121297. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121298. };
  121299. static static_codebook _huff_book_line_128x7_1sub2 = {
  121300. 1, 25,
  121301. _huff_lengthlist_line_128x7_1sub2,
  121302. 0, 0, 0, 0, 0,
  121303. NULL,
  121304. NULL,
  121305. NULL,
  121306. NULL,
  121307. 0
  121308. };
  121309. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121312. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121313. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121314. };
  121315. static static_codebook _huff_book_line_128x7_1sub3 = {
  121316. 1, 64,
  121317. _huff_lengthlist_line_128x7_1sub3,
  121318. 0, 0, 0, 0, 0,
  121319. NULL,
  121320. NULL,
  121321. NULL,
  121322. NULL,
  121323. 0
  121324. };
  121325. static long _huff_lengthlist_line_128x11_class1[] = {
  121326. 1, 6, 3, 7, 2, 4, 5, 7,
  121327. };
  121328. static static_codebook _huff_book_line_128x11_class1 = {
  121329. 1, 8,
  121330. _huff_lengthlist_line_128x11_class1,
  121331. 0, 0, 0, 0, 0,
  121332. NULL,
  121333. NULL,
  121334. NULL,
  121335. NULL,
  121336. 0
  121337. };
  121338. static long _huff_lengthlist_line_128x11_class2[] = {
  121339. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121340. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121341. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121342. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121343. };
  121344. static static_codebook _huff_book_line_128x11_class2 = {
  121345. 1, 64,
  121346. _huff_lengthlist_line_128x11_class2,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_128x11_class3[] = {
  121355. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121356. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121357. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121358. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121359. };
  121360. static static_codebook _huff_book_line_128x11_class3 = {
  121361. 1, 64,
  121362. _huff_lengthlist_line_128x11_class3,
  121363. 0, 0, 0, 0, 0,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. 0
  121369. };
  121370. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121371. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121372. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121373. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121374. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121375. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121376. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121377. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121378. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121379. };
  121380. static static_codebook _huff_book_line_128x11_0sub0 = {
  121381. 1, 128,
  121382. _huff_lengthlist_line_128x11_0sub0,
  121383. 0, 0, 0, 0, 0,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. NULL,
  121388. 0
  121389. };
  121390. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121391. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121392. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121393. };
  121394. static static_codebook _huff_book_line_128x11_1sub0 = {
  121395. 1, 32,
  121396. _huff_lengthlist_line_128x11_1sub0,
  121397. 0, 0, 0, 0, 0,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. 0
  121403. };
  121404. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121408. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121409. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121410. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121411. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121412. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121413. };
  121414. static static_codebook _huff_book_line_128x11_1sub1 = {
  121415. 1, 128,
  121416. _huff_lengthlist_line_128x11_1sub1,
  121417. 0, 0, 0, 0, 0,
  121418. NULL,
  121419. NULL,
  121420. NULL,
  121421. NULL,
  121422. 0
  121423. };
  121424. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121425. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121426. 5, 5,
  121427. };
  121428. static static_codebook _huff_book_line_128x11_2sub1 = {
  121429. 1, 18,
  121430. _huff_lengthlist_line_128x11_2sub1,
  121431. 0, 0, 0, 0, 0,
  121432. NULL,
  121433. NULL,
  121434. NULL,
  121435. NULL,
  121436. 0
  121437. };
  121438. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121440. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121441. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121442. 8,11,
  121443. };
  121444. static static_codebook _huff_book_line_128x11_2sub2 = {
  121445. 1, 50,
  121446. _huff_lengthlist_line_128x11_2sub2,
  121447. 0, 0, 0, 0, 0,
  121448. NULL,
  121449. NULL,
  121450. NULL,
  121451. NULL,
  121452. 0
  121453. };
  121454. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121459. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121460. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121461. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121462. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121463. };
  121464. static static_codebook _huff_book_line_128x11_2sub3 = {
  121465. 1, 128,
  121466. _huff_lengthlist_line_128x11_2sub3,
  121467. 0, 0, 0, 0, 0,
  121468. NULL,
  121469. NULL,
  121470. NULL,
  121471. NULL,
  121472. 0
  121473. };
  121474. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121475. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121476. 5, 4,
  121477. };
  121478. static static_codebook _huff_book_line_128x11_3sub1 = {
  121479. 1, 18,
  121480. _huff_lengthlist_line_128x11_3sub1,
  121481. 0, 0, 0, 0, 0,
  121482. NULL,
  121483. NULL,
  121484. NULL,
  121485. NULL,
  121486. 0
  121487. };
  121488. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121490. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121491. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121492. 12, 6,
  121493. };
  121494. static static_codebook _huff_book_line_128x11_3sub2 = {
  121495. 1, 50,
  121496. _huff_lengthlist_line_128x11_3sub2,
  121497. 0, 0, 0, 0, 0,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. NULL,
  121502. 0
  121503. };
  121504. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121508. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121509. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121510. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121511. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121512. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121513. };
  121514. static static_codebook _huff_book_line_128x11_3sub3 = {
  121515. 1, 128,
  121516. _huff_lengthlist_line_128x11_3sub3,
  121517. 0, 0, 0, 0, 0,
  121518. NULL,
  121519. NULL,
  121520. NULL,
  121521. NULL,
  121522. 0
  121523. };
  121524. static long _huff_lengthlist_line_128x17_class1[] = {
  121525. 1, 3, 4, 7, 2, 5, 6, 7,
  121526. };
  121527. static static_codebook _huff_book_line_128x17_class1 = {
  121528. 1, 8,
  121529. _huff_lengthlist_line_128x17_class1,
  121530. 0, 0, 0, 0, 0,
  121531. NULL,
  121532. NULL,
  121533. NULL,
  121534. NULL,
  121535. 0
  121536. };
  121537. static long _huff_lengthlist_line_128x17_class2[] = {
  121538. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121539. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121540. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121541. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121542. };
  121543. static static_codebook _huff_book_line_128x17_class2 = {
  121544. 1, 64,
  121545. _huff_lengthlist_line_128x17_class2,
  121546. 0, 0, 0, 0, 0,
  121547. NULL,
  121548. NULL,
  121549. NULL,
  121550. NULL,
  121551. 0
  121552. };
  121553. static long _huff_lengthlist_line_128x17_class3[] = {
  121554. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121555. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121556. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121557. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121558. };
  121559. static static_codebook _huff_book_line_128x17_class3 = {
  121560. 1, 64,
  121561. _huff_lengthlist_line_128x17_class3,
  121562. 0, 0, 0, 0, 0,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. NULL,
  121567. 0
  121568. };
  121569. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121570. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121571. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121572. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121573. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121574. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121575. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121576. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121577. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121578. };
  121579. static static_codebook _huff_book_line_128x17_0sub0 = {
  121580. 1, 128,
  121581. _huff_lengthlist_line_128x17_0sub0,
  121582. 0, 0, 0, 0, 0,
  121583. NULL,
  121584. NULL,
  121585. NULL,
  121586. NULL,
  121587. 0
  121588. };
  121589. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121590. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121591. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121592. };
  121593. static static_codebook _huff_book_line_128x17_1sub0 = {
  121594. 1, 32,
  121595. _huff_lengthlist_line_128x17_1sub0,
  121596. 0, 0, 0, 0, 0,
  121597. NULL,
  121598. NULL,
  121599. NULL,
  121600. NULL,
  121601. 0
  121602. };
  121603. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121607. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121608. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121609. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121610. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121611. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121612. };
  121613. static static_codebook _huff_book_line_128x17_1sub1 = {
  121614. 1, 128,
  121615. _huff_lengthlist_line_128x17_1sub1,
  121616. 0, 0, 0, 0, 0,
  121617. NULL,
  121618. NULL,
  121619. NULL,
  121620. NULL,
  121621. 0
  121622. };
  121623. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121624. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121625. 9, 4,
  121626. };
  121627. static static_codebook _huff_book_line_128x17_2sub1 = {
  121628. 1, 18,
  121629. _huff_lengthlist_line_128x17_2sub1,
  121630. 0, 0, 0, 0, 0,
  121631. NULL,
  121632. NULL,
  121633. NULL,
  121634. NULL,
  121635. 0
  121636. };
  121637. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121640. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121641. 13,13,
  121642. };
  121643. static static_codebook _huff_book_line_128x17_2sub2 = {
  121644. 1, 50,
  121645. _huff_lengthlist_line_128x17_2sub2,
  121646. 0, 0, 0, 0, 0,
  121647. NULL,
  121648. NULL,
  121649. NULL,
  121650. NULL,
  121651. 0
  121652. };
  121653. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121658. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121659. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121660. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121661. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121662. };
  121663. static static_codebook _huff_book_line_128x17_2sub3 = {
  121664. 1, 128,
  121665. _huff_lengthlist_line_128x17_2sub3,
  121666. 0, 0, 0, 0, 0,
  121667. NULL,
  121668. NULL,
  121669. NULL,
  121670. NULL,
  121671. 0
  121672. };
  121673. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121674. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121675. 6, 4,
  121676. };
  121677. static static_codebook _huff_book_line_128x17_3sub1 = {
  121678. 1, 18,
  121679. _huff_lengthlist_line_128x17_3sub1,
  121680. 0, 0, 0, 0, 0,
  121681. NULL,
  121682. NULL,
  121683. NULL,
  121684. NULL,
  121685. 0
  121686. };
  121687. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121690. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121691. 10, 8,
  121692. };
  121693. static static_codebook _huff_book_line_128x17_3sub2 = {
  121694. 1, 50,
  121695. _huff_lengthlist_line_128x17_3sub2,
  121696. 0, 0, 0, 0, 0,
  121697. NULL,
  121698. NULL,
  121699. NULL,
  121700. NULL,
  121701. 0
  121702. };
  121703. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121708. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121709. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121712. };
  121713. static static_codebook _huff_book_line_128x17_3sub3 = {
  121714. 1, 128,
  121715. _huff_lengthlist_line_128x17_3sub3,
  121716. 0, 0, 0, 0, 0,
  121717. NULL,
  121718. NULL,
  121719. NULL,
  121720. NULL,
  121721. 0
  121722. };
  121723. static long _huff_lengthlist_line_1024x27_class1[] = {
  121724. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121725. };
  121726. static static_codebook _huff_book_line_1024x27_class1 = {
  121727. 1, 16,
  121728. _huff_lengthlist_line_1024x27_class1,
  121729. 0, 0, 0, 0, 0,
  121730. NULL,
  121731. NULL,
  121732. NULL,
  121733. NULL,
  121734. 0
  121735. };
  121736. static long _huff_lengthlist_line_1024x27_class2[] = {
  121737. 1, 4, 2, 6, 3, 7, 5, 7,
  121738. };
  121739. static static_codebook _huff_book_line_1024x27_class2 = {
  121740. 1, 8,
  121741. _huff_lengthlist_line_1024x27_class2,
  121742. 0, 0, 0, 0, 0,
  121743. NULL,
  121744. NULL,
  121745. NULL,
  121746. NULL,
  121747. 0
  121748. };
  121749. static long _huff_lengthlist_line_1024x27_class3[] = {
  121750. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121751. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121752. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121753. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121754. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121755. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121756. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121757. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121758. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121759. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121760. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121761. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121762. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121763. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121764. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121765. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121766. };
  121767. static static_codebook _huff_book_line_1024x27_class3 = {
  121768. 1, 256,
  121769. _huff_lengthlist_line_1024x27_class3,
  121770. 0, 0, 0, 0, 0,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. NULL,
  121775. 0
  121776. };
  121777. static long _huff_lengthlist_line_1024x27_class4[] = {
  121778. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121779. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121780. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121781. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121782. };
  121783. static static_codebook _huff_book_line_1024x27_class4 = {
  121784. 1, 64,
  121785. _huff_lengthlist_line_1024x27_class4,
  121786. 0, 0, 0, 0, 0,
  121787. NULL,
  121788. NULL,
  121789. NULL,
  121790. NULL,
  121791. 0
  121792. };
  121793. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121794. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121795. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121796. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121797. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121798. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121799. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121800. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121801. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121802. };
  121803. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121804. 1, 128,
  121805. _huff_lengthlist_line_1024x27_0sub0,
  121806. 0, 0, 0, 0, 0,
  121807. NULL,
  121808. NULL,
  121809. NULL,
  121810. NULL,
  121811. 0
  121812. };
  121813. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121814. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121815. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121816. };
  121817. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121818. 1, 32,
  121819. _huff_lengthlist_line_1024x27_1sub0,
  121820. 0, 0, 0, 0, 0,
  121821. NULL,
  121822. NULL,
  121823. NULL,
  121824. NULL,
  121825. 0
  121826. };
  121827. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121831. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121832. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121833. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121834. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121835. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121836. };
  121837. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121838. 1, 128,
  121839. _huff_lengthlist_line_1024x27_1sub1,
  121840. 0, 0, 0, 0, 0,
  121841. NULL,
  121842. NULL,
  121843. NULL,
  121844. NULL,
  121845. 0
  121846. };
  121847. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121848. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121849. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121850. };
  121851. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121852. 1, 32,
  121853. _huff_lengthlist_line_1024x27_2sub0,
  121854. 0, 0, 0, 0, 0,
  121855. NULL,
  121856. NULL,
  121857. NULL,
  121858. NULL,
  121859. 0
  121860. };
  121861. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121865. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121866. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121867. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121868. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121869. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121870. };
  121871. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121872. 1, 128,
  121873. _huff_lengthlist_line_1024x27_2sub1,
  121874. 0, 0, 0, 0, 0,
  121875. NULL,
  121876. NULL,
  121877. NULL,
  121878. NULL,
  121879. 0
  121880. };
  121881. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121882. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121883. 5, 5,
  121884. };
  121885. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121886. 1, 18,
  121887. _huff_lengthlist_line_1024x27_3sub1,
  121888. 0, 0, 0, 0, 0,
  121889. NULL,
  121890. NULL,
  121891. NULL,
  121892. NULL,
  121893. 0
  121894. };
  121895. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121898. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121899. 9,11,
  121900. };
  121901. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121902. 1, 50,
  121903. _huff_lengthlist_line_1024x27_3sub2,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121916. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121917. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121918. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121919. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121920. };
  121921. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121922. 1, 128,
  121923. _huff_lengthlist_line_1024x27_3sub3,
  121924. 0, 0, 0, 0, 0,
  121925. NULL,
  121926. NULL,
  121927. NULL,
  121928. NULL,
  121929. 0
  121930. };
  121931. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121932. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121933. 5, 4,
  121934. };
  121935. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121936. 1, 18,
  121937. _huff_lengthlist_line_1024x27_4sub1,
  121938. 0, 0, 0, 0, 0,
  121939. NULL,
  121940. NULL,
  121941. NULL,
  121942. NULL,
  121943. 0
  121944. };
  121945. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121948. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121949. 9,12,
  121950. };
  121951. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121952. 1, 50,
  121953. _huff_lengthlist_line_1024x27_4sub2,
  121954. 0, 0, 0, 0, 0,
  121955. NULL,
  121956. NULL,
  121957. NULL,
  121958. NULL,
  121959. 0
  121960. };
  121961. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121966. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121968. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121969. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121970. };
  121971. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121972. 1, 128,
  121973. _huff_lengthlist_line_1024x27_4sub3,
  121974. 0, 0, 0, 0, 0,
  121975. NULL,
  121976. NULL,
  121977. NULL,
  121978. NULL,
  121979. 0
  121980. };
  121981. static long _huff_lengthlist_line_2048x27_class1[] = {
  121982. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121983. };
  121984. static static_codebook _huff_book_line_2048x27_class1 = {
  121985. 1, 16,
  121986. _huff_lengthlist_line_2048x27_class1,
  121987. 0, 0, 0, 0, 0,
  121988. NULL,
  121989. NULL,
  121990. NULL,
  121991. NULL,
  121992. 0
  121993. };
  121994. static long _huff_lengthlist_line_2048x27_class2[] = {
  121995. 1, 2, 3, 6, 4, 7, 5, 7,
  121996. };
  121997. static static_codebook _huff_book_line_2048x27_class2 = {
  121998. 1, 8,
  121999. _huff_lengthlist_line_2048x27_class2,
  122000. 0, 0, 0, 0, 0,
  122001. NULL,
  122002. NULL,
  122003. NULL,
  122004. NULL,
  122005. 0
  122006. };
  122007. static long _huff_lengthlist_line_2048x27_class3[] = {
  122008. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122009. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122010. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122011. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122012. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122013. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122014. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122015. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122016. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122017. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122018. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122019. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122020. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122021. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122022. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122023. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122024. };
  122025. static static_codebook _huff_book_line_2048x27_class3 = {
  122026. 1, 256,
  122027. _huff_lengthlist_line_2048x27_class3,
  122028. 0, 0, 0, 0, 0,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. NULL,
  122033. 0
  122034. };
  122035. static long _huff_lengthlist_line_2048x27_class4[] = {
  122036. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122037. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122038. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122039. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122040. };
  122041. static static_codebook _huff_book_line_2048x27_class4 = {
  122042. 1, 64,
  122043. _huff_lengthlist_line_2048x27_class4,
  122044. 0, 0, 0, 0, 0,
  122045. NULL,
  122046. NULL,
  122047. NULL,
  122048. NULL,
  122049. 0
  122050. };
  122051. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122052. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122053. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122054. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122055. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122056. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122057. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122058. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122059. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122060. };
  122061. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122062. 1, 128,
  122063. _huff_lengthlist_line_2048x27_0sub0,
  122064. 0, 0, 0, 0, 0,
  122065. NULL,
  122066. NULL,
  122067. NULL,
  122068. NULL,
  122069. 0
  122070. };
  122071. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122072. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122073. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122074. };
  122075. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122076. 1, 32,
  122077. _huff_lengthlist_line_2048x27_1sub0,
  122078. 0, 0, 0, 0, 0,
  122079. NULL,
  122080. NULL,
  122081. NULL,
  122082. NULL,
  122083. 0
  122084. };
  122085. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122089. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122090. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122091. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122092. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122093. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122094. };
  122095. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122096. 1, 128,
  122097. _huff_lengthlist_line_2048x27_1sub1,
  122098. 0, 0, 0, 0, 0,
  122099. NULL,
  122100. NULL,
  122101. NULL,
  122102. NULL,
  122103. 0
  122104. };
  122105. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122106. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122107. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122108. };
  122109. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122110. 1, 32,
  122111. _huff_lengthlist_line_2048x27_2sub0,
  122112. 0, 0, 0, 0, 0,
  122113. NULL,
  122114. NULL,
  122115. NULL,
  122116. NULL,
  122117. 0
  122118. };
  122119. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122123. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122124. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122125. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122126. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122127. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122128. };
  122129. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122130. 1, 128,
  122131. _huff_lengthlist_line_2048x27_2sub1,
  122132. 0, 0, 0, 0, 0,
  122133. NULL,
  122134. NULL,
  122135. NULL,
  122136. NULL,
  122137. 0
  122138. };
  122139. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122140. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122141. 5, 5,
  122142. };
  122143. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122144. 1, 18,
  122145. _huff_lengthlist_line_2048x27_3sub1,
  122146. 0, 0, 0, 0, 0,
  122147. NULL,
  122148. NULL,
  122149. NULL,
  122150. NULL,
  122151. 0
  122152. };
  122153. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122156. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122157. 10,12,
  122158. };
  122159. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122160. 1, 50,
  122161. _huff_lengthlist_line_2048x27_3sub2,
  122162. 0, 0, 0, 0, 0,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. NULL,
  122167. 0
  122168. };
  122169. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122174. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122175. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122176. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122177. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122178. };
  122179. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122180. 1, 128,
  122181. _huff_lengthlist_line_2048x27_3sub3,
  122182. 0, 0, 0, 0, 0,
  122183. NULL,
  122184. NULL,
  122185. NULL,
  122186. NULL,
  122187. 0
  122188. };
  122189. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122190. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122191. 4, 5,
  122192. };
  122193. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122194. 1, 18,
  122195. _huff_lengthlist_line_2048x27_4sub1,
  122196. 0, 0, 0, 0, 0,
  122197. NULL,
  122198. NULL,
  122199. NULL,
  122200. NULL,
  122201. 0
  122202. };
  122203. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122206. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122207. 10,10,
  122208. };
  122209. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122210. 1, 50,
  122211. _huff_lengthlist_line_2048x27_4sub2,
  122212. 0, 0, 0, 0, 0,
  122213. NULL,
  122214. NULL,
  122215. NULL,
  122216. NULL,
  122217. 0
  122218. };
  122219. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122224. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122225. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122226. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122227. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122228. };
  122229. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122230. 1, 128,
  122231. _huff_lengthlist_line_2048x27_4sub3,
  122232. 0, 0, 0, 0, 0,
  122233. NULL,
  122234. NULL,
  122235. NULL,
  122236. NULL,
  122237. 0
  122238. };
  122239. static long _huff_lengthlist_line_256x4low_class0[] = {
  122240. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122241. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122242. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122243. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122244. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122245. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122246. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122247. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122248. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122249. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122250. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122251. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122252. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122253. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122254. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122255. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122256. };
  122257. static static_codebook _huff_book_line_256x4low_class0 = {
  122258. 1, 256,
  122259. _huff_lengthlist_line_256x4low_class0,
  122260. 0, 0, 0, 0, 0,
  122261. NULL,
  122262. NULL,
  122263. NULL,
  122264. NULL,
  122265. 0
  122266. };
  122267. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122268. 1, 3, 2, 3,
  122269. };
  122270. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122271. 1, 4,
  122272. _huff_lengthlist_line_256x4low_0sub0,
  122273. 0, 0, 0, 0, 0,
  122274. NULL,
  122275. NULL,
  122276. NULL,
  122277. NULL,
  122278. 0
  122279. };
  122280. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122281. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122282. };
  122283. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122284. 1, 10,
  122285. _huff_lengthlist_line_256x4low_0sub1,
  122286. 0, 0, 0, 0, 0,
  122287. NULL,
  122288. NULL,
  122289. NULL,
  122290. NULL,
  122291. 0
  122292. };
  122293. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122295. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122296. };
  122297. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122298. 1, 25,
  122299. _huff_lengthlist_line_256x4low_0sub2,
  122300. 0, 0, 0, 0, 0,
  122301. NULL,
  122302. NULL,
  122303. NULL,
  122304. NULL,
  122305. 0
  122306. };
  122307. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122310. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122311. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122312. };
  122313. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122314. 1, 64,
  122315. _huff_lengthlist_line_256x4low_0sub3,
  122316. 0, 0, 0, 0, 0,
  122317. NULL,
  122318. NULL,
  122319. NULL,
  122320. NULL,
  122321. 0
  122322. };
  122323. /*** End of inlined file: floor_books.h ***/
  122324. static static_codebook *_floor_128x4_books[]={
  122325. &_huff_book_line_128x4_class0,
  122326. &_huff_book_line_128x4_0sub0,
  122327. &_huff_book_line_128x4_0sub1,
  122328. &_huff_book_line_128x4_0sub2,
  122329. &_huff_book_line_128x4_0sub3,
  122330. };
  122331. static static_codebook *_floor_256x4_books[]={
  122332. &_huff_book_line_256x4_class0,
  122333. &_huff_book_line_256x4_0sub0,
  122334. &_huff_book_line_256x4_0sub1,
  122335. &_huff_book_line_256x4_0sub2,
  122336. &_huff_book_line_256x4_0sub3,
  122337. };
  122338. static static_codebook *_floor_128x7_books[]={
  122339. &_huff_book_line_128x7_class0,
  122340. &_huff_book_line_128x7_class1,
  122341. &_huff_book_line_128x7_0sub1,
  122342. &_huff_book_line_128x7_0sub2,
  122343. &_huff_book_line_128x7_0sub3,
  122344. &_huff_book_line_128x7_1sub1,
  122345. &_huff_book_line_128x7_1sub2,
  122346. &_huff_book_line_128x7_1sub3,
  122347. };
  122348. static static_codebook *_floor_256x7_books[]={
  122349. &_huff_book_line_256x7_class0,
  122350. &_huff_book_line_256x7_class1,
  122351. &_huff_book_line_256x7_0sub1,
  122352. &_huff_book_line_256x7_0sub2,
  122353. &_huff_book_line_256x7_0sub3,
  122354. &_huff_book_line_256x7_1sub1,
  122355. &_huff_book_line_256x7_1sub2,
  122356. &_huff_book_line_256x7_1sub3,
  122357. };
  122358. static static_codebook *_floor_128x11_books[]={
  122359. &_huff_book_line_128x11_class1,
  122360. &_huff_book_line_128x11_class2,
  122361. &_huff_book_line_128x11_class3,
  122362. &_huff_book_line_128x11_0sub0,
  122363. &_huff_book_line_128x11_1sub0,
  122364. &_huff_book_line_128x11_1sub1,
  122365. &_huff_book_line_128x11_2sub1,
  122366. &_huff_book_line_128x11_2sub2,
  122367. &_huff_book_line_128x11_2sub3,
  122368. &_huff_book_line_128x11_3sub1,
  122369. &_huff_book_line_128x11_3sub2,
  122370. &_huff_book_line_128x11_3sub3,
  122371. };
  122372. static static_codebook *_floor_128x17_books[]={
  122373. &_huff_book_line_128x17_class1,
  122374. &_huff_book_line_128x17_class2,
  122375. &_huff_book_line_128x17_class3,
  122376. &_huff_book_line_128x17_0sub0,
  122377. &_huff_book_line_128x17_1sub0,
  122378. &_huff_book_line_128x17_1sub1,
  122379. &_huff_book_line_128x17_2sub1,
  122380. &_huff_book_line_128x17_2sub2,
  122381. &_huff_book_line_128x17_2sub3,
  122382. &_huff_book_line_128x17_3sub1,
  122383. &_huff_book_line_128x17_3sub2,
  122384. &_huff_book_line_128x17_3sub3,
  122385. };
  122386. static static_codebook *_floor_256x4low_books[]={
  122387. &_huff_book_line_256x4low_class0,
  122388. &_huff_book_line_256x4low_0sub0,
  122389. &_huff_book_line_256x4low_0sub1,
  122390. &_huff_book_line_256x4low_0sub2,
  122391. &_huff_book_line_256x4low_0sub3,
  122392. };
  122393. static static_codebook *_floor_1024x27_books[]={
  122394. &_huff_book_line_1024x27_class1,
  122395. &_huff_book_line_1024x27_class2,
  122396. &_huff_book_line_1024x27_class3,
  122397. &_huff_book_line_1024x27_class4,
  122398. &_huff_book_line_1024x27_0sub0,
  122399. &_huff_book_line_1024x27_1sub0,
  122400. &_huff_book_line_1024x27_1sub1,
  122401. &_huff_book_line_1024x27_2sub0,
  122402. &_huff_book_line_1024x27_2sub1,
  122403. &_huff_book_line_1024x27_3sub1,
  122404. &_huff_book_line_1024x27_3sub2,
  122405. &_huff_book_line_1024x27_3sub3,
  122406. &_huff_book_line_1024x27_4sub1,
  122407. &_huff_book_line_1024x27_4sub2,
  122408. &_huff_book_line_1024x27_4sub3,
  122409. };
  122410. static static_codebook *_floor_2048x27_books[]={
  122411. &_huff_book_line_2048x27_class1,
  122412. &_huff_book_line_2048x27_class2,
  122413. &_huff_book_line_2048x27_class3,
  122414. &_huff_book_line_2048x27_class4,
  122415. &_huff_book_line_2048x27_0sub0,
  122416. &_huff_book_line_2048x27_1sub0,
  122417. &_huff_book_line_2048x27_1sub1,
  122418. &_huff_book_line_2048x27_2sub0,
  122419. &_huff_book_line_2048x27_2sub1,
  122420. &_huff_book_line_2048x27_3sub1,
  122421. &_huff_book_line_2048x27_3sub2,
  122422. &_huff_book_line_2048x27_3sub3,
  122423. &_huff_book_line_2048x27_4sub1,
  122424. &_huff_book_line_2048x27_4sub2,
  122425. &_huff_book_line_2048x27_4sub3,
  122426. };
  122427. static static_codebook *_floor_512x17_books[]={
  122428. &_huff_book_line_512x17_class1,
  122429. &_huff_book_line_512x17_class2,
  122430. &_huff_book_line_512x17_class3,
  122431. &_huff_book_line_512x17_0sub0,
  122432. &_huff_book_line_512x17_1sub0,
  122433. &_huff_book_line_512x17_1sub1,
  122434. &_huff_book_line_512x17_2sub1,
  122435. &_huff_book_line_512x17_2sub2,
  122436. &_huff_book_line_512x17_2sub3,
  122437. &_huff_book_line_512x17_3sub1,
  122438. &_huff_book_line_512x17_3sub2,
  122439. &_huff_book_line_512x17_3sub3,
  122440. };
  122441. static static_codebook **_floor_books[10]={
  122442. _floor_128x4_books,
  122443. _floor_256x4_books,
  122444. _floor_128x7_books,
  122445. _floor_256x7_books,
  122446. _floor_128x11_books,
  122447. _floor_128x17_books,
  122448. _floor_256x4low_books,
  122449. _floor_1024x27_books,
  122450. _floor_2048x27_books,
  122451. _floor_512x17_books,
  122452. };
  122453. static vorbis_info_floor1 _floor[10]={
  122454. /* 128 x 4 */
  122455. {
  122456. 1,{0},{4},{2},{0},
  122457. {{1,2,3,4}},
  122458. 4,{0,128, 33,8,16,70},
  122459. 60,30,500, 1.,18., -1
  122460. },
  122461. /* 256 x 4 */
  122462. {
  122463. 1,{0},{4},{2},{0},
  122464. {{1,2,3,4}},
  122465. 4,{0,256, 66,16,32,140},
  122466. 60,30,500, 1.,18., -1
  122467. },
  122468. /* 128 x 7 */
  122469. {
  122470. 2,{0,1},{3,4},{2,2},{0,1},
  122471. {{-1,2,3,4},{-1,5,6,7}},
  122472. 4,{0,128, 14,4,58, 2,8,28,90},
  122473. 60,30,500, 1.,18., -1
  122474. },
  122475. /* 256 x 7 */
  122476. {
  122477. 2,{0,1},{3,4},{2,2},{0,1},
  122478. {{-1,2,3,4},{-1,5,6,7}},
  122479. 4,{0,256, 28,8,116, 4,16,56,180},
  122480. 60,30,500, 1.,18., -1
  122481. },
  122482. /* 128 x 11 */
  122483. {
  122484. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122485. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122486. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122487. 60,30,500, 1,18., -1
  122488. },
  122489. /* 128 x 17 */
  122490. {
  122491. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122492. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122493. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122494. 60,30,500, 1,18., -1
  122495. },
  122496. /* 256 x 4 (low bitrate version) */
  122497. {
  122498. 1,{0},{4},{2},{0},
  122499. {{1,2,3,4}},
  122500. 4,{0,256, 66,16,32,140},
  122501. 60,30,500, 1.,18., -1
  122502. },
  122503. /* 1024 x 27 */
  122504. {
  122505. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122506. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122507. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122508. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122509. 60,30,500, 3,18., -1 /* lowpass */
  122510. },
  122511. /* 2048 x 27 */
  122512. {
  122513. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122514. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122515. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122516. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122517. 60,30,500, 3,18., -1 /* lowpass */
  122518. },
  122519. /* 512 x 17 */
  122520. {
  122521. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122522. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122523. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122524. 7,23,39, 55,79,110, 156,232,360},
  122525. 60,30,500, 1,18., -1 /* lowpass! */
  122526. },
  122527. };
  122528. /*** End of inlined file: floor_all.h ***/
  122529. /*** Start of inlined file: residue_44.h ***/
  122530. /*** Start of inlined file: res_books_stereo.h ***/
  122531. static long _vq_quantlist__16c0_s_p1_0[] = {
  122532. 1,
  122533. 0,
  122534. 2,
  122535. };
  122536. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122537. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122538. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122543. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122548. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122583. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122588. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122593. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122629. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122634. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122639. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0,
  122948. };
  122949. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122950. -0.5, 0.5,
  122951. };
  122952. static long _vq_quantmap__16c0_s_p1_0[] = {
  122953. 1, 0, 2,
  122954. };
  122955. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122956. _vq_quantthresh__16c0_s_p1_0,
  122957. _vq_quantmap__16c0_s_p1_0,
  122958. 3,
  122959. 3
  122960. };
  122961. static static_codebook _16c0_s_p1_0 = {
  122962. 8, 6561,
  122963. _vq_lengthlist__16c0_s_p1_0,
  122964. 1, -535822336, 1611661312, 2, 0,
  122965. _vq_quantlist__16c0_s_p1_0,
  122966. NULL,
  122967. &_vq_auxt__16c0_s_p1_0,
  122968. NULL,
  122969. 0
  122970. };
  122971. static long _vq_quantlist__16c0_s_p2_0[] = {
  122972. 2,
  122973. 1,
  122974. 3,
  122975. 0,
  122976. 4,
  122977. };
  122978. static long _vq_lengthlist__16c0_s_p2_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,
  123019. };
  123020. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123021. -1.5, -0.5, 0.5, 1.5,
  123022. };
  123023. static long _vq_quantmap__16c0_s_p2_0[] = {
  123024. 3, 1, 0, 2, 4,
  123025. };
  123026. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123027. _vq_quantthresh__16c0_s_p2_0,
  123028. _vq_quantmap__16c0_s_p2_0,
  123029. 5,
  123030. 5
  123031. };
  123032. static static_codebook _16c0_s_p2_0 = {
  123033. 4, 625,
  123034. _vq_lengthlist__16c0_s_p2_0,
  123035. 1, -533725184, 1611661312, 3, 0,
  123036. _vq_quantlist__16c0_s_p2_0,
  123037. NULL,
  123038. &_vq_auxt__16c0_s_p2_0,
  123039. NULL,
  123040. 0
  123041. };
  123042. static long _vq_quantlist__16c0_s_p3_0[] = {
  123043. 2,
  123044. 1,
  123045. 3,
  123046. 0,
  123047. 4,
  123048. };
  123049. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123050. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  123090. };
  123091. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123092. -1.5, -0.5, 0.5, 1.5,
  123093. };
  123094. static long _vq_quantmap__16c0_s_p3_0[] = {
  123095. 3, 1, 0, 2, 4,
  123096. };
  123097. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123098. _vq_quantthresh__16c0_s_p3_0,
  123099. _vq_quantmap__16c0_s_p3_0,
  123100. 5,
  123101. 5
  123102. };
  123103. static static_codebook _16c0_s_p3_0 = {
  123104. 4, 625,
  123105. _vq_lengthlist__16c0_s_p3_0,
  123106. 1, -533725184, 1611661312, 3, 0,
  123107. _vq_quantlist__16c0_s_p3_0,
  123108. NULL,
  123109. &_vq_auxt__16c0_s_p3_0,
  123110. NULL,
  123111. 0
  123112. };
  123113. static long _vq_quantlist__16c0_s_p4_0[] = {
  123114. 4,
  123115. 3,
  123116. 5,
  123117. 2,
  123118. 6,
  123119. 1,
  123120. 7,
  123121. 0,
  123122. 8,
  123123. };
  123124. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123125. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123126. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123127. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123128. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123129. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0,
  123131. };
  123132. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123133. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123134. };
  123135. static long _vq_quantmap__16c0_s_p4_0[] = {
  123136. 7, 5, 3, 1, 0, 2, 4, 6,
  123137. 8,
  123138. };
  123139. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123140. _vq_quantthresh__16c0_s_p4_0,
  123141. _vq_quantmap__16c0_s_p4_0,
  123142. 9,
  123143. 9
  123144. };
  123145. static static_codebook _16c0_s_p4_0 = {
  123146. 2, 81,
  123147. _vq_lengthlist__16c0_s_p4_0,
  123148. 1, -531628032, 1611661312, 4, 0,
  123149. _vq_quantlist__16c0_s_p4_0,
  123150. NULL,
  123151. &_vq_auxt__16c0_s_p4_0,
  123152. NULL,
  123153. 0
  123154. };
  123155. static long _vq_quantlist__16c0_s_p5_0[] = {
  123156. 4,
  123157. 3,
  123158. 5,
  123159. 2,
  123160. 6,
  123161. 1,
  123162. 7,
  123163. 0,
  123164. 8,
  123165. };
  123166. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123167. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123168. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123169. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123170. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123171. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123172. 10,
  123173. };
  123174. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123175. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123176. };
  123177. static long _vq_quantmap__16c0_s_p5_0[] = {
  123178. 7, 5, 3, 1, 0, 2, 4, 6,
  123179. 8,
  123180. };
  123181. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123182. _vq_quantthresh__16c0_s_p5_0,
  123183. _vq_quantmap__16c0_s_p5_0,
  123184. 9,
  123185. 9
  123186. };
  123187. static static_codebook _16c0_s_p5_0 = {
  123188. 2, 81,
  123189. _vq_lengthlist__16c0_s_p5_0,
  123190. 1, -531628032, 1611661312, 4, 0,
  123191. _vq_quantlist__16c0_s_p5_0,
  123192. NULL,
  123193. &_vq_auxt__16c0_s_p5_0,
  123194. NULL,
  123195. 0
  123196. };
  123197. static long _vq_quantlist__16c0_s_p6_0[] = {
  123198. 8,
  123199. 7,
  123200. 9,
  123201. 6,
  123202. 10,
  123203. 5,
  123204. 11,
  123205. 4,
  123206. 12,
  123207. 3,
  123208. 13,
  123209. 2,
  123210. 14,
  123211. 1,
  123212. 15,
  123213. 0,
  123214. 16,
  123215. };
  123216. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123217. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123218. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123219. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123220. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123221. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123222. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123223. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123224. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123225. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123226. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123227. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123228. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123229. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123230. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123231. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123232. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123233. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123235. 14,
  123236. };
  123237. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123238. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123239. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123240. };
  123241. static long _vq_quantmap__16c0_s_p6_0[] = {
  123242. 15, 13, 11, 9, 7, 5, 3, 1,
  123243. 0, 2, 4, 6, 8, 10, 12, 14,
  123244. 16,
  123245. };
  123246. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123247. _vq_quantthresh__16c0_s_p6_0,
  123248. _vq_quantmap__16c0_s_p6_0,
  123249. 17,
  123250. 17
  123251. };
  123252. static static_codebook _16c0_s_p6_0 = {
  123253. 2, 289,
  123254. _vq_lengthlist__16c0_s_p6_0,
  123255. 1, -529530880, 1611661312, 5, 0,
  123256. _vq_quantlist__16c0_s_p6_0,
  123257. NULL,
  123258. &_vq_auxt__16c0_s_p6_0,
  123259. NULL,
  123260. 0
  123261. };
  123262. static long _vq_quantlist__16c0_s_p7_0[] = {
  123263. 1,
  123264. 0,
  123265. 2,
  123266. };
  123267. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123268. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123269. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123270. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123271. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123272. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123273. 13,
  123274. };
  123275. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123276. -5.5, 5.5,
  123277. };
  123278. static long _vq_quantmap__16c0_s_p7_0[] = {
  123279. 1, 0, 2,
  123280. };
  123281. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123282. _vq_quantthresh__16c0_s_p7_0,
  123283. _vq_quantmap__16c0_s_p7_0,
  123284. 3,
  123285. 3
  123286. };
  123287. static static_codebook _16c0_s_p7_0 = {
  123288. 4, 81,
  123289. _vq_lengthlist__16c0_s_p7_0,
  123290. 1, -529137664, 1618345984, 2, 0,
  123291. _vq_quantlist__16c0_s_p7_0,
  123292. NULL,
  123293. &_vq_auxt__16c0_s_p7_0,
  123294. NULL,
  123295. 0
  123296. };
  123297. static long _vq_quantlist__16c0_s_p7_1[] = {
  123298. 5,
  123299. 4,
  123300. 6,
  123301. 3,
  123302. 7,
  123303. 2,
  123304. 8,
  123305. 1,
  123306. 9,
  123307. 0,
  123308. 10,
  123309. };
  123310. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123311. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123312. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123313. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123314. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123315. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123316. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123317. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123318. 11,11,11, 9, 9, 9, 9,10,10,
  123319. };
  123320. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123321. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123322. 3.5, 4.5,
  123323. };
  123324. static long _vq_quantmap__16c0_s_p7_1[] = {
  123325. 9, 7, 5, 3, 1, 0, 2, 4,
  123326. 6, 8, 10,
  123327. };
  123328. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123329. _vq_quantthresh__16c0_s_p7_1,
  123330. _vq_quantmap__16c0_s_p7_1,
  123331. 11,
  123332. 11
  123333. };
  123334. static static_codebook _16c0_s_p7_1 = {
  123335. 2, 121,
  123336. _vq_lengthlist__16c0_s_p7_1,
  123337. 1, -531365888, 1611661312, 4, 0,
  123338. _vq_quantlist__16c0_s_p7_1,
  123339. NULL,
  123340. &_vq_auxt__16c0_s_p7_1,
  123341. NULL,
  123342. 0
  123343. };
  123344. static long _vq_quantlist__16c0_s_p8_0[] = {
  123345. 6,
  123346. 5,
  123347. 7,
  123348. 4,
  123349. 8,
  123350. 3,
  123351. 9,
  123352. 2,
  123353. 10,
  123354. 1,
  123355. 11,
  123356. 0,
  123357. 12,
  123358. };
  123359. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123360. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123361. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123362. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123363. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123364. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123365. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123366. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123367. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123368. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123369. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123370. 0,12,13,13,12,13,14,14,14,
  123371. };
  123372. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123373. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123374. 12.5, 17.5, 22.5, 27.5,
  123375. };
  123376. static long _vq_quantmap__16c0_s_p8_0[] = {
  123377. 11, 9, 7, 5, 3, 1, 0, 2,
  123378. 4, 6, 8, 10, 12,
  123379. };
  123380. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123381. _vq_quantthresh__16c0_s_p8_0,
  123382. _vq_quantmap__16c0_s_p8_0,
  123383. 13,
  123384. 13
  123385. };
  123386. static static_codebook _16c0_s_p8_0 = {
  123387. 2, 169,
  123388. _vq_lengthlist__16c0_s_p8_0,
  123389. 1, -526516224, 1616117760, 4, 0,
  123390. _vq_quantlist__16c0_s_p8_0,
  123391. NULL,
  123392. &_vq_auxt__16c0_s_p8_0,
  123393. NULL,
  123394. 0
  123395. };
  123396. static long _vq_quantlist__16c0_s_p8_1[] = {
  123397. 2,
  123398. 1,
  123399. 3,
  123400. 0,
  123401. 4,
  123402. };
  123403. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123404. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123405. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123406. };
  123407. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123408. -1.5, -0.5, 0.5, 1.5,
  123409. };
  123410. static long _vq_quantmap__16c0_s_p8_1[] = {
  123411. 3, 1, 0, 2, 4,
  123412. };
  123413. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123414. _vq_quantthresh__16c0_s_p8_1,
  123415. _vq_quantmap__16c0_s_p8_1,
  123416. 5,
  123417. 5
  123418. };
  123419. static static_codebook _16c0_s_p8_1 = {
  123420. 2, 25,
  123421. _vq_lengthlist__16c0_s_p8_1,
  123422. 1, -533725184, 1611661312, 3, 0,
  123423. _vq_quantlist__16c0_s_p8_1,
  123424. NULL,
  123425. &_vq_auxt__16c0_s_p8_1,
  123426. NULL,
  123427. 0
  123428. };
  123429. static long _vq_quantlist__16c0_s_p9_0[] = {
  123430. 1,
  123431. 0,
  123432. 2,
  123433. };
  123434. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123435. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123436. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123437. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123438. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123439. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123440. 7,
  123441. };
  123442. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123443. -157.5, 157.5,
  123444. };
  123445. static long _vq_quantmap__16c0_s_p9_0[] = {
  123446. 1, 0, 2,
  123447. };
  123448. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123449. _vq_quantthresh__16c0_s_p9_0,
  123450. _vq_quantmap__16c0_s_p9_0,
  123451. 3,
  123452. 3
  123453. };
  123454. static static_codebook _16c0_s_p9_0 = {
  123455. 4, 81,
  123456. _vq_lengthlist__16c0_s_p9_0,
  123457. 1, -518803456, 1628680192, 2, 0,
  123458. _vq_quantlist__16c0_s_p9_0,
  123459. NULL,
  123460. &_vq_auxt__16c0_s_p9_0,
  123461. NULL,
  123462. 0
  123463. };
  123464. static long _vq_quantlist__16c0_s_p9_1[] = {
  123465. 7,
  123466. 6,
  123467. 8,
  123468. 5,
  123469. 9,
  123470. 4,
  123471. 10,
  123472. 3,
  123473. 11,
  123474. 2,
  123475. 12,
  123476. 1,
  123477. 13,
  123478. 0,
  123479. 14,
  123480. };
  123481. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123482. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123483. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123484. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123485. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123486. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123487. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123488. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123489. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123490. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123491. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123492. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123493. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123494. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123495. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123496. 10,
  123497. };
  123498. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123499. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123500. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123501. };
  123502. static long _vq_quantmap__16c0_s_p9_1[] = {
  123503. 13, 11, 9, 7, 5, 3, 1, 0,
  123504. 2, 4, 6, 8, 10, 12, 14,
  123505. };
  123506. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123507. _vq_quantthresh__16c0_s_p9_1,
  123508. _vq_quantmap__16c0_s_p9_1,
  123509. 15,
  123510. 15
  123511. };
  123512. static static_codebook _16c0_s_p9_1 = {
  123513. 2, 225,
  123514. _vq_lengthlist__16c0_s_p9_1,
  123515. 1, -520986624, 1620377600, 4, 0,
  123516. _vq_quantlist__16c0_s_p9_1,
  123517. NULL,
  123518. &_vq_auxt__16c0_s_p9_1,
  123519. NULL,
  123520. 0
  123521. };
  123522. static long _vq_quantlist__16c0_s_p9_2[] = {
  123523. 10,
  123524. 9,
  123525. 11,
  123526. 8,
  123527. 12,
  123528. 7,
  123529. 13,
  123530. 6,
  123531. 14,
  123532. 5,
  123533. 15,
  123534. 4,
  123535. 16,
  123536. 3,
  123537. 17,
  123538. 2,
  123539. 18,
  123540. 1,
  123541. 19,
  123542. 0,
  123543. 20,
  123544. };
  123545. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123546. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123547. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123548. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123549. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123550. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123551. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123552. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123553. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123554. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123555. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123556. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123557. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123558. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123559. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123560. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123561. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123562. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123563. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123564. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123565. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123566. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123567. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123568. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123569. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123570. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123571. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123572. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123573. 10,11,10,10,11, 9,10,10,10,
  123574. };
  123575. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123576. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123577. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123578. 6.5, 7.5, 8.5, 9.5,
  123579. };
  123580. static long _vq_quantmap__16c0_s_p9_2[] = {
  123581. 19, 17, 15, 13, 11, 9, 7, 5,
  123582. 3, 1, 0, 2, 4, 6, 8, 10,
  123583. 12, 14, 16, 18, 20,
  123584. };
  123585. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123586. _vq_quantthresh__16c0_s_p9_2,
  123587. _vq_quantmap__16c0_s_p9_2,
  123588. 21,
  123589. 21
  123590. };
  123591. static static_codebook _16c0_s_p9_2 = {
  123592. 2, 441,
  123593. _vq_lengthlist__16c0_s_p9_2,
  123594. 1, -529268736, 1611661312, 5, 0,
  123595. _vq_quantlist__16c0_s_p9_2,
  123596. NULL,
  123597. &_vq_auxt__16c0_s_p9_2,
  123598. NULL,
  123599. 0
  123600. };
  123601. static long _huff_lengthlist__16c0_s_single[] = {
  123602. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123603. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123604. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123605. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123606. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123607. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123608. 16,16,18,18,
  123609. };
  123610. static static_codebook _huff_book__16c0_s_single = {
  123611. 2, 100,
  123612. _huff_lengthlist__16c0_s_single,
  123613. 0, 0, 0, 0, 0,
  123614. NULL,
  123615. NULL,
  123616. NULL,
  123617. NULL,
  123618. 0
  123619. };
  123620. static long _huff_lengthlist__16c1_s_long[] = {
  123621. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123622. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123623. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123624. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123625. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123626. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123627. 12,11,11,13,
  123628. };
  123629. static static_codebook _huff_book__16c1_s_long = {
  123630. 2, 100,
  123631. _huff_lengthlist__16c1_s_long,
  123632. 0, 0, 0, 0, 0,
  123633. NULL,
  123634. NULL,
  123635. NULL,
  123636. NULL,
  123637. 0
  123638. };
  123639. static long _vq_quantlist__16c1_s_p1_0[] = {
  123640. 1,
  123641. 0,
  123642. 2,
  123643. };
  123644. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123645. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123646. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123651. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123656. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123691. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123696. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123701. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123737. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123742. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123747. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0,
  124056. };
  124057. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124058. -0.5, 0.5,
  124059. };
  124060. static long _vq_quantmap__16c1_s_p1_0[] = {
  124061. 1, 0, 2,
  124062. };
  124063. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124064. _vq_quantthresh__16c1_s_p1_0,
  124065. _vq_quantmap__16c1_s_p1_0,
  124066. 3,
  124067. 3
  124068. };
  124069. static static_codebook _16c1_s_p1_0 = {
  124070. 8, 6561,
  124071. _vq_lengthlist__16c1_s_p1_0,
  124072. 1, -535822336, 1611661312, 2, 0,
  124073. _vq_quantlist__16c1_s_p1_0,
  124074. NULL,
  124075. &_vq_auxt__16c1_s_p1_0,
  124076. NULL,
  124077. 0
  124078. };
  124079. static long _vq_quantlist__16c1_s_p2_0[] = {
  124080. 2,
  124081. 1,
  124082. 3,
  124083. 0,
  124084. 4,
  124085. };
  124086. static long _vq_lengthlist__16c1_s_p2_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,
  124127. };
  124128. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124129. -1.5, -0.5, 0.5, 1.5,
  124130. };
  124131. static long _vq_quantmap__16c1_s_p2_0[] = {
  124132. 3, 1, 0, 2, 4,
  124133. };
  124134. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124135. _vq_quantthresh__16c1_s_p2_0,
  124136. _vq_quantmap__16c1_s_p2_0,
  124137. 5,
  124138. 5
  124139. };
  124140. static static_codebook _16c1_s_p2_0 = {
  124141. 4, 625,
  124142. _vq_lengthlist__16c1_s_p2_0,
  124143. 1, -533725184, 1611661312, 3, 0,
  124144. _vq_quantlist__16c1_s_p2_0,
  124145. NULL,
  124146. &_vq_auxt__16c1_s_p2_0,
  124147. NULL,
  124148. 0
  124149. };
  124150. static long _vq_quantlist__16c1_s_p3_0[] = {
  124151. 2,
  124152. 1,
  124153. 3,
  124154. 0,
  124155. 4,
  124156. };
  124157. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124158. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  124198. };
  124199. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124200. -1.5, -0.5, 0.5, 1.5,
  124201. };
  124202. static long _vq_quantmap__16c1_s_p3_0[] = {
  124203. 3, 1, 0, 2, 4,
  124204. };
  124205. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124206. _vq_quantthresh__16c1_s_p3_0,
  124207. _vq_quantmap__16c1_s_p3_0,
  124208. 5,
  124209. 5
  124210. };
  124211. static static_codebook _16c1_s_p3_0 = {
  124212. 4, 625,
  124213. _vq_lengthlist__16c1_s_p3_0,
  124214. 1, -533725184, 1611661312, 3, 0,
  124215. _vq_quantlist__16c1_s_p3_0,
  124216. NULL,
  124217. &_vq_auxt__16c1_s_p3_0,
  124218. NULL,
  124219. 0
  124220. };
  124221. static long _vq_quantlist__16c1_s_p4_0[] = {
  124222. 4,
  124223. 3,
  124224. 5,
  124225. 2,
  124226. 6,
  124227. 1,
  124228. 7,
  124229. 0,
  124230. 8,
  124231. };
  124232. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124233. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124234. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124235. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124236. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124237. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0,
  124239. };
  124240. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124241. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124242. };
  124243. static long _vq_quantmap__16c1_s_p4_0[] = {
  124244. 7, 5, 3, 1, 0, 2, 4, 6,
  124245. 8,
  124246. };
  124247. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124248. _vq_quantthresh__16c1_s_p4_0,
  124249. _vq_quantmap__16c1_s_p4_0,
  124250. 9,
  124251. 9
  124252. };
  124253. static static_codebook _16c1_s_p4_0 = {
  124254. 2, 81,
  124255. _vq_lengthlist__16c1_s_p4_0,
  124256. 1, -531628032, 1611661312, 4, 0,
  124257. _vq_quantlist__16c1_s_p4_0,
  124258. NULL,
  124259. &_vq_auxt__16c1_s_p4_0,
  124260. NULL,
  124261. 0
  124262. };
  124263. static long _vq_quantlist__16c1_s_p5_0[] = {
  124264. 4,
  124265. 3,
  124266. 5,
  124267. 2,
  124268. 6,
  124269. 1,
  124270. 7,
  124271. 0,
  124272. 8,
  124273. };
  124274. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124275. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124276. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124277. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124278. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124279. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124280. 10,
  124281. };
  124282. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124283. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124284. };
  124285. static long _vq_quantmap__16c1_s_p5_0[] = {
  124286. 7, 5, 3, 1, 0, 2, 4, 6,
  124287. 8,
  124288. };
  124289. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124290. _vq_quantthresh__16c1_s_p5_0,
  124291. _vq_quantmap__16c1_s_p5_0,
  124292. 9,
  124293. 9
  124294. };
  124295. static static_codebook _16c1_s_p5_0 = {
  124296. 2, 81,
  124297. _vq_lengthlist__16c1_s_p5_0,
  124298. 1, -531628032, 1611661312, 4, 0,
  124299. _vq_quantlist__16c1_s_p5_0,
  124300. NULL,
  124301. &_vq_auxt__16c1_s_p5_0,
  124302. NULL,
  124303. 0
  124304. };
  124305. static long _vq_quantlist__16c1_s_p6_0[] = {
  124306. 8,
  124307. 7,
  124308. 9,
  124309. 6,
  124310. 10,
  124311. 5,
  124312. 11,
  124313. 4,
  124314. 12,
  124315. 3,
  124316. 13,
  124317. 2,
  124318. 14,
  124319. 1,
  124320. 15,
  124321. 0,
  124322. 16,
  124323. };
  124324. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124325. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124326. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124327. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124328. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124329. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124330. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124331. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124332. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124333. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124334. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124335. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124336. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124337. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124338. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124339. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124340. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124341. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124343. 14,
  124344. };
  124345. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124346. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124347. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124348. };
  124349. static long _vq_quantmap__16c1_s_p6_0[] = {
  124350. 15, 13, 11, 9, 7, 5, 3, 1,
  124351. 0, 2, 4, 6, 8, 10, 12, 14,
  124352. 16,
  124353. };
  124354. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124355. _vq_quantthresh__16c1_s_p6_0,
  124356. _vq_quantmap__16c1_s_p6_0,
  124357. 17,
  124358. 17
  124359. };
  124360. static static_codebook _16c1_s_p6_0 = {
  124361. 2, 289,
  124362. _vq_lengthlist__16c1_s_p6_0,
  124363. 1, -529530880, 1611661312, 5, 0,
  124364. _vq_quantlist__16c1_s_p6_0,
  124365. NULL,
  124366. &_vq_auxt__16c1_s_p6_0,
  124367. NULL,
  124368. 0
  124369. };
  124370. static long _vq_quantlist__16c1_s_p7_0[] = {
  124371. 1,
  124372. 0,
  124373. 2,
  124374. };
  124375. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124376. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124377. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124378. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124379. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124380. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124381. 11,
  124382. };
  124383. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124384. -5.5, 5.5,
  124385. };
  124386. static long _vq_quantmap__16c1_s_p7_0[] = {
  124387. 1, 0, 2,
  124388. };
  124389. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124390. _vq_quantthresh__16c1_s_p7_0,
  124391. _vq_quantmap__16c1_s_p7_0,
  124392. 3,
  124393. 3
  124394. };
  124395. static static_codebook _16c1_s_p7_0 = {
  124396. 4, 81,
  124397. _vq_lengthlist__16c1_s_p7_0,
  124398. 1, -529137664, 1618345984, 2, 0,
  124399. _vq_quantlist__16c1_s_p7_0,
  124400. NULL,
  124401. &_vq_auxt__16c1_s_p7_0,
  124402. NULL,
  124403. 0
  124404. };
  124405. static long _vq_quantlist__16c1_s_p7_1[] = {
  124406. 5,
  124407. 4,
  124408. 6,
  124409. 3,
  124410. 7,
  124411. 2,
  124412. 8,
  124413. 1,
  124414. 9,
  124415. 0,
  124416. 10,
  124417. };
  124418. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124419. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124420. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124421. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124422. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124423. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124424. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124425. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124426. 10,10,10, 8, 8, 8, 8, 9, 9,
  124427. };
  124428. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124429. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124430. 3.5, 4.5,
  124431. };
  124432. static long _vq_quantmap__16c1_s_p7_1[] = {
  124433. 9, 7, 5, 3, 1, 0, 2, 4,
  124434. 6, 8, 10,
  124435. };
  124436. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124437. _vq_quantthresh__16c1_s_p7_1,
  124438. _vq_quantmap__16c1_s_p7_1,
  124439. 11,
  124440. 11
  124441. };
  124442. static static_codebook _16c1_s_p7_1 = {
  124443. 2, 121,
  124444. _vq_lengthlist__16c1_s_p7_1,
  124445. 1, -531365888, 1611661312, 4, 0,
  124446. _vq_quantlist__16c1_s_p7_1,
  124447. NULL,
  124448. &_vq_auxt__16c1_s_p7_1,
  124449. NULL,
  124450. 0
  124451. };
  124452. static long _vq_quantlist__16c1_s_p8_0[] = {
  124453. 6,
  124454. 5,
  124455. 7,
  124456. 4,
  124457. 8,
  124458. 3,
  124459. 9,
  124460. 2,
  124461. 10,
  124462. 1,
  124463. 11,
  124464. 0,
  124465. 12,
  124466. };
  124467. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124468. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124469. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124470. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124471. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124472. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124473. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124474. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124475. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124476. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124477. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124478. 0,12,12,12,12,13,13,14,15,
  124479. };
  124480. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124481. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124482. 12.5, 17.5, 22.5, 27.5,
  124483. };
  124484. static long _vq_quantmap__16c1_s_p8_0[] = {
  124485. 11, 9, 7, 5, 3, 1, 0, 2,
  124486. 4, 6, 8, 10, 12,
  124487. };
  124488. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124489. _vq_quantthresh__16c1_s_p8_0,
  124490. _vq_quantmap__16c1_s_p8_0,
  124491. 13,
  124492. 13
  124493. };
  124494. static static_codebook _16c1_s_p8_0 = {
  124495. 2, 169,
  124496. _vq_lengthlist__16c1_s_p8_0,
  124497. 1, -526516224, 1616117760, 4, 0,
  124498. _vq_quantlist__16c1_s_p8_0,
  124499. NULL,
  124500. &_vq_auxt__16c1_s_p8_0,
  124501. NULL,
  124502. 0
  124503. };
  124504. static long _vq_quantlist__16c1_s_p8_1[] = {
  124505. 2,
  124506. 1,
  124507. 3,
  124508. 0,
  124509. 4,
  124510. };
  124511. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124512. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124513. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124514. };
  124515. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124516. -1.5, -0.5, 0.5, 1.5,
  124517. };
  124518. static long _vq_quantmap__16c1_s_p8_1[] = {
  124519. 3, 1, 0, 2, 4,
  124520. };
  124521. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124522. _vq_quantthresh__16c1_s_p8_1,
  124523. _vq_quantmap__16c1_s_p8_1,
  124524. 5,
  124525. 5
  124526. };
  124527. static static_codebook _16c1_s_p8_1 = {
  124528. 2, 25,
  124529. _vq_lengthlist__16c1_s_p8_1,
  124530. 1, -533725184, 1611661312, 3, 0,
  124531. _vq_quantlist__16c1_s_p8_1,
  124532. NULL,
  124533. &_vq_auxt__16c1_s_p8_1,
  124534. NULL,
  124535. 0
  124536. };
  124537. static long _vq_quantlist__16c1_s_p9_0[] = {
  124538. 6,
  124539. 5,
  124540. 7,
  124541. 4,
  124542. 8,
  124543. 3,
  124544. 9,
  124545. 2,
  124546. 10,
  124547. 1,
  124548. 11,
  124549. 0,
  124550. 12,
  124551. };
  124552. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124553. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124554. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124555. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124556. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124557. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124558. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124559. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124560. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124561. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124562. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124563. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124564. };
  124565. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124566. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124567. 787.5, 1102.5, 1417.5, 1732.5,
  124568. };
  124569. static long _vq_quantmap__16c1_s_p9_0[] = {
  124570. 11, 9, 7, 5, 3, 1, 0, 2,
  124571. 4, 6, 8, 10, 12,
  124572. };
  124573. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124574. _vq_quantthresh__16c1_s_p9_0,
  124575. _vq_quantmap__16c1_s_p9_0,
  124576. 13,
  124577. 13
  124578. };
  124579. static static_codebook _16c1_s_p9_0 = {
  124580. 2, 169,
  124581. _vq_lengthlist__16c1_s_p9_0,
  124582. 1, -513964032, 1628680192, 4, 0,
  124583. _vq_quantlist__16c1_s_p9_0,
  124584. NULL,
  124585. &_vq_auxt__16c1_s_p9_0,
  124586. NULL,
  124587. 0
  124588. };
  124589. static long _vq_quantlist__16c1_s_p9_1[] = {
  124590. 7,
  124591. 6,
  124592. 8,
  124593. 5,
  124594. 9,
  124595. 4,
  124596. 10,
  124597. 3,
  124598. 11,
  124599. 2,
  124600. 12,
  124601. 1,
  124602. 13,
  124603. 0,
  124604. 14,
  124605. };
  124606. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124607. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124608. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124609. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124610. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124611. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124612. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124613. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124614. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124615. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124616. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124617. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124618. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124619. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124620. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124621. 13,
  124622. };
  124623. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124624. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124625. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124626. };
  124627. static long _vq_quantmap__16c1_s_p9_1[] = {
  124628. 13, 11, 9, 7, 5, 3, 1, 0,
  124629. 2, 4, 6, 8, 10, 12, 14,
  124630. };
  124631. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124632. _vq_quantthresh__16c1_s_p9_1,
  124633. _vq_quantmap__16c1_s_p9_1,
  124634. 15,
  124635. 15
  124636. };
  124637. static static_codebook _16c1_s_p9_1 = {
  124638. 2, 225,
  124639. _vq_lengthlist__16c1_s_p9_1,
  124640. 1, -520986624, 1620377600, 4, 0,
  124641. _vq_quantlist__16c1_s_p9_1,
  124642. NULL,
  124643. &_vq_auxt__16c1_s_p9_1,
  124644. NULL,
  124645. 0
  124646. };
  124647. static long _vq_quantlist__16c1_s_p9_2[] = {
  124648. 10,
  124649. 9,
  124650. 11,
  124651. 8,
  124652. 12,
  124653. 7,
  124654. 13,
  124655. 6,
  124656. 14,
  124657. 5,
  124658. 15,
  124659. 4,
  124660. 16,
  124661. 3,
  124662. 17,
  124663. 2,
  124664. 18,
  124665. 1,
  124666. 19,
  124667. 0,
  124668. 20,
  124669. };
  124670. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124671. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124672. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124673. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124674. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124675. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124676. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124677. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124678. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124679. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124680. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124681. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124682. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124683. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124684. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124685. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124686. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124687. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124688. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124689. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124690. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124691. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124692. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124693. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124694. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124695. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124696. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124697. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124698. 11,11,11,11,12,11,11,12,11,
  124699. };
  124700. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124701. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124702. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124703. 6.5, 7.5, 8.5, 9.5,
  124704. };
  124705. static long _vq_quantmap__16c1_s_p9_2[] = {
  124706. 19, 17, 15, 13, 11, 9, 7, 5,
  124707. 3, 1, 0, 2, 4, 6, 8, 10,
  124708. 12, 14, 16, 18, 20,
  124709. };
  124710. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124711. _vq_quantthresh__16c1_s_p9_2,
  124712. _vq_quantmap__16c1_s_p9_2,
  124713. 21,
  124714. 21
  124715. };
  124716. static static_codebook _16c1_s_p9_2 = {
  124717. 2, 441,
  124718. _vq_lengthlist__16c1_s_p9_2,
  124719. 1, -529268736, 1611661312, 5, 0,
  124720. _vq_quantlist__16c1_s_p9_2,
  124721. NULL,
  124722. &_vq_auxt__16c1_s_p9_2,
  124723. NULL,
  124724. 0
  124725. };
  124726. static long _huff_lengthlist__16c1_s_short[] = {
  124727. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124728. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124729. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124730. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124731. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124732. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124733. 9, 9,10,13,
  124734. };
  124735. static static_codebook _huff_book__16c1_s_short = {
  124736. 2, 100,
  124737. _huff_lengthlist__16c1_s_short,
  124738. 0, 0, 0, 0, 0,
  124739. NULL,
  124740. NULL,
  124741. NULL,
  124742. NULL,
  124743. 0
  124744. };
  124745. static long _huff_lengthlist__16c2_s_long[] = {
  124746. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124747. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124748. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124749. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124750. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124751. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124752. 14,14,16,18,
  124753. };
  124754. static static_codebook _huff_book__16c2_s_long = {
  124755. 2, 100,
  124756. _huff_lengthlist__16c2_s_long,
  124757. 0, 0, 0, 0, 0,
  124758. NULL,
  124759. NULL,
  124760. NULL,
  124761. NULL,
  124762. 0
  124763. };
  124764. static long _vq_quantlist__16c2_s_p1_0[] = {
  124765. 1,
  124766. 0,
  124767. 2,
  124768. };
  124769. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124770. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124771. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0,
  124776. };
  124777. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124778. -0.5, 0.5,
  124779. };
  124780. static long _vq_quantmap__16c2_s_p1_0[] = {
  124781. 1, 0, 2,
  124782. };
  124783. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124784. _vq_quantthresh__16c2_s_p1_0,
  124785. _vq_quantmap__16c2_s_p1_0,
  124786. 3,
  124787. 3
  124788. };
  124789. static static_codebook _16c2_s_p1_0 = {
  124790. 4, 81,
  124791. _vq_lengthlist__16c2_s_p1_0,
  124792. 1, -535822336, 1611661312, 2, 0,
  124793. _vq_quantlist__16c2_s_p1_0,
  124794. NULL,
  124795. &_vq_auxt__16c2_s_p1_0,
  124796. NULL,
  124797. 0
  124798. };
  124799. static long _vq_quantlist__16c2_s_p2_0[] = {
  124800. 2,
  124801. 1,
  124802. 3,
  124803. 0,
  124804. 4,
  124805. };
  124806. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124807. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124808. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124809. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124810. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124811. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124812. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124813. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124814. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124820. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124821. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124822. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124828. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124829. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124830. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124836. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124837. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124838. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124843. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124844. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124845. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124846. 13,
  124847. };
  124848. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124849. -1.5, -0.5, 0.5, 1.5,
  124850. };
  124851. static long _vq_quantmap__16c2_s_p2_0[] = {
  124852. 3, 1, 0, 2, 4,
  124853. };
  124854. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124855. _vq_quantthresh__16c2_s_p2_0,
  124856. _vq_quantmap__16c2_s_p2_0,
  124857. 5,
  124858. 5
  124859. };
  124860. static static_codebook _16c2_s_p2_0 = {
  124861. 4, 625,
  124862. _vq_lengthlist__16c2_s_p2_0,
  124863. 1, -533725184, 1611661312, 3, 0,
  124864. _vq_quantlist__16c2_s_p2_0,
  124865. NULL,
  124866. &_vq_auxt__16c2_s_p2_0,
  124867. NULL,
  124868. 0
  124869. };
  124870. static long _vq_quantlist__16c2_s_p3_0[] = {
  124871. 4,
  124872. 3,
  124873. 5,
  124874. 2,
  124875. 6,
  124876. 1,
  124877. 7,
  124878. 0,
  124879. 8,
  124880. };
  124881. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124882. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124883. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124884. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124885. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0,
  124888. };
  124889. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124890. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124891. };
  124892. static long _vq_quantmap__16c2_s_p3_0[] = {
  124893. 7, 5, 3, 1, 0, 2, 4, 6,
  124894. 8,
  124895. };
  124896. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124897. _vq_quantthresh__16c2_s_p3_0,
  124898. _vq_quantmap__16c2_s_p3_0,
  124899. 9,
  124900. 9
  124901. };
  124902. static static_codebook _16c2_s_p3_0 = {
  124903. 2, 81,
  124904. _vq_lengthlist__16c2_s_p3_0,
  124905. 1, -531628032, 1611661312, 4, 0,
  124906. _vq_quantlist__16c2_s_p3_0,
  124907. NULL,
  124908. &_vq_auxt__16c2_s_p3_0,
  124909. NULL,
  124910. 0
  124911. };
  124912. static long _vq_quantlist__16c2_s_p4_0[] = {
  124913. 8,
  124914. 7,
  124915. 9,
  124916. 6,
  124917. 10,
  124918. 5,
  124919. 11,
  124920. 4,
  124921. 12,
  124922. 3,
  124923. 13,
  124924. 2,
  124925. 14,
  124926. 1,
  124927. 15,
  124928. 0,
  124929. 16,
  124930. };
  124931. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124932. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124933. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124934. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124935. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124936. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124937. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124938. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124939. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124940. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124941. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0,
  124951. };
  124952. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124953. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124954. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124955. };
  124956. static long _vq_quantmap__16c2_s_p4_0[] = {
  124957. 15, 13, 11, 9, 7, 5, 3, 1,
  124958. 0, 2, 4, 6, 8, 10, 12, 14,
  124959. 16,
  124960. };
  124961. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124962. _vq_quantthresh__16c2_s_p4_0,
  124963. _vq_quantmap__16c2_s_p4_0,
  124964. 17,
  124965. 17
  124966. };
  124967. static static_codebook _16c2_s_p4_0 = {
  124968. 2, 289,
  124969. _vq_lengthlist__16c2_s_p4_0,
  124970. 1, -529530880, 1611661312, 5, 0,
  124971. _vq_quantlist__16c2_s_p4_0,
  124972. NULL,
  124973. &_vq_auxt__16c2_s_p4_0,
  124974. NULL,
  124975. 0
  124976. };
  124977. static long _vq_quantlist__16c2_s_p5_0[] = {
  124978. 1,
  124979. 0,
  124980. 2,
  124981. };
  124982. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124983. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124984. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124985. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124986. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124987. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124988. 12,
  124989. };
  124990. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124991. -5.5, 5.5,
  124992. };
  124993. static long _vq_quantmap__16c2_s_p5_0[] = {
  124994. 1, 0, 2,
  124995. };
  124996. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124997. _vq_quantthresh__16c2_s_p5_0,
  124998. _vq_quantmap__16c2_s_p5_0,
  124999. 3,
  125000. 3
  125001. };
  125002. static static_codebook _16c2_s_p5_0 = {
  125003. 4, 81,
  125004. _vq_lengthlist__16c2_s_p5_0,
  125005. 1, -529137664, 1618345984, 2, 0,
  125006. _vq_quantlist__16c2_s_p5_0,
  125007. NULL,
  125008. &_vq_auxt__16c2_s_p5_0,
  125009. NULL,
  125010. 0
  125011. };
  125012. static long _vq_quantlist__16c2_s_p5_1[] = {
  125013. 5,
  125014. 4,
  125015. 6,
  125016. 3,
  125017. 7,
  125018. 2,
  125019. 8,
  125020. 1,
  125021. 9,
  125022. 0,
  125023. 10,
  125024. };
  125025. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125026. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125027. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125028. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125029. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125030. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125031. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125032. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125033. 11,11,11, 7, 7, 8, 8, 8, 8,
  125034. };
  125035. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125036. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125037. 3.5, 4.5,
  125038. };
  125039. static long _vq_quantmap__16c2_s_p5_1[] = {
  125040. 9, 7, 5, 3, 1, 0, 2, 4,
  125041. 6, 8, 10,
  125042. };
  125043. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125044. _vq_quantthresh__16c2_s_p5_1,
  125045. _vq_quantmap__16c2_s_p5_1,
  125046. 11,
  125047. 11
  125048. };
  125049. static static_codebook _16c2_s_p5_1 = {
  125050. 2, 121,
  125051. _vq_lengthlist__16c2_s_p5_1,
  125052. 1, -531365888, 1611661312, 4, 0,
  125053. _vq_quantlist__16c2_s_p5_1,
  125054. NULL,
  125055. &_vq_auxt__16c2_s_p5_1,
  125056. NULL,
  125057. 0
  125058. };
  125059. static long _vq_quantlist__16c2_s_p6_0[] = {
  125060. 6,
  125061. 5,
  125062. 7,
  125063. 4,
  125064. 8,
  125065. 3,
  125066. 9,
  125067. 2,
  125068. 10,
  125069. 1,
  125070. 11,
  125071. 0,
  125072. 12,
  125073. };
  125074. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125075. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125076. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125077. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125078. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125079. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125080. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. };
  125087. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125088. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125089. 12.5, 17.5, 22.5, 27.5,
  125090. };
  125091. static long _vq_quantmap__16c2_s_p6_0[] = {
  125092. 11, 9, 7, 5, 3, 1, 0, 2,
  125093. 4, 6, 8, 10, 12,
  125094. };
  125095. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125096. _vq_quantthresh__16c2_s_p6_0,
  125097. _vq_quantmap__16c2_s_p6_0,
  125098. 13,
  125099. 13
  125100. };
  125101. static static_codebook _16c2_s_p6_0 = {
  125102. 2, 169,
  125103. _vq_lengthlist__16c2_s_p6_0,
  125104. 1, -526516224, 1616117760, 4, 0,
  125105. _vq_quantlist__16c2_s_p6_0,
  125106. NULL,
  125107. &_vq_auxt__16c2_s_p6_0,
  125108. NULL,
  125109. 0
  125110. };
  125111. static long _vq_quantlist__16c2_s_p6_1[] = {
  125112. 2,
  125113. 1,
  125114. 3,
  125115. 0,
  125116. 4,
  125117. };
  125118. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125119. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125120. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125121. };
  125122. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125123. -1.5, -0.5, 0.5, 1.5,
  125124. };
  125125. static long _vq_quantmap__16c2_s_p6_1[] = {
  125126. 3, 1, 0, 2, 4,
  125127. };
  125128. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125129. _vq_quantthresh__16c2_s_p6_1,
  125130. _vq_quantmap__16c2_s_p6_1,
  125131. 5,
  125132. 5
  125133. };
  125134. static static_codebook _16c2_s_p6_1 = {
  125135. 2, 25,
  125136. _vq_lengthlist__16c2_s_p6_1,
  125137. 1, -533725184, 1611661312, 3, 0,
  125138. _vq_quantlist__16c2_s_p6_1,
  125139. NULL,
  125140. &_vq_auxt__16c2_s_p6_1,
  125141. NULL,
  125142. 0
  125143. };
  125144. static long _vq_quantlist__16c2_s_p7_0[] = {
  125145. 6,
  125146. 5,
  125147. 7,
  125148. 4,
  125149. 8,
  125150. 3,
  125151. 9,
  125152. 2,
  125153. 10,
  125154. 1,
  125155. 11,
  125156. 0,
  125157. 12,
  125158. };
  125159. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125160. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125161. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125162. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125163. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125164. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125165. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125166. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125167. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125168. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125169. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125170. 18,13,14,13,13,14,13,15,14,
  125171. };
  125172. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125173. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125174. 27.5, 38.5, 49.5, 60.5,
  125175. };
  125176. static long _vq_quantmap__16c2_s_p7_0[] = {
  125177. 11, 9, 7, 5, 3, 1, 0, 2,
  125178. 4, 6, 8, 10, 12,
  125179. };
  125180. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125181. _vq_quantthresh__16c2_s_p7_0,
  125182. _vq_quantmap__16c2_s_p7_0,
  125183. 13,
  125184. 13
  125185. };
  125186. static static_codebook _16c2_s_p7_0 = {
  125187. 2, 169,
  125188. _vq_lengthlist__16c2_s_p7_0,
  125189. 1, -523206656, 1618345984, 4, 0,
  125190. _vq_quantlist__16c2_s_p7_0,
  125191. NULL,
  125192. &_vq_auxt__16c2_s_p7_0,
  125193. NULL,
  125194. 0
  125195. };
  125196. static long _vq_quantlist__16c2_s_p7_1[] = {
  125197. 5,
  125198. 4,
  125199. 6,
  125200. 3,
  125201. 7,
  125202. 2,
  125203. 8,
  125204. 1,
  125205. 9,
  125206. 0,
  125207. 10,
  125208. };
  125209. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125210. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125211. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125212. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125213. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125214. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125215. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125216. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125217. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125218. };
  125219. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125220. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125221. 3.5, 4.5,
  125222. };
  125223. static long _vq_quantmap__16c2_s_p7_1[] = {
  125224. 9, 7, 5, 3, 1, 0, 2, 4,
  125225. 6, 8, 10,
  125226. };
  125227. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125228. _vq_quantthresh__16c2_s_p7_1,
  125229. _vq_quantmap__16c2_s_p7_1,
  125230. 11,
  125231. 11
  125232. };
  125233. static static_codebook _16c2_s_p7_1 = {
  125234. 2, 121,
  125235. _vq_lengthlist__16c2_s_p7_1,
  125236. 1, -531365888, 1611661312, 4, 0,
  125237. _vq_quantlist__16c2_s_p7_1,
  125238. NULL,
  125239. &_vq_auxt__16c2_s_p7_1,
  125240. NULL,
  125241. 0
  125242. };
  125243. static long _vq_quantlist__16c2_s_p8_0[] = {
  125244. 7,
  125245. 6,
  125246. 8,
  125247. 5,
  125248. 9,
  125249. 4,
  125250. 10,
  125251. 3,
  125252. 11,
  125253. 2,
  125254. 12,
  125255. 1,
  125256. 13,
  125257. 0,
  125258. 14,
  125259. };
  125260. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125261. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125262. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125263. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125264. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125265. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125266. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125267. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125268. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125269. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125270. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125271. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125272. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125273. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125274. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125275. 13,
  125276. };
  125277. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125278. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125279. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125280. };
  125281. static long _vq_quantmap__16c2_s_p8_0[] = {
  125282. 13, 11, 9, 7, 5, 3, 1, 0,
  125283. 2, 4, 6, 8, 10, 12, 14,
  125284. };
  125285. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125286. _vq_quantthresh__16c2_s_p8_0,
  125287. _vq_quantmap__16c2_s_p8_0,
  125288. 15,
  125289. 15
  125290. };
  125291. static static_codebook _16c2_s_p8_0 = {
  125292. 2, 225,
  125293. _vq_lengthlist__16c2_s_p8_0,
  125294. 1, -520986624, 1620377600, 4, 0,
  125295. _vq_quantlist__16c2_s_p8_0,
  125296. NULL,
  125297. &_vq_auxt__16c2_s_p8_0,
  125298. NULL,
  125299. 0
  125300. };
  125301. static long _vq_quantlist__16c2_s_p8_1[] = {
  125302. 10,
  125303. 9,
  125304. 11,
  125305. 8,
  125306. 12,
  125307. 7,
  125308. 13,
  125309. 6,
  125310. 14,
  125311. 5,
  125312. 15,
  125313. 4,
  125314. 16,
  125315. 3,
  125316. 17,
  125317. 2,
  125318. 18,
  125319. 1,
  125320. 19,
  125321. 0,
  125322. 20,
  125323. };
  125324. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125325. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125326. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125327. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125328. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125329. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125330. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125331. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125332. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125333. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125334. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125335. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125336. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125337. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125338. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125339. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125340. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125341. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125342. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125343. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125344. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125345. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125346. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125347. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125348. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125349. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125350. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125351. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125352. 10,11,10,10,10,10,10,10,10,
  125353. };
  125354. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125355. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125356. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125357. 6.5, 7.5, 8.5, 9.5,
  125358. };
  125359. static long _vq_quantmap__16c2_s_p8_1[] = {
  125360. 19, 17, 15, 13, 11, 9, 7, 5,
  125361. 3, 1, 0, 2, 4, 6, 8, 10,
  125362. 12, 14, 16, 18, 20,
  125363. };
  125364. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125365. _vq_quantthresh__16c2_s_p8_1,
  125366. _vq_quantmap__16c2_s_p8_1,
  125367. 21,
  125368. 21
  125369. };
  125370. static static_codebook _16c2_s_p8_1 = {
  125371. 2, 441,
  125372. _vq_lengthlist__16c2_s_p8_1,
  125373. 1, -529268736, 1611661312, 5, 0,
  125374. _vq_quantlist__16c2_s_p8_1,
  125375. NULL,
  125376. &_vq_auxt__16c2_s_p8_1,
  125377. NULL,
  125378. 0
  125379. };
  125380. static long _vq_quantlist__16c2_s_p9_0[] = {
  125381. 6,
  125382. 5,
  125383. 7,
  125384. 4,
  125385. 8,
  125386. 3,
  125387. 9,
  125388. 2,
  125389. 10,
  125390. 1,
  125391. 11,
  125392. 0,
  125393. 12,
  125394. };
  125395. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125396. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125397. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125398. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125399. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125400. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125401. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125402. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125403. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125404. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125405. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125406. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125407. };
  125408. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125409. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125410. 2327.5, 3258.5, 4189.5, 5120.5,
  125411. };
  125412. static long _vq_quantmap__16c2_s_p9_0[] = {
  125413. 11, 9, 7, 5, 3, 1, 0, 2,
  125414. 4, 6, 8, 10, 12,
  125415. };
  125416. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125417. _vq_quantthresh__16c2_s_p9_0,
  125418. _vq_quantmap__16c2_s_p9_0,
  125419. 13,
  125420. 13
  125421. };
  125422. static static_codebook _16c2_s_p9_0 = {
  125423. 2, 169,
  125424. _vq_lengthlist__16c2_s_p9_0,
  125425. 1, -510275072, 1631393792, 4, 0,
  125426. _vq_quantlist__16c2_s_p9_0,
  125427. NULL,
  125428. &_vq_auxt__16c2_s_p9_0,
  125429. NULL,
  125430. 0
  125431. };
  125432. static long _vq_quantlist__16c2_s_p9_1[] = {
  125433. 8,
  125434. 7,
  125435. 9,
  125436. 6,
  125437. 10,
  125438. 5,
  125439. 11,
  125440. 4,
  125441. 12,
  125442. 3,
  125443. 13,
  125444. 2,
  125445. 14,
  125446. 1,
  125447. 15,
  125448. 0,
  125449. 16,
  125450. };
  125451. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125452. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125453. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125454. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125455. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125456. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125457. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125458. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125459. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125460. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125461. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125462. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125463. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125464. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125465. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125466. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125467. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125468. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125469. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125470. 10,
  125471. };
  125472. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125473. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125474. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125475. };
  125476. static long _vq_quantmap__16c2_s_p9_1[] = {
  125477. 15, 13, 11, 9, 7, 5, 3, 1,
  125478. 0, 2, 4, 6, 8, 10, 12, 14,
  125479. 16,
  125480. };
  125481. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125482. _vq_quantthresh__16c2_s_p9_1,
  125483. _vq_quantmap__16c2_s_p9_1,
  125484. 17,
  125485. 17
  125486. };
  125487. static static_codebook _16c2_s_p9_1 = {
  125488. 2, 289,
  125489. _vq_lengthlist__16c2_s_p9_1,
  125490. 1, -518488064, 1622704128, 5, 0,
  125491. _vq_quantlist__16c2_s_p9_1,
  125492. NULL,
  125493. &_vq_auxt__16c2_s_p9_1,
  125494. NULL,
  125495. 0
  125496. };
  125497. static long _vq_quantlist__16c2_s_p9_2[] = {
  125498. 13,
  125499. 12,
  125500. 14,
  125501. 11,
  125502. 15,
  125503. 10,
  125504. 16,
  125505. 9,
  125506. 17,
  125507. 8,
  125508. 18,
  125509. 7,
  125510. 19,
  125511. 6,
  125512. 20,
  125513. 5,
  125514. 21,
  125515. 4,
  125516. 22,
  125517. 3,
  125518. 23,
  125519. 2,
  125520. 24,
  125521. 1,
  125522. 25,
  125523. 0,
  125524. 26,
  125525. };
  125526. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125527. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125528. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125529. };
  125530. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125531. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125532. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125533. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125534. 11.5, 12.5,
  125535. };
  125536. static long _vq_quantmap__16c2_s_p9_2[] = {
  125537. 25, 23, 21, 19, 17, 15, 13, 11,
  125538. 9, 7, 5, 3, 1, 0, 2, 4,
  125539. 6, 8, 10, 12, 14, 16, 18, 20,
  125540. 22, 24, 26,
  125541. };
  125542. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125543. _vq_quantthresh__16c2_s_p9_2,
  125544. _vq_quantmap__16c2_s_p9_2,
  125545. 27,
  125546. 27
  125547. };
  125548. static static_codebook _16c2_s_p9_2 = {
  125549. 1, 27,
  125550. _vq_lengthlist__16c2_s_p9_2,
  125551. 1, -528875520, 1611661312, 5, 0,
  125552. _vq_quantlist__16c2_s_p9_2,
  125553. NULL,
  125554. &_vq_auxt__16c2_s_p9_2,
  125555. NULL,
  125556. 0
  125557. };
  125558. static long _huff_lengthlist__16c2_s_short[] = {
  125559. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125560. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125561. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125562. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125563. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125564. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125565. 15,12,14,14,
  125566. };
  125567. static static_codebook _huff_book__16c2_s_short = {
  125568. 2, 100,
  125569. _huff_lengthlist__16c2_s_short,
  125570. 0, 0, 0, 0, 0,
  125571. NULL,
  125572. NULL,
  125573. NULL,
  125574. NULL,
  125575. 0
  125576. };
  125577. static long _vq_quantlist__8c0_s_p1_0[] = {
  125578. 1,
  125579. 0,
  125580. 2,
  125581. };
  125582. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125583. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125584. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125589. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125594. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125629. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125634. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125639. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125675. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125680. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125685. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0,
  125994. };
  125995. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125996. -0.5, 0.5,
  125997. };
  125998. static long _vq_quantmap__8c0_s_p1_0[] = {
  125999. 1, 0, 2,
  126000. };
  126001. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126002. _vq_quantthresh__8c0_s_p1_0,
  126003. _vq_quantmap__8c0_s_p1_0,
  126004. 3,
  126005. 3
  126006. };
  126007. static static_codebook _8c0_s_p1_0 = {
  126008. 8, 6561,
  126009. _vq_lengthlist__8c0_s_p1_0,
  126010. 1, -535822336, 1611661312, 2, 0,
  126011. _vq_quantlist__8c0_s_p1_0,
  126012. NULL,
  126013. &_vq_auxt__8c0_s_p1_0,
  126014. NULL,
  126015. 0
  126016. };
  126017. static long _vq_quantlist__8c0_s_p2_0[] = {
  126018. 2,
  126019. 1,
  126020. 3,
  126021. 0,
  126022. 4,
  126023. };
  126024. static long _vq_lengthlist__8c0_s_p2_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,
  126065. };
  126066. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126067. -1.5, -0.5, 0.5, 1.5,
  126068. };
  126069. static long _vq_quantmap__8c0_s_p2_0[] = {
  126070. 3, 1, 0, 2, 4,
  126071. };
  126072. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126073. _vq_quantthresh__8c0_s_p2_0,
  126074. _vq_quantmap__8c0_s_p2_0,
  126075. 5,
  126076. 5
  126077. };
  126078. static static_codebook _8c0_s_p2_0 = {
  126079. 4, 625,
  126080. _vq_lengthlist__8c0_s_p2_0,
  126081. 1, -533725184, 1611661312, 3, 0,
  126082. _vq_quantlist__8c0_s_p2_0,
  126083. NULL,
  126084. &_vq_auxt__8c0_s_p2_0,
  126085. NULL,
  126086. 0
  126087. };
  126088. static long _vq_quantlist__8c0_s_p3_0[] = {
  126089. 2,
  126090. 1,
  126091. 3,
  126092. 0,
  126093. 4,
  126094. };
  126095. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126096. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  126136. };
  126137. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126138. -1.5, -0.5, 0.5, 1.5,
  126139. };
  126140. static long _vq_quantmap__8c0_s_p3_0[] = {
  126141. 3, 1, 0, 2, 4,
  126142. };
  126143. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126144. _vq_quantthresh__8c0_s_p3_0,
  126145. _vq_quantmap__8c0_s_p3_0,
  126146. 5,
  126147. 5
  126148. };
  126149. static static_codebook _8c0_s_p3_0 = {
  126150. 4, 625,
  126151. _vq_lengthlist__8c0_s_p3_0,
  126152. 1, -533725184, 1611661312, 3, 0,
  126153. _vq_quantlist__8c0_s_p3_0,
  126154. NULL,
  126155. &_vq_auxt__8c0_s_p3_0,
  126156. NULL,
  126157. 0
  126158. };
  126159. static long _vq_quantlist__8c0_s_p4_0[] = {
  126160. 4,
  126161. 3,
  126162. 5,
  126163. 2,
  126164. 6,
  126165. 1,
  126166. 7,
  126167. 0,
  126168. 8,
  126169. };
  126170. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126171. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126172. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126173. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126174. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126175. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0,
  126177. };
  126178. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126179. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126180. };
  126181. static long _vq_quantmap__8c0_s_p4_0[] = {
  126182. 7, 5, 3, 1, 0, 2, 4, 6,
  126183. 8,
  126184. };
  126185. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126186. _vq_quantthresh__8c0_s_p4_0,
  126187. _vq_quantmap__8c0_s_p4_0,
  126188. 9,
  126189. 9
  126190. };
  126191. static static_codebook _8c0_s_p4_0 = {
  126192. 2, 81,
  126193. _vq_lengthlist__8c0_s_p4_0,
  126194. 1, -531628032, 1611661312, 4, 0,
  126195. _vq_quantlist__8c0_s_p4_0,
  126196. NULL,
  126197. &_vq_auxt__8c0_s_p4_0,
  126198. NULL,
  126199. 0
  126200. };
  126201. static long _vq_quantlist__8c0_s_p5_0[] = {
  126202. 4,
  126203. 3,
  126204. 5,
  126205. 2,
  126206. 6,
  126207. 1,
  126208. 7,
  126209. 0,
  126210. 8,
  126211. };
  126212. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126213. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126214. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126215. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126216. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126217. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126218. 10,
  126219. };
  126220. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126221. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126222. };
  126223. static long _vq_quantmap__8c0_s_p5_0[] = {
  126224. 7, 5, 3, 1, 0, 2, 4, 6,
  126225. 8,
  126226. };
  126227. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126228. _vq_quantthresh__8c0_s_p5_0,
  126229. _vq_quantmap__8c0_s_p5_0,
  126230. 9,
  126231. 9
  126232. };
  126233. static static_codebook _8c0_s_p5_0 = {
  126234. 2, 81,
  126235. _vq_lengthlist__8c0_s_p5_0,
  126236. 1, -531628032, 1611661312, 4, 0,
  126237. _vq_quantlist__8c0_s_p5_0,
  126238. NULL,
  126239. &_vq_auxt__8c0_s_p5_0,
  126240. NULL,
  126241. 0
  126242. };
  126243. static long _vq_quantlist__8c0_s_p6_0[] = {
  126244. 8,
  126245. 7,
  126246. 9,
  126247. 6,
  126248. 10,
  126249. 5,
  126250. 11,
  126251. 4,
  126252. 12,
  126253. 3,
  126254. 13,
  126255. 2,
  126256. 14,
  126257. 1,
  126258. 15,
  126259. 0,
  126260. 16,
  126261. };
  126262. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126263. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126264. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126265. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126266. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126267. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126268. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126269. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126270. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126271. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126272. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126273. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126274. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126275. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126276. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126277. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126278. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126279. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126281. 14,
  126282. };
  126283. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126284. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126285. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126286. };
  126287. static long _vq_quantmap__8c0_s_p6_0[] = {
  126288. 15, 13, 11, 9, 7, 5, 3, 1,
  126289. 0, 2, 4, 6, 8, 10, 12, 14,
  126290. 16,
  126291. };
  126292. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126293. _vq_quantthresh__8c0_s_p6_0,
  126294. _vq_quantmap__8c0_s_p6_0,
  126295. 17,
  126296. 17
  126297. };
  126298. static static_codebook _8c0_s_p6_0 = {
  126299. 2, 289,
  126300. _vq_lengthlist__8c0_s_p6_0,
  126301. 1, -529530880, 1611661312, 5, 0,
  126302. _vq_quantlist__8c0_s_p6_0,
  126303. NULL,
  126304. &_vq_auxt__8c0_s_p6_0,
  126305. NULL,
  126306. 0
  126307. };
  126308. static long _vq_quantlist__8c0_s_p7_0[] = {
  126309. 1,
  126310. 0,
  126311. 2,
  126312. };
  126313. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126314. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126315. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126316. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126317. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126318. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126319. 10,
  126320. };
  126321. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126322. -5.5, 5.5,
  126323. };
  126324. static long _vq_quantmap__8c0_s_p7_0[] = {
  126325. 1, 0, 2,
  126326. };
  126327. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126328. _vq_quantthresh__8c0_s_p7_0,
  126329. _vq_quantmap__8c0_s_p7_0,
  126330. 3,
  126331. 3
  126332. };
  126333. static static_codebook _8c0_s_p7_0 = {
  126334. 4, 81,
  126335. _vq_lengthlist__8c0_s_p7_0,
  126336. 1, -529137664, 1618345984, 2, 0,
  126337. _vq_quantlist__8c0_s_p7_0,
  126338. NULL,
  126339. &_vq_auxt__8c0_s_p7_0,
  126340. NULL,
  126341. 0
  126342. };
  126343. static long _vq_quantlist__8c0_s_p7_1[] = {
  126344. 5,
  126345. 4,
  126346. 6,
  126347. 3,
  126348. 7,
  126349. 2,
  126350. 8,
  126351. 1,
  126352. 9,
  126353. 0,
  126354. 10,
  126355. };
  126356. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126357. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126358. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126359. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126360. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126361. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126362. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126363. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126364. 10,10,10, 9, 9, 9,10,10,10,
  126365. };
  126366. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126367. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126368. 3.5, 4.5,
  126369. };
  126370. static long _vq_quantmap__8c0_s_p7_1[] = {
  126371. 9, 7, 5, 3, 1, 0, 2, 4,
  126372. 6, 8, 10,
  126373. };
  126374. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126375. _vq_quantthresh__8c0_s_p7_1,
  126376. _vq_quantmap__8c0_s_p7_1,
  126377. 11,
  126378. 11
  126379. };
  126380. static static_codebook _8c0_s_p7_1 = {
  126381. 2, 121,
  126382. _vq_lengthlist__8c0_s_p7_1,
  126383. 1, -531365888, 1611661312, 4, 0,
  126384. _vq_quantlist__8c0_s_p7_1,
  126385. NULL,
  126386. &_vq_auxt__8c0_s_p7_1,
  126387. NULL,
  126388. 0
  126389. };
  126390. static long _vq_quantlist__8c0_s_p8_0[] = {
  126391. 6,
  126392. 5,
  126393. 7,
  126394. 4,
  126395. 8,
  126396. 3,
  126397. 9,
  126398. 2,
  126399. 10,
  126400. 1,
  126401. 11,
  126402. 0,
  126403. 12,
  126404. };
  126405. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126406. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126407. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126408. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126409. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126410. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126411. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126412. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126413. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126414. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126415. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126416. 0, 0,13,13,11,13,13,11,12,
  126417. };
  126418. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126419. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126420. 12.5, 17.5, 22.5, 27.5,
  126421. };
  126422. static long _vq_quantmap__8c0_s_p8_0[] = {
  126423. 11, 9, 7, 5, 3, 1, 0, 2,
  126424. 4, 6, 8, 10, 12,
  126425. };
  126426. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126427. _vq_quantthresh__8c0_s_p8_0,
  126428. _vq_quantmap__8c0_s_p8_0,
  126429. 13,
  126430. 13
  126431. };
  126432. static static_codebook _8c0_s_p8_0 = {
  126433. 2, 169,
  126434. _vq_lengthlist__8c0_s_p8_0,
  126435. 1, -526516224, 1616117760, 4, 0,
  126436. _vq_quantlist__8c0_s_p8_0,
  126437. NULL,
  126438. &_vq_auxt__8c0_s_p8_0,
  126439. NULL,
  126440. 0
  126441. };
  126442. static long _vq_quantlist__8c0_s_p8_1[] = {
  126443. 2,
  126444. 1,
  126445. 3,
  126446. 0,
  126447. 4,
  126448. };
  126449. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126450. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126451. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126452. };
  126453. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126454. -1.5, -0.5, 0.5, 1.5,
  126455. };
  126456. static long _vq_quantmap__8c0_s_p8_1[] = {
  126457. 3, 1, 0, 2, 4,
  126458. };
  126459. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126460. _vq_quantthresh__8c0_s_p8_1,
  126461. _vq_quantmap__8c0_s_p8_1,
  126462. 5,
  126463. 5
  126464. };
  126465. static static_codebook _8c0_s_p8_1 = {
  126466. 2, 25,
  126467. _vq_lengthlist__8c0_s_p8_1,
  126468. 1, -533725184, 1611661312, 3, 0,
  126469. _vq_quantlist__8c0_s_p8_1,
  126470. NULL,
  126471. &_vq_auxt__8c0_s_p8_1,
  126472. NULL,
  126473. 0
  126474. };
  126475. static long _vq_quantlist__8c0_s_p9_0[] = {
  126476. 1,
  126477. 0,
  126478. 2,
  126479. };
  126480. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126481. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126482. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126483. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126484. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126485. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126486. 7,
  126487. };
  126488. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126489. -157.5, 157.5,
  126490. };
  126491. static long _vq_quantmap__8c0_s_p9_0[] = {
  126492. 1, 0, 2,
  126493. };
  126494. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126495. _vq_quantthresh__8c0_s_p9_0,
  126496. _vq_quantmap__8c0_s_p9_0,
  126497. 3,
  126498. 3
  126499. };
  126500. static static_codebook _8c0_s_p9_0 = {
  126501. 4, 81,
  126502. _vq_lengthlist__8c0_s_p9_0,
  126503. 1, -518803456, 1628680192, 2, 0,
  126504. _vq_quantlist__8c0_s_p9_0,
  126505. NULL,
  126506. &_vq_auxt__8c0_s_p9_0,
  126507. NULL,
  126508. 0
  126509. };
  126510. static long _vq_quantlist__8c0_s_p9_1[] = {
  126511. 7,
  126512. 6,
  126513. 8,
  126514. 5,
  126515. 9,
  126516. 4,
  126517. 10,
  126518. 3,
  126519. 11,
  126520. 2,
  126521. 12,
  126522. 1,
  126523. 13,
  126524. 0,
  126525. 14,
  126526. };
  126527. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126528. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126529. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126530. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126531. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126532. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126533. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126542. 11,
  126543. };
  126544. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126545. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126546. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126547. };
  126548. static long _vq_quantmap__8c0_s_p9_1[] = {
  126549. 13, 11, 9, 7, 5, 3, 1, 0,
  126550. 2, 4, 6, 8, 10, 12, 14,
  126551. };
  126552. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126553. _vq_quantthresh__8c0_s_p9_1,
  126554. _vq_quantmap__8c0_s_p9_1,
  126555. 15,
  126556. 15
  126557. };
  126558. static static_codebook _8c0_s_p9_1 = {
  126559. 2, 225,
  126560. _vq_lengthlist__8c0_s_p9_1,
  126561. 1, -520986624, 1620377600, 4, 0,
  126562. _vq_quantlist__8c0_s_p9_1,
  126563. NULL,
  126564. &_vq_auxt__8c0_s_p9_1,
  126565. NULL,
  126566. 0
  126567. };
  126568. static long _vq_quantlist__8c0_s_p9_2[] = {
  126569. 10,
  126570. 9,
  126571. 11,
  126572. 8,
  126573. 12,
  126574. 7,
  126575. 13,
  126576. 6,
  126577. 14,
  126578. 5,
  126579. 15,
  126580. 4,
  126581. 16,
  126582. 3,
  126583. 17,
  126584. 2,
  126585. 18,
  126586. 1,
  126587. 19,
  126588. 0,
  126589. 20,
  126590. };
  126591. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126592. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126593. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126594. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126595. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126596. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126597. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126598. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126599. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126600. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126601. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126602. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126603. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126604. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126605. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126606. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126607. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126608. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126609. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126610. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126611. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126612. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126613. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126614. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126615. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126616. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126617. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126618. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126619. 10,11, 9,11,10, 9,10, 9,10,
  126620. };
  126621. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126622. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126623. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126624. 6.5, 7.5, 8.5, 9.5,
  126625. };
  126626. static long _vq_quantmap__8c0_s_p9_2[] = {
  126627. 19, 17, 15, 13, 11, 9, 7, 5,
  126628. 3, 1, 0, 2, 4, 6, 8, 10,
  126629. 12, 14, 16, 18, 20,
  126630. };
  126631. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126632. _vq_quantthresh__8c0_s_p9_2,
  126633. _vq_quantmap__8c0_s_p9_2,
  126634. 21,
  126635. 21
  126636. };
  126637. static static_codebook _8c0_s_p9_2 = {
  126638. 2, 441,
  126639. _vq_lengthlist__8c0_s_p9_2,
  126640. 1, -529268736, 1611661312, 5, 0,
  126641. _vq_quantlist__8c0_s_p9_2,
  126642. NULL,
  126643. &_vq_auxt__8c0_s_p9_2,
  126644. NULL,
  126645. 0
  126646. };
  126647. static long _huff_lengthlist__8c0_s_single[] = {
  126648. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126649. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126650. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126651. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126652. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126653. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126654. 17,16,17,17,
  126655. };
  126656. static static_codebook _huff_book__8c0_s_single = {
  126657. 2, 100,
  126658. _huff_lengthlist__8c0_s_single,
  126659. 0, 0, 0, 0, 0,
  126660. NULL,
  126661. NULL,
  126662. NULL,
  126663. NULL,
  126664. 0
  126665. };
  126666. static long _vq_quantlist__8c1_s_p1_0[] = {
  126667. 1,
  126668. 0,
  126669. 2,
  126670. };
  126671. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126672. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126673. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126678. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126683. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126718. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126723. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126728. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126764. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126769. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126774. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0,
  127083. };
  127084. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127085. -0.5, 0.5,
  127086. };
  127087. static long _vq_quantmap__8c1_s_p1_0[] = {
  127088. 1, 0, 2,
  127089. };
  127090. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127091. _vq_quantthresh__8c1_s_p1_0,
  127092. _vq_quantmap__8c1_s_p1_0,
  127093. 3,
  127094. 3
  127095. };
  127096. static static_codebook _8c1_s_p1_0 = {
  127097. 8, 6561,
  127098. _vq_lengthlist__8c1_s_p1_0,
  127099. 1, -535822336, 1611661312, 2, 0,
  127100. _vq_quantlist__8c1_s_p1_0,
  127101. NULL,
  127102. &_vq_auxt__8c1_s_p1_0,
  127103. NULL,
  127104. 0
  127105. };
  127106. static long _vq_quantlist__8c1_s_p2_0[] = {
  127107. 2,
  127108. 1,
  127109. 3,
  127110. 0,
  127111. 4,
  127112. };
  127113. static long _vq_lengthlist__8c1_s_p2_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,
  127154. };
  127155. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127156. -1.5, -0.5, 0.5, 1.5,
  127157. };
  127158. static long _vq_quantmap__8c1_s_p2_0[] = {
  127159. 3, 1, 0, 2, 4,
  127160. };
  127161. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127162. _vq_quantthresh__8c1_s_p2_0,
  127163. _vq_quantmap__8c1_s_p2_0,
  127164. 5,
  127165. 5
  127166. };
  127167. static static_codebook _8c1_s_p2_0 = {
  127168. 4, 625,
  127169. _vq_lengthlist__8c1_s_p2_0,
  127170. 1, -533725184, 1611661312, 3, 0,
  127171. _vq_quantlist__8c1_s_p2_0,
  127172. NULL,
  127173. &_vq_auxt__8c1_s_p2_0,
  127174. NULL,
  127175. 0
  127176. };
  127177. static long _vq_quantlist__8c1_s_p3_0[] = {
  127178. 2,
  127179. 1,
  127180. 3,
  127181. 0,
  127182. 4,
  127183. };
  127184. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127185. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  127225. };
  127226. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127227. -1.5, -0.5, 0.5, 1.5,
  127228. };
  127229. static long _vq_quantmap__8c1_s_p3_0[] = {
  127230. 3, 1, 0, 2, 4,
  127231. };
  127232. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127233. _vq_quantthresh__8c1_s_p3_0,
  127234. _vq_quantmap__8c1_s_p3_0,
  127235. 5,
  127236. 5
  127237. };
  127238. static static_codebook _8c1_s_p3_0 = {
  127239. 4, 625,
  127240. _vq_lengthlist__8c1_s_p3_0,
  127241. 1, -533725184, 1611661312, 3, 0,
  127242. _vq_quantlist__8c1_s_p3_0,
  127243. NULL,
  127244. &_vq_auxt__8c1_s_p3_0,
  127245. NULL,
  127246. 0
  127247. };
  127248. static long _vq_quantlist__8c1_s_p4_0[] = {
  127249. 4,
  127250. 3,
  127251. 5,
  127252. 2,
  127253. 6,
  127254. 1,
  127255. 7,
  127256. 0,
  127257. 8,
  127258. };
  127259. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127260. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127261. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127262. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127263. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127264. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0,
  127266. };
  127267. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127268. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127269. };
  127270. static long _vq_quantmap__8c1_s_p4_0[] = {
  127271. 7, 5, 3, 1, 0, 2, 4, 6,
  127272. 8,
  127273. };
  127274. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127275. _vq_quantthresh__8c1_s_p4_0,
  127276. _vq_quantmap__8c1_s_p4_0,
  127277. 9,
  127278. 9
  127279. };
  127280. static static_codebook _8c1_s_p4_0 = {
  127281. 2, 81,
  127282. _vq_lengthlist__8c1_s_p4_0,
  127283. 1, -531628032, 1611661312, 4, 0,
  127284. _vq_quantlist__8c1_s_p4_0,
  127285. NULL,
  127286. &_vq_auxt__8c1_s_p4_0,
  127287. NULL,
  127288. 0
  127289. };
  127290. static long _vq_quantlist__8c1_s_p5_0[] = {
  127291. 4,
  127292. 3,
  127293. 5,
  127294. 2,
  127295. 6,
  127296. 1,
  127297. 7,
  127298. 0,
  127299. 8,
  127300. };
  127301. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127302. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127303. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127304. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127305. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127306. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127307. 10,
  127308. };
  127309. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127310. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127311. };
  127312. static long _vq_quantmap__8c1_s_p5_0[] = {
  127313. 7, 5, 3, 1, 0, 2, 4, 6,
  127314. 8,
  127315. };
  127316. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127317. _vq_quantthresh__8c1_s_p5_0,
  127318. _vq_quantmap__8c1_s_p5_0,
  127319. 9,
  127320. 9
  127321. };
  127322. static static_codebook _8c1_s_p5_0 = {
  127323. 2, 81,
  127324. _vq_lengthlist__8c1_s_p5_0,
  127325. 1, -531628032, 1611661312, 4, 0,
  127326. _vq_quantlist__8c1_s_p5_0,
  127327. NULL,
  127328. &_vq_auxt__8c1_s_p5_0,
  127329. NULL,
  127330. 0
  127331. };
  127332. static long _vq_quantlist__8c1_s_p6_0[] = {
  127333. 8,
  127334. 7,
  127335. 9,
  127336. 6,
  127337. 10,
  127338. 5,
  127339. 11,
  127340. 4,
  127341. 12,
  127342. 3,
  127343. 13,
  127344. 2,
  127345. 14,
  127346. 1,
  127347. 15,
  127348. 0,
  127349. 16,
  127350. };
  127351. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127352. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127353. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127354. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127355. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127356. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127357. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127358. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127359. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127360. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127361. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127362. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127363. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127364. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127365. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127366. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127367. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127368. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127370. 14,
  127371. };
  127372. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127373. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127374. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127375. };
  127376. static long _vq_quantmap__8c1_s_p6_0[] = {
  127377. 15, 13, 11, 9, 7, 5, 3, 1,
  127378. 0, 2, 4, 6, 8, 10, 12, 14,
  127379. 16,
  127380. };
  127381. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127382. _vq_quantthresh__8c1_s_p6_0,
  127383. _vq_quantmap__8c1_s_p6_0,
  127384. 17,
  127385. 17
  127386. };
  127387. static static_codebook _8c1_s_p6_0 = {
  127388. 2, 289,
  127389. _vq_lengthlist__8c1_s_p6_0,
  127390. 1, -529530880, 1611661312, 5, 0,
  127391. _vq_quantlist__8c1_s_p6_0,
  127392. NULL,
  127393. &_vq_auxt__8c1_s_p6_0,
  127394. NULL,
  127395. 0
  127396. };
  127397. static long _vq_quantlist__8c1_s_p7_0[] = {
  127398. 1,
  127399. 0,
  127400. 2,
  127401. };
  127402. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127403. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127404. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127405. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127406. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127407. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127408. 9,
  127409. };
  127410. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127411. -5.5, 5.5,
  127412. };
  127413. static long _vq_quantmap__8c1_s_p7_0[] = {
  127414. 1, 0, 2,
  127415. };
  127416. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127417. _vq_quantthresh__8c1_s_p7_0,
  127418. _vq_quantmap__8c1_s_p7_0,
  127419. 3,
  127420. 3
  127421. };
  127422. static static_codebook _8c1_s_p7_0 = {
  127423. 4, 81,
  127424. _vq_lengthlist__8c1_s_p7_0,
  127425. 1, -529137664, 1618345984, 2, 0,
  127426. _vq_quantlist__8c1_s_p7_0,
  127427. NULL,
  127428. &_vq_auxt__8c1_s_p7_0,
  127429. NULL,
  127430. 0
  127431. };
  127432. static long _vq_quantlist__8c1_s_p7_1[] = {
  127433. 5,
  127434. 4,
  127435. 6,
  127436. 3,
  127437. 7,
  127438. 2,
  127439. 8,
  127440. 1,
  127441. 9,
  127442. 0,
  127443. 10,
  127444. };
  127445. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127446. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127447. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127448. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127449. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127450. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127451. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127452. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127453. 10,10,10, 8, 8, 8, 8, 8, 8,
  127454. };
  127455. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127456. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127457. 3.5, 4.5,
  127458. };
  127459. static long _vq_quantmap__8c1_s_p7_1[] = {
  127460. 9, 7, 5, 3, 1, 0, 2, 4,
  127461. 6, 8, 10,
  127462. };
  127463. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127464. _vq_quantthresh__8c1_s_p7_1,
  127465. _vq_quantmap__8c1_s_p7_1,
  127466. 11,
  127467. 11
  127468. };
  127469. static static_codebook _8c1_s_p7_1 = {
  127470. 2, 121,
  127471. _vq_lengthlist__8c1_s_p7_1,
  127472. 1, -531365888, 1611661312, 4, 0,
  127473. _vq_quantlist__8c1_s_p7_1,
  127474. NULL,
  127475. &_vq_auxt__8c1_s_p7_1,
  127476. NULL,
  127477. 0
  127478. };
  127479. static long _vq_quantlist__8c1_s_p8_0[] = {
  127480. 6,
  127481. 5,
  127482. 7,
  127483. 4,
  127484. 8,
  127485. 3,
  127486. 9,
  127487. 2,
  127488. 10,
  127489. 1,
  127490. 11,
  127491. 0,
  127492. 12,
  127493. };
  127494. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127495. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127496. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127497. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127498. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127499. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127500. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127501. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127502. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127503. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127504. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127505. 0,12,12,11,10,12,11,13,12,
  127506. };
  127507. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127508. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127509. 12.5, 17.5, 22.5, 27.5,
  127510. };
  127511. static long _vq_quantmap__8c1_s_p8_0[] = {
  127512. 11, 9, 7, 5, 3, 1, 0, 2,
  127513. 4, 6, 8, 10, 12,
  127514. };
  127515. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127516. _vq_quantthresh__8c1_s_p8_0,
  127517. _vq_quantmap__8c1_s_p8_0,
  127518. 13,
  127519. 13
  127520. };
  127521. static static_codebook _8c1_s_p8_0 = {
  127522. 2, 169,
  127523. _vq_lengthlist__8c1_s_p8_0,
  127524. 1, -526516224, 1616117760, 4, 0,
  127525. _vq_quantlist__8c1_s_p8_0,
  127526. NULL,
  127527. &_vq_auxt__8c1_s_p8_0,
  127528. NULL,
  127529. 0
  127530. };
  127531. static long _vq_quantlist__8c1_s_p8_1[] = {
  127532. 2,
  127533. 1,
  127534. 3,
  127535. 0,
  127536. 4,
  127537. };
  127538. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127539. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127540. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127541. };
  127542. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127543. -1.5, -0.5, 0.5, 1.5,
  127544. };
  127545. static long _vq_quantmap__8c1_s_p8_1[] = {
  127546. 3, 1, 0, 2, 4,
  127547. };
  127548. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127549. _vq_quantthresh__8c1_s_p8_1,
  127550. _vq_quantmap__8c1_s_p8_1,
  127551. 5,
  127552. 5
  127553. };
  127554. static static_codebook _8c1_s_p8_1 = {
  127555. 2, 25,
  127556. _vq_lengthlist__8c1_s_p8_1,
  127557. 1, -533725184, 1611661312, 3, 0,
  127558. _vq_quantlist__8c1_s_p8_1,
  127559. NULL,
  127560. &_vq_auxt__8c1_s_p8_1,
  127561. NULL,
  127562. 0
  127563. };
  127564. static long _vq_quantlist__8c1_s_p9_0[] = {
  127565. 6,
  127566. 5,
  127567. 7,
  127568. 4,
  127569. 8,
  127570. 3,
  127571. 9,
  127572. 2,
  127573. 10,
  127574. 1,
  127575. 11,
  127576. 0,
  127577. 12,
  127578. };
  127579. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127580. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127581. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127584. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127585. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127586. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127588. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127589. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127590. 10,10,10,10,10, 9, 9, 9, 9,
  127591. };
  127592. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127593. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127594. 787.5, 1102.5, 1417.5, 1732.5,
  127595. };
  127596. static long _vq_quantmap__8c1_s_p9_0[] = {
  127597. 11, 9, 7, 5, 3, 1, 0, 2,
  127598. 4, 6, 8, 10, 12,
  127599. };
  127600. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127601. _vq_quantthresh__8c1_s_p9_0,
  127602. _vq_quantmap__8c1_s_p9_0,
  127603. 13,
  127604. 13
  127605. };
  127606. static static_codebook _8c1_s_p9_0 = {
  127607. 2, 169,
  127608. _vq_lengthlist__8c1_s_p9_0,
  127609. 1, -513964032, 1628680192, 4, 0,
  127610. _vq_quantlist__8c1_s_p9_0,
  127611. NULL,
  127612. &_vq_auxt__8c1_s_p9_0,
  127613. NULL,
  127614. 0
  127615. };
  127616. static long _vq_quantlist__8c1_s_p9_1[] = {
  127617. 7,
  127618. 6,
  127619. 8,
  127620. 5,
  127621. 9,
  127622. 4,
  127623. 10,
  127624. 3,
  127625. 11,
  127626. 2,
  127627. 12,
  127628. 1,
  127629. 13,
  127630. 0,
  127631. 14,
  127632. };
  127633. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127634. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127635. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127636. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127637. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127638. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127639. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127640. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127641. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127642. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127643. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127644. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127645. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127646. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127647. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127648. 15,
  127649. };
  127650. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127651. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127652. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127653. };
  127654. static long _vq_quantmap__8c1_s_p9_1[] = {
  127655. 13, 11, 9, 7, 5, 3, 1, 0,
  127656. 2, 4, 6, 8, 10, 12, 14,
  127657. };
  127658. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127659. _vq_quantthresh__8c1_s_p9_1,
  127660. _vq_quantmap__8c1_s_p9_1,
  127661. 15,
  127662. 15
  127663. };
  127664. static static_codebook _8c1_s_p9_1 = {
  127665. 2, 225,
  127666. _vq_lengthlist__8c1_s_p9_1,
  127667. 1, -520986624, 1620377600, 4, 0,
  127668. _vq_quantlist__8c1_s_p9_1,
  127669. NULL,
  127670. &_vq_auxt__8c1_s_p9_1,
  127671. NULL,
  127672. 0
  127673. };
  127674. static long _vq_quantlist__8c1_s_p9_2[] = {
  127675. 10,
  127676. 9,
  127677. 11,
  127678. 8,
  127679. 12,
  127680. 7,
  127681. 13,
  127682. 6,
  127683. 14,
  127684. 5,
  127685. 15,
  127686. 4,
  127687. 16,
  127688. 3,
  127689. 17,
  127690. 2,
  127691. 18,
  127692. 1,
  127693. 19,
  127694. 0,
  127695. 20,
  127696. };
  127697. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127698. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127699. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127700. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127701. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127702. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127703. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127704. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127705. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127706. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127707. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127708. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127709. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127710. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127711. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127712. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127713. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127714. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127715. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127716. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127717. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127718. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127719. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127720. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127721. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127722. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127723. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127724. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127725. 10,10,10,10,10,10,10,10,10,
  127726. };
  127727. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127728. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127729. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127730. 6.5, 7.5, 8.5, 9.5,
  127731. };
  127732. static long _vq_quantmap__8c1_s_p9_2[] = {
  127733. 19, 17, 15, 13, 11, 9, 7, 5,
  127734. 3, 1, 0, 2, 4, 6, 8, 10,
  127735. 12, 14, 16, 18, 20,
  127736. };
  127737. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127738. _vq_quantthresh__8c1_s_p9_2,
  127739. _vq_quantmap__8c1_s_p9_2,
  127740. 21,
  127741. 21
  127742. };
  127743. static static_codebook _8c1_s_p9_2 = {
  127744. 2, 441,
  127745. _vq_lengthlist__8c1_s_p9_2,
  127746. 1, -529268736, 1611661312, 5, 0,
  127747. _vq_quantlist__8c1_s_p9_2,
  127748. NULL,
  127749. &_vq_auxt__8c1_s_p9_2,
  127750. NULL,
  127751. 0
  127752. };
  127753. static long _huff_lengthlist__8c1_s_single[] = {
  127754. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127755. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127756. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127757. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127758. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127759. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127760. 9, 7, 7, 8,
  127761. };
  127762. static static_codebook _huff_book__8c1_s_single = {
  127763. 2, 100,
  127764. _huff_lengthlist__8c1_s_single,
  127765. 0, 0, 0, 0, 0,
  127766. NULL,
  127767. NULL,
  127768. NULL,
  127769. NULL,
  127770. 0
  127771. };
  127772. static long _huff_lengthlist__44c2_s_long[] = {
  127773. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127774. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127775. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127776. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127777. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127778. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127779. 10, 8, 8, 9,
  127780. };
  127781. static static_codebook _huff_book__44c2_s_long = {
  127782. 2, 100,
  127783. _huff_lengthlist__44c2_s_long,
  127784. 0, 0, 0, 0, 0,
  127785. NULL,
  127786. NULL,
  127787. NULL,
  127788. NULL,
  127789. 0
  127790. };
  127791. static long _vq_quantlist__44c2_s_p1_0[] = {
  127792. 1,
  127793. 0,
  127794. 2,
  127795. };
  127796. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127797. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127798. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127803. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127808. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127843. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127848. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127853. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127889. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127894. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127899. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0,
  128208. };
  128209. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128210. -0.5, 0.5,
  128211. };
  128212. static long _vq_quantmap__44c2_s_p1_0[] = {
  128213. 1, 0, 2,
  128214. };
  128215. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128216. _vq_quantthresh__44c2_s_p1_0,
  128217. _vq_quantmap__44c2_s_p1_0,
  128218. 3,
  128219. 3
  128220. };
  128221. static static_codebook _44c2_s_p1_0 = {
  128222. 8, 6561,
  128223. _vq_lengthlist__44c2_s_p1_0,
  128224. 1, -535822336, 1611661312, 2, 0,
  128225. _vq_quantlist__44c2_s_p1_0,
  128226. NULL,
  128227. &_vq_auxt__44c2_s_p1_0,
  128228. NULL,
  128229. 0
  128230. };
  128231. static long _vq_quantlist__44c2_s_p2_0[] = {
  128232. 2,
  128233. 1,
  128234. 3,
  128235. 0,
  128236. 4,
  128237. };
  128238. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128239. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128240. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128241. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128242. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128243. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128249. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128250. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128251. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128257. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128258. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128265. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128266. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128279. };
  128280. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128281. -1.5, -0.5, 0.5, 1.5,
  128282. };
  128283. static long _vq_quantmap__44c2_s_p2_0[] = {
  128284. 3, 1, 0, 2, 4,
  128285. };
  128286. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128287. _vq_quantthresh__44c2_s_p2_0,
  128288. _vq_quantmap__44c2_s_p2_0,
  128289. 5,
  128290. 5
  128291. };
  128292. static static_codebook _44c2_s_p2_0 = {
  128293. 4, 625,
  128294. _vq_lengthlist__44c2_s_p2_0,
  128295. 1, -533725184, 1611661312, 3, 0,
  128296. _vq_quantlist__44c2_s_p2_0,
  128297. NULL,
  128298. &_vq_auxt__44c2_s_p2_0,
  128299. NULL,
  128300. 0
  128301. };
  128302. static long _vq_quantlist__44c2_s_p3_0[] = {
  128303. 2,
  128304. 1,
  128305. 3,
  128306. 0,
  128307. 4,
  128308. };
  128309. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128310. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128350. };
  128351. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128352. -1.5, -0.5, 0.5, 1.5,
  128353. };
  128354. static long _vq_quantmap__44c2_s_p3_0[] = {
  128355. 3, 1, 0, 2, 4,
  128356. };
  128357. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128358. _vq_quantthresh__44c2_s_p3_0,
  128359. _vq_quantmap__44c2_s_p3_0,
  128360. 5,
  128361. 5
  128362. };
  128363. static static_codebook _44c2_s_p3_0 = {
  128364. 4, 625,
  128365. _vq_lengthlist__44c2_s_p3_0,
  128366. 1, -533725184, 1611661312, 3, 0,
  128367. _vq_quantlist__44c2_s_p3_0,
  128368. NULL,
  128369. &_vq_auxt__44c2_s_p3_0,
  128370. NULL,
  128371. 0
  128372. };
  128373. static long _vq_quantlist__44c2_s_p4_0[] = {
  128374. 4,
  128375. 3,
  128376. 5,
  128377. 2,
  128378. 6,
  128379. 1,
  128380. 7,
  128381. 0,
  128382. 8,
  128383. };
  128384. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128385. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128386. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128387. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128388. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128389. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0,
  128391. };
  128392. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128393. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128394. };
  128395. static long _vq_quantmap__44c2_s_p4_0[] = {
  128396. 7, 5, 3, 1, 0, 2, 4, 6,
  128397. 8,
  128398. };
  128399. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128400. _vq_quantthresh__44c2_s_p4_0,
  128401. _vq_quantmap__44c2_s_p4_0,
  128402. 9,
  128403. 9
  128404. };
  128405. static static_codebook _44c2_s_p4_0 = {
  128406. 2, 81,
  128407. _vq_lengthlist__44c2_s_p4_0,
  128408. 1, -531628032, 1611661312, 4, 0,
  128409. _vq_quantlist__44c2_s_p4_0,
  128410. NULL,
  128411. &_vq_auxt__44c2_s_p4_0,
  128412. NULL,
  128413. 0
  128414. };
  128415. static long _vq_quantlist__44c2_s_p5_0[] = {
  128416. 4,
  128417. 3,
  128418. 5,
  128419. 2,
  128420. 6,
  128421. 1,
  128422. 7,
  128423. 0,
  128424. 8,
  128425. };
  128426. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128427. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128428. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128429. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128430. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128431. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128432. 11,
  128433. };
  128434. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128435. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128436. };
  128437. static long _vq_quantmap__44c2_s_p5_0[] = {
  128438. 7, 5, 3, 1, 0, 2, 4, 6,
  128439. 8,
  128440. };
  128441. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128442. _vq_quantthresh__44c2_s_p5_0,
  128443. _vq_quantmap__44c2_s_p5_0,
  128444. 9,
  128445. 9
  128446. };
  128447. static static_codebook _44c2_s_p5_0 = {
  128448. 2, 81,
  128449. _vq_lengthlist__44c2_s_p5_0,
  128450. 1, -531628032, 1611661312, 4, 0,
  128451. _vq_quantlist__44c2_s_p5_0,
  128452. NULL,
  128453. &_vq_auxt__44c2_s_p5_0,
  128454. NULL,
  128455. 0
  128456. };
  128457. static long _vq_quantlist__44c2_s_p6_0[] = {
  128458. 8,
  128459. 7,
  128460. 9,
  128461. 6,
  128462. 10,
  128463. 5,
  128464. 11,
  128465. 4,
  128466. 12,
  128467. 3,
  128468. 13,
  128469. 2,
  128470. 14,
  128471. 1,
  128472. 15,
  128473. 0,
  128474. 16,
  128475. };
  128476. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128477. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128478. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128479. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128480. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128481. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128482. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128483. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128484. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128485. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128486. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128487. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128488. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128489. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128490. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128491. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128492. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128493. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128495. 14,
  128496. };
  128497. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128498. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128499. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128500. };
  128501. static long _vq_quantmap__44c2_s_p6_0[] = {
  128502. 15, 13, 11, 9, 7, 5, 3, 1,
  128503. 0, 2, 4, 6, 8, 10, 12, 14,
  128504. 16,
  128505. };
  128506. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128507. _vq_quantthresh__44c2_s_p6_0,
  128508. _vq_quantmap__44c2_s_p6_0,
  128509. 17,
  128510. 17
  128511. };
  128512. static static_codebook _44c2_s_p6_0 = {
  128513. 2, 289,
  128514. _vq_lengthlist__44c2_s_p6_0,
  128515. 1, -529530880, 1611661312, 5, 0,
  128516. _vq_quantlist__44c2_s_p6_0,
  128517. NULL,
  128518. &_vq_auxt__44c2_s_p6_0,
  128519. NULL,
  128520. 0
  128521. };
  128522. static long _vq_quantlist__44c2_s_p7_0[] = {
  128523. 1,
  128524. 0,
  128525. 2,
  128526. };
  128527. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128528. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128529. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128530. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128531. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128532. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128533. 11,
  128534. };
  128535. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128536. -5.5, 5.5,
  128537. };
  128538. static long _vq_quantmap__44c2_s_p7_0[] = {
  128539. 1, 0, 2,
  128540. };
  128541. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128542. _vq_quantthresh__44c2_s_p7_0,
  128543. _vq_quantmap__44c2_s_p7_0,
  128544. 3,
  128545. 3
  128546. };
  128547. static static_codebook _44c2_s_p7_0 = {
  128548. 4, 81,
  128549. _vq_lengthlist__44c2_s_p7_0,
  128550. 1, -529137664, 1618345984, 2, 0,
  128551. _vq_quantlist__44c2_s_p7_0,
  128552. NULL,
  128553. &_vq_auxt__44c2_s_p7_0,
  128554. NULL,
  128555. 0
  128556. };
  128557. static long _vq_quantlist__44c2_s_p7_1[] = {
  128558. 5,
  128559. 4,
  128560. 6,
  128561. 3,
  128562. 7,
  128563. 2,
  128564. 8,
  128565. 1,
  128566. 9,
  128567. 0,
  128568. 10,
  128569. };
  128570. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128571. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128572. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128573. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128574. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128575. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128576. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128577. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128578. 10,10,10, 8, 8, 8, 8, 8, 8,
  128579. };
  128580. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128581. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128582. 3.5, 4.5,
  128583. };
  128584. static long _vq_quantmap__44c2_s_p7_1[] = {
  128585. 9, 7, 5, 3, 1, 0, 2, 4,
  128586. 6, 8, 10,
  128587. };
  128588. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128589. _vq_quantthresh__44c2_s_p7_1,
  128590. _vq_quantmap__44c2_s_p7_1,
  128591. 11,
  128592. 11
  128593. };
  128594. static static_codebook _44c2_s_p7_1 = {
  128595. 2, 121,
  128596. _vq_lengthlist__44c2_s_p7_1,
  128597. 1, -531365888, 1611661312, 4, 0,
  128598. _vq_quantlist__44c2_s_p7_1,
  128599. NULL,
  128600. &_vq_auxt__44c2_s_p7_1,
  128601. NULL,
  128602. 0
  128603. };
  128604. static long _vq_quantlist__44c2_s_p8_0[] = {
  128605. 6,
  128606. 5,
  128607. 7,
  128608. 4,
  128609. 8,
  128610. 3,
  128611. 9,
  128612. 2,
  128613. 10,
  128614. 1,
  128615. 11,
  128616. 0,
  128617. 12,
  128618. };
  128619. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128620. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128621. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128622. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128623. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128624. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128625. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128626. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128627. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128628. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128629. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128630. 0,12,12,12,12,13,12,14,14,
  128631. };
  128632. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128633. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128634. 12.5, 17.5, 22.5, 27.5,
  128635. };
  128636. static long _vq_quantmap__44c2_s_p8_0[] = {
  128637. 11, 9, 7, 5, 3, 1, 0, 2,
  128638. 4, 6, 8, 10, 12,
  128639. };
  128640. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128641. _vq_quantthresh__44c2_s_p8_0,
  128642. _vq_quantmap__44c2_s_p8_0,
  128643. 13,
  128644. 13
  128645. };
  128646. static static_codebook _44c2_s_p8_0 = {
  128647. 2, 169,
  128648. _vq_lengthlist__44c2_s_p8_0,
  128649. 1, -526516224, 1616117760, 4, 0,
  128650. _vq_quantlist__44c2_s_p8_0,
  128651. NULL,
  128652. &_vq_auxt__44c2_s_p8_0,
  128653. NULL,
  128654. 0
  128655. };
  128656. static long _vq_quantlist__44c2_s_p8_1[] = {
  128657. 2,
  128658. 1,
  128659. 3,
  128660. 0,
  128661. 4,
  128662. };
  128663. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128664. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128665. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128666. };
  128667. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128668. -1.5, -0.5, 0.5, 1.5,
  128669. };
  128670. static long _vq_quantmap__44c2_s_p8_1[] = {
  128671. 3, 1, 0, 2, 4,
  128672. };
  128673. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128674. _vq_quantthresh__44c2_s_p8_1,
  128675. _vq_quantmap__44c2_s_p8_1,
  128676. 5,
  128677. 5
  128678. };
  128679. static static_codebook _44c2_s_p8_1 = {
  128680. 2, 25,
  128681. _vq_lengthlist__44c2_s_p8_1,
  128682. 1, -533725184, 1611661312, 3, 0,
  128683. _vq_quantlist__44c2_s_p8_1,
  128684. NULL,
  128685. &_vq_auxt__44c2_s_p8_1,
  128686. NULL,
  128687. 0
  128688. };
  128689. static long _vq_quantlist__44c2_s_p9_0[] = {
  128690. 6,
  128691. 5,
  128692. 7,
  128693. 4,
  128694. 8,
  128695. 3,
  128696. 9,
  128697. 2,
  128698. 10,
  128699. 1,
  128700. 11,
  128701. 0,
  128702. 12,
  128703. };
  128704. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128705. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128706. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128708. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128715. 11,11,11,11,11,11,11,11,11,
  128716. };
  128717. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128718. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128719. 552.5, 773.5, 994.5, 1215.5,
  128720. };
  128721. static long _vq_quantmap__44c2_s_p9_0[] = {
  128722. 11, 9, 7, 5, 3, 1, 0, 2,
  128723. 4, 6, 8, 10, 12,
  128724. };
  128725. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128726. _vq_quantthresh__44c2_s_p9_0,
  128727. _vq_quantmap__44c2_s_p9_0,
  128728. 13,
  128729. 13
  128730. };
  128731. static static_codebook _44c2_s_p9_0 = {
  128732. 2, 169,
  128733. _vq_lengthlist__44c2_s_p9_0,
  128734. 1, -514541568, 1627103232, 4, 0,
  128735. _vq_quantlist__44c2_s_p9_0,
  128736. NULL,
  128737. &_vq_auxt__44c2_s_p9_0,
  128738. NULL,
  128739. 0
  128740. };
  128741. static long _vq_quantlist__44c2_s_p9_1[] = {
  128742. 6,
  128743. 5,
  128744. 7,
  128745. 4,
  128746. 8,
  128747. 3,
  128748. 9,
  128749. 2,
  128750. 10,
  128751. 1,
  128752. 11,
  128753. 0,
  128754. 12,
  128755. };
  128756. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128757. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128758. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128759. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128760. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128761. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128762. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128763. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128764. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128765. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128766. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128767. 17,13,12,12,10,13,11,14,14,
  128768. };
  128769. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128770. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128771. 42.5, 59.5, 76.5, 93.5,
  128772. };
  128773. static long _vq_quantmap__44c2_s_p9_1[] = {
  128774. 11, 9, 7, 5, 3, 1, 0, 2,
  128775. 4, 6, 8, 10, 12,
  128776. };
  128777. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128778. _vq_quantthresh__44c2_s_p9_1,
  128779. _vq_quantmap__44c2_s_p9_1,
  128780. 13,
  128781. 13
  128782. };
  128783. static static_codebook _44c2_s_p9_1 = {
  128784. 2, 169,
  128785. _vq_lengthlist__44c2_s_p9_1,
  128786. 1, -522616832, 1620115456, 4, 0,
  128787. _vq_quantlist__44c2_s_p9_1,
  128788. NULL,
  128789. &_vq_auxt__44c2_s_p9_1,
  128790. NULL,
  128791. 0
  128792. };
  128793. static long _vq_quantlist__44c2_s_p9_2[] = {
  128794. 8,
  128795. 7,
  128796. 9,
  128797. 6,
  128798. 10,
  128799. 5,
  128800. 11,
  128801. 4,
  128802. 12,
  128803. 3,
  128804. 13,
  128805. 2,
  128806. 14,
  128807. 1,
  128808. 15,
  128809. 0,
  128810. 16,
  128811. };
  128812. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128813. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128814. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128815. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128816. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128817. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128818. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128819. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128820. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128821. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128822. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128823. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128824. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128825. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128826. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128827. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128828. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128829. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128830. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128831. 10,
  128832. };
  128833. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128834. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128835. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128836. };
  128837. static long _vq_quantmap__44c2_s_p9_2[] = {
  128838. 15, 13, 11, 9, 7, 5, 3, 1,
  128839. 0, 2, 4, 6, 8, 10, 12, 14,
  128840. 16,
  128841. };
  128842. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128843. _vq_quantthresh__44c2_s_p9_2,
  128844. _vq_quantmap__44c2_s_p9_2,
  128845. 17,
  128846. 17
  128847. };
  128848. static static_codebook _44c2_s_p9_2 = {
  128849. 2, 289,
  128850. _vq_lengthlist__44c2_s_p9_2,
  128851. 1, -529530880, 1611661312, 5, 0,
  128852. _vq_quantlist__44c2_s_p9_2,
  128853. NULL,
  128854. &_vq_auxt__44c2_s_p9_2,
  128855. NULL,
  128856. 0
  128857. };
  128858. static long _huff_lengthlist__44c2_s_short[] = {
  128859. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128860. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128861. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128862. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128863. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128864. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128865. 6, 8, 9,12,
  128866. };
  128867. static static_codebook _huff_book__44c2_s_short = {
  128868. 2, 100,
  128869. _huff_lengthlist__44c2_s_short,
  128870. 0, 0, 0, 0, 0,
  128871. NULL,
  128872. NULL,
  128873. NULL,
  128874. NULL,
  128875. 0
  128876. };
  128877. static long _huff_lengthlist__44c3_s_long[] = {
  128878. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128879. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128880. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128881. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128882. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128883. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128884. 9, 8, 8, 8,
  128885. };
  128886. static static_codebook _huff_book__44c3_s_long = {
  128887. 2, 100,
  128888. _huff_lengthlist__44c3_s_long,
  128889. 0, 0, 0, 0, 0,
  128890. NULL,
  128891. NULL,
  128892. NULL,
  128893. NULL,
  128894. 0
  128895. };
  128896. static long _vq_quantlist__44c3_s_p1_0[] = {
  128897. 1,
  128898. 0,
  128899. 2,
  128900. };
  128901. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128902. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128903. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128908. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128913. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128948. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128953. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128958. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128994. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128999. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129004. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0,
  129313. };
  129314. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129315. -0.5, 0.5,
  129316. };
  129317. static long _vq_quantmap__44c3_s_p1_0[] = {
  129318. 1, 0, 2,
  129319. };
  129320. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129321. _vq_quantthresh__44c3_s_p1_0,
  129322. _vq_quantmap__44c3_s_p1_0,
  129323. 3,
  129324. 3
  129325. };
  129326. static static_codebook _44c3_s_p1_0 = {
  129327. 8, 6561,
  129328. _vq_lengthlist__44c3_s_p1_0,
  129329. 1, -535822336, 1611661312, 2, 0,
  129330. _vq_quantlist__44c3_s_p1_0,
  129331. NULL,
  129332. &_vq_auxt__44c3_s_p1_0,
  129333. NULL,
  129334. 0
  129335. };
  129336. static long _vq_quantlist__44c3_s_p2_0[] = {
  129337. 2,
  129338. 1,
  129339. 3,
  129340. 0,
  129341. 4,
  129342. };
  129343. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129344. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129345. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129346. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129347. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129348. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129354. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129355. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129356. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129362. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129363. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129370. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129371. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129384. };
  129385. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129386. -1.5, -0.5, 0.5, 1.5,
  129387. };
  129388. static long _vq_quantmap__44c3_s_p2_0[] = {
  129389. 3, 1, 0, 2, 4,
  129390. };
  129391. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129392. _vq_quantthresh__44c3_s_p2_0,
  129393. _vq_quantmap__44c3_s_p2_0,
  129394. 5,
  129395. 5
  129396. };
  129397. static static_codebook _44c3_s_p2_0 = {
  129398. 4, 625,
  129399. _vq_lengthlist__44c3_s_p2_0,
  129400. 1, -533725184, 1611661312, 3, 0,
  129401. _vq_quantlist__44c3_s_p2_0,
  129402. NULL,
  129403. &_vq_auxt__44c3_s_p2_0,
  129404. NULL,
  129405. 0
  129406. };
  129407. static long _vq_quantlist__44c3_s_p3_0[] = {
  129408. 2,
  129409. 1,
  129410. 3,
  129411. 0,
  129412. 4,
  129413. };
  129414. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129415. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129455. };
  129456. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129457. -1.5, -0.5, 0.5, 1.5,
  129458. };
  129459. static long _vq_quantmap__44c3_s_p3_0[] = {
  129460. 3, 1, 0, 2, 4,
  129461. };
  129462. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129463. _vq_quantthresh__44c3_s_p3_0,
  129464. _vq_quantmap__44c3_s_p3_0,
  129465. 5,
  129466. 5
  129467. };
  129468. static static_codebook _44c3_s_p3_0 = {
  129469. 4, 625,
  129470. _vq_lengthlist__44c3_s_p3_0,
  129471. 1, -533725184, 1611661312, 3, 0,
  129472. _vq_quantlist__44c3_s_p3_0,
  129473. NULL,
  129474. &_vq_auxt__44c3_s_p3_0,
  129475. NULL,
  129476. 0
  129477. };
  129478. static long _vq_quantlist__44c3_s_p4_0[] = {
  129479. 4,
  129480. 3,
  129481. 5,
  129482. 2,
  129483. 6,
  129484. 1,
  129485. 7,
  129486. 0,
  129487. 8,
  129488. };
  129489. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129490. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129491. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129492. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129493. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129494. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0,
  129496. };
  129497. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129498. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129499. };
  129500. static long _vq_quantmap__44c3_s_p4_0[] = {
  129501. 7, 5, 3, 1, 0, 2, 4, 6,
  129502. 8,
  129503. };
  129504. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129505. _vq_quantthresh__44c3_s_p4_0,
  129506. _vq_quantmap__44c3_s_p4_0,
  129507. 9,
  129508. 9
  129509. };
  129510. static static_codebook _44c3_s_p4_0 = {
  129511. 2, 81,
  129512. _vq_lengthlist__44c3_s_p4_0,
  129513. 1, -531628032, 1611661312, 4, 0,
  129514. _vq_quantlist__44c3_s_p4_0,
  129515. NULL,
  129516. &_vq_auxt__44c3_s_p4_0,
  129517. NULL,
  129518. 0
  129519. };
  129520. static long _vq_quantlist__44c3_s_p5_0[] = {
  129521. 4,
  129522. 3,
  129523. 5,
  129524. 2,
  129525. 6,
  129526. 1,
  129527. 7,
  129528. 0,
  129529. 8,
  129530. };
  129531. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129532. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129533. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129534. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129535. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129536. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129537. 11,
  129538. };
  129539. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129540. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129541. };
  129542. static long _vq_quantmap__44c3_s_p5_0[] = {
  129543. 7, 5, 3, 1, 0, 2, 4, 6,
  129544. 8,
  129545. };
  129546. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129547. _vq_quantthresh__44c3_s_p5_0,
  129548. _vq_quantmap__44c3_s_p5_0,
  129549. 9,
  129550. 9
  129551. };
  129552. static static_codebook _44c3_s_p5_0 = {
  129553. 2, 81,
  129554. _vq_lengthlist__44c3_s_p5_0,
  129555. 1, -531628032, 1611661312, 4, 0,
  129556. _vq_quantlist__44c3_s_p5_0,
  129557. NULL,
  129558. &_vq_auxt__44c3_s_p5_0,
  129559. NULL,
  129560. 0
  129561. };
  129562. static long _vq_quantlist__44c3_s_p6_0[] = {
  129563. 8,
  129564. 7,
  129565. 9,
  129566. 6,
  129567. 10,
  129568. 5,
  129569. 11,
  129570. 4,
  129571. 12,
  129572. 3,
  129573. 13,
  129574. 2,
  129575. 14,
  129576. 1,
  129577. 15,
  129578. 0,
  129579. 16,
  129580. };
  129581. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129582. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129583. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129584. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129585. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129586. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129587. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129588. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129589. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129590. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129591. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129592. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129593. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129594. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129595. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129596. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129597. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129598. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129600. 13,
  129601. };
  129602. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129603. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129604. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129605. };
  129606. static long _vq_quantmap__44c3_s_p6_0[] = {
  129607. 15, 13, 11, 9, 7, 5, 3, 1,
  129608. 0, 2, 4, 6, 8, 10, 12, 14,
  129609. 16,
  129610. };
  129611. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129612. _vq_quantthresh__44c3_s_p6_0,
  129613. _vq_quantmap__44c3_s_p6_0,
  129614. 17,
  129615. 17
  129616. };
  129617. static static_codebook _44c3_s_p6_0 = {
  129618. 2, 289,
  129619. _vq_lengthlist__44c3_s_p6_0,
  129620. 1, -529530880, 1611661312, 5, 0,
  129621. _vq_quantlist__44c3_s_p6_0,
  129622. NULL,
  129623. &_vq_auxt__44c3_s_p6_0,
  129624. NULL,
  129625. 0
  129626. };
  129627. static long _vq_quantlist__44c3_s_p7_0[] = {
  129628. 1,
  129629. 0,
  129630. 2,
  129631. };
  129632. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129633. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129634. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129635. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129636. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129637. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129638. 10,
  129639. };
  129640. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129641. -5.5, 5.5,
  129642. };
  129643. static long _vq_quantmap__44c3_s_p7_0[] = {
  129644. 1, 0, 2,
  129645. };
  129646. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129647. _vq_quantthresh__44c3_s_p7_0,
  129648. _vq_quantmap__44c3_s_p7_0,
  129649. 3,
  129650. 3
  129651. };
  129652. static static_codebook _44c3_s_p7_0 = {
  129653. 4, 81,
  129654. _vq_lengthlist__44c3_s_p7_0,
  129655. 1, -529137664, 1618345984, 2, 0,
  129656. _vq_quantlist__44c3_s_p7_0,
  129657. NULL,
  129658. &_vq_auxt__44c3_s_p7_0,
  129659. NULL,
  129660. 0
  129661. };
  129662. static long _vq_quantlist__44c3_s_p7_1[] = {
  129663. 5,
  129664. 4,
  129665. 6,
  129666. 3,
  129667. 7,
  129668. 2,
  129669. 8,
  129670. 1,
  129671. 9,
  129672. 0,
  129673. 10,
  129674. };
  129675. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129676. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129677. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129678. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129679. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129680. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129681. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129682. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129683. 10,10,10, 8, 8, 8, 8, 8, 8,
  129684. };
  129685. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129686. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129687. 3.5, 4.5,
  129688. };
  129689. static long _vq_quantmap__44c3_s_p7_1[] = {
  129690. 9, 7, 5, 3, 1, 0, 2, 4,
  129691. 6, 8, 10,
  129692. };
  129693. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129694. _vq_quantthresh__44c3_s_p7_1,
  129695. _vq_quantmap__44c3_s_p7_1,
  129696. 11,
  129697. 11
  129698. };
  129699. static static_codebook _44c3_s_p7_1 = {
  129700. 2, 121,
  129701. _vq_lengthlist__44c3_s_p7_1,
  129702. 1, -531365888, 1611661312, 4, 0,
  129703. _vq_quantlist__44c3_s_p7_1,
  129704. NULL,
  129705. &_vq_auxt__44c3_s_p7_1,
  129706. NULL,
  129707. 0
  129708. };
  129709. static long _vq_quantlist__44c3_s_p8_0[] = {
  129710. 6,
  129711. 5,
  129712. 7,
  129713. 4,
  129714. 8,
  129715. 3,
  129716. 9,
  129717. 2,
  129718. 10,
  129719. 1,
  129720. 11,
  129721. 0,
  129722. 12,
  129723. };
  129724. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129725. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129726. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129727. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129728. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129729. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129730. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129731. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129732. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129733. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129734. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129735. 0,13,13,12,12,13,12,14,13,
  129736. };
  129737. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129738. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129739. 12.5, 17.5, 22.5, 27.5,
  129740. };
  129741. static long _vq_quantmap__44c3_s_p8_0[] = {
  129742. 11, 9, 7, 5, 3, 1, 0, 2,
  129743. 4, 6, 8, 10, 12,
  129744. };
  129745. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129746. _vq_quantthresh__44c3_s_p8_0,
  129747. _vq_quantmap__44c3_s_p8_0,
  129748. 13,
  129749. 13
  129750. };
  129751. static static_codebook _44c3_s_p8_0 = {
  129752. 2, 169,
  129753. _vq_lengthlist__44c3_s_p8_0,
  129754. 1, -526516224, 1616117760, 4, 0,
  129755. _vq_quantlist__44c3_s_p8_0,
  129756. NULL,
  129757. &_vq_auxt__44c3_s_p8_0,
  129758. NULL,
  129759. 0
  129760. };
  129761. static long _vq_quantlist__44c3_s_p8_1[] = {
  129762. 2,
  129763. 1,
  129764. 3,
  129765. 0,
  129766. 4,
  129767. };
  129768. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129769. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129770. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129771. };
  129772. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129773. -1.5, -0.5, 0.5, 1.5,
  129774. };
  129775. static long _vq_quantmap__44c3_s_p8_1[] = {
  129776. 3, 1, 0, 2, 4,
  129777. };
  129778. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129779. _vq_quantthresh__44c3_s_p8_1,
  129780. _vq_quantmap__44c3_s_p8_1,
  129781. 5,
  129782. 5
  129783. };
  129784. static static_codebook _44c3_s_p8_1 = {
  129785. 2, 25,
  129786. _vq_lengthlist__44c3_s_p8_1,
  129787. 1, -533725184, 1611661312, 3, 0,
  129788. _vq_quantlist__44c3_s_p8_1,
  129789. NULL,
  129790. &_vq_auxt__44c3_s_p8_1,
  129791. NULL,
  129792. 0
  129793. };
  129794. static long _vq_quantlist__44c3_s_p9_0[] = {
  129795. 6,
  129796. 5,
  129797. 7,
  129798. 4,
  129799. 8,
  129800. 3,
  129801. 9,
  129802. 2,
  129803. 10,
  129804. 1,
  129805. 11,
  129806. 0,
  129807. 12,
  129808. };
  129809. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129810. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129811. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129812. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129813. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129814. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129817. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129818. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129820. 11,11,11,11,11,11,11,11,11,
  129821. };
  129822. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129823. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129824. 637.5, 892.5, 1147.5, 1402.5,
  129825. };
  129826. static long _vq_quantmap__44c3_s_p9_0[] = {
  129827. 11, 9, 7, 5, 3, 1, 0, 2,
  129828. 4, 6, 8, 10, 12,
  129829. };
  129830. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129831. _vq_quantthresh__44c3_s_p9_0,
  129832. _vq_quantmap__44c3_s_p9_0,
  129833. 13,
  129834. 13
  129835. };
  129836. static static_codebook _44c3_s_p9_0 = {
  129837. 2, 169,
  129838. _vq_lengthlist__44c3_s_p9_0,
  129839. 1, -514332672, 1627381760, 4, 0,
  129840. _vq_quantlist__44c3_s_p9_0,
  129841. NULL,
  129842. &_vq_auxt__44c3_s_p9_0,
  129843. NULL,
  129844. 0
  129845. };
  129846. static long _vq_quantlist__44c3_s_p9_1[] = {
  129847. 7,
  129848. 6,
  129849. 8,
  129850. 5,
  129851. 9,
  129852. 4,
  129853. 10,
  129854. 3,
  129855. 11,
  129856. 2,
  129857. 12,
  129858. 1,
  129859. 13,
  129860. 0,
  129861. 14,
  129862. };
  129863. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129864. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129865. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129866. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129867. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129868. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129869. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129870. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129871. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129872. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129873. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129874. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129875. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129876. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129877. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129878. 15,
  129879. };
  129880. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129881. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129882. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129883. };
  129884. static long _vq_quantmap__44c3_s_p9_1[] = {
  129885. 13, 11, 9, 7, 5, 3, 1, 0,
  129886. 2, 4, 6, 8, 10, 12, 14,
  129887. };
  129888. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129889. _vq_quantthresh__44c3_s_p9_1,
  129890. _vq_quantmap__44c3_s_p9_1,
  129891. 15,
  129892. 15
  129893. };
  129894. static static_codebook _44c3_s_p9_1 = {
  129895. 2, 225,
  129896. _vq_lengthlist__44c3_s_p9_1,
  129897. 1, -522338304, 1620115456, 4, 0,
  129898. _vq_quantlist__44c3_s_p9_1,
  129899. NULL,
  129900. &_vq_auxt__44c3_s_p9_1,
  129901. NULL,
  129902. 0
  129903. };
  129904. static long _vq_quantlist__44c3_s_p9_2[] = {
  129905. 8,
  129906. 7,
  129907. 9,
  129908. 6,
  129909. 10,
  129910. 5,
  129911. 11,
  129912. 4,
  129913. 12,
  129914. 3,
  129915. 13,
  129916. 2,
  129917. 14,
  129918. 1,
  129919. 15,
  129920. 0,
  129921. 16,
  129922. };
  129923. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129924. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129925. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129926. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129927. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129928. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129929. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129930. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129931. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129932. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129933. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129934. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129935. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129936. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129937. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129938. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129939. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129940. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129941. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129942. 10,
  129943. };
  129944. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129945. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129946. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129947. };
  129948. static long _vq_quantmap__44c3_s_p9_2[] = {
  129949. 15, 13, 11, 9, 7, 5, 3, 1,
  129950. 0, 2, 4, 6, 8, 10, 12, 14,
  129951. 16,
  129952. };
  129953. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129954. _vq_quantthresh__44c3_s_p9_2,
  129955. _vq_quantmap__44c3_s_p9_2,
  129956. 17,
  129957. 17
  129958. };
  129959. static static_codebook _44c3_s_p9_2 = {
  129960. 2, 289,
  129961. _vq_lengthlist__44c3_s_p9_2,
  129962. 1, -529530880, 1611661312, 5, 0,
  129963. _vq_quantlist__44c3_s_p9_2,
  129964. NULL,
  129965. &_vq_auxt__44c3_s_p9_2,
  129966. NULL,
  129967. 0
  129968. };
  129969. static long _huff_lengthlist__44c3_s_short[] = {
  129970. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129971. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129972. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129973. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129974. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129975. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129976. 6, 8, 9,11,
  129977. };
  129978. static static_codebook _huff_book__44c3_s_short = {
  129979. 2, 100,
  129980. _huff_lengthlist__44c3_s_short,
  129981. 0, 0, 0, 0, 0,
  129982. NULL,
  129983. NULL,
  129984. NULL,
  129985. NULL,
  129986. 0
  129987. };
  129988. static long _huff_lengthlist__44c4_s_long[] = {
  129989. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129990. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129991. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129992. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129993. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129994. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129995. 9, 8, 7, 7,
  129996. };
  129997. static static_codebook _huff_book__44c4_s_long = {
  129998. 2, 100,
  129999. _huff_lengthlist__44c4_s_long,
  130000. 0, 0, 0, 0, 0,
  130001. NULL,
  130002. NULL,
  130003. NULL,
  130004. NULL,
  130005. 0
  130006. };
  130007. static long _vq_quantlist__44c4_s_p1_0[] = {
  130008. 1,
  130009. 0,
  130010. 2,
  130011. };
  130012. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130013. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130014. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130019. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130024. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130059. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130064. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130069. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130105. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130110. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130115. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0,
  130424. };
  130425. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130426. -0.5, 0.5,
  130427. };
  130428. static long _vq_quantmap__44c4_s_p1_0[] = {
  130429. 1, 0, 2,
  130430. };
  130431. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130432. _vq_quantthresh__44c4_s_p1_0,
  130433. _vq_quantmap__44c4_s_p1_0,
  130434. 3,
  130435. 3
  130436. };
  130437. static static_codebook _44c4_s_p1_0 = {
  130438. 8, 6561,
  130439. _vq_lengthlist__44c4_s_p1_0,
  130440. 1, -535822336, 1611661312, 2, 0,
  130441. _vq_quantlist__44c4_s_p1_0,
  130442. NULL,
  130443. &_vq_auxt__44c4_s_p1_0,
  130444. NULL,
  130445. 0
  130446. };
  130447. static long _vq_quantlist__44c4_s_p2_0[] = {
  130448. 2,
  130449. 1,
  130450. 3,
  130451. 0,
  130452. 4,
  130453. };
  130454. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130455. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130456. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130457. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130458. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130459. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130465. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130466. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130467. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130473. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130474. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130481. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130482. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130495. };
  130496. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130497. -1.5, -0.5, 0.5, 1.5,
  130498. };
  130499. static long _vq_quantmap__44c4_s_p2_0[] = {
  130500. 3, 1, 0, 2, 4,
  130501. };
  130502. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130503. _vq_quantthresh__44c4_s_p2_0,
  130504. _vq_quantmap__44c4_s_p2_0,
  130505. 5,
  130506. 5
  130507. };
  130508. static static_codebook _44c4_s_p2_0 = {
  130509. 4, 625,
  130510. _vq_lengthlist__44c4_s_p2_0,
  130511. 1, -533725184, 1611661312, 3, 0,
  130512. _vq_quantlist__44c4_s_p2_0,
  130513. NULL,
  130514. &_vq_auxt__44c4_s_p2_0,
  130515. NULL,
  130516. 0
  130517. };
  130518. static long _vq_quantlist__44c4_s_p3_0[] = {
  130519. 2,
  130520. 1,
  130521. 3,
  130522. 0,
  130523. 4,
  130524. };
  130525. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130526. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130566. };
  130567. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130568. -1.5, -0.5, 0.5, 1.5,
  130569. };
  130570. static long _vq_quantmap__44c4_s_p3_0[] = {
  130571. 3, 1, 0, 2, 4,
  130572. };
  130573. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130574. _vq_quantthresh__44c4_s_p3_0,
  130575. _vq_quantmap__44c4_s_p3_0,
  130576. 5,
  130577. 5
  130578. };
  130579. static static_codebook _44c4_s_p3_0 = {
  130580. 4, 625,
  130581. _vq_lengthlist__44c4_s_p3_0,
  130582. 1, -533725184, 1611661312, 3, 0,
  130583. _vq_quantlist__44c4_s_p3_0,
  130584. NULL,
  130585. &_vq_auxt__44c4_s_p3_0,
  130586. NULL,
  130587. 0
  130588. };
  130589. static long _vq_quantlist__44c4_s_p4_0[] = {
  130590. 4,
  130591. 3,
  130592. 5,
  130593. 2,
  130594. 6,
  130595. 1,
  130596. 7,
  130597. 0,
  130598. 8,
  130599. };
  130600. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130601. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130602. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130603. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130604. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130605. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0,
  130607. };
  130608. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130609. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130610. };
  130611. static long _vq_quantmap__44c4_s_p4_0[] = {
  130612. 7, 5, 3, 1, 0, 2, 4, 6,
  130613. 8,
  130614. };
  130615. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130616. _vq_quantthresh__44c4_s_p4_0,
  130617. _vq_quantmap__44c4_s_p4_0,
  130618. 9,
  130619. 9
  130620. };
  130621. static static_codebook _44c4_s_p4_0 = {
  130622. 2, 81,
  130623. _vq_lengthlist__44c4_s_p4_0,
  130624. 1, -531628032, 1611661312, 4, 0,
  130625. _vq_quantlist__44c4_s_p4_0,
  130626. NULL,
  130627. &_vq_auxt__44c4_s_p4_0,
  130628. NULL,
  130629. 0
  130630. };
  130631. static long _vq_quantlist__44c4_s_p5_0[] = {
  130632. 4,
  130633. 3,
  130634. 5,
  130635. 2,
  130636. 6,
  130637. 1,
  130638. 7,
  130639. 0,
  130640. 8,
  130641. };
  130642. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130643. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130644. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130645. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130646. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130647. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130648. 10,
  130649. };
  130650. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130651. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130652. };
  130653. static long _vq_quantmap__44c4_s_p5_0[] = {
  130654. 7, 5, 3, 1, 0, 2, 4, 6,
  130655. 8,
  130656. };
  130657. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130658. _vq_quantthresh__44c4_s_p5_0,
  130659. _vq_quantmap__44c4_s_p5_0,
  130660. 9,
  130661. 9
  130662. };
  130663. static static_codebook _44c4_s_p5_0 = {
  130664. 2, 81,
  130665. _vq_lengthlist__44c4_s_p5_0,
  130666. 1, -531628032, 1611661312, 4, 0,
  130667. _vq_quantlist__44c4_s_p5_0,
  130668. NULL,
  130669. &_vq_auxt__44c4_s_p5_0,
  130670. NULL,
  130671. 0
  130672. };
  130673. static long _vq_quantlist__44c4_s_p6_0[] = {
  130674. 8,
  130675. 7,
  130676. 9,
  130677. 6,
  130678. 10,
  130679. 5,
  130680. 11,
  130681. 4,
  130682. 12,
  130683. 3,
  130684. 13,
  130685. 2,
  130686. 14,
  130687. 1,
  130688. 15,
  130689. 0,
  130690. 16,
  130691. };
  130692. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130693. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130694. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130695. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130696. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130697. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130698. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130699. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130700. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130701. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130702. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130703. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130704. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130705. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130706. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130707. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130708. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130709. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130711. 13,
  130712. };
  130713. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130714. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130715. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130716. };
  130717. static long _vq_quantmap__44c4_s_p6_0[] = {
  130718. 15, 13, 11, 9, 7, 5, 3, 1,
  130719. 0, 2, 4, 6, 8, 10, 12, 14,
  130720. 16,
  130721. };
  130722. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130723. _vq_quantthresh__44c4_s_p6_0,
  130724. _vq_quantmap__44c4_s_p6_0,
  130725. 17,
  130726. 17
  130727. };
  130728. static static_codebook _44c4_s_p6_0 = {
  130729. 2, 289,
  130730. _vq_lengthlist__44c4_s_p6_0,
  130731. 1, -529530880, 1611661312, 5, 0,
  130732. _vq_quantlist__44c4_s_p6_0,
  130733. NULL,
  130734. &_vq_auxt__44c4_s_p6_0,
  130735. NULL,
  130736. 0
  130737. };
  130738. static long _vq_quantlist__44c4_s_p7_0[] = {
  130739. 1,
  130740. 0,
  130741. 2,
  130742. };
  130743. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130744. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130745. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130746. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130747. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130748. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130749. 10,
  130750. };
  130751. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130752. -5.5, 5.5,
  130753. };
  130754. static long _vq_quantmap__44c4_s_p7_0[] = {
  130755. 1, 0, 2,
  130756. };
  130757. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130758. _vq_quantthresh__44c4_s_p7_0,
  130759. _vq_quantmap__44c4_s_p7_0,
  130760. 3,
  130761. 3
  130762. };
  130763. static static_codebook _44c4_s_p7_0 = {
  130764. 4, 81,
  130765. _vq_lengthlist__44c4_s_p7_0,
  130766. 1, -529137664, 1618345984, 2, 0,
  130767. _vq_quantlist__44c4_s_p7_0,
  130768. NULL,
  130769. &_vq_auxt__44c4_s_p7_0,
  130770. NULL,
  130771. 0
  130772. };
  130773. static long _vq_quantlist__44c4_s_p7_1[] = {
  130774. 5,
  130775. 4,
  130776. 6,
  130777. 3,
  130778. 7,
  130779. 2,
  130780. 8,
  130781. 1,
  130782. 9,
  130783. 0,
  130784. 10,
  130785. };
  130786. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130787. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130788. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130789. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130790. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130791. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130792. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130793. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130794. 10,10,10, 8, 8, 8, 8, 9, 9,
  130795. };
  130796. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130797. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130798. 3.5, 4.5,
  130799. };
  130800. static long _vq_quantmap__44c4_s_p7_1[] = {
  130801. 9, 7, 5, 3, 1, 0, 2, 4,
  130802. 6, 8, 10,
  130803. };
  130804. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130805. _vq_quantthresh__44c4_s_p7_1,
  130806. _vq_quantmap__44c4_s_p7_1,
  130807. 11,
  130808. 11
  130809. };
  130810. static static_codebook _44c4_s_p7_1 = {
  130811. 2, 121,
  130812. _vq_lengthlist__44c4_s_p7_1,
  130813. 1, -531365888, 1611661312, 4, 0,
  130814. _vq_quantlist__44c4_s_p7_1,
  130815. NULL,
  130816. &_vq_auxt__44c4_s_p7_1,
  130817. NULL,
  130818. 0
  130819. };
  130820. static long _vq_quantlist__44c4_s_p8_0[] = {
  130821. 6,
  130822. 5,
  130823. 7,
  130824. 4,
  130825. 8,
  130826. 3,
  130827. 9,
  130828. 2,
  130829. 10,
  130830. 1,
  130831. 11,
  130832. 0,
  130833. 12,
  130834. };
  130835. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130836. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130837. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130838. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130839. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130840. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130841. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130842. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130843. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130844. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130845. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130846. 0,13,12,12,12,12,12,13,13,
  130847. };
  130848. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130849. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130850. 12.5, 17.5, 22.5, 27.5,
  130851. };
  130852. static long _vq_quantmap__44c4_s_p8_0[] = {
  130853. 11, 9, 7, 5, 3, 1, 0, 2,
  130854. 4, 6, 8, 10, 12,
  130855. };
  130856. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130857. _vq_quantthresh__44c4_s_p8_0,
  130858. _vq_quantmap__44c4_s_p8_0,
  130859. 13,
  130860. 13
  130861. };
  130862. static static_codebook _44c4_s_p8_0 = {
  130863. 2, 169,
  130864. _vq_lengthlist__44c4_s_p8_0,
  130865. 1, -526516224, 1616117760, 4, 0,
  130866. _vq_quantlist__44c4_s_p8_0,
  130867. NULL,
  130868. &_vq_auxt__44c4_s_p8_0,
  130869. NULL,
  130870. 0
  130871. };
  130872. static long _vq_quantlist__44c4_s_p8_1[] = {
  130873. 2,
  130874. 1,
  130875. 3,
  130876. 0,
  130877. 4,
  130878. };
  130879. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130880. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130881. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130882. };
  130883. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130884. -1.5, -0.5, 0.5, 1.5,
  130885. };
  130886. static long _vq_quantmap__44c4_s_p8_1[] = {
  130887. 3, 1, 0, 2, 4,
  130888. };
  130889. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130890. _vq_quantthresh__44c4_s_p8_1,
  130891. _vq_quantmap__44c4_s_p8_1,
  130892. 5,
  130893. 5
  130894. };
  130895. static static_codebook _44c4_s_p8_1 = {
  130896. 2, 25,
  130897. _vq_lengthlist__44c4_s_p8_1,
  130898. 1, -533725184, 1611661312, 3, 0,
  130899. _vq_quantlist__44c4_s_p8_1,
  130900. NULL,
  130901. &_vq_auxt__44c4_s_p8_1,
  130902. NULL,
  130903. 0
  130904. };
  130905. static long _vq_quantlist__44c4_s_p9_0[] = {
  130906. 6,
  130907. 5,
  130908. 7,
  130909. 4,
  130910. 8,
  130911. 3,
  130912. 9,
  130913. 2,
  130914. 10,
  130915. 1,
  130916. 11,
  130917. 0,
  130918. 12,
  130919. };
  130920. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130921. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130922. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130923. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130924. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130925. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130926. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130927. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130928. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130929. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130930. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130931. 12,12,12,12,12,12,12,12,12,
  130932. };
  130933. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130934. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130935. 787.5, 1102.5, 1417.5, 1732.5,
  130936. };
  130937. static long _vq_quantmap__44c4_s_p9_0[] = {
  130938. 11, 9, 7, 5, 3, 1, 0, 2,
  130939. 4, 6, 8, 10, 12,
  130940. };
  130941. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130942. _vq_quantthresh__44c4_s_p9_0,
  130943. _vq_quantmap__44c4_s_p9_0,
  130944. 13,
  130945. 13
  130946. };
  130947. static static_codebook _44c4_s_p9_0 = {
  130948. 2, 169,
  130949. _vq_lengthlist__44c4_s_p9_0,
  130950. 1, -513964032, 1628680192, 4, 0,
  130951. _vq_quantlist__44c4_s_p9_0,
  130952. NULL,
  130953. &_vq_auxt__44c4_s_p9_0,
  130954. NULL,
  130955. 0
  130956. };
  130957. static long _vq_quantlist__44c4_s_p9_1[] = {
  130958. 7,
  130959. 6,
  130960. 8,
  130961. 5,
  130962. 9,
  130963. 4,
  130964. 10,
  130965. 3,
  130966. 11,
  130967. 2,
  130968. 12,
  130969. 1,
  130970. 13,
  130971. 0,
  130972. 14,
  130973. };
  130974. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130975. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130976. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130977. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130978. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130979. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130980. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130981. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130982. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130983. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130984. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130985. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130986. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130987. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130988. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130989. 15,
  130990. };
  130991. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130992. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130993. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130994. };
  130995. static long _vq_quantmap__44c4_s_p9_1[] = {
  130996. 13, 11, 9, 7, 5, 3, 1, 0,
  130997. 2, 4, 6, 8, 10, 12, 14,
  130998. };
  130999. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131000. _vq_quantthresh__44c4_s_p9_1,
  131001. _vq_quantmap__44c4_s_p9_1,
  131002. 15,
  131003. 15
  131004. };
  131005. static static_codebook _44c4_s_p9_1 = {
  131006. 2, 225,
  131007. _vq_lengthlist__44c4_s_p9_1,
  131008. 1, -520986624, 1620377600, 4, 0,
  131009. _vq_quantlist__44c4_s_p9_1,
  131010. NULL,
  131011. &_vq_auxt__44c4_s_p9_1,
  131012. NULL,
  131013. 0
  131014. };
  131015. static long _vq_quantlist__44c4_s_p9_2[] = {
  131016. 10,
  131017. 9,
  131018. 11,
  131019. 8,
  131020. 12,
  131021. 7,
  131022. 13,
  131023. 6,
  131024. 14,
  131025. 5,
  131026. 15,
  131027. 4,
  131028. 16,
  131029. 3,
  131030. 17,
  131031. 2,
  131032. 18,
  131033. 1,
  131034. 19,
  131035. 0,
  131036. 20,
  131037. };
  131038. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131039. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131040. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131041. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131042. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131043. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131044. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131045. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131046. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131047. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131048. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131049. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131050. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131051. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131052. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131053. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131054. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131055. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131056. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131057. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131058. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131059. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131060. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131061. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131062. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131063. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131064. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131065. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131066. 10,10,10,10,10,10,10,10,10,
  131067. };
  131068. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131069. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131070. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131071. 6.5, 7.5, 8.5, 9.5,
  131072. };
  131073. static long _vq_quantmap__44c4_s_p9_2[] = {
  131074. 19, 17, 15, 13, 11, 9, 7, 5,
  131075. 3, 1, 0, 2, 4, 6, 8, 10,
  131076. 12, 14, 16, 18, 20,
  131077. };
  131078. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131079. _vq_quantthresh__44c4_s_p9_2,
  131080. _vq_quantmap__44c4_s_p9_2,
  131081. 21,
  131082. 21
  131083. };
  131084. static static_codebook _44c4_s_p9_2 = {
  131085. 2, 441,
  131086. _vq_lengthlist__44c4_s_p9_2,
  131087. 1, -529268736, 1611661312, 5, 0,
  131088. _vq_quantlist__44c4_s_p9_2,
  131089. NULL,
  131090. &_vq_auxt__44c4_s_p9_2,
  131091. NULL,
  131092. 0
  131093. };
  131094. static long _huff_lengthlist__44c4_s_short[] = {
  131095. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131096. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131097. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131098. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131099. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131100. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131101. 7, 9,12,17,
  131102. };
  131103. static static_codebook _huff_book__44c4_s_short = {
  131104. 2, 100,
  131105. _huff_lengthlist__44c4_s_short,
  131106. 0, 0, 0, 0, 0,
  131107. NULL,
  131108. NULL,
  131109. NULL,
  131110. NULL,
  131111. 0
  131112. };
  131113. static long _huff_lengthlist__44c5_s_long[] = {
  131114. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131115. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131116. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131117. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131118. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131119. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131120. 9, 8, 7, 7,
  131121. };
  131122. static static_codebook _huff_book__44c5_s_long = {
  131123. 2, 100,
  131124. _huff_lengthlist__44c5_s_long,
  131125. 0, 0, 0, 0, 0,
  131126. NULL,
  131127. NULL,
  131128. NULL,
  131129. NULL,
  131130. 0
  131131. };
  131132. static long _vq_quantlist__44c5_s_p1_0[] = {
  131133. 1,
  131134. 0,
  131135. 2,
  131136. };
  131137. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131138. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131139. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131144. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131149. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131184. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131189. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131194. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131230. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131235. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131240. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0,
  131549. };
  131550. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131551. -0.5, 0.5,
  131552. };
  131553. static long _vq_quantmap__44c5_s_p1_0[] = {
  131554. 1, 0, 2,
  131555. };
  131556. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131557. _vq_quantthresh__44c5_s_p1_0,
  131558. _vq_quantmap__44c5_s_p1_0,
  131559. 3,
  131560. 3
  131561. };
  131562. static static_codebook _44c5_s_p1_0 = {
  131563. 8, 6561,
  131564. _vq_lengthlist__44c5_s_p1_0,
  131565. 1, -535822336, 1611661312, 2, 0,
  131566. _vq_quantlist__44c5_s_p1_0,
  131567. NULL,
  131568. &_vq_auxt__44c5_s_p1_0,
  131569. NULL,
  131570. 0
  131571. };
  131572. static long _vq_quantlist__44c5_s_p2_0[] = {
  131573. 2,
  131574. 1,
  131575. 3,
  131576. 0,
  131577. 4,
  131578. };
  131579. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131580. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131581. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131582. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131583. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131584. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131590. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131591. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131592. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131598. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131599. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131606. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131607. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131620. };
  131621. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131622. -1.5, -0.5, 0.5, 1.5,
  131623. };
  131624. static long _vq_quantmap__44c5_s_p2_0[] = {
  131625. 3, 1, 0, 2, 4,
  131626. };
  131627. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131628. _vq_quantthresh__44c5_s_p2_0,
  131629. _vq_quantmap__44c5_s_p2_0,
  131630. 5,
  131631. 5
  131632. };
  131633. static static_codebook _44c5_s_p2_0 = {
  131634. 4, 625,
  131635. _vq_lengthlist__44c5_s_p2_0,
  131636. 1, -533725184, 1611661312, 3, 0,
  131637. _vq_quantlist__44c5_s_p2_0,
  131638. NULL,
  131639. &_vq_auxt__44c5_s_p2_0,
  131640. NULL,
  131641. 0
  131642. };
  131643. static long _vq_quantlist__44c5_s_p3_0[] = {
  131644. 2,
  131645. 1,
  131646. 3,
  131647. 0,
  131648. 4,
  131649. };
  131650. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131651. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131691. };
  131692. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131693. -1.5, -0.5, 0.5, 1.5,
  131694. };
  131695. static long _vq_quantmap__44c5_s_p3_0[] = {
  131696. 3, 1, 0, 2, 4,
  131697. };
  131698. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131699. _vq_quantthresh__44c5_s_p3_0,
  131700. _vq_quantmap__44c5_s_p3_0,
  131701. 5,
  131702. 5
  131703. };
  131704. static static_codebook _44c5_s_p3_0 = {
  131705. 4, 625,
  131706. _vq_lengthlist__44c5_s_p3_0,
  131707. 1, -533725184, 1611661312, 3, 0,
  131708. _vq_quantlist__44c5_s_p3_0,
  131709. NULL,
  131710. &_vq_auxt__44c5_s_p3_0,
  131711. NULL,
  131712. 0
  131713. };
  131714. static long _vq_quantlist__44c5_s_p4_0[] = {
  131715. 4,
  131716. 3,
  131717. 5,
  131718. 2,
  131719. 6,
  131720. 1,
  131721. 7,
  131722. 0,
  131723. 8,
  131724. };
  131725. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131726. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131727. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131728. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131729. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131730. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0,
  131732. };
  131733. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131734. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131735. };
  131736. static long _vq_quantmap__44c5_s_p4_0[] = {
  131737. 7, 5, 3, 1, 0, 2, 4, 6,
  131738. 8,
  131739. };
  131740. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131741. _vq_quantthresh__44c5_s_p4_0,
  131742. _vq_quantmap__44c5_s_p4_0,
  131743. 9,
  131744. 9
  131745. };
  131746. static static_codebook _44c5_s_p4_0 = {
  131747. 2, 81,
  131748. _vq_lengthlist__44c5_s_p4_0,
  131749. 1, -531628032, 1611661312, 4, 0,
  131750. _vq_quantlist__44c5_s_p4_0,
  131751. NULL,
  131752. &_vq_auxt__44c5_s_p4_0,
  131753. NULL,
  131754. 0
  131755. };
  131756. static long _vq_quantlist__44c5_s_p5_0[] = {
  131757. 4,
  131758. 3,
  131759. 5,
  131760. 2,
  131761. 6,
  131762. 1,
  131763. 7,
  131764. 0,
  131765. 8,
  131766. };
  131767. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131768. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131769. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131770. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131771. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131772. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131773. 10,
  131774. };
  131775. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131776. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131777. };
  131778. static long _vq_quantmap__44c5_s_p5_0[] = {
  131779. 7, 5, 3, 1, 0, 2, 4, 6,
  131780. 8,
  131781. };
  131782. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131783. _vq_quantthresh__44c5_s_p5_0,
  131784. _vq_quantmap__44c5_s_p5_0,
  131785. 9,
  131786. 9
  131787. };
  131788. static static_codebook _44c5_s_p5_0 = {
  131789. 2, 81,
  131790. _vq_lengthlist__44c5_s_p5_0,
  131791. 1, -531628032, 1611661312, 4, 0,
  131792. _vq_quantlist__44c5_s_p5_0,
  131793. NULL,
  131794. &_vq_auxt__44c5_s_p5_0,
  131795. NULL,
  131796. 0
  131797. };
  131798. static long _vq_quantlist__44c5_s_p6_0[] = {
  131799. 8,
  131800. 7,
  131801. 9,
  131802. 6,
  131803. 10,
  131804. 5,
  131805. 11,
  131806. 4,
  131807. 12,
  131808. 3,
  131809. 13,
  131810. 2,
  131811. 14,
  131812. 1,
  131813. 15,
  131814. 0,
  131815. 16,
  131816. };
  131817. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131818. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131819. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131820. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131821. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131822. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131823. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131824. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131825. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131826. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131827. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131828. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131829. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131830. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131831. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131832. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131833. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131834. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131836. 13,
  131837. };
  131838. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131839. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131840. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131841. };
  131842. static long _vq_quantmap__44c5_s_p6_0[] = {
  131843. 15, 13, 11, 9, 7, 5, 3, 1,
  131844. 0, 2, 4, 6, 8, 10, 12, 14,
  131845. 16,
  131846. };
  131847. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131848. _vq_quantthresh__44c5_s_p6_0,
  131849. _vq_quantmap__44c5_s_p6_0,
  131850. 17,
  131851. 17
  131852. };
  131853. static static_codebook _44c5_s_p6_0 = {
  131854. 2, 289,
  131855. _vq_lengthlist__44c5_s_p6_0,
  131856. 1, -529530880, 1611661312, 5, 0,
  131857. _vq_quantlist__44c5_s_p6_0,
  131858. NULL,
  131859. &_vq_auxt__44c5_s_p6_0,
  131860. NULL,
  131861. 0
  131862. };
  131863. static long _vq_quantlist__44c5_s_p7_0[] = {
  131864. 1,
  131865. 0,
  131866. 2,
  131867. };
  131868. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131869. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131870. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131871. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131872. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131873. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131874. 10,
  131875. };
  131876. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131877. -5.5, 5.5,
  131878. };
  131879. static long _vq_quantmap__44c5_s_p7_0[] = {
  131880. 1, 0, 2,
  131881. };
  131882. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131883. _vq_quantthresh__44c5_s_p7_0,
  131884. _vq_quantmap__44c5_s_p7_0,
  131885. 3,
  131886. 3
  131887. };
  131888. static static_codebook _44c5_s_p7_0 = {
  131889. 4, 81,
  131890. _vq_lengthlist__44c5_s_p7_0,
  131891. 1, -529137664, 1618345984, 2, 0,
  131892. _vq_quantlist__44c5_s_p7_0,
  131893. NULL,
  131894. &_vq_auxt__44c5_s_p7_0,
  131895. NULL,
  131896. 0
  131897. };
  131898. static long _vq_quantlist__44c5_s_p7_1[] = {
  131899. 5,
  131900. 4,
  131901. 6,
  131902. 3,
  131903. 7,
  131904. 2,
  131905. 8,
  131906. 1,
  131907. 9,
  131908. 0,
  131909. 10,
  131910. };
  131911. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131912. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131913. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131914. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131915. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131916. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131917. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131918. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131919. 10,10,10, 8, 8, 8, 8, 8, 8,
  131920. };
  131921. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131922. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131923. 3.5, 4.5,
  131924. };
  131925. static long _vq_quantmap__44c5_s_p7_1[] = {
  131926. 9, 7, 5, 3, 1, 0, 2, 4,
  131927. 6, 8, 10,
  131928. };
  131929. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131930. _vq_quantthresh__44c5_s_p7_1,
  131931. _vq_quantmap__44c5_s_p7_1,
  131932. 11,
  131933. 11
  131934. };
  131935. static static_codebook _44c5_s_p7_1 = {
  131936. 2, 121,
  131937. _vq_lengthlist__44c5_s_p7_1,
  131938. 1, -531365888, 1611661312, 4, 0,
  131939. _vq_quantlist__44c5_s_p7_1,
  131940. NULL,
  131941. &_vq_auxt__44c5_s_p7_1,
  131942. NULL,
  131943. 0
  131944. };
  131945. static long _vq_quantlist__44c5_s_p8_0[] = {
  131946. 6,
  131947. 5,
  131948. 7,
  131949. 4,
  131950. 8,
  131951. 3,
  131952. 9,
  131953. 2,
  131954. 10,
  131955. 1,
  131956. 11,
  131957. 0,
  131958. 12,
  131959. };
  131960. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131961. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131962. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131963. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131964. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131965. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131966. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131967. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131968. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131969. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131970. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131971. 0,12,12,12,12,12,12,13,13,
  131972. };
  131973. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131974. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131975. 12.5, 17.5, 22.5, 27.5,
  131976. };
  131977. static long _vq_quantmap__44c5_s_p8_0[] = {
  131978. 11, 9, 7, 5, 3, 1, 0, 2,
  131979. 4, 6, 8, 10, 12,
  131980. };
  131981. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131982. _vq_quantthresh__44c5_s_p8_0,
  131983. _vq_quantmap__44c5_s_p8_0,
  131984. 13,
  131985. 13
  131986. };
  131987. static static_codebook _44c5_s_p8_0 = {
  131988. 2, 169,
  131989. _vq_lengthlist__44c5_s_p8_0,
  131990. 1, -526516224, 1616117760, 4, 0,
  131991. _vq_quantlist__44c5_s_p8_0,
  131992. NULL,
  131993. &_vq_auxt__44c5_s_p8_0,
  131994. NULL,
  131995. 0
  131996. };
  131997. static long _vq_quantlist__44c5_s_p8_1[] = {
  131998. 2,
  131999. 1,
  132000. 3,
  132001. 0,
  132002. 4,
  132003. };
  132004. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132005. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132006. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132007. };
  132008. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132009. -1.5, -0.5, 0.5, 1.5,
  132010. };
  132011. static long _vq_quantmap__44c5_s_p8_1[] = {
  132012. 3, 1, 0, 2, 4,
  132013. };
  132014. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132015. _vq_quantthresh__44c5_s_p8_1,
  132016. _vq_quantmap__44c5_s_p8_1,
  132017. 5,
  132018. 5
  132019. };
  132020. static static_codebook _44c5_s_p8_1 = {
  132021. 2, 25,
  132022. _vq_lengthlist__44c5_s_p8_1,
  132023. 1, -533725184, 1611661312, 3, 0,
  132024. _vq_quantlist__44c5_s_p8_1,
  132025. NULL,
  132026. &_vq_auxt__44c5_s_p8_1,
  132027. NULL,
  132028. 0
  132029. };
  132030. static long _vq_quantlist__44c5_s_p9_0[] = {
  132031. 7,
  132032. 6,
  132033. 8,
  132034. 5,
  132035. 9,
  132036. 4,
  132037. 10,
  132038. 3,
  132039. 11,
  132040. 2,
  132041. 12,
  132042. 1,
  132043. 13,
  132044. 0,
  132045. 14,
  132046. };
  132047. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132048. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132049. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132050. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132051. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132052. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132053. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132054. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132055. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132056. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132057. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132058. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132059. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132060. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132061. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132062. 12,
  132063. };
  132064. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132065. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132066. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132067. };
  132068. static long _vq_quantmap__44c5_s_p9_0[] = {
  132069. 13, 11, 9, 7, 5, 3, 1, 0,
  132070. 2, 4, 6, 8, 10, 12, 14,
  132071. };
  132072. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132073. _vq_quantthresh__44c5_s_p9_0,
  132074. _vq_quantmap__44c5_s_p9_0,
  132075. 15,
  132076. 15
  132077. };
  132078. static static_codebook _44c5_s_p9_0 = {
  132079. 2, 225,
  132080. _vq_lengthlist__44c5_s_p9_0,
  132081. 1, -512522752, 1628852224, 4, 0,
  132082. _vq_quantlist__44c5_s_p9_0,
  132083. NULL,
  132084. &_vq_auxt__44c5_s_p9_0,
  132085. NULL,
  132086. 0
  132087. };
  132088. static long _vq_quantlist__44c5_s_p9_1[] = {
  132089. 8,
  132090. 7,
  132091. 9,
  132092. 6,
  132093. 10,
  132094. 5,
  132095. 11,
  132096. 4,
  132097. 12,
  132098. 3,
  132099. 13,
  132100. 2,
  132101. 14,
  132102. 1,
  132103. 15,
  132104. 0,
  132105. 16,
  132106. };
  132107. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132108. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132109. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132110. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132111. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132112. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132113. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132114. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132115. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132116. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132117. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132118. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132119. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132120. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132121. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132122. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132123. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132124. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132125. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132126. 15,
  132127. };
  132128. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132129. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132130. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132131. };
  132132. static long _vq_quantmap__44c5_s_p9_1[] = {
  132133. 15, 13, 11, 9, 7, 5, 3, 1,
  132134. 0, 2, 4, 6, 8, 10, 12, 14,
  132135. 16,
  132136. };
  132137. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132138. _vq_quantthresh__44c5_s_p9_1,
  132139. _vq_quantmap__44c5_s_p9_1,
  132140. 17,
  132141. 17
  132142. };
  132143. static static_codebook _44c5_s_p9_1 = {
  132144. 2, 289,
  132145. _vq_lengthlist__44c5_s_p9_1,
  132146. 1, -520814592, 1620377600, 5, 0,
  132147. _vq_quantlist__44c5_s_p9_1,
  132148. NULL,
  132149. &_vq_auxt__44c5_s_p9_1,
  132150. NULL,
  132151. 0
  132152. };
  132153. static long _vq_quantlist__44c5_s_p9_2[] = {
  132154. 10,
  132155. 9,
  132156. 11,
  132157. 8,
  132158. 12,
  132159. 7,
  132160. 13,
  132161. 6,
  132162. 14,
  132163. 5,
  132164. 15,
  132165. 4,
  132166. 16,
  132167. 3,
  132168. 17,
  132169. 2,
  132170. 18,
  132171. 1,
  132172. 19,
  132173. 0,
  132174. 20,
  132175. };
  132176. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132177. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132178. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132179. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132180. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132181. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132182. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132183. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132184. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132185. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132186. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132187. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132188. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132189. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132190. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132191. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132192. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132193. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132194. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132195. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132196. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132197. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132198. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132199. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132200. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132201. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132202. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132203. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132204. 10,10,10,10,10,10,10,10,10,
  132205. };
  132206. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132207. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132208. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132209. 6.5, 7.5, 8.5, 9.5,
  132210. };
  132211. static long _vq_quantmap__44c5_s_p9_2[] = {
  132212. 19, 17, 15, 13, 11, 9, 7, 5,
  132213. 3, 1, 0, 2, 4, 6, 8, 10,
  132214. 12, 14, 16, 18, 20,
  132215. };
  132216. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132217. _vq_quantthresh__44c5_s_p9_2,
  132218. _vq_quantmap__44c5_s_p9_2,
  132219. 21,
  132220. 21
  132221. };
  132222. static static_codebook _44c5_s_p9_2 = {
  132223. 2, 441,
  132224. _vq_lengthlist__44c5_s_p9_2,
  132225. 1, -529268736, 1611661312, 5, 0,
  132226. _vq_quantlist__44c5_s_p9_2,
  132227. NULL,
  132228. &_vq_auxt__44c5_s_p9_2,
  132229. NULL,
  132230. 0
  132231. };
  132232. static long _huff_lengthlist__44c5_s_short[] = {
  132233. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132234. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132235. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132236. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132237. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132238. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132239. 6, 8,11,16,
  132240. };
  132241. static static_codebook _huff_book__44c5_s_short = {
  132242. 2, 100,
  132243. _huff_lengthlist__44c5_s_short,
  132244. 0, 0, 0, 0, 0,
  132245. NULL,
  132246. NULL,
  132247. NULL,
  132248. NULL,
  132249. 0
  132250. };
  132251. static long _huff_lengthlist__44c6_s_long[] = {
  132252. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132253. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132254. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132255. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132256. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132257. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132258. 11,10,10,12,
  132259. };
  132260. static static_codebook _huff_book__44c6_s_long = {
  132261. 2, 100,
  132262. _huff_lengthlist__44c6_s_long,
  132263. 0, 0, 0, 0, 0,
  132264. NULL,
  132265. NULL,
  132266. NULL,
  132267. NULL,
  132268. 0
  132269. };
  132270. static long _vq_quantlist__44c6_s_p1_0[] = {
  132271. 1,
  132272. 0,
  132273. 2,
  132274. };
  132275. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132276. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132277. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132278. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132279. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132280. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132281. 8,
  132282. };
  132283. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132284. -0.5, 0.5,
  132285. };
  132286. static long _vq_quantmap__44c6_s_p1_0[] = {
  132287. 1, 0, 2,
  132288. };
  132289. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132290. _vq_quantthresh__44c6_s_p1_0,
  132291. _vq_quantmap__44c6_s_p1_0,
  132292. 3,
  132293. 3
  132294. };
  132295. static static_codebook _44c6_s_p1_0 = {
  132296. 4, 81,
  132297. _vq_lengthlist__44c6_s_p1_0,
  132298. 1, -535822336, 1611661312, 2, 0,
  132299. _vq_quantlist__44c6_s_p1_0,
  132300. NULL,
  132301. &_vq_auxt__44c6_s_p1_0,
  132302. NULL,
  132303. 0
  132304. };
  132305. static long _vq_quantlist__44c6_s_p2_0[] = {
  132306. 2,
  132307. 1,
  132308. 3,
  132309. 0,
  132310. 4,
  132311. };
  132312. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132313. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132314. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132315. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132316. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132317. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132318. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132319. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132320. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132322. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132323. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132324. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132325. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132326. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132327. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132328. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132331. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132332. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132333. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132334. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132335. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132336. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132339. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132340. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132341. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132342. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132343. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132344. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132349. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132350. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132351. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132352. 13,
  132353. };
  132354. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132355. -1.5, -0.5, 0.5, 1.5,
  132356. };
  132357. static long _vq_quantmap__44c6_s_p2_0[] = {
  132358. 3, 1, 0, 2, 4,
  132359. };
  132360. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132361. _vq_quantthresh__44c6_s_p2_0,
  132362. _vq_quantmap__44c6_s_p2_0,
  132363. 5,
  132364. 5
  132365. };
  132366. static static_codebook _44c6_s_p2_0 = {
  132367. 4, 625,
  132368. _vq_lengthlist__44c6_s_p2_0,
  132369. 1, -533725184, 1611661312, 3, 0,
  132370. _vq_quantlist__44c6_s_p2_0,
  132371. NULL,
  132372. &_vq_auxt__44c6_s_p2_0,
  132373. NULL,
  132374. 0
  132375. };
  132376. static long _vq_quantlist__44c6_s_p3_0[] = {
  132377. 4,
  132378. 3,
  132379. 5,
  132380. 2,
  132381. 6,
  132382. 1,
  132383. 7,
  132384. 0,
  132385. 8,
  132386. };
  132387. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132388. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132389. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132390. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132391. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0,
  132394. };
  132395. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132396. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132397. };
  132398. static long _vq_quantmap__44c6_s_p3_0[] = {
  132399. 7, 5, 3, 1, 0, 2, 4, 6,
  132400. 8,
  132401. };
  132402. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132403. _vq_quantthresh__44c6_s_p3_0,
  132404. _vq_quantmap__44c6_s_p3_0,
  132405. 9,
  132406. 9
  132407. };
  132408. static static_codebook _44c6_s_p3_0 = {
  132409. 2, 81,
  132410. _vq_lengthlist__44c6_s_p3_0,
  132411. 1, -531628032, 1611661312, 4, 0,
  132412. _vq_quantlist__44c6_s_p3_0,
  132413. NULL,
  132414. &_vq_auxt__44c6_s_p3_0,
  132415. NULL,
  132416. 0
  132417. };
  132418. static long _vq_quantlist__44c6_s_p4_0[] = {
  132419. 8,
  132420. 7,
  132421. 9,
  132422. 6,
  132423. 10,
  132424. 5,
  132425. 11,
  132426. 4,
  132427. 12,
  132428. 3,
  132429. 13,
  132430. 2,
  132431. 14,
  132432. 1,
  132433. 15,
  132434. 0,
  132435. 16,
  132436. };
  132437. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132438. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132439. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132440. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132441. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132442. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132443. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132444. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132445. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132446. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132447. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132456. 0,
  132457. };
  132458. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132459. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132460. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132461. };
  132462. static long _vq_quantmap__44c6_s_p4_0[] = {
  132463. 15, 13, 11, 9, 7, 5, 3, 1,
  132464. 0, 2, 4, 6, 8, 10, 12, 14,
  132465. 16,
  132466. };
  132467. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132468. _vq_quantthresh__44c6_s_p4_0,
  132469. _vq_quantmap__44c6_s_p4_0,
  132470. 17,
  132471. 17
  132472. };
  132473. static static_codebook _44c6_s_p4_0 = {
  132474. 2, 289,
  132475. _vq_lengthlist__44c6_s_p4_0,
  132476. 1, -529530880, 1611661312, 5, 0,
  132477. _vq_quantlist__44c6_s_p4_0,
  132478. NULL,
  132479. &_vq_auxt__44c6_s_p4_0,
  132480. NULL,
  132481. 0
  132482. };
  132483. static long _vq_quantlist__44c6_s_p5_0[] = {
  132484. 1,
  132485. 0,
  132486. 2,
  132487. };
  132488. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132489. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132490. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132491. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132492. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132493. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132494. 12,
  132495. };
  132496. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132497. -5.5, 5.5,
  132498. };
  132499. static long _vq_quantmap__44c6_s_p5_0[] = {
  132500. 1, 0, 2,
  132501. };
  132502. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132503. _vq_quantthresh__44c6_s_p5_0,
  132504. _vq_quantmap__44c6_s_p5_0,
  132505. 3,
  132506. 3
  132507. };
  132508. static static_codebook _44c6_s_p5_0 = {
  132509. 4, 81,
  132510. _vq_lengthlist__44c6_s_p5_0,
  132511. 1, -529137664, 1618345984, 2, 0,
  132512. _vq_quantlist__44c6_s_p5_0,
  132513. NULL,
  132514. &_vq_auxt__44c6_s_p5_0,
  132515. NULL,
  132516. 0
  132517. };
  132518. static long _vq_quantlist__44c6_s_p5_1[] = {
  132519. 5,
  132520. 4,
  132521. 6,
  132522. 3,
  132523. 7,
  132524. 2,
  132525. 8,
  132526. 1,
  132527. 9,
  132528. 0,
  132529. 10,
  132530. };
  132531. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132532. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132533. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132534. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132535. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132536. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132537. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132538. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132539. 11,10,10, 7, 7, 8, 8, 8, 8,
  132540. };
  132541. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132542. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132543. 3.5, 4.5,
  132544. };
  132545. static long _vq_quantmap__44c6_s_p5_1[] = {
  132546. 9, 7, 5, 3, 1, 0, 2, 4,
  132547. 6, 8, 10,
  132548. };
  132549. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132550. _vq_quantthresh__44c6_s_p5_1,
  132551. _vq_quantmap__44c6_s_p5_1,
  132552. 11,
  132553. 11
  132554. };
  132555. static static_codebook _44c6_s_p5_1 = {
  132556. 2, 121,
  132557. _vq_lengthlist__44c6_s_p5_1,
  132558. 1, -531365888, 1611661312, 4, 0,
  132559. _vq_quantlist__44c6_s_p5_1,
  132560. NULL,
  132561. &_vq_auxt__44c6_s_p5_1,
  132562. NULL,
  132563. 0
  132564. };
  132565. static long _vq_quantlist__44c6_s_p6_0[] = {
  132566. 6,
  132567. 5,
  132568. 7,
  132569. 4,
  132570. 8,
  132571. 3,
  132572. 9,
  132573. 2,
  132574. 10,
  132575. 1,
  132576. 11,
  132577. 0,
  132578. 12,
  132579. };
  132580. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132581. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132582. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132583. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132584. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132585. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132586. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. };
  132593. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132594. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132595. 12.5, 17.5, 22.5, 27.5,
  132596. };
  132597. static long _vq_quantmap__44c6_s_p6_0[] = {
  132598. 11, 9, 7, 5, 3, 1, 0, 2,
  132599. 4, 6, 8, 10, 12,
  132600. };
  132601. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132602. _vq_quantthresh__44c6_s_p6_0,
  132603. _vq_quantmap__44c6_s_p6_0,
  132604. 13,
  132605. 13
  132606. };
  132607. static static_codebook _44c6_s_p6_0 = {
  132608. 2, 169,
  132609. _vq_lengthlist__44c6_s_p6_0,
  132610. 1, -526516224, 1616117760, 4, 0,
  132611. _vq_quantlist__44c6_s_p6_0,
  132612. NULL,
  132613. &_vq_auxt__44c6_s_p6_0,
  132614. NULL,
  132615. 0
  132616. };
  132617. static long _vq_quantlist__44c6_s_p6_1[] = {
  132618. 2,
  132619. 1,
  132620. 3,
  132621. 0,
  132622. 4,
  132623. };
  132624. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132625. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132626. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132627. };
  132628. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132629. -1.5, -0.5, 0.5, 1.5,
  132630. };
  132631. static long _vq_quantmap__44c6_s_p6_1[] = {
  132632. 3, 1, 0, 2, 4,
  132633. };
  132634. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132635. _vq_quantthresh__44c6_s_p6_1,
  132636. _vq_quantmap__44c6_s_p6_1,
  132637. 5,
  132638. 5
  132639. };
  132640. static static_codebook _44c6_s_p6_1 = {
  132641. 2, 25,
  132642. _vq_lengthlist__44c6_s_p6_1,
  132643. 1, -533725184, 1611661312, 3, 0,
  132644. _vq_quantlist__44c6_s_p6_1,
  132645. NULL,
  132646. &_vq_auxt__44c6_s_p6_1,
  132647. NULL,
  132648. 0
  132649. };
  132650. static long _vq_quantlist__44c6_s_p7_0[] = {
  132651. 6,
  132652. 5,
  132653. 7,
  132654. 4,
  132655. 8,
  132656. 3,
  132657. 9,
  132658. 2,
  132659. 10,
  132660. 1,
  132661. 11,
  132662. 0,
  132663. 12,
  132664. };
  132665. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132666. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132667. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132668. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132669. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132670. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132671. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132672. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132673. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132674. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132675. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132676. 20,13,13,13,13,13,13,14,14,
  132677. };
  132678. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132679. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132680. 27.5, 38.5, 49.5, 60.5,
  132681. };
  132682. static long _vq_quantmap__44c6_s_p7_0[] = {
  132683. 11, 9, 7, 5, 3, 1, 0, 2,
  132684. 4, 6, 8, 10, 12,
  132685. };
  132686. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132687. _vq_quantthresh__44c6_s_p7_0,
  132688. _vq_quantmap__44c6_s_p7_0,
  132689. 13,
  132690. 13
  132691. };
  132692. static static_codebook _44c6_s_p7_0 = {
  132693. 2, 169,
  132694. _vq_lengthlist__44c6_s_p7_0,
  132695. 1, -523206656, 1618345984, 4, 0,
  132696. _vq_quantlist__44c6_s_p7_0,
  132697. NULL,
  132698. &_vq_auxt__44c6_s_p7_0,
  132699. NULL,
  132700. 0
  132701. };
  132702. static long _vq_quantlist__44c6_s_p7_1[] = {
  132703. 5,
  132704. 4,
  132705. 6,
  132706. 3,
  132707. 7,
  132708. 2,
  132709. 8,
  132710. 1,
  132711. 9,
  132712. 0,
  132713. 10,
  132714. };
  132715. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132716. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132717. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132718. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132719. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132720. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132721. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132722. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132723. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132724. };
  132725. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132726. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132727. 3.5, 4.5,
  132728. };
  132729. static long _vq_quantmap__44c6_s_p7_1[] = {
  132730. 9, 7, 5, 3, 1, 0, 2, 4,
  132731. 6, 8, 10,
  132732. };
  132733. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132734. _vq_quantthresh__44c6_s_p7_1,
  132735. _vq_quantmap__44c6_s_p7_1,
  132736. 11,
  132737. 11
  132738. };
  132739. static static_codebook _44c6_s_p7_1 = {
  132740. 2, 121,
  132741. _vq_lengthlist__44c6_s_p7_1,
  132742. 1, -531365888, 1611661312, 4, 0,
  132743. _vq_quantlist__44c6_s_p7_1,
  132744. NULL,
  132745. &_vq_auxt__44c6_s_p7_1,
  132746. NULL,
  132747. 0
  132748. };
  132749. static long _vq_quantlist__44c6_s_p8_0[] = {
  132750. 7,
  132751. 6,
  132752. 8,
  132753. 5,
  132754. 9,
  132755. 4,
  132756. 10,
  132757. 3,
  132758. 11,
  132759. 2,
  132760. 12,
  132761. 1,
  132762. 13,
  132763. 0,
  132764. 14,
  132765. };
  132766. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132767. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132768. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132769. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132770. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132771. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132772. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132773. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132774. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132775. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132776. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132777. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132778. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132779. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132780. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132781. 14,
  132782. };
  132783. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132784. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132785. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132786. };
  132787. static long _vq_quantmap__44c6_s_p8_0[] = {
  132788. 13, 11, 9, 7, 5, 3, 1, 0,
  132789. 2, 4, 6, 8, 10, 12, 14,
  132790. };
  132791. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132792. _vq_quantthresh__44c6_s_p8_0,
  132793. _vq_quantmap__44c6_s_p8_0,
  132794. 15,
  132795. 15
  132796. };
  132797. static static_codebook _44c6_s_p8_0 = {
  132798. 2, 225,
  132799. _vq_lengthlist__44c6_s_p8_0,
  132800. 1, -520986624, 1620377600, 4, 0,
  132801. _vq_quantlist__44c6_s_p8_0,
  132802. NULL,
  132803. &_vq_auxt__44c6_s_p8_0,
  132804. NULL,
  132805. 0
  132806. };
  132807. static long _vq_quantlist__44c6_s_p8_1[] = {
  132808. 10,
  132809. 9,
  132810. 11,
  132811. 8,
  132812. 12,
  132813. 7,
  132814. 13,
  132815. 6,
  132816. 14,
  132817. 5,
  132818. 15,
  132819. 4,
  132820. 16,
  132821. 3,
  132822. 17,
  132823. 2,
  132824. 18,
  132825. 1,
  132826. 19,
  132827. 0,
  132828. 20,
  132829. };
  132830. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132831. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132832. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132834. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132835. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132836. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132837. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132838. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132839. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132840. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132841. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132842. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132843. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132844. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132845. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132846. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132847. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132848. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132849. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132850. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132851. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132852. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132853. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132854. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132855. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132856. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132857. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132858. 10,10,10,10,10,10,10,10,10,
  132859. };
  132860. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132861. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132862. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132863. 6.5, 7.5, 8.5, 9.5,
  132864. };
  132865. static long _vq_quantmap__44c6_s_p8_1[] = {
  132866. 19, 17, 15, 13, 11, 9, 7, 5,
  132867. 3, 1, 0, 2, 4, 6, 8, 10,
  132868. 12, 14, 16, 18, 20,
  132869. };
  132870. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132871. _vq_quantthresh__44c6_s_p8_1,
  132872. _vq_quantmap__44c6_s_p8_1,
  132873. 21,
  132874. 21
  132875. };
  132876. static static_codebook _44c6_s_p8_1 = {
  132877. 2, 441,
  132878. _vq_lengthlist__44c6_s_p8_1,
  132879. 1, -529268736, 1611661312, 5, 0,
  132880. _vq_quantlist__44c6_s_p8_1,
  132881. NULL,
  132882. &_vq_auxt__44c6_s_p8_1,
  132883. NULL,
  132884. 0
  132885. };
  132886. static long _vq_quantlist__44c6_s_p9_0[] = {
  132887. 6,
  132888. 5,
  132889. 7,
  132890. 4,
  132891. 8,
  132892. 3,
  132893. 9,
  132894. 2,
  132895. 10,
  132896. 1,
  132897. 11,
  132898. 0,
  132899. 12,
  132900. };
  132901. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132902. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132903. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132905. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132906. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132907. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132908. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132909. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132910. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132911. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132912. 10,10,10,10,10,10,10,10,10,
  132913. };
  132914. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132915. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132916. 1592.5, 2229.5, 2866.5, 3503.5,
  132917. };
  132918. static long _vq_quantmap__44c6_s_p9_0[] = {
  132919. 11, 9, 7, 5, 3, 1, 0, 2,
  132920. 4, 6, 8, 10, 12,
  132921. };
  132922. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132923. _vq_quantthresh__44c6_s_p9_0,
  132924. _vq_quantmap__44c6_s_p9_0,
  132925. 13,
  132926. 13
  132927. };
  132928. static static_codebook _44c6_s_p9_0 = {
  132929. 2, 169,
  132930. _vq_lengthlist__44c6_s_p9_0,
  132931. 1, -511845376, 1630791680, 4, 0,
  132932. _vq_quantlist__44c6_s_p9_0,
  132933. NULL,
  132934. &_vq_auxt__44c6_s_p9_0,
  132935. NULL,
  132936. 0
  132937. };
  132938. static long _vq_quantlist__44c6_s_p9_1[] = {
  132939. 6,
  132940. 5,
  132941. 7,
  132942. 4,
  132943. 8,
  132944. 3,
  132945. 9,
  132946. 2,
  132947. 10,
  132948. 1,
  132949. 11,
  132950. 0,
  132951. 12,
  132952. };
  132953. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132954. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132955. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132956. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132957. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132958. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132959. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132960. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132961. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132962. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132963. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132964. 15,12,10,11,11,13,11,12,13,
  132965. };
  132966. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132967. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132968. 122.5, 171.5, 220.5, 269.5,
  132969. };
  132970. static long _vq_quantmap__44c6_s_p9_1[] = {
  132971. 11, 9, 7, 5, 3, 1, 0, 2,
  132972. 4, 6, 8, 10, 12,
  132973. };
  132974. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132975. _vq_quantthresh__44c6_s_p9_1,
  132976. _vq_quantmap__44c6_s_p9_1,
  132977. 13,
  132978. 13
  132979. };
  132980. static static_codebook _44c6_s_p9_1 = {
  132981. 2, 169,
  132982. _vq_lengthlist__44c6_s_p9_1,
  132983. 1, -518889472, 1622704128, 4, 0,
  132984. _vq_quantlist__44c6_s_p9_1,
  132985. NULL,
  132986. &_vq_auxt__44c6_s_p9_1,
  132987. NULL,
  132988. 0
  132989. };
  132990. static long _vq_quantlist__44c6_s_p9_2[] = {
  132991. 24,
  132992. 23,
  132993. 25,
  132994. 22,
  132995. 26,
  132996. 21,
  132997. 27,
  132998. 20,
  132999. 28,
  133000. 19,
  133001. 29,
  133002. 18,
  133003. 30,
  133004. 17,
  133005. 31,
  133006. 16,
  133007. 32,
  133008. 15,
  133009. 33,
  133010. 14,
  133011. 34,
  133012. 13,
  133013. 35,
  133014. 12,
  133015. 36,
  133016. 11,
  133017. 37,
  133018. 10,
  133019. 38,
  133020. 9,
  133021. 39,
  133022. 8,
  133023. 40,
  133024. 7,
  133025. 41,
  133026. 6,
  133027. 42,
  133028. 5,
  133029. 43,
  133030. 4,
  133031. 44,
  133032. 3,
  133033. 45,
  133034. 2,
  133035. 46,
  133036. 1,
  133037. 47,
  133038. 0,
  133039. 48,
  133040. };
  133041. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133042. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133043. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133044. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133045. 7,
  133046. };
  133047. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133048. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133049. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133050. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133051. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133052. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133053. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133054. };
  133055. static long _vq_quantmap__44c6_s_p9_2[] = {
  133056. 47, 45, 43, 41, 39, 37, 35, 33,
  133057. 31, 29, 27, 25, 23, 21, 19, 17,
  133058. 15, 13, 11, 9, 7, 5, 3, 1,
  133059. 0, 2, 4, 6, 8, 10, 12, 14,
  133060. 16, 18, 20, 22, 24, 26, 28, 30,
  133061. 32, 34, 36, 38, 40, 42, 44, 46,
  133062. 48,
  133063. };
  133064. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133065. _vq_quantthresh__44c6_s_p9_2,
  133066. _vq_quantmap__44c6_s_p9_2,
  133067. 49,
  133068. 49
  133069. };
  133070. static static_codebook _44c6_s_p9_2 = {
  133071. 1, 49,
  133072. _vq_lengthlist__44c6_s_p9_2,
  133073. 1, -526909440, 1611661312, 6, 0,
  133074. _vq_quantlist__44c6_s_p9_2,
  133075. NULL,
  133076. &_vq_auxt__44c6_s_p9_2,
  133077. NULL,
  133078. 0
  133079. };
  133080. static long _huff_lengthlist__44c6_s_short[] = {
  133081. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133082. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133083. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133084. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133085. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133086. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133087. 9,10,17,18,
  133088. };
  133089. static static_codebook _huff_book__44c6_s_short = {
  133090. 2, 100,
  133091. _huff_lengthlist__44c6_s_short,
  133092. 0, 0, 0, 0, 0,
  133093. NULL,
  133094. NULL,
  133095. NULL,
  133096. NULL,
  133097. 0
  133098. };
  133099. static long _huff_lengthlist__44c7_s_long[] = {
  133100. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133101. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133102. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133103. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133104. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133105. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133106. 11,10,10,12,
  133107. };
  133108. static static_codebook _huff_book__44c7_s_long = {
  133109. 2, 100,
  133110. _huff_lengthlist__44c7_s_long,
  133111. 0, 0, 0, 0, 0,
  133112. NULL,
  133113. NULL,
  133114. NULL,
  133115. NULL,
  133116. 0
  133117. };
  133118. static long _vq_quantlist__44c7_s_p1_0[] = {
  133119. 1,
  133120. 0,
  133121. 2,
  133122. };
  133123. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133124. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133125. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133126. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133127. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133128. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133129. 8,
  133130. };
  133131. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133132. -0.5, 0.5,
  133133. };
  133134. static long _vq_quantmap__44c7_s_p1_0[] = {
  133135. 1, 0, 2,
  133136. };
  133137. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133138. _vq_quantthresh__44c7_s_p1_0,
  133139. _vq_quantmap__44c7_s_p1_0,
  133140. 3,
  133141. 3
  133142. };
  133143. static static_codebook _44c7_s_p1_0 = {
  133144. 4, 81,
  133145. _vq_lengthlist__44c7_s_p1_0,
  133146. 1, -535822336, 1611661312, 2, 0,
  133147. _vq_quantlist__44c7_s_p1_0,
  133148. NULL,
  133149. &_vq_auxt__44c7_s_p1_0,
  133150. NULL,
  133151. 0
  133152. };
  133153. static long _vq_quantlist__44c7_s_p2_0[] = {
  133154. 2,
  133155. 1,
  133156. 3,
  133157. 0,
  133158. 4,
  133159. };
  133160. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133161. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133162. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133163. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133164. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133165. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133166. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133167. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133168. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133170. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133171. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133172. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133173. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133174. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133175. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133176. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133179. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133180. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133181. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133182. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133183. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133184. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133186. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133187. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133188. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133189. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133190. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133191. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133192. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133197. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133198. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133199. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133200. 13,
  133201. };
  133202. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133203. -1.5, -0.5, 0.5, 1.5,
  133204. };
  133205. static long _vq_quantmap__44c7_s_p2_0[] = {
  133206. 3, 1, 0, 2, 4,
  133207. };
  133208. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133209. _vq_quantthresh__44c7_s_p2_0,
  133210. _vq_quantmap__44c7_s_p2_0,
  133211. 5,
  133212. 5
  133213. };
  133214. static static_codebook _44c7_s_p2_0 = {
  133215. 4, 625,
  133216. _vq_lengthlist__44c7_s_p2_0,
  133217. 1, -533725184, 1611661312, 3, 0,
  133218. _vq_quantlist__44c7_s_p2_0,
  133219. NULL,
  133220. &_vq_auxt__44c7_s_p2_0,
  133221. NULL,
  133222. 0
  133223. };
  133224. static long _vq_quantlist__44c7_s_p3_0[] = {
  133225. 4,
  133226. 3,
  133227. 5,
  133228. 2,
  133229. 6,
  133230. 1,
  133231. 7,
  133232. 0,
  133233. 8,
  133234. };
  133235. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133236. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133237. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133238. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133239. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0,
  133242. };
  133243. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133244. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133245. };
  133246. static long _vq_quantmap__44c7_s_p3_0[] = {
  133247. 7, 5, 3, 1, 0, 2, 4, 6,
  133248. 8,
  133249. };
  133250. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133251. _vq_quantthresh__44c7_s_p3_0,
  133252. _vq_quantmap__44c7_s_p3_0,
  133253. 9,
  133254. 9
  133255. };
  133256. static static_codebook _44c7_s_p3_0 = {
  133257. 2, 81,
  133258. _vq_lengthlist__44c7_s_p3_0,
  133259. 1, -531628032, 1611661312, 4, 0,
  133260. _vq_quantlist__44c7_s_p3_0,
  133261. NULL,
  133262. &_vq_auxt__44c7_s_p3_0,
  133263. NULL,
  133264. 0
  133265. };
  133266. static long _vq_quantlist__44c7_s_p4_0[] = {
  133267. 8,
  133268. 7,
  133269. 9,
  133270. 6,
  133271. 10,
  133272. 5,
  133273. 11,
  133274. 4,
  133275. 12,
  133276. 3,
  133277. 13,
  133278. 2,
  133279. 14,
  133280. 1,
  133281. 15,
  133282. 0,
  133283. 16,
  133284. };
  133285. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133286. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133287. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133288. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133289. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133290. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133291. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133292. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133293. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133294. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133295. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133304. 0,
  133305. };
  133306. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133307. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133308. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133309. };
  133310. static long _vq_quantmap__44c7_s_p4_0[] = {
  133311. 15, 13, 11, 9, 7, 5, 3, 1,
  133312. 0, 2, 4, 6, 8, 10, 12, 14,
  133313. 16,
  133314. };
  133315. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133316. _vq_quantthresh__44c7_s_p4_0,
  133317. _vq_quantmap__44c7_s_p4_0,
  133318. 17,
  133319. 17
  133320. };
  133321. static static_codebook _44c7_s_p4_0 = {
  133322. 2, 289,
  133323. _vq_lengthlist__44c7_s_p4_0,
  133324. 1, -529530880, 1611661312, 5, 0,
  133325. _vq_quantlist__44c7_s_p4_0,
  133326. NULL,
  133327. &_vq_auxt__44c7_s_p4_0,
  133328. NULL,
  133329. 0
  133330. };
  133331. static long _vq_quantlist__44c7_s_p5_0[] = {
  133332. 1,
  133333. 0,
  133334. 2,
  133335. };
  133336. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133337. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133338. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133339. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133340. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133341. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133342. 12,
  133343. };
  133344. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133345. -5.5, 5.5,
  133346. };
  133347. static long _vq_quantmap__44c7_s_p5_0[] = {
  133348. 1, 0, 2,
  133349. };
  133350. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133351. _vq_quantthresh__44c7_s_p5_0,
  133352. _vq_quantmap__44c7_s_p5_0,
  133353. 3,
  133354. 3
  133355. };
  133356. static static_codebook _44c7_s_p5_0 = {
  133357. 4, 81,
  133358. _vq_lengthlist__44c7_s_p5_0,
  133359. 1, -529137664, 1618345984, 2, 0,
  133360. _vq_quantlist__44c7_s_p5_0,
  133361. NULL,
  133362. &_vq_auxt__44c7_s_p5_0,
  133363. NULL,
  133364. 0
  133365. };
  133366. static long _vq_quantlist__44c7_s_p5_1[] = {
  133367. 5,
  133368. 4,
  133369. 6,
  133370. 3,
  133371. 7,
  133372. 2,
  133373. 8,
  133374. 1,
  133375. 9,
  133376. 0,
  133377. 10,
  133378. };
  133379. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133380. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133381. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133382. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133383. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133384. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133385. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133386. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133387. 11,11,11, 7, 7, 8, 8, 8, 8,
  133388. };
  133389. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133390. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133391. 3.5, 4.5,
  133392. };
  133393. static long _vq_quantmap__44c7_s_p5_1[] = {
  133394. 9, 7, 5, 3, 1, 0, 2, 4,
  133395. 6, 8, 10,
  133396. };
  133397. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133398. _vq_quantthresh__44c7_s_p5_1,
  133399. _vq_quantmap__44c7_s_p5_1,
  133400. 11,
  133401. 11
  133402. };
  133403. static static_codebook _44c7_s_p5_1 = {
  133404. 2, 121,
  133405. _vq_lengthlist__44c7_s_p5_1,
  133406. 1, -531365888, 1611661312, 4, 0,
  133407. _vq_quantlist__44c7_s_p5_1,
  133408. NULL,
  133409. &_vq_auxt__44c7_s_p5_1,
  133410. NULL,
  133411. 0
  133412. };
  133413. static long _vq_quantlist__44c7_s_p6_0[] = {
  133414. 6,
  133415. 5,
  133416. 7,
  133417. 4,
  133418. 8,
  133419. 3,
  133420. 9,
  133421. 2,
  133422. 10,
  133423. 1,
  133424. 11,
  133425. 0,
  133426. 12,
  133427. };
  133428. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133429. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133430. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133431. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133432. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133433. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133434. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133439. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133440. };
  133441. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133442. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133443. 12.5, 17.5, 22.5, 27.5,
  133444. };
  133445. static long _vq_quantmap__44c7_s_p6_0[] = {
  133446. 11, 9, 7, 5, 3, 1, 0, 2,
  133447. 4, 6, 8, 10, 12,
  133448. };
  133449. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133450. _vq_quantthresh__44c7_s_p6_0,
  133451. _vq_quantmap__44c7_s_p6_0,
  133452. 13,
  133453. 13
  133454. };
  133455. static static_codebook _44c7_s_p6_0 = {
  133456. 2, 169,
  133457. _vq_lengthlist__44c7_s_p6_0,
  133458. 1, -526516224, 1616117760, 4, 0,
  133459. _vq_quantlist__44c7_s_p6_0,
  133460. NULL,
  133461. &_vq_auxt__44c7_s_p6_0,
  133462. NULL,
  133463. 0
  133464. };
  133465. static long _vq_quantlist__44c7_s_p6_1[] = {
  133466. 2,
  133467. 1,
  133468. 3,
  133469. 0,
  133470. 4,
  133471. };
  133472. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133473. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133474. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133475. };
  133476. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133477. -1.5, -0.5, 0.5, 1.5,
  133478. };
  133479. static long _vq_quantmap__44c7_s_p6_1[] = {
  133480. 3, 1, 0, 2, 4,
  133481. };
  133482. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133483. _vq_quantthresh__44c7_s_p6_1,
  133484. _vq_quantmap__44c7_s_p6_1,
  133485. 5,
  133486. 5
  133487. };
  133488. static static_codebook _44c7_s_p6_1 = {
  133489. 2, 25,
  133490. _vq_lengthlist__44c7_s_p6_1,
  133491. 1, -533725184, 1611661312, 3, 0,
  133492. _vq_quantlist__44c7_s_p6_1,
  133493. NULL,
  133494. &_vq_auxt__44c7_s_p6_1,
  133495. NULL,
  133496. 0
  133497. };
  133498. static long _vq_quantlist__44c7_s_p7_0[] = {
  133499. 6,
  133500. 5,
  133501. 7,
  133502. 4,
  133503. 8,
  133504. 3,
  133505. 9,
  133506. 2,
  133507. 10,
  133508. 1,
  133509. 11,
  133510. 0,
  133511. 12,
  133512. };
  133513. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133514. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133515. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133516. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133517. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133518. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133519. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133520. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133521. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133522. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133523. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133524. 19,13,13,13,13,14,14,15,15,
  133525. };
  133526. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133527. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133528. 27.5, 38.5, 49.5, 60.5,
  133529. };
  133530. static long _vq_quantmap__44c7_s_p7_0[] = {
  133531. 11, 9, 7, 5, 3, 1, 0, 2,
  133532. 4, 6, 8, 10, 12,
  133533. };
  133534. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133535. _vq_quantthresh__44c7_s_p7_0,
  133536. _vq_quantmap__44c7_s_p7_0,
  133537. 13,
  133538. 13
  133539. };
  133540. static static_codebook _44c7_s_p7_0 = {
  133541. 2, 169,
  133542. _vq_lengthlist__44c7_s_p7_0,
  133543. 1, -523206656, 1618345984, 4, 0,
  133544. _vq_quantlist__44c7_s_p7_0,
  133545. NULL,
  133546. &_vq_auxt__44c7_s_p7_0,
  133547. NULL,
  133548. 0
  133549. };
  133550. static long _vq_quantlist__44c7_s_p7_1[] = {
  133551. 5,
  133552. 4,
  133553. 6,
  133554. 3,
  133555. 7,
  133556. 2,
  133557. 8,
  133558. 1,
  133559. 9,
  133560. 0,
  133561. 10,
  133562. };
  133563. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133564. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133565. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133566. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133567. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133568. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133569. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133570. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133571. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133572. };
  133573. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133574. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133575. 3.5, 4.5,
  133576. };
  133577. static long _vq_quantmap__44c7_s_p7_1[] = {
  133578. 9, 7, 5, 3, 1, 0, 2, 4,
  133579. 6, 8, 10,
  133580. };
  133581. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133582. _vq_quantthresh__44c7_s_p7_1,
  133583. _vq_quantmap__44c7_s_p7_1,
  133584. 11,
  133585. 11
  133586. };
  133587. static static_codebook _44c7_s_p7_1 = {
  133588. 2, 121,
  133589. _vq_lengthlist__44c7_s_p7_1,
  133590. 1, -531365888, 1611661312, 4, 0,
  133591. _vq_quantlist__44c7_s_p7_1,
  133592. NULL,
  133593. &_vq_auxt__44c7_s_p7_1,
  133594. NULL,
  133595. 0
  133596. };
  133597. static long _vq_quantlist__44c7_s_p8_0[] = {
  133598. 7,
  133599. 6,
  133600. 8,
  133601. 5,
  133602. 9,
  133603. 4,
  133604. 10,
  133605. 3,
  133606. 11,
  133607. 2,
  133608. 12,
  133609. 1,
  133610. 13,
  133611. 0,
  133612. 14,
  133613. };
  133614. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133615. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133616. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133617. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133618. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133619. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133620. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133621. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133622. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133623. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133624. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133625. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133626. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133627. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133628. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133629. 14,
  133630. };
  133631. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133632. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133633. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133634. };
  133635. static long _vq_quantmap__44c7_s_p8_0[] = {
  133636. 13, 11, 9, 7, 5, 3, 1, 0,
  133637. 2, 4, 6, 8, 10, 12, 14,
  133638. };
  133639. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133640. _vq_quantthresh__44c7_s_p8_0,
  133641. _vq_quantmap__44c7_s_p8_0,
  133642. 15,
  133643. 15
  133644. };
  133645. static static_codebook _44c7_s_p8_0 = {
  133646. 2, 225,
  133647. _vq_lengthlist__44c7_s_p8_0,
  133648. 1, -520986624, 1620377600, 4, 0,
  133649. _vq_quantlist__44c7_s_p8_0,
  133650. NULL,
  133651. &_vq_auxt__44c7_s_p8_0,
  133652. NULL,
  133653. 0
  133654. };
  133655. static long _vq_quantlist__44c7_s_p8_1[] = {
  133656. 10,
  133657. 9,
  133658. 11,
  133659. 8,
  133660. 12,
  133661. 7,
  133662. 13,
  133663. 6,
  133664. 14,
  133665. 5,
  133666. 15,
  133667. 4,
  133668. 16,
  133669. 3,
  133670. 17,
  133671. 2,
  133672. 18,
  133673. 1,
  133674. 19,
  133675. 0,
  133676. 20,
  133677. };
  133678. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133679. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133680. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133681. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133682. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133683. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133684. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133685. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133686. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133687. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133688. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133689. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133690. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133691. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133692. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133693. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133694. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133695. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133696. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133697. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133698. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133699. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133700. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133701. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133702. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133703. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133704. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133705. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133706. 10,10,10,10,10,10,10,10,10,
  133707. };
  133708. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133709. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133710. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133711. 6.5, 7.5, 8.5, 9.5,
  133712. };
  133713. static long _vq_quantmap__44c7_s_p8_1[] = {
  133714. 19, 17, 15, 13, 11, 9, 7, 5,
  133715. 3, 1, 0, 2, 4, 6, 8, 10,
  133716. 12, 14, 16, 18, 20,
  133717. };
  133718. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133719. _vq_quantthresh__44c7_s_p8_1,
  133720. _vq_quantmap__44c7_s_p8_1,
  133721. 21,
  133722. 21
  133723. };
  133724. static static_codebook _44c7_s_p8_1 = {
  133725. 2, 441,
  133726. _vq_lengthlist__44c7_s_p8_1,
  133727. 1, -529268736, 1611661312, 5, 0,
  133728. _vq_quantlist__44c7_s_p8_1,
  133729. NULL,
  133730. &_vq_auxt__44c7_s_p8_1,
  133731. NULL,
  133732. 0
  133733. };
  133734. static long _vq_quantlist__44c7_s_p9_0[] = {
  133735. 6,
  133736. 5,
  133737. 7,
  133738. 4,
  133739. 8,
  133740. 3,
  133741. 9,
  133742. 2,
  133743. 10,
  133744. 1,
  133745. 11,
  133746. 0,
  133747. 12,
  133748. };
  133749. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133750. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133751. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133760. 11,11,11,11,11,11,11,11,11,
  133761. };
  133762. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133763. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133764. 1592.5, 2229.5, 2866.5, 3503.5,
  133765. };
  133766. static long _vq_quantmap__44c7_s_p9_0[] = {
  133767. 11, 9, 7, 5, 3, 1, 0, 2,
  133768. 4, 6, 8, 10, 12,
  133769. };
  133770. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133771. _vq_quantthresh__44c7_s_p9_0,
  133772. _vq_quantmap__44c7_s_p9_0,
  133773. 13,
  133774. 13
  133775. };
  133776. static static_codebook _44c7_s_p9_0 = {
  133777. 2, 169,
  133778. _vq_lengthlist__44c7_s_p9_0,
  133779. 1, -511845376, 1630791680, 4, 0,
  133780. _vq_quantlist__44c7_s_p9_0,
  133781. NULL,
  133782. &_vq_auxt__44c7_s_p9_0,
  133783. NULL,
  133784. 0
  133785. };
  133786. static long _vq_quantlist__44c7_s_p9_1[] = {
  133787. 6,
  133788. 5,
  133789. 7,
  133790. 4,
  133791. 8,
  133792. 3,
  133793. 9,
  133794. 2,
  133795. 10,
  133796. 1,
  133797. 11,
  133798. 0,
  133799. 12,
  133800. };
  133801. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133802. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133803. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133804. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133805. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133806. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133807. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133808. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133809. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133810. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133811. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133812. 15,11,11,10,10,12,12,12,12,
  133813. };
  133814. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133815. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133816. 122.5, 171.5, 220.5, 269.5,
  133817. };
  133818. static long _vq_quantmap__44c7_s_p9_1[] = {
  133819. 11, 9, 7, 5, 3, 1, 0, 2,
  133820. 4, 6, 8, 10, 12,
  133821. };
  133822. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133823. _vq_quantthresh__44c7_s_p9_1,
  133824. _vq_quantmap__44c7_s_p9_1,
  133825. 13,
  133826. 13
  133827. };
  133828. static static_codebook _44c7_s_p9_1 = {
  133829. 2, 169,
  133830. _vq_lengthlist__44c7_s_p9_1,
  133831. 1, -518889472, 1622704128, 4, 0,
  133832. _vq_quantlist__44c7_s_p9_1,
  133833. NULL,
  133834. &_vq_auxt__44c7_s_p9_1,
  133835. NULL,
  133836. 0
  133837. };
  133838. static long _vq_quantlist__44c7_s_p9_2[] = {
  133839. 24,
  133840. 23,
  133841. 25,
  133842. 22,
  133843. 26,
  133844. 21,
  133845. 27,
  133846. 20,
  133847. 28,
  133848. 19,
  133849. 29,
  133850. 18,
  133851. 30,
  133852. 17,
  133853. 31,
  133854. 16,
  133855. 32,
  133856. 15,
  133857. 33,
  133858. 14,
  133859. 34,
  133860. 13,
  133861. 35,
  133862. 12,
  133863. 36,
  133864. 11,
  133865. 37,
  133866. 10,
  133867. 38,
  133868. 9,
  133869. 39,
  133870. 8,
  133871. 40,
  133872. 7,
  133873. 41,
  133874. 6,
  133875. 42,
  133876. 5,
  133877. 43,
  133878. 4,
  133879. 44,
  133880. 3,
  133881. 45,
  133882. 2,
  133883. 46,
  133884. 1,
  133885. 47,
  133886. 0,
  133887. 48,
  133888. };
  133889. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133890. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133891. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133892. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133893. 7,
  133894. };
  133895. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133896. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133897. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133898. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133899. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133900. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133901. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133902. };
  133903. static long _vq_quantmap__44c7_s_p9_2[] = {
  133904. 47, 45, 43, 41, 39, 37, 35, 33,
  133905. 31, 29, 27, 25, 23, 21, 19, 17,
  133906. 15, 13, 11, 9, 7, 5, 3, 1,
  133907. 0, 2, 4, 6, 8, 10, 12, 14,
  133908. 16, 18, 20, 22, 24, 26, 28, 30,
  133909. 32, 34, 36, 38, 40, 42, 44, 46,
  133910. 48,
  133911. };
  133912. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133913. _vq_quantthresh__44c7_s_p9_2,
  133914. _vq_quantmap__44c7_s_p9_2,
  133915. 49,
  133916. 49
  133917. };
  133918. static static_codebook _44c7_s_p9_2 = {
  133919. 1, 49,
  133920. _vq_lengthlist__44c7_s_p9_2,
  133921. 1, -526909440, 1611661312, 6, 0,
  133922. _vq_quantlist__44c7_s_p9_2,
  133923. NULL,
  133924. &_vq_auxt__44c7_s_p9_2,
  133925. NULL,
  133926. 0
  133927. };
  133928. static long _huff_lengthlist__44c7_s_short[] = {
  133929. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133930. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133931. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133932. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133933. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133934. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133935. 10, 9,11,14,
  133936. };
  133937. static static_codebook _huff_book__44c7_s_short = {
  133938. 2, 100,
  133939. _huff_lengthlist__44c7_s_short,
  133940. 0, 0, 0, 0, 0,
  133941. NULL,
  133942. NULL,
  133943. NULL,
  133944. NULL,
  133945. 0
  133946. };
  133947. static long _huff_lengthlist__44c8_s_long[] = {
  133948. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133949. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133950. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133951. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133952. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133953. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133954. 11, 9, 9,10,
  133955. };
  133956. static static_codebook _huff_book__44c8_s_long = {
  133957. 2, 100,
  133958. _huff_lengthlist__44c8_s_long,
  133959. 0, 0, 0, 0, 0,
  133960. NULL,
  133961. NULL,
  133962. NULL,
  133963. NULL,
  133964. 0
  133965. };
  133966. static long _vq_quantlist__44c8_s_p1_0[] = {
  133967. 1,
  133968. 0,
  133969. 2,
  133970. };
  133971. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133972. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133973. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133974. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133975. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133976. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133977. 8,
  133978. };
  133979. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133980. -0.5, 0.5,
  133981. };
  133982. static long _vq_quantmap__44c8_s_p1_0[] = {
  133983. 1, 0, 2,
  133984. };
  133985. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133986. _vq_quantthresh__44c8_s_p1_0,
  133987. _vq_quantmap__44c8_s_p1_0,
  133988. 3,
  133989. 3
  133990. };
  133991. static static_codebook _44c8_s_p1_0 = {
  133992. 4, 81,
  133993. _vq_lengthlist__44c8_s_p1_0,
  133994. 1, -535822336, 1611661312, 2, 0,
  133995. _vq_quantlist__44c8_s_p1_0,
  133996. NULL,
  133997. &_vq_auxt__44c8_s_p1_0,
  133998. NULL,
  133999. 0
  134000. };
  134001. static long _vq_quantlist__44c8_s_p2_0[] = {
  134002. 2,
  134003. 1,
  134004. 3,
  134005. 0,
  134006. 4,
  134007. };
  134008. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134009. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134010. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134011. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134012. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134013. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134014. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134015. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134016. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134019. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134020. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134021. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134022. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134023. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134024. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134027. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134028. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134029. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134030. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134031. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134032. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134035. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134036. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134037. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134038. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134039. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134040. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134045. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134046. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134047. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134048. 13,
  134049. };
  134050. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134051. -1.5, -0.5, 0.5, 1.5,
  134052. };
  134053. static long _vq_quantmap__44c8_s_p2_0[] = {
  134054. 3, 1, 0, 2, 4,
  134055. };
  134056. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134057. _vq_quantthresh__44c8_s_p2_0,
  134058. _vq_quantmap__44c8_s_p2_0,
  134059. 5,
  134060. 5
  134061. };
  134062. static static_codebook _44c8_s_p2_0 = {
  134063. 4, 625,
  134064. _vq_lengthlist__44c8_s_p2_0,
  134065. 1, -533725184, 1611661312, 3, 0,
  134066. _vq_quantlist__44c8_s_p2_0,
  134067. NULL,
  134068. &_vq_auxt__44c8_s_p2_0,
  134069. NULL,
  134070. 0
  134071. };
  134072. static long _vq_quantlist__44c8_s_p3_0[] = {
  134073. 4,
  134074. 3,
  134075. 5,
  134076. 2,
  134077. 6,
  134078. 1,
  134079. 7,
  134080. 0,
  134081. 8,
  134082. };
  134083. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134084. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134085. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134086. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134087. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0,
  134090. };
  134091. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134092. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134093. };
  134094. static long _vq_quantmap__44c8_s_p3_0[] = {
  134095. 7, 5, 3, 1, 0, 2, 4, 6,
  134096. 8,
  134097. };
  134098. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134099. _vq_quantthresh__44c8_s_p3_0,
  134100. _vq_quantmap__44c8_s_p3_0,
  134101. 9,
  134102. 9
  134103. };
  134104. static static_codebook _44c8_s_p3_0 = {
  134105. 2, 81,
  134106. _vq_lengthlist__44c8_s_p3_0,
  134107. 1, -531628032, 1611661312, 4, 0,
  134108. _vq_quantlist__44c8_s_p3_0,
  134109. NULL,
  134110. &_vq_auxt__44c8_s_p3_0,
  134111. NULL,
  134112. 0
  134113. };
  134114. static long _vq_quantlist__44c8_s_p4_0[] = {
  134115. 8,
  134116. 7,
  134117. 9,
  134118. 6,
  134119. 10,
  134120. 5,
  134121. 11,
  134122. 4,
  134123. 12,
  134124. 3,
  134125. 13,
  134126. 2,
  134127. 14,
  134128. 1,
  134129. 15,
  134130. 0,
  134131. 16,
  134132. };
  134133. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134134. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134135. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134136. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134137. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134138. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134139. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134140. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134141. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134142. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134143. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134152. 0,
  134153. };
  134154. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134155. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134156. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134157. };
  134158. static long _vq_quantmap__44c8_s_p4_0[] = {
  134159. 15, 13, 11, 9, 7, 5, 3, 1,
  134160. 0, 2, 4, 6, 8, 10, 12, 14,
  134161. 16,
  134162. };
  134163. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134164. _vq_quantthresh__44c8_s_p4_0,
  134165. _vq_quantmap__44c8_s_p4_0,
  134166. 17,
  134167. 17
  134168. };
  134169. static static_codebook _44c8_s_p4_0 = {
  134170. 2, 289,
  134171. _vq_lengthlist__44c8_s_p4_0,
  134172. 1, -529530880, 1611661312, 5, 0,
  134173. _vq_quantlist__44c8_s_p4_0,
  134174. NULL,
  134175. &_vq_auxt__44c8_s_p4_0,
  134176. NULL,
  134177. 0
  134178. };
  134179. static long _vq_quantlist__44c8_s_p5_0[] = {
  134180. 1,
  134181. 0,
  134182. 2,
  134183. };
  134184. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134185. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134186. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134187. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134188. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134189. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134190. 12,
  134191. };
  134192. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134193. -5.5, 5.5,
  134194. };
  134195. static long _vq_quantmap__44c8_s_p5_0[] = {
  134196. 1, 0, 2,
  134197. };
  134198. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134199. _vq_quantthresh__44c8_s_p5_0,
  134200. _vq_quantmap__44c8_s_p5_0,
  134201. 3,
  134202. 3
  134203. };
  134204. static static_codebook _44c8_s_p5_0 = {
  134205. 4, 81,
  134206. _vq_lengthlist__44c8_s_p5_0,
  134207. 1, -529137664, 1618345984, 2, 0,
  134208. _vq_quantlist__44c8_s_p5_0,
  134209. NULL,
  134210. &_vq_auxt__44c8_s_p5_0,
  134211. NULL,
  134212. 0
  134213. };
  134214. static long _vq_quantlist__44c8_s_p5_1[] = {
  134215. 5,
  134216. 4,
  134217. 6,
  134218. 3,
  134219. 7,
  134220. 2,
  134221. 8,
  134222. 1,
  134223. 9,
  134224. 0,
  134225. 10,
  134226. };
  134227. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134228. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134229. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134230. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134231. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134232. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134233. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134234. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134235. 11,11,11, 7, 7, 7, 7, 8, 8,
  134236. };
  134237. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134238. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134239. 3.5, 4.5,
  134240. };
  134241. static long _vq_quantmap__44c8_s_p5_1[] = {
  134242. 9, 7, 5, 3, 1, 0, 2, 4,
  134243. 6, 8, 10,
  134244. };
  134245. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134246. _vq_quantthresh__44c8_s_p5_1,
  134247. _vq_quantmap__44c8_s_p5_1,
  134248. 11,
  134249. 11
  134250. };
  134251. static static_codebook _44c8_s_p5_1 = {
  134252. 2, 121,
  134253. _vq_lengthlist__44c8_s_p5_1,
  134254. 1, -531365888, 1611661312, 4, 0,
  134255. _vq_quantlist__44c8_s_p5_1,
  134256. NULL,
  134257. &_vq_auxt__44c8_s_p5_1,
  134258. NULL,
  134259. 0
  134260. };
  134261. static long _vq_quantlist__44c8_s_p6_0[] = {
  134262. 6,
  134263. 5,
  134264. 7,
  134265. 4,
  134266. 8,
  134267. 3,
  134268. 9,
  134269. 2,
  134270. 10,
  134271. 1,
  134272. 11,
  134273. 0,
  134274. 12,
  134275. };
  134276. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134277. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134278. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134279. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134280. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134281. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134282. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. };
  134289. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134290. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134291. 12.5, 17.5, 22.5, 27.5,
  134292. };
  134293. static long _vq_quantmap__44c8_s_p6_0[] = {
  134294. 11, 9, 7, 5, 3, 1, 0, 2,
  134295. 4, 6, 8, 10, 12,
  134296. };
  134297. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134298. _vq_quantthresh__44c8_s_p6_0,
  134299. _vq_quantmap__44c8_s_p6_0,
  134300. 13,
  134301. 13
  134302. };
  134303. static static_codebook _44c8_s_p6_0 = {
  134304. 2, 169,
  134305. _vq_lengthlist__44c8_s_p6_0,
  134306. 1, -526516224, 1616117760, 4, 0,
  134307. _vq_quantlist__44c8_s_p6_0,
  134308. NULL,
  134309. &_vq_auxt__44c8_s_p6_0,
  134310. NULL,
  134311. 0
  134312. };
  134313. static long _vq_quantlist__44c8_s_p6_1[] = {
  134314. 2,
  134315. 1,
  134316. 3,
  134317. 0,
  134318. 4,
  134319. };
  134320. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134321. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134322. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134323. };
  134324. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134325. -1.5, -0.5, 0.5, 1.5,
  134326. };
  134327. static long _vq_quantmap__44c8_s_p6_1[] = {
  134328. 3, 1, 0, 2, 4,
  134329. };
  134330. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134331. _vq_quantthresh__44c8_s_p6_1,
  134332. _vq_quantmap__44c8_s_p6_1,
  134333. 5,
  134334. 5
  134335. };
  134336. static static_codebook _44c8_s_p6_1 = {
  134337. 2, 25,
  134338. _vq_lengthlist__44c8_s_p6_1,
  134339. 1, -533725184, 1611661312, 3, 0,
  134340. _vq_quantlist__44c8_s_p6_1,
  134341. NULL,
  134342. &_vq_auxt__44c8_s_p6_1,
  134343. NULL,
  134344. 0
  134345. };
  134346. static long _vq_quantlist__44c8_s_p7_0[] = {
  134347. 6,
  134348. 5,
  134349. 7,
  134350. 4,
  134351. 8,
  134352. 3,
  134353. 9,
  134354. 2,
  134355. 10,
  134356. 1,
  134357. 11,
  134358. 0,
  134359. 12,
  134360. };
  134361. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134362. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134363. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134364. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134365. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134366. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134367. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134368. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134369. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134370. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134371. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134372. 20,13,13,13,13,14,13,15,15,
  134373. };
  134374. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134375. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134376. 27.5, 38.5, 49.5, 60.5,
  134377. };
  134378. static long _vq_quantmap__44c8_s_p7_0[] = {
  134379. 11, 9, 7, 5, 3, 1, 0, 2,
  134380. 4, 6, 8, 10, 12,
  134381. };
  134382. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134383. _vq_quantthresh__44c8_s_p7_0,
  134384. _vq_quantmap__44c8_s_p7_0,
  134385. 13,
  134386. 13
  134387. };
  134388. static static_codebook _44c8_s_p7_0 = {
  134389. 2, 169,
  134390. _vq_lengthlist__44c8_s_p7_0,
  134391. 1, -523206656, 1618345984, 4, 0,
  134392. _vq_quantlist__44c8_s_p7_0,
  134393. NULL,
  134394. &_vq_auxt__44c8_s_p7_0,
  134395. NULL,
  134396. 0
  134397. };
  134398. static long _vq_quantlist__44c8_s_p7_1[] = {
  134399. 5,
  134400. 4,
  134401. 6,
  134402. 3,
  134403. 7,
  134404. 2,
  134405. 8,
  134406. 1,
  134407. 9,
  134408. 0,
  134409. 10,
  134410. };
  134411. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134412. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134413. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134414. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134415. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134416. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134417. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134418. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134419. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134420. };
  134421. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134422. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134423. 3.5, 4.5,
  134424. };
  134425. static long _vq_quantmap__44c8_s_p7_1[] = {
  134426. 9, 7, 5, 3, 1, 0, 2, 4,
  134427. 6, 8, 10,
  134428. };
  134429. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134430. _vq_quantthresh__44c8_s_p7_1,
  134431. _vq_quantmap__44c8_s_p7_1,
  134432. 11,
  134433. 11
  134434. };
  134435. static static_codebook _44c8_s_p7_1 = {
  134436. 2, 121,
  134437. _vq_lengthlist__44c8_s_p7_1,
  134438. 1, -531365888, 1611661312, 4, 0,
  134439. _vq_quantlist__44c8_s_p7_1,
  134440. NULL,
  134441. &_vq_auxt__44c8_s_p7_1,
  134442. NULL,
  134443. 0
  134444. };
  134445. static long _vq_quantlist__44c8_s_p8_0[] = {
  134446. 7,
  134447. 6,
  134448. 8,
  134449. 5,
  134450. 9,
  134451. 4,
  134452. 10,
  134453. 3,
  134454. 11,
  134455. 2,
  134456. 12,
  134457. 1,
  134458. 13,
  134459. 0,
  134460. 14,
  134461. };
  134462. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134463. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134464. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134465. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134466. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134467. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134468. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134469. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134470. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134471. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134472. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134473. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134474. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134475. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134476. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134477. 15,
  134478. };
  134479. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134480. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134481. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134482. };
  134483. static long _vq_quantmap__44c8_s_p8_0[] = {
  134484. 13, 11, 9, 7, 5, 3, 1, 0,
  134485. 2, 4, 6, 8, 10, 12, 14,
  134486. };
  134487. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134488. _vq_quantthresh__44c8_s_p8_0,
  134489. _vq_quantmap__44c8_s_p8_0,
  134490. 15,
  134491. 15
  134492. };
  134493. static static_codebook _44c8_s_p8_0 = {
  134494. 2, 225,
  134495. _vq_lengthlist__44c8_s_p8_0,
  134496. 1, -520986624, 1620377600, 4, 0,
  134497. _vq_quantlist__44c8_s_p8_0,
  134498. NULL,
  134499. &_vq_auxt__44c8_s_p8_0,
  134500. NULL,
  134501. 0
  134502. };
  134503. static long _vq_quantlist__44c8_s_p8_1[] = {
  134504. 10,
  134505. 9,
  134506. 11,
  134507. 8,
  134508. 12,
  134509. 7,
  134510. 13,
  134511. 6,
  134512. 14,
  134513. 5,
  134514. 15,
  134515. 4,
  134516. 16,
  134517. 3,
  134518. 17,
  134519. 2,
  134520. 18,
  134521. 1,
  134522. 19,
  134523. 0,
  134524. 20,
  134525. };
  134526. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134527. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134528. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134530. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134531. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134532. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134533. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134534. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134535. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134536. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134537. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134538. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134539. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134540. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134541. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134542. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134543. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134544. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134545. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134546. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134547. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134548. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134549. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134550. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134551. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134552. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134553. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134554. 10, 9, 9,10,10, 9,10, 9, 9,
  134555. };
  134556. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134557. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134558. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134559. 6.5, 7.5, 8.5, 9.5,
  134560. };
  134561. static long _vq_quantmap__44c8_s_p8_1[] = {
  134562. 19, 17, 15, 13, 11, 9, 7, 5,
  134563. 3, 1, 0, 2, 4, 6, 8, 10,
  134564. 12, 14, 16, 18, 20,
  134565. };
  134566. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134567. _vq_quantthresh__44c8_s_p8_1,
  134568. _vq_quantmap__44c8_s_p8_1,
  134569. 21,
  134570. 21
  134571. };
  134572. static static_codebook _44c8_s_p8_1 = {
  134573. 2, 441,
  134574. _vq_lengthlist__44c8_s_p8_1,
  134575. 1, -529268736, 1611661312, 5, 0,
  134576. _vq_quantlist__44c8_s_p8_1,
  134577. NULL,
  134578. &_vq_auxt__44c8_s_p8_1,
  134579. NULL,
  134580. 0
  134581. };
  134582. static long _vq_quantlist__44c8_s_p9_0[] = {
  134583. 8,
  134584. 7,
  134585. 9,
  134586. 6,
  134587. 10,
  134588. 5,
  134589. 11,
  134590. 4,
  134591. 12,
  134592. 3,
  134593. 13,
  134594. 2,
  134595. 14,
  134596. 1,
  134597. 15,
  134598. 0,
  134599. 16,
  134600. };
  134601. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134602. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134603. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134604. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134616. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134617. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134618. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134620. 10,
  134621. };
  134622. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134623. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134624. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134625. };
  134626. static long _vq_quantmap__44c8_s_p9_0[] = {
  134627. 15, 13, 11, 9, 7, 5, 3, 1,
  134628. 0, 2, 4, 6, 8, 10, 12, 14,
  134629. 16,
  134630. };
  134631. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134632. _vq_quantthresh__44c8_s_p9_0,
  134633. _vq_quantmap__44c8_s_p9_0,
  134634. 17,
  134635. 17
  134636. };
  134637. static static_codebook _44c8_s_p9_0 = {
  134638. 2, 289,
  134639. _vq_lengthlist__44c8_s_p9_0,
  134640. 1, -509798400, 1631393792, 5, 0,
  134641. _vq_quantlist__44c8_s_p9_0,
  134642. NULL,
  134643. &_vq_auxt__44c8_s_p9_0,
  134644. NULL,
  134645. 0
  134646. };
  134647. static long _vq_quantlist__44c8_s_p9_1[] = {
  134648. 9,
  134649. 8,
  134650. 10,
  134651. 7,
  134652. 11,
  134653. 6,
  134654. 12,
  134655. 5,
  134656. 13,
  134657. 4,
  134658. 14,
  134659. 3,
  134660. 15,
  134661. 2,
  134662. 16,
  134663. 1,
  134664. 17,
  134665. 0,
  134666. 18,
  134667. };
  134668. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134669. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134670. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134671. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134672. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134673. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134674. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134675. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134676. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134677. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134678. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134679. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134680. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134681. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134682. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134683. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134684. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134685. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134686. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134687. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134688. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134689. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134690. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134691. 14,13,13,14,14,15,14,15,14,
  134692. };
  134693. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134694. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134695. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134696. 367.5, 416.5,
  134697. };
  134698. static long _vq_quantmap__44c8_s_p9_1[] = {
  134699. 17, 15, 13, 11, 9, 7, 5, 3,
  134700. 1, 0, 2, 4, 6, 8, 10, 12,
  134701. 14, 16, 18,
  134702. };
  134703. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134704. _vq_quantthresh__44c8_s_p9_1,
  134705. _vq_quantmap__44c8_s_p9_1,
  134706. 19,
  134707. 19
  134708. };
  134709. static static_codebook _44c8_s_p9_1 = {
  134710. 2, 361,
  134711. _vq_lengthlist__44c8_s_p9_1,
  134712. 1, -518287360, 1622704128, 5, 0,
  134713. _vq_quantlist__44c8_s_p9_1,
  134714. NULL,
  134715. &_vq_auxt__44c8_s_p9_1,
  134716. NULL,
  134717. 0
  134718. };
  134719. static long _vq_quantlist__44c8_s_p9_2[] = {
  134720. 24,
  134721. 23,
  134722. 25,
  134723. 22,
  134724. 26,
  134725. 21,
  134726. 27,
  134727. 20,
  134728. 28,
  134729. 19,
  134730. 29,
  134731. 18,
  134732. 30,
  134733. 17,
  134734. 31,
  134735. 16,
  134736. 32,
  134737. 15,
  134738. 33,
  134739. 14,
  134740. 34,
  134741. 13,
  134742. 35,
  134743. 12,
  134744. 36,
  134745. 11,
  134746. 37,
  134747. 10,
  134748. 38,
  134749. 9,
  134750. 39,
  134751. 8,
  134752. 40,
  134753. 7,
  134754. 41,
  134755. 6,
  134756. 42,
  134757. 5,
  134758. 43,
  134759. 4,
  134760. 44,
  134761. 3,
  134762. 45,
  134763. 2,
  134764. 46,
  134765. 1,
  134766. 47,
  134767. 0,
  134768. 48,
  134769. };
  134770. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134771. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134772. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134773. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134774. 7,
  134775. };
  134776. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134777. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134778. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134779. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134780. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134781. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134782. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134783. };
  134784. static long _vq_quantmap__44c8_s_p9_2[] = {
  134785. 47, 45, 43, 41, 39, 37, 35, 33,
  134786. 31, 29, 27, 25, 23, 21, 19, 17,
  134787. 15, 13, 11, 9, 7, 5, 3, 1,
  134788. 0, 2, 4, 6, 8, 10, 12, 14,
  134789. 16, 18, 20, 22, 24, 26, 28, 30,
  134790. 32, 34, 36, 38, 40, 42, 44, 46,
  134791. 48,
  134792. };
  134793. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134794. _vq_quantthresh__44c8_s_p9_2,
  134795. _vq_quantmap__44c8_s_p9_2,
  134796. 49,
  134797. 49
  134798. };
  134799. static static_codebook _44c8_s_p9_2 = {
  134800. 1, 49,
  134801. _vq_lengthlist__44c8_s_p9_2,
  134802. 1, -526909440, 1611661312, 6, 0,
  134803. _vq_quantlist__44c8_s_p9_2,
  134804. NULL,
  134805. &_vq_auxt__44c8_s_p9_2,
  134806. NULL,
  134807. 0
  134808. };
  134809. static long _huff_lengthlist__44c8_s_short[] = {
  134810. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134811. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134812. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134813. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134814. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134815. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134816. 10, 9,11,14,
  134817. };
  134818. static static_codebook _huff_book__44c8_s_short = {
  134819. 2, 100,
  134820. _huff_lengthlist__44c8_s_short,
  134821. 0, 0, 0, 0, 0,
  134822. NULL,
  134823. NULL,
  134824. NULL,
  134825. NULL,
  134826. 0
  134827. };
  134828. static long _huff_lengthlist__44c9_s_long[] = {
  134829. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134830. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134831. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134832. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134833. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134834. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134835. 10, 9, 8, 9,
  134836. };
  134837. static static_codebook _huff_book__44c9_s_long = {
  134838. 2, 100,
  134839. _huff_lengthlist__44c9_s_long,
  134840. 0, 0, 0, 0, 0,
  134841. NULL,
  134842. NULL,
  134843. NULL,
  134844. NULL,
  134845. 0
  134846. };
  134847. static long _vq_quantlist__44c9_s_p1_0[] = {
  134848. 1,
  134849. 0,
  134850. 2,
  134851. };
  134852. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134853. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134854. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134855. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134856. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134857. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134858. 7,
  134859. };
  134860. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134861. -0.5, 0.5,
  134862. };
  134863. static long _vq_quantmap__44c9_s_p1_0[] = {
  134864. 1, 0, 2,
  134865. };
  134866. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134867. _vq_quantthresh__44c9_s_p1_0,
  134868. _vq_quantmap__44c9_s_p1_0,
  134869. 3,
  134870. 3
  134871. };
  134872. static static_codebook _44c9_s_p1_0 = {
  134873. 4, 81,
  134874. _vq_lengthlist__44c9_s_p1_0,
  134875. 1, -535822336, 1611661312, 2, 0,
  134876. _vq_quantlist__44c9_s_p1_0,
  134877. NULL,
  134878. &_vq_auxt__44c9_s_p1_0,
  134879. NULL,
  134880. 0
  134881. };
  134882. static long _vq_quantlist__44c9_s_p2_0[] = {
  134883. 2,
  134884. 1,
  134885. 3,
  134886. 0,
  134887. 4,
  134888. };
  134889. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134890. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134891. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134892. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134893. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134894. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134895. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134896. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134897. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134900. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134901. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134902. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134903. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134904. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134905. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134908. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134909. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134910. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134911. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134912. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134913. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134916. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134917. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134918. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134919. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134920. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134921. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134926. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134927. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134928. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134929. 12,
  134930. };
  134931. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134932. -1.5, -0.5, 0.5, 1.5,
  134933. };
  134934. static long _vq_quantmap__44c9_s_p2_0[] = {
  134935. 3, 1, 0, 2, 4,
  134936. };
  134937. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134938. _vq_quantthresh__44c9_s_p2_0,
  134939. _vq_quantmap__44c9_s_p2_0,
  134940. 5,
  134941. 5
  134942. };
  134943. static static_codebook _44c9_s_p2_0 = {
  134944. 4, 625,
  134945. _vq_lengthlist__44c9_s_p2_0,
  134946. 1, -533725184, 1611661312, 3, 0,
  134947. _vq_quantlist__44c9_s_p2_0,
  134948. NULL,
  134949. &_vq_auxt__44c9_s_p2_0,
  134950. NULL,
  134951. 0
  134952. };
  134953. static long _vq_quantlist__44c9_s_p3_0[] = {
  134954. 4,
  134955. 3,
  134956. 5,
  134957. 2,
  134958. 6,
  134959. 1,
  134960. 7,
  134961. 0,
  134962. 8,
  134963. };
  134964. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134965. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134966. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134967. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134968. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0,
  134971. };
  134972. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134973. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134974. };
  134975. static long _vq_quantmap__44c9_s_p3_0[] = {
  134976. 7, 5, 3, 1, 0, 2, 4, 6,
  134977. 8,
  134978. };
  134979. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134980. _vq_quantthresh__44c9_s_p3_0,
  134981. _vq_quantmap__44c9_s_p3_0,
  134982. 9,
  134983. 9
  134984. };
  134985. static static_codebook _44c9_s_p3_0 = {
  134986. 2, 81,
  134987. _vq_lengthlist__44c9_s_p3_0,
  134988. 1, -531628032, 1611661312, 4, 0,
  134989. _vq_quantlist__44c9_s_p3_0,
  134990. NULL,
  134991. &_vq_auxt__44c9_s_p3_0,
  134992. NULL,
  134993. 0
  134994. };
  134995. static long _vq_quantlist__44c9_s_p4_0[] = {
  134996. 8,
  134997. 7,
  134998. 9,
  134999. 6,
  135000. 10,
  135001. 5,
  135002. 11,
  135003. 4,
  135004. 12,
  135005. 3,
  135006. 13,
  135007. 2,
  135008. 14,
  135009. 1,
  135010. 15,
  135011. 0,
  135012. 16,
  135013. };
  135014. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135015. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135016. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135017. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135018. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135019. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135020. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135021. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135022. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135023. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135024. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0,
  135034. };
  135035. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135036. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135037. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135038. };
  135039. static long _vq_quantmap__44c9_s_p4_0[] = {
  135040. 15, 13, 11, 9, 7, 5, 3, 1,
  135041. 0, 2, 4, 6, 8, 10, 12, 14,
  135042. 16,
  135043. };
  135044. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135045. _vq_quantthresh__44c9_s_p4_0,
  135046. _vq_quantmap__44c9_s_p4_0,
  135047. 17,
  135048. 17
  135049. };
  135050. static static_codebook _44c9_s_p4_0 = {
  135051. 2, 289,
  135052. _vq_lengthlist__44c9_s_p4_0,
  135053. 1, -529530880, 1611661312, 5, 0,
  135054. _vq_quantlist__44c9_s_p4_0,
  135055. NULL,
  135056. &_vq_auxt__44c9_s_p4_0,
  135057. NULL,
  135058. 0
  135059. };
  135060. static long _vq_quantlist__44c9_s_p5_0[] = {
  135061. 1,
  135062. 0,
  135063. 2,
  135064. };
  135065. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135066. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135067. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135068. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135069. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135070. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135071. 12,
  135072. };
  135073. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135074. -5.5, 5.5,
  135075. };
  135076. static long _vq_quantmap__44c9_s_p5_0[] = {
  135077. 1, 0, 2,
  135078. };
  135079. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135080. _vq_quantthresh__44c9_s_p5_0,
  135081. _vq_quantmap__44c9_s_p5_0,
  135082. 3,
  135083. 3
  135084. };
  135085. static static_codebook _44c9_s_p5_0 = {
  135086. 4, 81,
  135087. _vq_lengthlist__44c9_s_p5_0,
  135088. 1, -529137664, 1618345984, 2, 0,
  135089. _vq_quantlist__44c9_s_p5_0,
  135090. NULL,
  135091. &_vq_auxt__44c9_s_p5_0,
  135092. NULL,
  135093. 0
  135094. };
  135095. static long _vq_quantlist__44c9_s_p5_1[] = {
  135096. 5,
  135097. 4,
  135098. 6,
  135099. 3,
  135100. 7,
  135101. 2,
  135102. 8,
  135103. 1,
  135104. 9,
  135105. 0,
  135106. 10,
  135107. };
  135108. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135109. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135110. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135111. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135112. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135113. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135114. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135115. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135116. 11,11,11, 7, 7, 7, 7, 7, 7,
  135117. };
  135118. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135119. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135120. 3.5, 4.5,
  135121. };
  135122. static long _vq_quantmap__44c9_s_p5_1[] = {
  135123. 9, 7, 5, 3, 1, 0, 2, 4,
  135124. 6, 8, 10,
  135125. };
  135126. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135127. _vq_quantthresh__44c9_s_p5_1,
  135128. _vq_quantmap__44c9_s_p5_1,
  135129. 11,
  135130. 11
  135131. };
  135132. static static_codebook _44c9_s_p5_1 = {
  135133. 2, 121,
  135134. _vq_lengthlist__44c9_s_p5_1,
  135135. 1, -531365888, 1611661312, 4, 0,
  135136. _vq_quantlist__44c9_s_p5_1,
  135137. NULL,
  135138. &_vq_auxt__44c9_s_p5_1,
  135139. NULL,
  135140. 0
  135141. };
  135142. static long _vq_quantlist__44c9_s_p6_0[] = {
  135143. 6,
  135144. 5,
  135145. 7,
  135146. 4,
  135147. 8,
  135148. 3,
  135149. 9,
  135150. 2,
  135151. 10,
  135152. 1,
  135153. 11,
  135154. 0,
  135155. 12,
  135156. };
  135157. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135158. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135159. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135160. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135161. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135162. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135163. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. };
  135170. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135171. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135172. 12.5, 17.5, 22.5, 27.5,
  135173. };
  135174. static long _vq_quantmap__44c9_s_p6_0[] = {
  135175. 11, 9, 7, 5, 3, 1, 0, 2,
  135176. 4, 6, 8, 10, 12,
  135177. };
  135178. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135179. _vq_quantthresh__44c9_s_p6_0,
  135180. _vq_quantmap__44c9_s_p6_0,
  135181. 13,
  135182. 13
  135183. };
  135184. static static_codebook _44c9_s_p6_0 = {
  135185. 2, 169,
  135186. _vq_lengthlist__44c9_s_p6_0,
  135187. 1, -526516224, 1616117760, 4, 0,
  135188. _vq_quantlist__44c9_s_p6_0,
  135189. NULL,
  135190. &_vq_auxt__44c9_s_p6_0,
  135191. NULL,
  135192. 0
  135193. };
  135194. static long _vq_quantlist__44c9_s_p6_1[] = {
  135195. 2,
  135196. 1,
  135197. 3,
  135198. 0,
  135199. 4,
  135200. };
  135201. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135202. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135203. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135204. };
  135205. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135206. -1.5, -0.5, 0.5, 1.5,
  135207. };
  135208. static long _vq_quantmap__44c9_s_p6_1[] = {
  135209. 3, 1, 0, 2, 4,
  135210. };
  135211. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135212. _vq_quantthresh__44c9_s_p6_1,
  135213. _vq_quantmap__44c9_s_p6_1,
  135214. 5,
  135215. 5
  135216. };
  135217. static static_codebook _44c9_s_p6_1 = {
  135218. 2, 25,
  135219. _vq_lengthlist__44c9_s_p6_1,
  135220. 1, -533725184, 1611661312, 3, 0,
  135221. _vq_quantlist__44c9_s_p6_1,
  135222. NULL,
  135223. &_vq_auxt__44c9_s_p6_1,
  135224. NULL,
  135225. 0
  135226. };
  135227. static long _vq_quantlist__44c9_s_p7_0[] = {
  135228. 6,
  135229. 5,
  135230. 7,
  135231. 4,
  135232. 8,
  135233. 3,
  135234. 9,
  135235. 2,
  135236. 10,
  135237. 1,
  135238. 11,
  135239. 0,
  135240. 12,
  135241. };
  135242. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135243. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135244. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135245. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135246. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135247. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135248. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135249. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135250. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135251. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135252. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135253. 19,12,12,12,12,13,13,14,14,
  135254. };
  135255. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135256. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135257. 27.5, 38.5, 49.5, 60.5,
  135258. };
  135259. static long _vq_quantmap__44c9_s_p7_0[] = {
  135260. 11, 9, 7, 5, 3, 1, 0, 2,
  135261. 4, 6, 8, 10, 12,
  135262. };
  135263. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135264. _vq_quantthresh__44c9_s_p7_0,
  135265. _vq_quantmap__44c9_s_p7_0,
  135266. 13,
  135267. 13
  135268. };
  135269. static static_codebook _44c9_s_p7_0 = {
  135270. 2, 169,
  135271. _vq_lengthlist__44c9_s_p7_0,
  135272. 1, -523206656, 1618345984, 4, 0,
  135273. _vq_quantlist__44c9_s_p7_0,
  135274. NULL,
  135275. &_vq_auxt__44c9_s_p7_0,
  135276. NULL,
  135277. 0
  135278. };
  135279. static long _vq_quantlist__44c9_s_p7_1[] = {
  135280. 5,
  135281. 4,
  135282. 6,
  135283. 3,
  135284. 7,
  135285. 2,
  135286. 8,
  135287. 1,
  135288. 9,
  135289. 0,
  135290. 10,
  135291. };
  135292. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135293. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135294. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135295. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135296. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135297. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135298. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135299. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135300. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135301. };
  135302. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135303. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135304. 3.5, 4.5,
  135305. };
  135306. static long _vq_quantmap__44c9_s_p7_1[] = {
  135307. 9, 7, 5, 3, 1, 0, 2, 4,
  135308. 6, 8, 10,
  135309. };
  135310. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135311. _vq_quantthresh__44c9_s_p7_1,
  135312. _vq_quantmap__44c9_s_p7_1,
  135313. 11,
  135314. 11
  135315. };
  135316. static static_codebook _44c9_s_p7_1 = {
  135317. 2, 121,
  135318. _vq_lengthlist__44c9_s_p7_1,
  135319. 1, -531365888, 1611661312, 4, 0,
  135320. _vq_quantlist__44c9_s_p7_1,
  135321. NULL,
  135322. &_vq_auxt__44c9_s_p7_1,
  135323. NULL,
  135324. 0
  135325. };
  135326. static long _vq_quantlist__44c9_s_p8_0[] = {
  135327. 7,
  135328. 6,
  135329. 8,
  135330. 5,
  135331. 9,
  135332. 4,
  135333. 10,
  135334. 3,
  135335. 11,
  135336. 2,
  135337. 12,
  135338. 1,
  135339. 13,
  135340. 0,
  135341. 14,
  135342. };
  135343. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135344. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135345. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135346. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135347. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135348. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135349. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135350. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135351. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135352. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135353. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135354. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135355. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135356. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135357. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135358. 14,
  135359. };
  135360. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135361. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135362. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135363. };
  135364. static long _vq_quantmap__44c9_s_p8_0[] = {
  135365. 13, 11, 9, 7, 5, 3, 1, 0,
  135366. 2, 4, 6, 8, 10, 12, 14,
  135367. };
  135368. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135369. _vq_quantthresh__44c9_s_p8_0,
  135370. _vq_quantmap__44c9_s_p8_0,
  135371. 15,
  135372. 15
  135373. };
  135374. static static_codebook _44c9_s_p8_0 = {
  135375. 2, 225,
  135376. _vq_lengthlist__44c9_s_p8_0,
  135377. 1, -520986624, 1620377600, 4, 0,
  135378. _vq_quantlist__44c9_s_p8_0,
  135379. NULL,
  135380. &_vq_auxt__44c9_s_p8_0,
  135381. NULL,
  135382. 0
  135383. };
  135384. static long _vq_quantlist__44c9_s_p8_1[] = {
  135385. 10,
  135386. 9,
  135387. 11,
  135388. 8,
  135389. 12,
  135390. 7,
  135391. 13,
  135392. 6,
  135393. 14,
  135394. 5,
  135395. 15,
  135396. 4,
  135397. 16,
  135398. 3,
  135399. 17,
  135400. 2,
  135401. 18,
  135402. 1,
  135403. 19,
  135404. 0,
  135405. 20,
  135406. };
  135407. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135408. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135409. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135410. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135411. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135412. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135413. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135414. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135416. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135417. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135418. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135419. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135420. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135421. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135422. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135423. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135424. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135425. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135426. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135427. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135428. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135429. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135430. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135431. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135432. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135433. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135434. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135435. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135436. };
  135437. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135438. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135439. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135440. 6.5, 7.5, 8.5, 9.5,
  135441. };
  135442. static long _vq_quantmap__44c9_s_p8_1[] = {
  135443. 19, 17, 15, 13, 11, 9, 7, 5,
  135444. 3, 1, 0, 2, 4, 6, 8, 10,
  135445. 12, 14, 16, 18, 20,
  135446. };
  135447. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135448. _vq_quantthresh__44c9_s_p8_1,
  135449. _vq_quantmap__44c9_s_p8_1,
  135450. 21,
  135451. 21
  135452. };
  135453. static static_codebook _44c9_s_p8_1 = {
  135454. 2, 441,
  135455. _vq_lengthlist__44c9_s_p8_1,
  135456. 1, -529268736, 1611661312, 5, 0,
  135457. _vq_quantlist__44c9_s_p8_1,
  135458. NULL,
  135459. &_vq_auxt__44c9_s_p8_1,
  135460. NULL,
  135461. 0
  135462. };
  135463. static long _vq_quantlist__44c9_s_p9_0[] = {
  135464. 9,
  135465. 8,
  135466. 10,
  135467. 7,
  135468. 11,
  135469. 6,
  135470. 12,
  135471. 5,
  135472. 13,
  135473. 4,
  135474. 14,
  135475. 3,
  135476. 15,
  135477. 2,
  135478. 16,
  135479. 1,
  135480. 17,
  135481. 0,
  135482. 18,
  135483. };
  135484. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135485. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135486. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135487. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135488. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135489. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135490. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135491. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135492. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135493. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135494. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135495. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135496. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135497. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135498. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135499. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135500. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135501. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135507. 11,11,11,11,11,11,11,11,11,
  135508. };
  135509. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135510. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135511. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135512. 6982.5, 7913.5,
  135513. };
  135514. static long _vq_quantmap__44c9_s_p9_0[] = {
  135515. 17, 15, 13, 11, 9, 7, 5, 3,
  135516. 1, 0, 2, 4, 6, 8, 10, 12,
  135517. 14, 16, 18,
  135518. };
  135519. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135520. _vq_quantthresh__44c9_s_p9_0,
  135521. _vq_quantmap__44c9_s_p9_0,
  135522. 19,
  135523. 19
  135524. };
  135525. static static_codebook _44c9_s_p9_0 = {
  135526. 2, 361,
  135527. _vq_lengthlist__44c9_s_p9_0,
  135528. 1, -508535424, 1631393792, 5, 0,
  135529. _vq_quantlist__44c9_s_p9_0,
  135530. NULL,
  135531. &_vq_auxt__44c9_s_p9_0,
  135532. NULL,
  135533. 0
  135534. };
  135535. static long _vq_quantlist__44c9_s_p9_1[] = {
  135536. 9,
  135537. 8,
  135538. 10,
  135539. 7,
  135540. 11,
  135541. 6,
  135542. 12,
  135543. 5,
  135544. 13,
  135545. 4,
  135546. 14,
  135547. 3,
  135548. 15,
  135549. 2,
  135550. 16,
  135551. 1,
  135552. 17,
  135553. 0,
  135554. 18,
  135555. };
  135556. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135557. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135558. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135559. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135560. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135561. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135562. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135563. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135564. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135565. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135566. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135567. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135568. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135569. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135570. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135571. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135572. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135573. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135574. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135575. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135576. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135577. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135578. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135579. 13,13,13,14,13,14,15,15,15,
  135580. };
  135581. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135582. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135583. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135584. 367.5, 416.5,
  135585. };
  135586. static long _vq_quantmap__44c9_s_p9_1[] = {
  135587. 17, 15, 13, 11, 9, 7, 5, 3,
  135588. 1, 0, 2, 4, 6, 8, 10, 12,
  135589. 14, 16, 18,
  135590. };
  135591. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135592. _vq_quantthresh__44c9_s_p9_1,
  135593. _vq_quantmap__44c9_s_p9_1,
  135594. 19,
  135595. 19
  135596. };
  135597. static static_codebook _44c9_s_p9_1 = {
  135598. 2, 361,
  135599. _vq_lengthlist__44c9_s_p9_1,
  135600. 1, -518287360, 1622704128, 5, 0,
  135601. _vq_quantlist__44c9_s_p9_1,
  135602. NULL,
  135603. &_vq_auxt__44c9_s_p9_1,
  135604. NULL,
  135605. 0
  135606. };
  135607. static long _vq_quantlist__44c9_s_p9_2[] = {
  135608. 24,
  135609. 23,
  135610. 25,
  135611. 22,
  135612. 26,
  135613. 21,
  135614. 27,
  135615. 20,
  135616. 28,
  135617. 19,
  135618. 29,
  135619. 18,
  135620. 30,
  135621. 17,
  135622. 31,
  135623. 16,
  135624. 32,
  135625. 15,
  135626. 33,
  135627. 14,
  135628. 34,
  135629. 13,
  135630. 35,
  135631. 12,
  135632. 36,
  135633. 11,
  135634. 37,
  135635. 10,
  135636. 38,
  135637. 9,
  135638. 39,
  135639. 8,
  135640. 40,
  135641. 7,
  135642. 41,
  135643. 6,
  135644. 42,
  135645. 5,
  135646. 43,
  135647. 4,
  135648. 44,
  135649. 3,
  135650. 45,
  135651. 2,
  135652. 46,
  135653. 1,
  135654. 47,
  135655. 0,
  135656. 48,
  135657. };
  135658. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135659. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135660. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135661. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135662. 7,
  135663. };
  135664. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135665. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135666. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135667. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135668. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135669. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135670. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135671. };
  135672. static long _vq_quantmap__44c9_s_p9_2[] = {
  135673. 47, 45, 43, 41, 39, 37, 35, 33,
  135674. 31, 29, 27, 25, 23, 21, 19, 17,
  135675. 15, 13, 11, 9, 7, 5, 3, 1,
  135676. 0, 2, 4, 6, 8, 10, 12, 14,
  135677. 16, 18, 20, 22, 24, 26, 28, 30,
  135678. 32, 34, 36, 38, 40, 42, 44, 46,
  135679. 48,
  135680. };
  135681. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135682. _vq_quantthresh__44c9_s_p9_2,
  135683. _vq_quantmap__44c9_s_p9_2,
  135684. 49,
  135685. 49
  135686. };
  135687. static static_codebook _44c9_s_p9_2 = {
  135688. 1, 49,
  135689. _vq_lengthlist__44c9_s_p9_2,
  135690. 1, -526909440, 1611661312, 6, 0,
  135691. _vq_quantlist__44c9_s_p9_2,
  135692. NULL,
  135693. &_vq_auxt__44c9_s_p9_2,
  135694. NULL,
  135695. 0
  135696. };
  135697. static long _huff_lengthlist__44c9_s_short[] = {
  135698. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135699. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135700. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135701. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135702. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135703. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135704. 9, 8,10,13,
  135705. };
  135706. static static_codebook _huff_book__44c9_s_short = {
  135707. 2, 100,
  135708. _huff_lengthlist__44c9_s_short,
  135709. 0, 0, 0, 0, 0,
  135710. NULL,
  135711. NULL,
  135712. NULL,
  135713. NULL,
  135714. 0
  135715. };
  135716. static long _huff_lengthlist__44c0_s_long[] = {
  135717. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135718. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135719. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135720. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135721. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135722. 12,
  135723. };
  135724. static static_codebook _huff_book__44c0_s_long = {
  135725. 2, 81,
  135726. _huff_lengthlist__44c0_s_long,
  135727. 0, 0, 0, 0, 0,
  135728. NULL,
  135729. NULL,
  135730. NULL,
  135731. NULL,
  135732. 0
  135733. };
  135734. static long _vq_quantlist__44c0_s_p1_0[] = {
  135735. 1,
  135736. 0,
  135737. 2,
  135738. };
  135739. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135740. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135741. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135746. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135751. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135786. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135791. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135796. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135832. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135837. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135842. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0,
  136151. };
  136152. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136153. -0.5, 0.5,
  136154. };
  136155. static long _vq_quantmap__44c0_s_p1_0[] = {
  136156. 1, 0, 2,
  136157. };
  136158. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136159. _vq_quantthresh__44c0_s_p1_0,
  136160. _vq_quantmap__44c0_s_p1_0,
  136161. 3,
  136162. 3
  136163. };
  136164. static static_codebook _44c0_s_p1_0 = {
  136165. 8, 6561,
  136166. _vq_lengthlist__44c0_s_p1_0,
  136167. 1, -535822336, 1611661312, 2, 0,
  136168. _vq_quantlist__44c0_s_p1_0,
  136169. NULL,
  136170. &_vq_auxt__44c0_s_p1_0,
  136171. NULL,
  136172. 0
  136173. };
  136174. static long _vq_quantlist__44c0_s_p2_0[] = {
  136175. 2,
  136176. 1,
  136177. 3,
  136178. 0,
  136179. 4,
  136180. };
  136181. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136182. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  136222. };
  136223. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136224. -1.5, -0.5, 0.5, 1.5,
  136225. };
  136226. static long _vq_quantmap__44c0_s_p2_0[] = {
  136227. 3, 1, 0, 2, 4,
  136228. };
  136229. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136230. _vq_quantthresh__44c0_s_p2_0,
  136231. _vq_quantmap__44c0_s_p2_0,
  136232. 5,
  136233. 5
  136234. };
  136235. static static_codebook _44c0_s_p2_0 = {
  136236. 4, 625,
  136237. _vq_lengthlist__44c0_s_p2_0,
  136238. 1, -533725184, 1611661312, 3, 0,
  136239. _vq_quantlist__44c0_s_p2_0,
  136240. NULL,
  136241. &_vq_auxt__44c0_s_p2_0,
  136242. NULL,
  136243. 0
  136244. };
  136245. static long _vq_quantlist__44c0_s_p3_0[] = {
  136246. 4,
  136247. 3,
  136248. 5,
  136249. 2,
  136250. 6,
  136251. 1,
  136252. 7,
  136253. 0,
  136254. 8,
  136255. };
  136256. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136257. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136258. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136259. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136260. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136261. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0,
  136263. };
  136264. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136265. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136266. };
  136267. static long _vq_quantmap__44c0_s_p3_0[] = {
  136268. 7, 5, 3, 1, 0, 2, 4, 6,
  136269. 8,
  136270. };
  136271. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136272. _vq_quantthresh__44c0_s_p3_0,
  136273. _vq_quantmap__44c0_s_p3_0,
  136274. 9,
  136275. 9
  136276. };
  136277. static static_codebook _44c0_s_p3_0 = {
  136278. 2, 81,
  136279. _vq_lengthlist__44c0_s_p3_0,
  136280. 1, -531628032, 1611661312, 4, 0,
  136281. _vq_quantlist__44c0_s_p3_0,
  136282. NULL,
  136283. &_vq_auxt__44c0_s_p3_0,
  136284. NULL,
  136285. 0
  136286. };
  136287. static long _vq_quantlist__44c0_s_p4_0[] = {
  136288. 4,
  136289. 3,
  136290. 5,
  136291. 2,
  136292. 6,
  136293. 1,
  136294. 7,
  136295. 0,
  136296. 8,
  136297. };
  136298. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136299. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136300. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136301. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136302. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136303. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136304. 10,
  136305. };
  136306. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136307. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136308. };
  136309. static long _vq_quantmap__44c0_s_p4_0[] = {
  136310. 7, 5, 3, 1, 0, 2, 4, 6,
  136311. 8,
  136312. };
  136313. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136314. _vq_quantthresh__44c0_s_p4_0,
  136315. _vq_quantmap__44c0_s_p4_0,
  136316. 9,
  136317. 9
  136318. };
  136319. static static_codebook _44c0_s_p4_0 = {
  136320. 2, 81,
  136321. _vq_lengthlist__44c0_s_p4_0,
  136322. 1, -531628032, 1611661312, 4, 0,
  136323. _vq_quantlist__44c0_s_p4_0,
  136324. NULL,
  136325. &_vq_auxt__44c0_s_p4_0,
  136326. NULL,
  136327. 0
  136328. };
  136329. static long _vq_quantlist__44c0_s_p5_0[] = {
  136330. 8,
  136331. 7,
  136332. 9,
  136333. 6,
  136334. 10,
  136335. 5,
  136336. 11,
  136337. 4,
  136338. 12,
  136339. 3,
  136340. 13,
  136341. 2,
  136342. 14,
  136343. 1,
  136344. 15,
  136345. 0,
  136346. 16,
  136347. };
  136348. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136349. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136350. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136351. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136352. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136353. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136354. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136355. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136356. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136357. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136358. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136359. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136360. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136361. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136362. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136363. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136364. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136365. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136367. 14,
  136368. };
  136369. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136370. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136371. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136372. };
  136373. static long _vq_quantmap__44c0_s_p5_0[] = {
  136374. 15, 13, 11, 9, 7, 5, 3, 1,
  136375. 0, 2, 4, 6, 8, 10, 12, 14,
  136376. 16,
  136377. };
  136378. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136379. _vq_quantthresh__44c0_s_p5_0,
  136380. _vq_quantmap__44c0_s_p5_0,
  136381. 17,
  136382. 17
  136383. };
  136384. static static_codebook _44c0_s_p5_0 = {
  136385. 2, 289,
  136386. _vq_lengthlist__44c0_s_p5_0,
  136387. 1, -529530880, 1611661312, 5, 0,
  136388. _vq_quantlist__44c0_s_p5_0,
  136389. NULL,
  136390. &_vq_auxt__44c0_s_p5_0,
  136391. NULL,
  136392. 0
  136393. };
  136394. static long _vq_quantlist__44c0_s_p6_0[] = {
  136395. 1,
  136396. 0,
  136397. 2,
  136398. };
  136399. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136400. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136401. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136402. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136403. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136404. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136405. 10,
  136406. };
  136407. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136408. -5.5, 5.5,
  136409. };
  136410. static long _vq_quantmap__44c0_s_p6_0[] = {
  136411. 1, 0, 2,
  136412. };
  136413. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136414. _vq_quantthresh__44c0_s_p6_0,
  136415. _vq_quantmap__44c0_s_p6_0,
  136416. 3,
  136417. 3
  136418. };
  136419. static static_codebook _44c0_s_p6_0 = {
  136420. 4, 81,
  136421. _vq_lengthlist__44c0_s_p6_0,
  136422. 1, -529137664, 1618345984, 2, 0,
  136423. _vq_quantlist__44c0_s_p6_0,
  136424. NULL,
  136425. &_vq_auxt__44c0_s_p6_0,
  136426. NULL,
  136427. 0
  136428. };
  136429. static long _vq_quantlist__44c0_s_p6_1[] = {
  136430. 5,
  136431. 4,
  136432. 6,
  136433. 3,
  136434. 7,
  136435. 2,
  136436. 8,
  136437. 1,
  136438. 9,
  136439. 0,
  136440. 10,
  136441. };
  136442. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136443. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136444. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136445. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136446. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136447. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136448. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136449. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136450. 10,10,10, 8, 8, 8, 8, 8, 8,
  136451. };
  136452. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136453. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136454. 3.5, 4.5,
  136455. };
  136456. static long _vq_quantmap__44c0_s_p6_1[] = {
  136457. 9, 7, 5, 3, 1, 0, 2, 4,
  136458. 6, 8, 10,
  136459. };
  136460. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136461. _vq_quantthresh__44c0_s_p6_1,
  136462. _vq_quantmap__44c0_s_p6_1,
  136463. 11,
  136464. 11
  136465. };
  136466. static static_codebook _44c0_s_p6_1 = {
  136467. 2, 121,
  136468. _vq_lengthlist__44c0_s_p6_1,
  136469. 1, -531365888, 1611661312, 4, 0,
  136470. _vq_quantlist__44c0_s_p6_1,
  136471. NULL,
  136472. &_vq_auxt__44c0_s_p6_1,
  136473. NULL,
  136474. 0
  136475. };
  136476. static long _vq_quantlist__44c0_s_p7_0[] = {
  136477. 6,
  136478. 5,
  136479. 7,
  136480. 4,
  136481. 8,
  136482. 3,
  136483. 9,
  136484. 2,
  136485. 10,
  136486. 1,
  136487. 11,
  136488. 0,
  136489. 12,
  136490. };
  136491. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136492. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136493. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136494. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136495. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136496. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136497. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136498. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136499. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136500. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136501. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136502. 0,12,12,11,11,12,12,13,13,
  136503. };
  136504. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136505. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136506. 12.5, 17.5, 22.5, 27.5,
  136507. };
  136508. static long _vq_quantmap__44c0_s_p7_0[] = {
  136509. 11, 9, 7, 5, 3, 1, 0, 2,
  136510. 4, 6, 8, 10, 12,
  136511. };
  136512. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136513. _vq_quantthresh__44c0_s_p7_0,
  136514. _vq_quantmap__44c0_s_p7_0,
  136515. 13,
  136516. 13
  136517. };
  136518. static static_codebook _44c0_s_p7_0 = {
  136519. 2, 169,
  136520. _vq_lengthlist__44c0_s_p7_0,
  136521. 1, -526516224, 1616117760, 4, 0,
  136522. _vq_quantlist__44c0_s_p7_0,
  136523. NULL,
  136524. &_vq_auxt__44c0_s_p7_0,
  136525. NULL,
  136526. 0
  136527. };
  136528. static long _vq_quantlist__44c0_s_p7_1[] = {
  136529. 2,
  136530. 1,
  136531. 3,
  136532. 0,
  136533. 4,
  136534. };
  136535. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136536. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136537. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136538. };
  136539. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136540. -1.5, -0.5, 0.5, 1.5,
  136541. };
  136542. static long _vq_quantmap__44c0_s_p7_1[] = {
  136543. 3, 1, 0, 2, 4,
  136544. };
  136545. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136546. _vq_quantthresh__44c0_s_p7_1,
  136547. _vq_quantmap__44c0_s_p7_1,
  136548. 5,
  136549. 5
  136550. };
  136551. static static_codebook _44c0_s_p7_1 = {
  136552. 2, 25,
  136553. _vq_lengthlist__44c0_s_p7_1,
  136554. 1, -533725184, 1611661312, 3, 0,
  136555. _vq_quantlist__44c0_s_p7_1,
  136556. NULL,
  136557. &_vq_auxt__44c0_s_p7_1,
  136558. NULL,
  136559. 0
  136560. };
  136561. static long _vq_quantlist__44c0_s_p8_0[] = {
  136562. 2,
  136563. 1,
  136564. 3,
  136565. 0,
  136566. 4,
  136567. };
  136568. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136569. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136570. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136571. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136572. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136573. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136574. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136575. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136576. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136577. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136578. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136579. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136580. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136581. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136582. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136584. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136585. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136586. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136587. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136588. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136589. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136590. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136608. 11,
  136609. };
  136610. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136611. -331.5, -110.5, 110.5, 331.5,
  136612. };
  136613. static long _vq_quantmap__44c0_s_p8_0[] = {
  136614. 3, 1, 0, 2, 4,
  136615. };
  136616. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136617. _vq_quantthresh__44c0_s_p8_0,
  136618. _vq_quantmap__44c0_s_p8_0,
  136619. 5,
  136620. 5
  136621. };
  136622. static static_codebook _44c0_s_p8_0 = {
  136623. 4, 625,
  136624. _vq_lengthlist__44c0_s_p8_0,
  136625. 1, -518283264, 1627103232, 3, 0,
  136626. _vq_quantlist__44c0_s_p8_0,
  136627. NULL,
  136628. &_vq_auxt__44c0_s_p8_0,
  136629. NULL,
  136630. 0
  136631. };
  136632. static long _vq_quantlist__44c0_s_p8_1[] = {
  136633. 6,
  136634. 5,
  136635. 7,
  136636. 4,
  136637. 8,
  136638. 3,
  136639. 9,
  136640. 2,
  136641. 10,
  136642. 1,
  136643. 11,
  136644. 0,
  136645. 12,
  136646. };
  136647. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136648. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136649. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136650. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136651. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136652. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136653. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136654. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136655. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136656. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136657. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136658. 16,13,13,12,12,14,14,15,13,
  136659. };
  136660. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136661. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136662. 42.5, 59.5, 76.5, 93.5,
  136663. };
  136664. static long _vq_quantmap__44c0_s_p8_1[] = {
  136665. 11, 9, 7, 5, 3, 1, 0, 2,
  136666. 4, 6, 8, 10, 12,
  136667. };
  136668. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136669. _vq_quantthresh__44c0_s_p8_1,
  136670. _vq_quantmap__44c0_s_p8_1,
  136671. 13,
  136672. 13
  136673. };
  136674. static static_codebook _44c0_s_p8_1 = {
  136675. 2, 169,
  136676. _vq_lengthlist__44c0_s_p8_1,
  136677. 1, -522616832, 1620115456, 4, 0,
  136678. _vq_quantlist__44c0_s_p8_1,
  136679. NULL,
  136680. &_vq_auxt__44c0_s_p8_1,
  136681. NULL,
  136682. 0
  136683. };
  136684. static long _vq_quantlist__44c0_s_p8_2[] = {
  136685. 8,
  136686. 7,
  136687. 9,
  136688. 6,
  136689. 10,
  136690. 5,
  136691. 11,
  136692. 4,
  136693. 12,
  136694. 3,
  136695. 13,
  136696. 2,
  136697. 14,
  136698. 1,
  136699. 15,
  136700. 0,
  136701. 16,
  136702. };
  136703. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136704. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136705. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136706. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136707. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136708. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136709. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136710. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136711. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136712. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136713. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136714. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136715. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136716. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136717. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136718. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136719. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136720. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136721. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136722. 10,
  136723. };
  136724. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136725. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136726. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136727. };
  136728. static long _vq_quantmap__44c0_s_p8_2[] = {
  136729. 15, 13, 11, 9, 7, 5, 3, 1,
  136730. 0, 2, 4, 6, 8, 10, 12, 14,
  136731. 16,
  136732. };
  136733. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136734. _vq_quantthresh__44c0_s_p8_2,
  136735. _vq_quantmap__44c0_s_p8_2,
  136736. 17,
  136737. 17
  136738. };
  136739. static static_codebook _44c0_s_p8_2 = {
  136740. 2, 289,
  136741. _vq_lengthlist__44c0_s_p8_2,
  136742. 1, -529530880, 1611661312, 5, 0,
  136743. _vq_quantlist__44c0_s_p8_2,
  136744. NULL,
  136745. &_vq_auxt__44c0_s_p8_2,
  136746. NULL,
  136747. 0
  136748. };
  136749. static long _huff_lengthlist__44c0_s_short[] = {
  136750. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136751. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136752. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136753. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136754. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136755. 12,
  136756. };
  136757. static static_codebook _huff_book__44c0_s_short = {
  136758. 2, 81,
  136759. _huff_lengthlist__44c0_s_short,
  136760. 0, 0, 0, 0, 0,
  136761. NULL,
  136762. NULL,
  136763. NULL,
  136764. NULL,
  136765. 0
  136766. };
  136767. static long _huff_lengthlist__44c0_sm_long[] = {
  136768. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136769. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136770. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136771. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136772. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136773. 13,
  136774. };
  136775. static static_codebook _huff_book__44c0_sm_long = {
  136776. 2, 81,
  136777. _huff_lengthlist__44c0_sm_long,
  136778. 0, 0, 0, 0, 0,
  136779. NULL,
  136780. NULL,
  136781. NULL,
  136782. NULL,
  136783. 0
  136784. };
  136785. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136786. 1,
  136787. 0,
  136788. 2,
  136789. };
  136790. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136791. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136792. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136797. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136802. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136837. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136842. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136847. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136883. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136888. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136893. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0,
  137202. };
  137203. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137204. -0.5, 0.5,
  137205. };
  137206. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137207. 1, 0, 2,
  137208. };
  137209. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137210. _vq_quantthresh__44c0_sm_p1_0,
  137211. _vq_quantmap__44c0_sm_p1_0,
  137212. 3,
  137213. 3
  137214. };
  137215. static static_codebook _44c0_sm_p1_0 = {
  137216. 8, 6561,
  137217. _vq_lengthlist__44c0_sm_p1_0,
  137218. 1, -535822336, 1611661312, 2, 0,
  137219. _vq_quantlist__44c0_sm_p1_0,
  137220. NULL,
  137221. &_vq_auxt__44c0_sm_p1_0,
  137222. NULL,
  137223. 0
  137224. };
  137225. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137226. 2,
  137227. 1,
  137228. 3,
  137229. 0,
  137230. 4,
  137231. };
  137232. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137233. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137273. };
  137274. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137275. -1.5, -0.5, 0.5, 1.5,
  137276. };
  137277. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137278. 3, 1, 0, 2, 4,
  137279. };
  137280. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137281. _vq_quantthresh__44c0_sm_p2_0,
  137282. _vq_quantmap__44c0_sm_p2_0,
  137283. 5,
  137284. 5
  137285. };
  137286. static static_codebook _44c0_sm_p2_0 = {
  137287. 4, 625,
  137288. _vq_lengthlist__44c0_sm_p2_0,
  137289. 1, -533725184, 1611661312, 3, 0,
  137290. _vq_quantlist__44c0_sm_p2_0,
  137291. NULL,
  137292. &_vq_auxt__44c0_sm_p2_0,
  137293. NULL,
  137294. 0
  137295. };
  137296. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137297. 4,
  137298. 3,
  137299. 5,
  137300. 2,
  137301. 6,
  137302. 1,
  137303. 7,
  137304. 0,
  137305. 8,
  137306. };
  137307. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137308. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137309. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137310. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137311. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137312. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0,
  137314. };
  137315. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137317. };
  137318. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137319. 7, 5, 3, 1, 0, 2, 4, 6,
  137320. 8,
  137321. };
  137322. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137323. _vq_quantthresh__44c0_sm_p3_0,
  137324. _vq_quantmap__44c0_sm_p3_0,
  137325. 9,
  137326. 9
  137327. };
  137328. static static_codebook _44c0_sm_p3_0 = {
  137329. 2, 81,
  137330. _vq_lengthlist__44c0_sm_p3_0,
  137331. 1, -531628032, 1611661312, 4, 0,
  137332. _vq_quantlist__44c0_sm_p3_0,
  137333. NULL,
  137334. &_vq_auxt__44c0_sm_p3_0,
  137335. NULL,
  137336. 0
  137337. };
  137338. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137339. 4,
  137340. 3,
  137341. 5,
  137342. 2,
  137343. 6,
  137344. 1,
  137345. 7,
  137346. 0,
  137347. 8,
  137348. };
  137349. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137350. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137351. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137352. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137353. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137354. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137355. 11,
  137356. };
  137357. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137358. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137359. };
  137360. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137361. 7, 5, 3, 1, 0, 2, 4, 6,
  137362. 8,
  137363. };
  137364. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137365. _vq_quantthresh__44c0_sm_p4_0,
  137366. _vq_quantmap__44c0_sm_p4_0,
  137367. 9,
  137368. 9
  137369. };
  137370. static static_codebook _44c0_sm_p4_0 = {
  137371. 2, 81,
  137372. _vq_lengthlist__44c0_sm_p4_0,
  137373. 1, -531628032, 1611661312, 4, 0,
  137374. _vq_quantlist__44c0_sm_p4_0,
  137375. NULL,
  137376. &_vq_auxt__44c0_sm_p4_0,
  137377. NULL,
  137378. 0
  137379. };
  137380. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137381. 8,
  137382. 7,
  137383. 9,
  137384. 6,
  137385. 10,
  137386. 5,
  137387. 11,
  137388. 4,
  137389. 12,
  137390. 3,
  137391. 13,
  137392. 2,
  137393. 14,
  137394. 1,
  137395. 15,
  137396. 0,
  137397. 16,
  137398. };
  137399. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137400. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137401. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137402. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137403. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137404. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137405. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137406. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137407. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137408. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137409. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137410. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137411. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137412. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137413. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137414. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137415. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137416. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137418. 14,
  137419. };
  137420. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137421. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137422. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137423. };
  137424. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137425. 15, 13, 11, 9, 7, 5, 3, 1,
  137426. 0, 2, 4, 6, 8, 10, 12, 14,
  137427. 16,
  137428. };
  137429. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137430. _vq_quantthresh__44c0_sm_p5_0,
  137431. _vq_quantmap__44c0_sm_p5_0,
  137432. 17,
  137433. 17
  137434. };
  137435. static static_codebook _44c0_sm_p5_0 = {
  137436. 2, 289,
  137437. _vq_lengthlist__44c0_sm_p5_0,
  137438. 1, -529530880, 1611661312, 5, 0,
  137439. _vq_quantlist__44c0_sm_p5_0,
  137440. NULL,
  137441. &_vq_auxt__44c0_sm_p5_0,
  137442. NULL,
  137443. 0
  137444. };
  137445. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137446. 1,
  137447. 0,
  137448. 2,
  137449. };
  137450. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137451. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137452. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137453. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137454. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137455. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137456. 11,
  137457. };
  137458. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137459. -5.5, 5.5,
  137460. };
  137461. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137462. 1, 0, 2,
  137463. };
  137464. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137465. _vq_quantthresh__44c0_sm_p6_0,
  137466. _vq_quantmap__44c0_sm_p6_0,
  137467. 3,
  137468. 3
  137469. };
  137470. static static_codebook _44c0_sm_p6_0 = {
  137471. 4, 81,
  137472. _vq_lengthlist__44c0_sm_p6_0,
  137473. 1, -529137664, 1618345984, 2, 0,
  137474. _vq_quantlist__44c0_sm_p6_0,
  137475. NULL,
  137476. &_vq_auxt__44c0_sm_p6_0,
  137477. NULL,
  137478. 0
  137479. };
  137480. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137481. 5,
  137482. 4,
  137483. 6,
  137484. 3,
  137485. 7,
  137486. 2,
  137487. 8,
  137488. 1,
  137489. 9,
  137490. 0,
  137491. 10,
  137492. };
  137493. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137494. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137495. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137496. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137497. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137498. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137499. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137500. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137501. 10,10,10, 8, 8, 8, 8, 8, 8,
  137502. };
  137503. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137504. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137505. 3.5, 4.5,
  137506. };
  137507. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137508. 9, 7, 5, 3, 1, 0, 2, 4,
  137509. 6, 8, 10,
  137510. };
  137511. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137512. _vq_quantthresh__44c0_sm_p6_1,
  137513. _vq_quantmap__44c0_sm_p6_1,
  137514. 11,
  137515. 11
  137516. };
  137517. static static_codebook _44c0_sm_p6_1 = {
  137518. 2, 121,
  137519. _vq_lengthlist__44c0_sm_p6_1,
  137520. 1, -531365888, 1611661312, 4, 0,
  137521. _vq_quantlist__44c0_sm_p6_1,
  137522. NULL,
  137523. &_vq_auxt__44c0_sm_p6_1,
  137524. NULL,
  137525. 0
  137526. };
  137527. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137528. 6,
  137529. 5,
  137530. 7,
  137531. 4,
  137532. 8,
  137533. 3,
  137534. 9,
  137535. 2,
  137536. 10,
  137537. 1,
  137538. 11,
  137539. 0,
  137540. 12,
  137541. };
  137542. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137543. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137544. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137545. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137546. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137547. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137548. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137549. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137550. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137551. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137552. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137553. 0,12,12,11,11,13,12,14,14,
  137554. };
  137555. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137556. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137557. 12.5, 17.5, 22.5, 27.5,
  137558. };
  137559. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137560. 11, 9, 7, 5, 3, 1, 0, 2,
  137561. 4, 6, 8, 10, 12,
  137562. };
  137563. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137564. _vq_quantthresh__44c0_sm_p7_0,
  137565. _vq_quantmap__44c0_sm_p7_0,
  137566. 13,
  137567. 13
  137568. };
  137569. static static_codebook _44c0_sm_p7_0 = {
  137570. 2, 169,
  137571. _vq_lengthlist__44c0_sm_p7_0,
  137572. 1, -526516224, 1616117760, 4, 0,
  137573. _vq_quantlist__44c0_sm_p7_0,
  137574. NULL,
  137575. &_vq_auxt__44c0_sm_p7_0,
  137576. NULL,
  137577. 0
  137578. };
  137579. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137580. 2,
  137581. 1,
  137582. 3,
  137583. 0,
  137584. 4,
  137585. };
  137586. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137587. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137588. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137589. };
  137590. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137591. -1.5, -0.5, 0.5, 1.5,
  137592. };
  137593. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137594. 3, 1, 0, 2, 4,
  137595. };
  137596. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137597. _vq_quantthresh__44c0_sm_p7_1,
  137598. _vq_quantmap__44c0_sm_p7_1,
  137599. 5,
  137600. 5
  137601. };
  137602. static static_codebook _44c0_sm_p7_1 = {
  137603. 2, 25,
  137604. _vq_lengthlist__44c0_sm_p7_1,
  137605. 1, -533725184, 1611661312, 3, 0,
  137606. _vq_quantlist__44c0_sm_p7_1,
  137607. NULL,
  137608. &_vq_auxt__44c0_sm_p7_1,
  137609. NULL,
  137610. 0
  137611. };
  137612. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137613. 4,
  137614. 3,
  137615. 5,
  137616. 2,
  137617. 6,
  137618. 1,
  137619. 7,
  137620. 0,
  137621. 8,
  137622. };
  137623. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137624. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137625. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137627. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137628. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137629. 12,
  137630. };
  137631. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137632. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137633. };
  137634. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137635. 7, 5, 3, 1, 0, 2, 4, 6,
  137636. 8,
  137637. };
  137638. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137639. _vq_quantthresh__44c0_sm_p8_0,
  137640. _vq_quantmap__44c0_sm_p8_0,
  137641. 9,
  137642. 9
  137643. };
  137644. static static_codebook _44c0_sm_p8_0 = {
  137645. 2, 81,
  137646. _vq_lengthlist__44c0_sm_p8_0,
  137647. 1, -516186112, 1627103232, 4, 0,
  137648. _vq_quantlist__44c0_sm_p8_0,
  137649. NULL,
  137650. &_vq_auxt__44c0_sm_p8_0,
  137651. NULL,
  137652. 0
  137653. };
  137654. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137655. 6,
  137656. 5,
  137657. 7,
  137658. 4,
  137659. 8,
  137660. 3,
  137661. 9,
  137662. 2,
  137663. 10,
  137664. 1,
  137665. 11,
  137666. 0,
  137667. 12,
  137668. };
  137669. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137670. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137671. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137672. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137673. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137674. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137675. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137676. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137677. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137678. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137679. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137680. 20,13,13,12,12,16,13,15,13,
  137681. };
  137682. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137683. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137684. 42.5, 59.5, 76.5, 93.5,
  137685. };
  137686. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137687. 11, 9, 7, 5, 3, 1, 0, 2,
  137688. 4, 6, 8, 10, 12,
  137689. };
  137690. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137691. _vq_quantthresh__44c0_sm_p8_1,
  137692. _vq_quantmap__44c0_sm_p8_1,
  137693. 13,
  137694. 13
  137695. };
  137696. static static_codebook _44c0_sm_p8_1 = {
  137697. 2, 169,
  137698. _vq_lengthlist__44c0_sm_p8_1,
  137699. 1, -522616832, 1620115456, 4, 0,
  137700. _vq_quantlist__44c0_sm_p8_1,
  137701. NULL,
  137702. &_vq_auxt__44c0_sm_p8_1,
  137703. NULL,
  137704. 0
  137705. };
  137706. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137707. 8,
  137708. 7,
  137709. 9,
  137710. 6,
  137711. 10,
  137712. 5,
  137713. 11,
  137714. 4,
  137715. 12,
  137716. 3,
  137717. 13,
  137718. 2,
  137719. 14,
  137720. 1,
  137721. 15,
  137722. 0,
  137723. 16,
  137724. };
  137725. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137726. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137727. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137728. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137729. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137730. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137731. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137732. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137733. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137734. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137735. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137736. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137737. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137738. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137739. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137740. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137741. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137742. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137743. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137744. 9,
  137745. };
  137746. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137747. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137748. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137749. };
  137750. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137751. 15, 13, 11, 9, 7, 5, 3, 1,
  137752. 0, 2, 4, 6, 8, 10, 12, 14,
  137753. 16,
  137754. };
  137755. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137756. _vq_quantthresh__44c0_sm_p8_2,
  137757. _vq_quantmap__44c0_sm_p8_2,
  137758. 17,
  137759. 17
  137760. };
  137761. static static_codebook _44c0_sm_p8_2 = {
  137762. 2, 289,
  137763. _vq_lengthlist__44c0_sm_p8_2,
  137764. 1, -529530880, 1611661312, 5, 0,
  137765. _vq_quantlist__44c0_sm_p8_2,
  137766. NULL,
  137767. &_vq_auxt__44c0_sm_p8_2,
  137768. NULL,
  137769. 0
  137770. };
  137771. static long _huff_lengthlist__44c0_sm_short[] = {
  137772. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137773. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137774. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137775. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137776. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137777. 12,
  137778. };
  137779. static static_codebook _huff_book__44c0_sm_short = {
  137780. 2, 81,
  137781. _huff_lengthlist__44c0_sm_short,
  137782. 0, 0, 0, 0, 0,
  137783. NULL,
  137784. NULL,
  137785. NULL,
  137786. NULL,
  137787. 0
  137788. };
  137789. static long _huff_lengthlist__44c1_s_long[] = {
  137790. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137791. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137792. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137793. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137794. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137795. 11,
  137796. };
  137797. static static_codebook _huff_book__44c1_s_long = {
  137798. 2, 81,
  137799. _huff_lengthlist__44c1_s_long,
  137800. 0, 0, 0, 0, 0,
  137801. NULL,
  137802. NULL,
  137803. NULL,
  137804. NULL,
  137805. 0
  137806. };
  137807. static long _vq_quantlist__44c1_s_p1_0[] = {
  137808. 1,
  137809. 0,
  137810. 2,
  137811. };
  137812. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137813. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137814. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137819. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137824. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137859. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137864. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137869. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137905. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137910. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137915. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0,
  138224. };
  138225. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138226. -0.5, 0.5,
  138227. };
  138228. static long _vq_quantmap__44c1_s_p1_0[] = {
  138229. 1, 0, 2,
  138230. };
  138231. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138232. _vq_quantthresh__44c1_s_p1_0,
  138233. _vq_quantmap__44c1_s_p1_0,
  138234. 3,
  138235. 3
  138236. };
  138237. static static_codebook _44c1_s_p1_0 = {
  138238. 8, 6561,
  138239. _vq_lengthlist__44c1_s_p1_0,
  138240. 1, -535822336, 1611661312, 2, 0,
  138241. _vq_quantlist__44c1_s_p1_0,
  138242. NULL,
  138243. &_vq_auxt__44c1_s_p1_0,
  138244. NULL,
  138245. 0
  138246. };
  138247. static long _vq_quantlist__44c1_s_p2_0[] = {
  138248. 2,
  138249. 1,
  138250. 3,
  138251. 0,
  138252. 4,
  138253. };
  138254. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138255. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138295. };
  138296. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138297. -1.5, -0.5, 0.5, 1.5,
  138298. };
  138299. static long _vq_quantmap__44c1_s_p2_0[] = {
  138300. 3, 1, 0, 2, 4,
  138301. };
  138302. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138303. _vq_quantthresh__44c1_s_p2_0,
  138304. _vq_quantmap__44c1_s_p2_0,
  138305. 5,
  138306. 5
  138307. };
  138308. static static_codebook _44c1_s_p2_0 = {
  138309. 4, 625,
  138310. _vq_lengthlist__44c1_s_p2_0,
  138311. 1, -533725184, 1611661312, 3, 0,
  138312. _vq_quantlist__44c1_s_p2_0,
  138313. NULL,
  138314. &_vq_auxt__44c1_s_p2_0,
  138315. NULL,
  138316. 0
  138317. };
  138318. static long _vq_quantlist__44c1_s_p3_0[] = {
  138319. 4,
  138320. 3,
  138321. 5,
  138322. 2,
  138323. 6,
  138324. 1,
  138325. 7,
  138326. 0,
  138327. 8,
  138328. };
  138329. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138330. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138331. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138332. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138333. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138334. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0,
  138336. };
  138337. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138338. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138339. };
  138340. static long _vq_quantmap__44c1_s_p3_0[] = {
  138341. 7, 5, 3, 1, 0, 2, 4, 6,
  138342. 8,
  138343. };
  138344. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138345. _vq_quantthresh__44c1_s_p3_0,
  138346. _vq_quantmap__44c1_s_p3_0,
  138347. 9,
  138348. 9
  138349. };
  138350. static static_codebook _44c1_s_p3_0 = {
  138351. 2, 81,
  138352. _vq_lengthlist__44c1_s_p3_0,
  138353. 1, -531628032, 1611661312, 4, 0,
  138354. _vq_quantlist__44c1_s_p3_0,
  138355. NULL,
  138356. &_vq_auxt__44c1_s_p3_0,
  138357. NULL,
  138358. 0
  138359. };
  138360. static long _vq_quantlist__44c1_s_p4_0[] = {
  138361. 4,
  138362. 3,
  138363. 5,
  138364. 2,
  138365. 6,
  138366. 1,
  138367. 7,
  138368. 0,
  138369. 8,
  138370. };
  138371. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138372. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138373. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138374. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138375. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138376. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138377. 11,
  138378. };
  138379. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138380. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138381. };
  138382. static long _vq_quantmap__44c1_s_p4_0[] = {
  138383. 7, 5, 3, 1, 0, 2, 4, 6,
  138384. 8,
  138385. };
  138386. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138387. _vq_quantthresh__44c1_s_p4_0,
  138388. _vq_quantmap__44c1_s_p4_0,
  138389. 9,
  138390. 9
  138391. };
  138392. static static_codebook _44c1_s_p4_0 = {
  138393. 2, 81,
  138394. _vq_lengthlist__44c1_s_p4_0,
  138395. 1, -531628032, 1611661312, 4, 0,
  138396. _vq_quantlist__44c1_s_p4_0,
  138397. NULL,
  138398. &_vq_auxt__44c1_s_p4_0,
  138399. NULL,
  138400. 0
  138401. };
  138402. static long _vq_quantlist__44c1_s_p5_0[] = {
  138403. 8,
  138404. 7,
  138405. 9,
  138406. 6,
  138407. 10,
  138408. 5,
  138409. 11,
  138410. 4,
  138411. 12,
  138412. 3,
  138413. 13,
  138414. 2,
  138415. 14,
  138416. 1,
  138417. 15,
  138418. 0,
  138419. 16,
  138420. };
  138421. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138422. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138423. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138424. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138425. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138426. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138427. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138428. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138429. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138430. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138431. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138432. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138433. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138434. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138435. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138436. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138437. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138438. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138440. 14,
  138441. };
  138442. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138443. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138444. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138445. };
  138446. static long _vq_quantmap__44c1_s_p5_0[] = {
  138447. 15, 13, 11, 9, 7, 5, 3, 1,
  138448. 0, 2, 4, 6, 8, 10, 12, 14,
  138449. 16,
  138450. };
  138451. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138452. _vq_quantthresh__44c1_s_p5_0,
  138453. _vq_quantmap__44c1_s_p5_0,
  138454. 17,
  138455. 17
  138456. };
  138457. static static_codebook _44c1_s_p5_0 = {
  138458. 2, 289,
  138459. _vq_lengthlist__44c1_s_p5_0,
  138460. 1, -529530880, 1611661312, 5, 0,
  138461. _vq_quantlist__44c1_s_p5_0,
  138462. NULL,
  138463. &_vq_auxt__44c1_s_p5_0,
  138464. NULL,
  138465. 0
  138466. };
  138467. static long _vq_quantlist__44c1_s_p6_0[] = {
  138468. 1,
  138469. 0,
  138470. 2,
  138471. };
  138472. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138473. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138474. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138475. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138476. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138477. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138478. 11,
  138479. };
  138480. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138481. -5.5, 5.5,
  138482. };
  138483. static long _vq_quantmap__44c1_s_p6_0[] = {
  138484. 1, 0, 2,
  138485. };
  138486. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138487. _vq_quantthresh__44c1_s_p6_0,
  138488. _vq_quantmap__44c1_s_p6_0,
  138489. 3,
  138490. 3
  138491. };
  138492. static static_codebook _44c1_s_p6_0 = {
  138493. 4, 81,
  138494. _vq_lengthlist__44c1_s_p6_0,
  138495. 1, -529137664, 1618345984, 2, 0,
  138496. _vq_quantlist__44c1_s_p6_0,
  138497. NULL,
  138498. &_vq_auxt__44c1_s_p6_0,
  138499. NULL,
  138500. 0
  138501. };
  138502. static long _vq_quantlist__44c1_s_p6_1[] = {
  138503. 5,
  138504. 4,
  138505. 6,
  138506. 3,
  138507. 7,
  138508. 2,
  138509. 8,
  138510. 1,
  138511. 9,
  138512. 0,
  138513. 10,
  138514. };
  138515. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138516. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138517. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138518. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138519. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138520. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138521. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138522. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138523. 10,10,10, 8, 8, 8, 8, 8, 8,
  138524. };
  138525. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138526. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138527. 3.5, 4.5,
  138528. };
  138529. static long _vq_quantmap__44c1_s_p6_1[] = {
  138530. 9, 7, 5, 3, 1, 0, 2, 4,
  138531. 6, 8, 10,
  138532. };
  138533. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138534. _vq_quantthresh__44c1_s_p6_1,
  138535. _vq_quantmap__44c1_s_p6_1,
  138536. 11,
  138537. 11
  138538. };
  138539. static static_codebook _44c1_s_p6_1 = {
  138540. 2, 121,
  138541. _vq_lengthlist__44c1_s_p6_1,
  138542. 1, -531365888, 1611661312, 4, 0,
  138543. _vq_quantlist__44c1_s_p6_1,
  138544. NULL,
  138545. &_vq_auxt__44c1_s_p6_1,
  138546. NULL,
  138547. 0
  138548. };
  138549. static long _vq_quantlist__44c1_s_p7_0[] = {
  138550. 6,
  138551. 5,
  138552. 7,
  138553. 4,
  138554. 8,
  138555. 3,
  138556. 9,
  138557. 2,
  138558. 10,
  138559. 1,
  138560. 11,
  138561. 0,
  138562. 12,
  138563. };
  138564. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138565. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138566. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138567. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138568. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138569. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138570. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138571. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138572. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138573. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138574. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138575. 0,12,11,11,11,13,10,14,13,
  138576. };
  138577. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138578. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138579. 12.5, 17.5, 22.5, 27.5,
  138580. };
  138581. static long _vq_quantmap__44c1_s_p7_0[] = {
  138582. 11, 9, 7, 5, 3, 1, 0, 2,
  138583. 4, 6, 8, 10, 12,
  138584. };
  138585. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138586. _vq_quantthresh__44c1_s_p7_0,
  138587. _vq_quantmap__44c1_s_p7_0,
  138588. 13,
  138589. 13
  138590. };
  138591. static static_codebook _44c1_s_p7_0 = {
  138592. 2, 169,
  138593. _vq_lengthlist__44c1_s_p7_0,
  138594. 1, -526516224, 1616117760, 4, 0,
  138595. _vq_quantlist__44c1_s_p7_0,
  138596. NULL,
  138597. &_vq_auxt__44c1_s_p7_0,
  138598. NULL,
  138599. 0
  138600. };
  138601. static long _vq_quantlist__44c1_s_p7_1[] = {
  138602. 2,
  138603. 1,
  138604. 3,
  138605. 0,
  138606. 4,
  138607. };
  138608. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138609. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138610. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138611. };
  138612. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138613. -1.5, -0.5, 0.5, 1.5,
  138614. };
  138615. static long _vq_quantmap__44c1_s_p7_1[] = {
  138616. 3, 1, 0, 2, 4,
  138617. };
  138618. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138619. _vq_quantthresh__44c1_s_p7_1,
  138620. _vq_quantmap__44c1_s_p7_1,
  138621. 5,
  138622. 5
  138623. };
  138624. static static_codebook _44c1_s_p7_1 = {
  138625. 2, 25,
  138626. _vq_lengthlist__44c1_s_p7_1,
  138627. 1, -533725184, 1611661312, 3, 0,
  138628. _vq_quantlist__44c1_s_p7_1,
  138629. NULL,
  138630. &_vq_auxt__44c1_s_p7_1,
  138631. NULL,
  138632. 0
  138633. };
  138634. static long _vq_quantlist__44c1_s_p8_0[] = {
  138635. 6,
  138636. 5,
  138637. 7,
  138638. 4,
  138639. 8,
  138640. 3,
  138641. 9,
  138642. 2,
  138643. 10,
  138644. 1,
  138645. 11,
  138646. 0,
  138647. 12,
  138648. };
  138649. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138650. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138651. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138652. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138653. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138654. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138655. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138656. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138657. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138658. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138659. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138660. 10,10,10,10,10,10,10,10,10,
  138661. };
  138662. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138663. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138664. 552.5, 773.5, 994.5, 1215.5,
  138665. };
  138666. static long _vq_quantmap__44c1_s_p8_0[] = {
  138667. 11, 9, 7, 5, 3, 1, 0, 2,
  138668. 4, 6, 8, 10, 12,
  138669. };
  138670. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138671. _vq_quantthresh__44c1_s_p8_0,
  138672. _vq_quantmap__44c1_s_p8_0,
  138673. 13,
  138674. 13
  138675. };
  138676. static static_codebook _44c1_s_p8_0 = {
  138677. 2, 169,
  138678. _vq_lengthlist__44c1_s_p8_0,
  138679. 1, -514541568, 1627103232, 4, 0,
  138680. _vq_quantlist__44c1_s_p8_0,
  138681. NULL,
  138682. &_vq_auxt__44c1_s_p8_0,
  138683. NULL,
  138684. 0
  138685. };
  138686. static long _vq_quantlist__44c1_s_p8_1[] = {
  138687. 6,
  138688. 5,
  138689. 7,
  138690. 4,
  138691. 8,
  138692. 3,
  138693. 9,
  138694. 2,
  138695. 10,
  138696. 1,
  138697. 11,
  138698. 0,
  138699. 12,
  138700. };
  138701. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138702. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138703. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138704. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138705. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138706. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138707. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138708. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138709. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138710. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138711. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138712. 16,13,12,12,11,14,12,15,13,
  138713. };
  138714. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138715. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138716. 42.5, 59.5, 76.5, 93.5,
  138717. };
  138718. static long _vq_quantmap__44c1_s_p8_1[] = {
  138719. 11, 9, 7, 5, 3, 1, 0, 2,
  138720. 4, 6, 8, 10, 12,
  138721. };
  138722. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138723. _vq_quantthresh__44c1_s_p8_1,
  138724. _vq_quantmap__44c1_s_p8_1,
  138725. 13,
  138726. 13
  138727. };
  138728. static static_codebook _44c1_s_p8_1 = {
  138729. 2, 169,
  138730. _vq_lengthlist__44c1_s_p8_1,
  138731. 1, -522616832, 1620115456, 4, 0,
  138732. _vq_quantlist__44c1_s_p8_1,
  138733. NULL,
  138734. &_vq_auxt__44c1_s_p8_1,
  138735. NULL,
  138736. 0
  138737. };
  138738. static long _vq_quantlist__44c1_s_p8_2[] = {
  138739. 8,
  138740. 7,
  138741. 9,
  138742. 6,
  138743. 10,
  138744. 5,
  138745. 11,
  138746. 4,
  138747. 12,
  138748. 3,
  138749. 13,
  138750. 2,
  138751. 14,
  138752. 1,
  138753. 15,
  138754. 0,
  138755. 16,
  138756. };
  138757. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138758. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138759. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138760. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138761. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138762. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138763. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138764. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138765. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138766. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138767. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138768. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138769. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138770. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138771. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138772. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138773. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138774. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138775. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138776. 9,
  138777. };
  138778. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138779. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138780. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138781. };
  138782. static long _vq_quantmap__44c1_s_p8_2[] = {
  138783. 15, 13, 11, 9, 7, 5, 3, 1,
  138784. 0, 2, 4, 6, 8, 10, 12, 14,
  138785. 16,
  138786. };
  138787. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138788. _vq_quantthresh__44c1_s_p8_2,
  138789. _vq_quantmap__44c1_s_p8_2,
  138790. 17,
  138791. 17
  138792. };
  138793. static static_codebook _44c1_s_p8_2 = {
  138794. 2, 289,
  138795. _vq_lengthlist__44c1_s_p8_2,
  138796. 1, -529530880, 1611661312, 5, 0,
  138797. _vq_quantlist__44c1_s_p8_2,
  138798. NULL,
  138799. &_vq_auxt__44c1_s_p8_2,
  138800. NULL,
  138801. 0
  138802. };
  138803. static long _huff_lengthlist__44c1_s_short[] = {
  138804. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138805. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138806. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138807. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138808. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138809. 11,
  138810. };
  138811. static static_codebook _huff_book__44c1_s_short = {
  138812. 2, 81,
  138813. _huff_lengthlist__44c1_s_short,
  138814. 0, 0, 0, 0, 0,
  138815. NULL,
  138816. NULL,
  138817. NULL,
  138818. NULL,
  138819. 0
  138820. };
  138821. static long _huff_lengthlist__44c1_sm_long[] = {
  138822. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138823. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138824. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138825. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138826. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138827. 11,
  138828. };
  138829. static static_codebook _huff_book__44c1_sm_long = {
  138830. 2, 81,
  138831. _huff_lengthlist__44c1_sm_long,
  138832. 0, 0, 0, 0, 0,
  138833. NULL,
  138834. NULL,
  138835. NULL,
  138836. NULL,
  138837. 0
  138838. };
  138839. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138840. 1,
  138841. 0,
  138842. 2,
  138843. };
  138844. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138845. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138846. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138851. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138856. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138891. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138896. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138901. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138937. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138942. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138947. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0,
  139256. };
  139257. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139258. -0.5, 0.5,
  139259. };
  139260. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139261. 1, 0, 2,
  139262. };
  139263. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139264. _vq_quantthresh__44c1_sm_p1_0,
  139265. _vq_quantmap__44c1_sm_p1_0,
  139266. 3,
  139267. 3
  139268. };
  139269. static static_codebook _44c1_sm_p1_0 = {
  139270. 8, 6561,
  139271. _vq_lengthlist__44c1_sm_p1_0,
  139272. 1, -535822336, 1611661312, 2, 0,
  139273. _vq_quantlist__44c1_sm_p1_0,
  139274. NULL,
  139275. &_vq_auxt__44c1_sm_p1_0,
  139276. NULL,
  139277. 0
  139278. };
  139279. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139280. 2,
  139281. 1,
  139282. 3,
  139283. 0,
  139284. 4,
  139285. };
  139286. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139287. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139327. };
  139328. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139329. -1.5, -0.5, 0.5, 1.5,
  139330. };
  139331. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139332. 3, 1, 0, 2, 4,
  139333. };
  139334. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139335. _vq_quantthresh__44c1_sm_p2_0,
  139336. _vq_quantmap__44c1_sm_p2_0,
  139337. 5,
  139338. 5
  139339. };
  139340. static static_codebook _44c1_sm_p2_0 = {
  139341. 4, 625,
  139342. _vq_lengthlist__44c1_sm_p2_0,
  139343. 1, -533725184, 1611661312, 3, 0,
  139344. _vq_quantlist__44c1_sm_p2_0,
  139345. NULL,
  139346. &_vq_auxt__44c1_sm_p2_0,
  139347. NULL,
  139348. 0
  139349. };
  139350. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139351. 4,
  139352. 3,
  139353. 5,
  139354. 2,
  139355. 6,
  139356. 1,
  139357. 7,
  139358. 0,
  139359. 8,
  139360. };
  139361. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139362. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139363. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139364. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139365. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139366. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0,
  139368. };
  139369. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139370. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139371. };
  139372. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139373. 7, 5, 3, 1, 0, 2, 4, 6,
  139374. 8,
  139375. };
  139376. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139377. _vq_quantthresh__44c1_sm_p3_0,
  139378. _vq_quantmap__44c1_sm_p3_0,
  139379. 9,
  139380. 9
  139381. };
  139382. static static_codebook _44c1_sm_p3_0 = {
  139383. 2, 81,
  139384. _vq_lengthlist__44c1_sm_p3_0,
  139385. 1, -531628032, 1611661312, 4, 0,
  139386. _vq_quantlist__44c1_sm_p3_0,
  139387. NULL,
  139388. &_vq_auxt__44c1_sm_p3_0,
  139389. NULL,
  139390. 0
  139391. };
  139392. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139393. 4,
  139394. 3,
  139395. 5,
  139396. 2,
  139397. 6,
  139398. 1,
  139399. 7,
  139400. 0,
  139401. 8,
  139402. };
  139403. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139404. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139405. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139406. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139407. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139408. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139409. 11,
  139410. };
  139411. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139412. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139413. };
  139414. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139415. 7, 5, 3, 1, 0, 2, 4, 6,
  139416. 8,
  139417. };
  139418. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139419. _vq_quantthresh__44c1_sm_p4_0,
  139420. _vq_quantmap__44c1_sm_p4_0,
  139421. 9,
  139422. 9
  139423. };
  139424. static static_codebook _44c1_sm_p4_0 = {
  139425. 2, 81,
  139426. _vq_lengthlist__44c1_sm_p4_0,
  139427. 1, -531628032, 1611661312, 4, 0,
  139428. _vq_quantlist__44c1_sm_p4_0,
  139429. NULL,
  139430. &_vq_auxt__44c1_sm_p4_0,
  139431. NULL,
  139432. 0
  139433. };
  139434. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139435. 8,
  139436. 7,
  139437. 9,
  139438. 6,
  139439. 10,
  139440. 5,
  139441. 11,
  139442. 4,
  139443. 12,
  139444. 3,
  139445. 13,
  139446. 2,
  139447. 14,
  139448. 1,
  139449. 15,
  139450. 0,
  139451. 16,
  139452. };
  139453. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139454. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139455. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139456. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139457. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139458. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139459. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139460. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139461. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139462. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139463. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139464. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139465. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139466. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139467. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139468. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139469. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139470. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139472. 14,
  139473. };
  139474. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139475. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139476. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139477. };
  139478. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139479. 15, 13, 11, 9, 7, 5, 3, 1,
  139480. 0, 2, 4, 6, 8, 10, 12, 14,
  139481. 16,
  139482. };
  139483. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139484. _vq_quantthresh__44c1_sm_p5_0,
  139485. _vq_quantmap__44c1_sm_p5_0,
  139486. 17,
  139487. 17
  139488. };
  139489. static static_codebook _44c1_sm_p5_0 = {
  139490. 2, 289,
  139491. _vq_lengthlist__44c1_sm_p5_0,
  139492. 1, -529530880, 1611661312, 5, 0,
  139493. _vq_quantlist__44c1_sm_p5_0,
  139494. NULL,
  139495. &_vq_auxt__44c1_sm_p5_0,
  139496. NULL,
  139497. 0
  139498. };
  139499. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139500. 1,
  139501. 0,
  139502. 2,
  139503. };
  139504. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139505. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139506. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139507. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139508. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139509. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139510. 11,
  139511. };
  139512. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139513. -5.5, 5.5,
  139514. };
  139515. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139516. 1, 0, 2,
  139517. };
  139518. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139519. _vq_quantthresh__44c1_sm_p6_0,
  139520. _vq_quantmap__44c1_sm_p6_0,
  139521. 3,
  139522. 3
  139523. };
  139524. static static_codebook _44c1_sm_p6_0 = {
  139525. 4, 81,
  139526. _vq_lengthlist__44c1_sm_p6_0,
  139527. 1, -529137664, 1618345984, 2, 0,
  139528. _vq_quantlist__44c1_sm_p6_0,
  139529. NULL,
  139530. &_vq_auxt__44c1_sm_p6_0,
  139531. NULL,
  139532. 0
  139533. };
  139534. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139535. 5,
  139536. 4,
  139537. 6,
  139538. 3,
  139539. 7,
  139540. 2,
  139541. 8,
  139542. 1,
  139543. 9,
  139544. 0,
  139545. 10,
  139546. };
  139547. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139548. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139549. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139550. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139551. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139552. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139553. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139554. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139555. 10,10,10, 8, 8, 8, 8, 8, 8,
  139556. };
  139557. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139558. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139559. 3.5, 4.5,
  139560. };
  139561. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139562. 9, 7, 5, 3, 1, 0, 2, 4,
  139563. 6, 8, 10,
  139564. };
  139565. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139566. _vq_quantthresh__44c1_sm_p6_1,
  139567. _vq_quantmap__44c1_sm_p6_1,
  139568. 11,
  139569. 11
  139570. };
  139571. static static_codebook _44c1_sm_p6_1 = {
  139572. 2, 121,
  139573. _vq_lengthlist__44c1_sm_p6_1,
  139574. 1, -531365888, 1611661312, 4, 0,
  139575. _vq_quantlist__44c1_sm_p6_1,
  139576. NULL,
  139577. &_vq_auxt__44c1_sm_p6_1,
  139578. NULL,
  139579. 0
  139580. };
  139581. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139582. 6,
  139583. 5,
  139584. 7,
  139585. 4,
  139586. 8,
  139587. 3,
  139588. 9,
  139589. 2,
  139590. 10,
  139591. 1,
  139592. 11,
  139593. 0,
  139594. 12,
  139595. };
  139596. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139597. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139598. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139599. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139600. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139601. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139602. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139603. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139604. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139605. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139606. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139607. 0,12,12,11,11,13,12,14,13,
  139608. };
  139609. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139610. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139611. 12.5, 17.5, 22.5, 27.5,
  139612. };
  139613. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139614. 11, 9, 7, 5, 3, 1, 0, 2,
  139615. 4, 6, 8, 10, 12,
  139616. };
  139617. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139618. _vq_quantthresh__44c1_sm_p7_0,
  139619. _vq_quantmap__44c1_sm_p7_0,
  139620. 13,
  139621. 13
  139622. };
  139623. static static_codebook _44c1_sm_p7_0 = {
  139624. 2, 169,
  139625. _vq_lengthlist__44c1_sm_p7_0,
  139626. 1, -526516224, 1616117760, 4, 0,
  139627. _vq_quantlist__44c1_sm_p7_0,
  139628. NULL,
  139629. &_vq_auxt__44c1_sm_p7_0,
  139630. NULL,
  139631. 0
  139632. };
  139633. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139634. 2,
  139635. 1,
  139636. 3,
  139637. 0,
  139638. 4,
  139639. };
  139640. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139641. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139642. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139643. };
  139644. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139645. -1.5, -0.5, 0.5, 1.5,
  139646. };
  139647. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139648. 3, 1, 0, 2, 4,
  139649. };
  139650. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139651. _vq_quantthresh__44c1_sm_p7_1,
  139652. _vq_quantmap__44c1_sm_p7_1,
  139653. 5,
  139654. 5
  139655. };
  139656. static static_codebook _44c1_sm_p7_1 = {
  139657. 2, 25,
  139658. _vq_lengthlist__44c1_sm_p7_1,
  139659. 1, -533725184, 1611661312, 3, 0,
  139660. _vq_quantlist__44c1_sm_p7_1,
  139661. NULL,
  139662. &_vq_auxt__44c1_sm_p7_1,
  139663. NULL,
  139664. 0
  139665. };
  139666. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139667. 6,
  139668. 5,
  139669. 7,
  139670. 4,
  139671. 8,
  139672. 3,
  139673. 9,
  139674. 2,
  139675. 10,
  139676. 1,
  139677. 11,
  139678. 0,
  139679. 12,
  139680. };
  139681. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139682. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139683. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139684. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139685. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139686. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139687. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139688. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139689. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139690. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139691. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139692. 13,13,13,13,13,13,13,13,13,
  139693. };
  139694. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139695. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139696. 552.5, 773.5, 994.5, 1215.5,
  139697. };
  139698. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139699. 11, 9, 7, 5, 3, 1, 0, 2,
  139700. 4, 6, 8, 10, 12,
  139701. };
  139702. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139703. _vq_quantthresh__44c1_sm_p8_0,
  139704. _vq_quantmap__44c1_sm_p8_0,
  139705. 13,
  139706. 13
  139707. };
  139708. static static_codebook _44c1_sm_p8_0 = {
  139709. 2, 169,
  139710. _vq_lengthlist__44c1_sm_p8_0,
  139711. 1, -514541568, 1627103232, 4, 0,
  139712. _vq_quantlist__44c1_sm_p8_0,
  139713. NULL,
  139714. &_vq_auxt__44c1_sm_p8_0,
  139715. NULL,
  139716. 0
  139717. };
  139718. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139719. 6,
  139720. 5,
  139721. 7,
  139722. 4,
  139723. 8,
  139724. 3,
  139725. 9,
  139726. 2,
  139727. 10,
  139728. 1,
  139729. 11,
  139730. 0,
  139731. 12,
  139732. };
  139733. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139734. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139735. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139736. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139737. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139738. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139739. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139740. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139741. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139742. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139743. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139744. 20,13,12,12,12,14,12,14,13,
  139745. };
  139746. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139747. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139748. 42.5, 59.5, 76.5, 93.5,
  139749. };
  139750. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139751. 11, 9, 7, 5, 3, 1, 0, 2,
  139752. 4, 6, 8, 10, 12,
  139753. };
  139754. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139755. _vq_quantthresh__44c1_sm_p8_1,
  139756. _vq_quantmap__44c1_sm_p8_1,
  139757. 13,
  139758. 13
  139759. };
  139760. static static_codebook _44c1_sm_p8_1 = {
  139761. 2, 169,
  139762. _vq_lengthlist__44c1_sm_p8_1,
  139763. 1, -522616832, 1620115456, 4, 0,
  139764. _vq_quantlist__44c1_sm_p8_1,
  139765. NULL,
  139766. &_vq_auxt__44c1_sm_p8_1,
  139767. NULL,
  139768. 0
  139769. };
  139770. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139771. 8,
  139772. 7,
  139773. 9,
  139774. 6,
  139775. 10,
  139776. 5,
  139777. 11,
  139778. 4,
  139779. 12,
  139780. 3,
  139781. 13,
  139782. 2,
  139783. 14,
  139784. 1,
  139785. 15,
  139786. 0,
  139787. 16,
  139788. };
  139789. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139790. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139791. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139792. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139793. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139794. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139795. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139796. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139797. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139798. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139799. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139800. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139801. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139802. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139803. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139804. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139805. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139806. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139807. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139808. 9,
  139809. };
  139810. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139811. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139812. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139813. };
  139814. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139815. 15, 13, 11, 9, 7, 5, 3, 1,
  139816. 0, 2, 4, 6, 8, 10, 12, 14,
  139817. 16,
  139818. };
  139819. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139820. _vq_quantthresh__44c1_sm_p8_2,
  139821. _vq_quantmap__44c1_sm_p8_2,
  139822. 17,
  139823. 17
  139824. };
  139825. static static_codebook _44c1_sm_p8_2 = {
  139826. 2, 289,
  139827. _vq_lengthlist__44c1_sm_p8_2,
  139828. 1, -529530880, 1611661312, 5, 0,
  139829. _vq_quantlist__44c1_sm_p8_2,
  139830. NULL,
  139831. &_vq_auxt__44c1_sm_p8_2,
  139832. NULL,
  139833. 0
  139834. };
  139835. static long _huff_lengthlist__44c1_sm_short[] = {
  139836. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139837. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139838. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139839. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139840. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139841. 11,
  139842. };
  139843. static static_codebook _huff_book__44c1_sm_short = {
  139844. 2, 81,
  139845. _huff_lengthlist__44c1_sm_short,
  139846. 0, 0, 0, 0, 0,
  139847. NULL,
  139848. NULL,
  139849. NULL,
  139850. NULL,
  139851. 0
  139852. };
  139853. static long _huff_lengthlist__44cn1_s_long[] = {
  139854. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139855. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139856. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139857. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139858. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139859. 20,
  139860. };
  139861. static static_codebook _huff_book__44cn1_s_long = {
  139862. 2, 81,
  139863. _huff_lengthlist__44cn1_s_long,
  139864. 0, 0, 0, 0, 0,
  139865. NULL,
  139866. NULL,
  139867. NULL,
  139868. NULL,
  139869. 0
  139870. };
  139871. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139872. 1,
  139873. 0,
  139874. 2,
  139875. };
  139876. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139877. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139878. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139883. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139888. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139923. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139928. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139933. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139969. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139974. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139979. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0,
  140288. };
  140289. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140290. -0.5, 0.5,
  140291. };
  140292. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140293. 1, 0, 2,
  140294. };
  140295. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140296. _vq_quantthresh__44cn1_s_p1_0,
  140297. _vq_quantmap__44cn1_s_p1_0,
  140298. 3,
  140299. 3
  140300. };
  140301. static static_codebook _44cn1_s_p1_0 = {
  140302. 8, 6561,
  140303. _vq_lengthlist__44cn1_s_p1_0,
  140304. 1, -535822336, 1611661312, 2, 0,
  140305. _vq_quantlist__44cn1_s_p1_0,
  140306. NULL,
  140307. &_vq_auxt__44cn1_s_p1_0,
  140308. NULL,
  140309. 0
  140310. };
  140311. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140312. 2,
  140313. 1,
  140314. 3,
  140315. 0,
  140316. 4,
  140317. };
  140318. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140319. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140359. };
  140360. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140361. -1.5, -0.5, 0.5, 1.5,
  140362. };
  140363. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140364. 3, 1, 0, 2, 4,
  140365. };
  140366. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140367. _vq_quantthresh__44cn1_s_p2_0,
  140368. _vq_quantmap__44cn1_s_p2_0,
  140369. 5,
  140370. 5
  140371. };
  140372. static static_codebook _44cn1_s_p2_0 = {
  140373. 4, 625,
  140374. _vq_lengthlist__44cn1_s_p2_0,
  140375. 1, -533725184, 1611661312, 3, 0,
  140376. _vq_quantlist__44cn1_s_p2_0,
  140377. NULL,
  140378. &_vq_auxt__44cn1_s_p2_0,
  140379. NULL,
  140380. 0
  140381. };
  140382. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140383. 4,
  140384. 3,
  140385. 5,
  140386. 2,
  140387. 6,
  140388. 1,
  140389. 7,
  140390. 0,
  140391. 8,
  140392. };
  140393. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140394. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140395. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140396. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140397. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140398. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0,
  140400. };
  140401. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140402. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140403. };
  140404. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140405. 7, 5, 3, 1, 0, 2, 4, 6,
  140406. 8,
  140407. };
  140408. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140409. _vq_quantthresh__44cn1_s_p3_0,
  140410. _vq_quantmap__44cn1_s_p3_0,
  140411. 9,
  140412. 9
  140413. };
  140414. static static_codebook _44cn1_s_p3_0 = {
  140415. 2, 81,
  140416. _vq_lengthlist__44cn1_s_p3_0,
  140417. 1, -531628032, 1611661312, 4, 0,
  140418. _vq_quantlist__44cn1_s_p3_0,
  140419. NULL,
  140420. &_vq_auxt__44cn1_s_p3_0,
  140421. NULL,
  140422. 0
  140423. };
  140424. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140425. 4,
  140426. 3,
  140427. 5,
  140428. 2,
  140429. 6,
  140430. 1,
  140431. 7,
  140432. 0,
  140433. 8,
  140434. };
  140435. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140436. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140437. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140438. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140439. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140440. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140441. 11,
  140442. };
  140443. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140445. };
  140446. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140447. 7, 5, 3, 1, 0, 2, 4, 6,
  140448. 8,
  140449. };
  140450. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140451. _vq_quantthresh__44cn1_s_p4_0,
  140452. _vq_quantmap__44cn1_s_p4_0,
  140453. 9,
  140454. 9
  140455. };
  140456. static static_codebook _44cn1_s_p4_0 = {
  140457. 2, 81,
  140458. _vq_lengthlist__44cn1_s_p4_0,
  140459. 1, -531628032, 1611661312, 4, 0,
  140460. _vq_quantlist__44cn1_s_p4_0,
  140461. NULL,
  140462. &_vq_auxt__44cn1_s_p4_0,
  140463. NULL,
  140464. 0
  140465. };
  140466. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140467. 8,
  140468. 7,
  140469. 9,
  140470. 6,
  140471. 10,
  140472. 5,
  140473. 11,
  140474. 4,
  140475. 12,
  140476. 3,
  140477. 13,
  140478. 2,
  140479. 14,
  140480. 1,
  140481. 15,
  140482. 0,
  140483. 16,
  140484. };
  140485. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140486. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140487. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140488. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140489. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140490. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140491. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140492. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140493. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140494. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140495. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140496. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140497. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140498. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140499. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140500. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140501. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140502. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140504. 14,
  140505. };
  140506. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140507. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140508. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140509. };
  140510. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140511. 15, 13, 11, 9, 7, 5, 3, 1,
  140512. 0, 2, 4, 6, 8, 10, 12, 14,
  140513. 16,
  140514. };
  140515. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140516. _vq_quantthresh__44cn1_s_p5_0,
  140517. _vq_quantmap__44cn1_s_p5_0,
  140518. 17,
  140519. 17
  140520. };
  140521. static static_codebook _44cn1_s_p5_0 = {
  140522. 2, 289,
  140523. _vq_lengthlist__44cn1_s_p5_0,
  140524. 1, -529530880, 1611661312, 5, 0,
  140525. _vq_quantlist__44cn1_s_p5_0,
  140526. NULL,
  140527. &_vq_auxt__44cn1_s_p5_0,
  140528. NULL,
  140529. 0
  140530. };
  140531. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140532. 1,
  140533. 0,
  140534. 2,
  140535. };
  140536. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140537. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140538. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140539. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140540. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140541. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140542. 10,
  140543. };
  140544. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140545. -5.5, 5.5,
  140546. };
  140547. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140548. 1, 0, 2,
  140549. };
  140550. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140551. _vq_quantthresh__44cn1_s_p6_0,
  140552. _vq_quantmap__44cn1_s_p6_0,
  140553. 3,
  140554. 3
  140555. };
  140556. static static_codebook _44cn1_s_p6_0 = {
  140557. 4, 81,
  140558. _vq_lengthlist__44cn1_s_p6_0,
  140559. 1, -529137664, 1618345984, 2, 0,
  140560. _vq_quantlist__44cn1_s_p6_0,
  140561. NULL,
  140562. &_vq_auxt__44cn1_s_p6_0,
  140563. NULL,
  140564. 0
  140565. };
  140566. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140567. 5,
  140568. 4,
  140569. 6,
  140570. 3,
  140571. 7,
  140572. 2,
  140573. 8,
  140574. 1,
  140575. 9,
  140576. 0,
  140577. 10,
  140578. };
  140579. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140580. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140581. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140582. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140583. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140584. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140585. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140586. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140587. 10,10,10, 9, 9, 9, 9, 9, 9,
  140588. };
  140589. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140590. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140591. 3.5, 4.5,
  140592. };
  140593. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140594. 9, 7, 5, 3, 1, 0, 2, 4,
  140595. 6, 8, 10,
  140596. };
  140597. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140598. _vq_quantthresh__44cn1_s_p6_1,
  140599. _vq_quantmap__44cn1_s_p6_1,
  140600. 11,
  140601. 11
  140602. };
  140603. static static_codebook _44cn1_s_p6_1 = {
  140604. 2, 121,
  140605. _vq_lengthlist__44cn1_s_p6_1,
  140606. 1, -531365888, 1611661312, 4, 0,
  140607. _vq_quantlist__44cn1_s_p6_1,
  140608. NULL,
  140609. &_vq_auxt__44cn1_s_p6_1,
  140610. NULL,
  140611. 0
  140612. };
  140613. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140614. 6,
  140615. 5,
  140616. 7,
  140617. 4,
  140618. 8,
  140619. 3,
  140620. 9,
  140621. 2,
  140622. 10,
  140623. 1,
  140624. 11,
  140625. 0,
  140626. 12,
  140627. };
  140628. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140629. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140630. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140631. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140632. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140633. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140634. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140635. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140636. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140637. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140638. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140639. 0,13,13,12,12,13,13,13,14,
  140640. };
  140641. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140642. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140643. 12.5, 17.5, 22.5, 27.5,
  140644. };
  140645. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140646. 11, 9, 7, 5, 3, 1, 0, 2,
  140647. 4, 6, 8, 10, 12,
  140648. };
  140649. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140650. _vq_quantthresh__44cn1_s_p7_0,
  140651. _vq_quantmap__44cn1_s_p7_0,
  140652. 13,
  140653. 13
  140654. };
  140655. static static_codebook _44cn1_s_p7_0 = {
  140656. 2, 169,
  140657. _vq_lengthlist__44cn1_s_p7_0,
  140658. 1, -526516224, 1616117760, 4, 0,
  140659. _vq_quantlist__44cn1_s_p7_0,
  140660. NULL,
  140661. &_vq_auxt__44cn1_s_p7_0,
  140662. NULL,
  140663. 0
  140664. };
  140665. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140666. 2,
  140667. 1,
  140668. 3,
  140669. 0,
  140670. 4,
  140671. };
  140672. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140673. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140674. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140675. };
  140676. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140677. -1.5, -0.5, 0.5, 1.5,
  140678. };
  140679. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140680. 3, 1, 0, 2, 4,
  140681. };
  140682. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140683. _vq_quantthresh__44cn1_s_p7_1,
  140684. _vq_quantmap__44cn1_s_p7_1,
  140685. 5,
  140686. 5
  140687. };
  140688. static static_codebook _44cn1_s_p7_1 = {
  140689. 2, 25,
  140690. _vq_lengthlist__44cn1_s_p7_1,
  140691. 1, -533725184, 1611661312, 3, 0,
  140692. _vq_quantlist__44cn1_s_p7_1,
  140693. NULL,
  140694. &_vq_auxt__44cn1_s_p7_1,
  140695. NULL,
  140696. 0
  140697. };
  140698. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140699. 2,
  140700. 1,
  140701. 3,
  140702. 0,
  140703. 4,
  140704. };
  140705. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140706. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140707. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140709. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140713. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140715. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140721. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140739. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140740. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140741. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140742. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140743. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140744. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140745. 12,
  140746. };
  140747. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140748. -331.5, -110.5, 110.5, 331.5,
  140749. };
  140750. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140751. 3, 1, 0, 2, 4,
  140752. };
  140753. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140754. _vq_quantthresh__44cn1_s_p8_0,
  140755. _vq_quantmap__44cn1_s_p8_0,
  140756. 5,
  140757. 5
  140758. };
  140759. static static_codebook _44cn1_s_p8_0 = {
  140760. 4, 625,
  140761. _vq_lengthlist__44cn1_s_p8_0,
  140762. 1, -518283264, 1627103232, 3, 0,
  140763. _vq_quantlist__44cn1_s_p8_0,
  140764. NULL,
  140765. &_vq_auxt__44cn1_s_p8_0,
  140766. NULL,
  140767. 0
  140768. };
  140769. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140770. 6,
  140771. 5,
  140772. 7,
  140773. 4,
  140774. 8,
  140775. 3,
  140776. 9,
  140777. 2,
  140778. 10,
  140779. 1,
  140780. 11,
  140781. 0,
  140782. 12,
  140783. };
  140784. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140785. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140786. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140787. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140788. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140789. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140790. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140791. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140792. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140793. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140794. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140795. 15,12,12,11,11,14,12,13,14,
  140796. };
  140797. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140798. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140799. 42.5, 59.5, 76.5, 93.5,
  140800. };
  140801. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140802. 11, 9, 7, 5, 3, 1, 0, 2,
  140803. 4, 6, 8, 10, 12,
  140804. };
  140805. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140806. _vq_quantthresh__44cn1_s_p8_1,
  140807. _vq_quantmap__44cn1_s_p8_1,
  140808. 13,
  140809. 13
  140810. };
  140811. static static_codebook _44cn1_s_p8_1 = {
  140812. 2, 169,
  140813. _vq_lengthlist__44cn1_s_p8_1,
  140814. 1, -522616832, 1620115456, 4, 0,
  140815. _vq_quantlist__44cn1_s_p8_1,
  140816. NULL,
  140817. &_vq_auxt__44cn1_s_p8_1,
  140818. NULL,
  140819. 0
  140820. };
  140821. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140822. 8,
  140823. 7,
  140824. 9,
  140825. 6,
  140826. 10,
  140827. 5,
  140828. 11,
  140829. 4,
  140830. 12,
  140831. 3,
  140832. 13,
  140833. 2,
  140834. 14,
  140835. 1,
  140836. 15,
  140837. 0,
  140838. 16,
  140839. };
  140840. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140841. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140842. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140843. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140844. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140845. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140846. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140847. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140848. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140849. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140850. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140851. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140852. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140853. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140854. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140855. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140856. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140857. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140858. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140859. 9,
  140860. };
  140861. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140862. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140863. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140864. };
  140865. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140866. 15, 13, 11, 9, 7, 5, 3, 1,
  140867. 0, 2, 4, 6, 8, 10, 12, 14,
  140868. 16,
  140869. };
  140870. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140871. _vq_quantthresh__44cn1_s_p8_2,
  140872. _vq_quantmap__44cn1_s_p8_2,
  140873. 17,
  140874. 17
  140875. };
  140876. static static_codebook _44cn1_s_p8_2 = {
  140877. 2, 289,
  140878. _vq_lengthlist__44cn1_s_p8_2,
  140879. 1, -529530880, 1611661312, 5, 0,
  140880. _vq_quantlist__44cn1_s_p8_2,
  140881. NULL,
  140882. &_vq_auxt__44cn1_s_p8_2,
  140883. NULL,
  140884. 0
  140885. };
  140886. static long _huff_lengthlist__44cn1_s_short[] = {
  140887. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140888. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140889. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140890. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140891. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140892. 10,
  140893. };
  140894. static static_codebook _huff_book__44cn1_s_short = {
  140895. 2, 81,
  140896. _huff_lengthlist__44cn1_s_short,
  140897. 0, 0, 0, 0, 0,
  140898. NULL,
  140899. NULL,
  140900. NULL,
  140901. NULL,
  140902. 0
  140903. };
  140904. static long _huff_lengthlist__44cn1_sm_long[] = {
  140905. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140906. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140907. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140908. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140909. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140910. 17,
  140911. };
  140912. static static_codebook _huff_book__44cn1_sm_long = {
  140913. 2, 81,
  140914. _huff_lengthlist__44cn1_sm_long,
  140915. 0, 0, 0, 0, 0,
  140916. NULL,
  140917. NULL,
  140918. NULL,
  140919. NULL,
  140920. 0
  140921. };
  140922. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140923. 1,
  140924. 0,
  140925. 2,
  140926. };
  140927. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140928. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140929. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140934. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140939. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140974. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140979. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140984. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141020. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141025. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141030. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0,
  141339. };
  141340. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141341. -0.5, 0.5,
  141342. };
  141343. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141344. 1, 0, 2,
  141345. };
  141346. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141347. _vq_quantthresh__44cn1_sm_p1_0,
  141348. _vq_quantmap__44cn1_sm_p1_0,
  141349. 3,
  141350. 3
  141351. };
  141352. static static_codebook _44cn1_sm_p1_0 = {
  141353. 8, 6561,
  141354. _vq_lengthlist__44cn1_sm_p1_0,
  141355. 1, -535822336, 1611661312, 2, 0,
  141356. _vq_quantlist__44cn1_sm_p1_0,
  141357. NULL,
  141358. &_vq_auxt__44cn1_sm_p1_0,
  141359. NULL,
  141360. 0
  141361. };
  141362. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141363. 2,
  141364. 1,
  141365. 3,
  141366. 0,
  141367. 4,
  141368. };
  141369. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141370. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141410. };
  141411. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141412. -1.5, -0.5, 0.5, 1.5,
  141413. };
  141414. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141415. 3, 1, 0, 2, 4,
  141416. };
  141417. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141418. _vq_quantthresh__44cn1_sm_p2_0,
  141419. _vq_quantmap__44cn1_sm_p2_0,
  141420. 5,
  141421. 5
  141422. };
  141423. static static_codebook _44cn1_sm_p2_0 = {
  141424. 4, 625,
  141425. _vq_lengthlist__44cn1_sm_p2_0,
  141426. 1, -533725184, 1611661312, 3, 0,
  141427. _vq_quantlist__44cn1_sm_p2_0,
  141428. NULL,
  141429. &_vq_auxt__44cn1_sm_p2_0,
  141430. NULL,
  141431. 0
  141432. };
  141433. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141434. 4,
  141435. 3,
  141436. 5,
  141437. 2,
  141438. 6,
  141439. 1,
  141440. 7,
  141441. 0,
  141442. 8,
  141443. };
  141444. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141445. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141446. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141447. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141448. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141449. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0,
  141451. };
  141452. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141453. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141454. };
  141455. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141456. 7, 5, 3, 1, 0, 2, 4, 6,
  141457. 8,
  141458. };
  141459. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141460. _vq_quantthresh__44cn1_sm_p3_0,
  141461. _vq_quantmap__44cn1_sm_p3_0,
  141462. 9,
  141463. 9
  141464. };
  141465. static static_codebook _44cn1_sm_p3_0 = {
  141466. 2, 81,
  141467. _vq_lengthlist__44cn1_sm_p3_0,
  141468. 1, -531628032, 1611661312, 4, 0,
  141469. _vq_quantlist__44cn1_sm_p3_0,
  141470. NULL,
  141471. &_vq_auxt__44cn1_sm_p3_0,
  141472. NULL,
  141473. 0
  141474. };
  141475. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141476. 4,
  141477. 3,
  141478. 5,
  141479. 2,
  141480. 6,
  141481. 1,
  141482. 7,
  141483. 0,
  141484. 8,
  141485. };
  141486. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141487. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141488. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141489. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141490. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141491. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141492. 11,
  141493. };
  141494. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141495. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141496. };
  141497. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141498. 7, 5, 3, 1, 0, 2, 4, 6,
  141499. 8,
  141500. };
  141501. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141502. _vq_quantthresh__44cn1_sm_p4_0,
  141503. _vq_quantmap__44cn1_sm_p4_0,
  141504. 9,
  141505. 9
  141506. };
  141507. static static_codebook _44cn1_sm_p4_0 = {
  141508. 2, 81,
  141509. _vq_lengthlist__44cn1_sm_p4_0,
  141510. 1, -531628032, 1611661312, 4, 0,
  141511. _vq_quantlist__44cn1_sm_p4_0,
  141512. NULL,
  141513. &_vq_auxt__44cn1_sm_p4_0,
  141514. NULL,
  141515. 0
  141516. };
  141517. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141518. 8,
  141519. 7,
  141520. 9,
  141521. 6,
  141522. 10,
  141523. 5,
  141524. 11,
  141525. 4,
  141526. 12,
  141527. 3,
  141528. 13,
  141529. 2,
  141530. 14,
  141531. 1,
  141532. 15,
  141533. 0,
  141534. 16,
  141535. };
  141536. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141537. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141538. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141539. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141540. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141541. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141542. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141543. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141544. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141545. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141546. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141547. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141548. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141549. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141550. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141551. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141552. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141553. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141555. 14,
  141556. };
  141557. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141560. };
  141561. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141562. 15, 13, 11, 9, 7, 5, 3, 1,
  141563. 0, 2, 4, 6, 8, 10, 12, 14,
  141564. 16,
  141565. };
  141566. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141567. _vq_quantthresh__44cn1_sm_p5_0,
  141568. _vq_quantmap__44cn1_sm_p5_0,
  141569. 17,
  141570. 17
  141571. };
  141572. static static_codebook _44cn1_sm_p5_0 = {
  141573. 2, 289,
  141574. _vq_lengthlist__44cn1_sm_p5_0,
  141575. 1, -529530880, 1611661312, 5, 0,
  141576. _vq_quantlist__44cn1_sm_p5_0,
  141577. NULL,
  141578. &_vq_auxt__44cn1_sm_p5_0,
  141579. NULL,
  141580. 0
  141581. };
  141582. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141583. 1,
  141584. 0,
  141585. 2,
  141586. };
  141587. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141588. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141589. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141590. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141591. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141592. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141593. 10,
  141594. };
  141595. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141596. -5.5, 5.5,
  141597. };
  141598. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141599. 1, 0, 2,
  141600. };
  141601. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141602. _vq_quantthresh__44cn1_sm_p6_0,
  141603. _vq_quantmap__44cn1_sm_p6_0,
  141604. 3,
  141605. 3
  141606. };
  141607. static static_codebook _44cn1_sm_p6_0 = {
  141608. 4, 81,
  141609. _vq_lengthlist__44cn1_sm_p6_0,
  141610. 1, -529137664, 1618345984, 2, 0,
  141611. _vq_quantlist__44cn1_sm_p6_0,
  141612. NULL,
  141613. &_vq_auxt__44cn1_sm_p6_0,
  141614. NULL,
  141615. 0
  141616. };
  141617. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141618. 5,
  141619. 4,
  141620. 6,
  141621. 3,
  141622. 7,
  141623. 2,
  141624. 8,
  141625. 1,
  141626. 9,
  141627. 0,
  141628. 10,
  141629. };
  141630. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141631. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141632. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141633. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141634. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141635. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141636. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141637. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141638. 10,10,10, 8, 9, 8, 8, 9, 8,
  141639. };
  141640. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141641. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141642. 3.5, 4.5,
  141643. };
  141644. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141645. 9, 7, 5, 3, 1, 0, 2, 4,
  141646. 6, 8, 10,
  141647. };
  141648. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141649. _vq_quantthresh__44cn1_sm_p6_1,
  141650. _vq_quantmap__44cn1_sm_p6_1,
  141651. 11,
  141652. 11
  141653. };
  141654. static static_codebook _44cn1_sm_p6_1 = {
  141655. 2, 121,
  141656. _vq_lengthlist__44cn1_sm_p6_1,
  141657. 1, -531365888, 1611661312, 4, 0,
  141658. _vq_quantlist__44cn1_sm_p6_1,
  141659. NULL,
  141660. &_vq_auxt__44cn1_sm_p6_1,
  141661. NULL,
  141662. 0
  141663. };
  141664. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141665. 6,
  141666. 5,
  141667. 7,
  141668. 4,
  141669. 8,
  141670. 3,
  141671. 9,
  141672. 2,
  141673. 10,
  141674. 1,
  141675. 11,
  141676. 0,
  141677. 12,
  141678. };
  141679. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141680. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141681. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141682. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141683. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141684. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141685. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141686. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141687. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141688. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141689. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141690. 0,13,12,12,12,13,13,13,14,
  141691. };
  141692. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141693. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141694. 12.5, 17.5, 22.5, 27.5,
  141695. };
  141696. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141697. 11, 9, 7, 5, 3, 1, 0, 2,
  141698. 4, 6, 8, 10, 12,
  141699. };
  141700. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141701. _vq_quantthresh__44cn1_sm_p7_0,
  141702. _vq_quantmap__44cn1_sm_p7_0,
  141703. 13,
  141704. 13
  141705. };
  141706. static static_codebook _44cn1_sm_p7_0 = {
  141707. 2, 169,
  141708. _vq_lengthlist__44cn1_sm_p7_0,
  141709. 1, -526516224, 1616117760, 4, 0,
  141710. _vq_quantlist__44cn1_sm_p7_0,
  141711. NULL,
  141712. &_vq_auxt__44cn1_sm_p7_0,
  141713. NULL,
  141714. 0
  141715. };
  141716. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141717. 2,
  141718. 1,
  141719. 3,
  141720. 0,
  141721. 4,
  141722. };
  141723. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141724. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141725. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141726. };
  141727. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141728. -1.5, -0.5, 0.5, 1.5,
  141729. };
  141730. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141731. 3, 1, 0, 2, 4,
  141732. };
  141733. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141734. _vq_quantthresh__44cn1_sm_p7_1,
  141735. _vq_quantmap__44cn1_sm_p7_1,
  141736. 5,
  141737. 5
  141738. };
  141739. static static_codebook _44cn1_sm_p7_1 = {
  141740. 2, 25,
  141741. _vq_lengthlist__44cn1_sm_p7_1,
  141742. 1, -533725184, 1611661312, 3, 0,
  141743. _vq_quantlist__44cn1_sm_p7_1,
  141744. NULL,
  141745. &_vq_auxt__44cn1_sm_p7_1,
  141746. NULL,
  141747. 0
  141748. };
  141749. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141750. 4,
  141751. 3,
  141752. 5,
  141753. 2,
  141754. 6,
  141755. 1,
  141756. 7,
  141757. 0,
  141758. 8,
  141759. };
  141760. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141761. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141762. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141763. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141764. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141765. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141766. 14,
  141767. };
  141768. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141769. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141770. };
  141771. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141772. 7, 5, 3, 1, 0, 2, 4, 6,
  141773. 8,
  141774. };
  141775. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141776. _vq_quantthresh__44cn1_sm_p8_0,
  141777. _vq_quantmap__44cn1_sm_p8_0,
  141778. 9,
  141779. 9
  141780. };
  141781. static static_codebook _44cn1_sm_p8_0 = {
  141782. 2, 81,
  141783. _vq_lengthlist__44cn1_sm_p8_0,
  141784. 1, -516186112, 1627103232, 4, 0,
  141785. _vq_quantlist__44cn1_sm_p8_0,
  141786. NULL,
  141787. &_vq_auxt__44cn1_sm_p8_0,
  141788. NULL,
  141789. 0
  141790. };
  141791. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141792. 6,
  141793. 5,
  141794. 7,
  141795. 4,
  141796. 8,
  141797. 3,
  141798. 9,
  141799. 2,
  141800. 10,
  141801. 1,
  141802. 11,
  141803. 0,
  141804. 12,
  141805. };
  141806. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141807. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141808. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141809. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141810. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141811. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141812. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141813. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141814. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141815. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141816. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141817. 17,12,12,11,10,13,11,13,13,
  141818. };
  141819. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141820. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141821. 42.5, 59.5, 76.5, 93.5,
  141822. };
  141823. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141824. 11, 9, 7, 5, 3, 1, 0, 2,
  141825. 4, 6, 8, 10, 12,
  141826. };
  141827. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141828. _vq_quantthresh__44cn1_sm_p8_1,
  141829. _vq_quantmap__44cn1_sm_p8_1,
  141830. 13,
  141831. 13
  141832. };
  141833. static static_codebook _44cn1_sm_p8_1 = {
  141834. 2, 169,
  141835. _vq_lengthlist__44cn1_sm_p8_1,
  141836. 1, -522616832, 1620115456, 4, 0,
  141837. _vq_quantlist__44cn1_sm_p8_1,
  141838. NULL,
  141839. &_vq_auxt__44cn1_sm_p8_1,
  141840. NULL,
  141841. 0
  141842. };
  141843. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141844. 8,
  141845. 7,
  141846. 9,
  141847. 6,
  141848. 10,
  141849. 5,
  141850. 11,
  141851. 4,
  141852. 12,
  141853. 3,
  141854. 13,
  141855. 2,
  141856. 14,
  141857. 1,
  141858. 15,
  141859. 0,
  141860. 16,
  141861. };
  141862. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141863. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141864. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141865. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141866. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141867. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141868. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141869. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141870. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141871. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141872. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141873. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141874. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141875. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141876. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141877. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141878. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141879. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141880. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141881. 9,
  141882. };
  141883. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141884. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141885. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141886. };
  141887. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141888. 15, 13, 11, 9, 7, 5, 3, 1,
  141889. 0, 2, 4, 6, 8, 10, 12, 14,
  141890. 16,
  141891. };
  141892. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141893. _vq_quantthresh__44cn1_sm_p8_2,
  141894. _vq_quantmap__44cn1_sm_p8_2,
  141895. 17,
  141896. 17
  141897. };
  141898. static static_codebook _44cn1_sm_p8_2 = {
  141899. 2, 289,
  141900. _vq_lengthlist__44cn1_sm_p8_2,
  141901. 1, -529530880, 1611661312, 5, 0,
  141902. _vq_quantlist__44cn1_sm_p8_2,
  141903. NULL,
  141904. &_vq_auxt__44cn1_sm_p8_2,
  141905. NULL,
  141906. 0
  141907. };
  141908. static long _huff_lengthlist__44cn1_sm_short[] = {
  141909. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141910. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141911. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141912. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141913. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141914. 9,
  141915. };
  141916. static static_codebook _huff_book__44cn1_sm_short = {
  141917. 2, 81,
  141918. _huff_lengthlist__44cn1_sm_short,
  141919. 0, 0, 0, 0, 0,
  141920. NULL,
  141921. NULL,
  141922. NULL,
  141923. NULL,
  141924. 0
  141925. };
  141926. /*** End of inlined file: res_books_stereo.h ***/
  141927. /***** residue backends *********************************************/
  141928. static vorbis_info_residue0 _residue_44_low={
  141929. 0,-1, -1, 9,-1,
  141930. /* 0 1 2 3 4 5 6 7 */
  141931. {0},
  141932. {-1},
  141933. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141934. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141935. };
  141936. static vorbis_info_residue0 _residue_44_mid={
  141937. 0,-1, -1, 10,-1,
  141938. /* 0 1 2 3 4 5 6 7 8 */
  141939. {0},
  141940. {-1},
  141941. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141942. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141943. };
  141944. static vorbis_info_residue0 _residue_44_high={
  141945. 0,-1, -1, 10,-1,
  141946. /* 0 1 2 3 4 5 6 7 8 */
  141947. {0},
  141948. {-1},
  141949. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141950. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141951. };
  141952. static static_bookblock _resbook_44s_n1={
  141953. {
  141954. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141955. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141956. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141957. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141958. }
  141959. };
  141960. static static_bookblock _resbook_44sm_n1={
  141961. {
  141962. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141963. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141964. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141965. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141966. }
  141967. };
  141968. static static_bookblock _resbook_44s_0={
  141969. {
  141970. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141971. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141972. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141973. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141974. }
  141975. };
  141976. static static_bookblock _resbook_44sm_0={
  141977. {
  141978. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141979. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141980. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141981. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141982. }
  141983. };
  141984. static static_bookblock _resbook_44s_1={
  141985. {
  141986. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141987. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141988. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141989. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141990. }
  141991. };
  141992. static static_bookblock _resbook_44sm_1={
  141993. {
  141994. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141995. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141996. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141997. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141998. }
  141999. };
  142000. static static_bookblock _resbook_44s_2={
  142001. {
  142002. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142003. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142004. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142005. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142006. }
  142007. };
  142008. static static_bookblock _resbook_44s_3={
  142009. {
  142010. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142011. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142012. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142013. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142014. }
  142015. };
  142016. static static_bookblock _resbook_44s_4={
  142017. {
  142018. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142019. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142020. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142021. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142022. }
  142023. };
  142024. static static_bookblock _resbook_44s_5={
  142025. {
  142026. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142027. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142028. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142029. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142030. }
  142031. };
  142032. static static_bookblock _resbook_44s_6={
  142033. {
  142034. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142035. {0,0,&_44c6_s_p4_0},
  142036. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142037. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142038. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142039. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142040. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142041. }
  142042. };
  142043. static static_bookblock _resbook_44s_7={
  142044. {
  142045. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142046. {0,0,&_44c7_s_p4_0},
  142047. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142048. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142049. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142050. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142051. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142052. }
  142053. };
  142054. static static_bookblock _resbook_44s_8={
  142055. {
  142056. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142057. {0,0,&_44c8_s_p4_0},
  142058. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142059. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142060. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142061. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142062. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142063. }
  142064. };
  142065. static static_bookblock _resbook_44s_9={
  142066. {
  142067. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142068. {0,0,&_44c9_s_p4_0},
  142069. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142070. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142071. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142072. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142073. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142074. }
  142075. };
  142076. static vorbis_residue_template _res_44s_n1[]={
  142077. {2,0, &_residue_44_low,
  142078. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142079. &_resbook_44s_n1,&_resbook_44sm_n1},
  142080. {2,0, &_residue_44_low,
  142081. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142082. &_resbook_44s_n1,&_resbook_44sm_n1}
  142083. };
  142084. static vorbis_residue_template _res_44s_0[]={
  142085. {2,0, &_residue_44_low,
  142086. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142087. &_resbook_44s_0,&_resbook_44sm_0},
  142088. {2,0, &_residue_44_low,
  142089. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142090. &_resbook_44s_0,&_resbook_44sm_0}
  142091. };
  142092. static vorbis_residue_template _res_44s_1[]={
  142093. {2,0, &_residue_44_low,
  142094. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142095. &_resbook_44s_1,&_resbook_44sm_1},
  142096. {2,0, &_residue_44_low,
  142097. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142098. &_resbook_44s_1,&_resbook_44sm_1}
  142099. };
  142100. static vorbis_residue_template _res_44s_2[]={
  142101. {2,0, &_residue_44_mid,
  142102. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142103. &_resbook_44s_2,&_resbook_44s_2},
  142104. {2,0, &_residue_44_mid,
  142105. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142106. &_resbook_44s_2,&_resbook_44s_2}
  142107. };
  142108. static vorbis_residue_template _res_44s_3[]={
  142109. {2,0, &_residue_44_mid,
  142110. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142111. &_resbook_44s_3,&_resbook_44s_3},
  142112. {2,0, &_residue_44_mid,
  142113. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142114. &_resbook_44s_3,&_resbook_44s_3}
  142115. };
  142116. static vorbis_residue_template _res_44s_4[]={
  142117. {2,0, &_residue_44_mid,
  142118. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142119. &_resbook_44s_4,&_resbook_44s_4},
  142120. {2,0, &_residue_44_mid,
  142121. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142122. &_resbook_44s_4,&_resbook_44s_4}
  142123. };
  142124. static vorbis_residue_template _res_44s_5[]={
  142125. {2,0, &_residue_44_mid,
  142126. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142127. &_resbook_44s_5,&_resbook_44s_5},
  142128. {2,0, &_residue_44_mid,
  142129. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142130. &_resbook_44s_5,&_resbook_44s_5}
  142131. };
  142132. static vorbis_residue_template _res_44s_6[]={
  142133. {2,0, &_residue_44_high,
  142134. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142135. &_resbook_44s_6,&_resbook_44s_6},
  142136. {2,0, &_residue_44_high,
  142137. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142138. &_resbook_44s_6,&_resbook_44s_6}
  142139. };
  142140. static vorbis_residue_template _res_44s_7[]={
  142141. {2,0, &_residue_44_high,
  142142. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142143. &_resbook_44s_7,&_resbook_44s_7},
  142144. {2,0, &_residue_44_high,
  142145. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142146. &_resbook_44s_7,&_resbook_44s_7}
  142147. };
  142148. static vorbis_residue_template _res_44s_8[]={
  142149. {2,0, &_residue_44_high,
  142150. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142151. &_resbook_44s_8,&_resbook_44s_8},
  142152. {2,0, &_residue_44_high,
  142153. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142154. &_resbook_44s_8,&_resbook_44s_8}
  142155. };
  142156. static vorbis_residue_template _res_44s_9[]={
  142157. {2,0, &_residue_44_high,
  142158. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142159. &_resbook_44s_9,&_resbook_44s_9},
  142160. {2,0, &_residue_44_high,
  142161. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142162. &_resbook_44s_9,&_resbook_44s_9}
  142163. };
  142164. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142165. { _map_nominal, _res_44s_n1 }, /* -1 */
  142166. { _map_nominal, _res_44s_0 }, /* 0 */
  142167. { _map_nominal, _res_44s_1 }, /* 1 */
  142168. { _map_nominal, _res_44s_2 }, /* 2 */
  142169. { _map_nominal, _res_44s_3 }, /* 3 */
  142170. { _map_nominal, _res_44s_4 }, /* 4 */
  142171. { _map_nominal, _res_44s_5 }, /* 5 */
  142172. { _map_nominal, _res_44s_6 }, /* 6 */
  142173. { _map_nominal, _res_44s_7 }, /* 7 */
  142174. { _map_nominal, _res_44s_8 }, /* 8 */
  142175. { _map_nominal, _res_44s_9 }, /* 9 */
  142176. };
  142177. /*** End of inlined file: residue_44.h ***/
  142178. /*** Start of inlined file: psych_44.h ***/
  142179. /* preecho trigger settings *****************************************/
  142180. static vorbis_info_psy_global _psy_global_44[5]={
  142181. {8, /* lines per eighth octave */
  142182. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142183. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142184. -6.f,
  142185. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142186. },
  142187. {8, /* lines per eighth octave */
  142188. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142189. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142190. -6.f,
  142191. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142192. },
  142193. {8, /* lines per eighth octave */
  142194. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142195. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142196. -6.f,
  142197. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142198. },
  142199. {8, /* lines per eighth octave */
  142200. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142201. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142202. -6.f,
  142203. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142204. },
  142205. {8, /* lines per eighth octave */
  142206. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142207. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142208. -6.f,
  142209. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142210. },
  142211. };
  142212. /* noise compander lookups * low, mid, high quality ****************/
  142213. static compandblock _psy_compand_44[6]={
  142214. /* sub-mode Z short */
  142215. {{
  142216. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142217. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142218. 16,17,18,19,20,21,22, 23, /* 23dB */
  142219. 24,25,26,27,28,29,30, 31, /* 31dB */
  142220. 32,33,34,35,36,37,38, 39, /* 39dB */
  142221. }},
  142222. /* mode_Z nominal short */
  142223. {{
  142224. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142225. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142226. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142227. 15,16,17,17,17,18,18, 19, /* 31dB */
  142228. 19,19,20,21,22,23,24, 25, /* 39dB */
  142229. }},
  142230. /* mode A short */
  142231. {{
  142232. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142233. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142234. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142235. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142236. 11,12,13,14,15,16,17, 18, /* 39dB */
  142237. }},
  142238. /* sub-mode Z long */
  142239. {{
  142240. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142241. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142242. 16,17,18,19,20,21,22, 23, /* 23dB */
  142243. 24,25,26,27,28,29,30, 31, /* 31dB */
  142244. 32,33,34,35,36,37,38, 39, /* 39dB */
  142245. }},
  142246. /* mode_Z nominal long */
  142247. {{
  142248. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142249. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142250. 13,14,14,14,15,15,15, 15, /* 23dB */
  142251. 16,16,17,17,17,18,18, 19, /* 31dB */
  142252. 19,19,20,21,22,23,24, 25, /* 39dB */
  142253. }},
  142254. /* mode A long */
  142255. {{
  142256. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142257. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142258. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142259. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142260. 11,12,13,14,15,16,17, 18, /* 39dB */
  142261. }}
  142262. };
  142263. /* tonal masking curve level adjustments *************************/
  142264. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142265. /* 63 125 250 500 1 2 4 8 16 */
  142266. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142267. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142268. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142269. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142270. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142271. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142272. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142273. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142274. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142275. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142276. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142277. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142278. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142279. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142280. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142281. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142282. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142283. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142284. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142285. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142286. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142287. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142288. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142289. };
  142290. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142291. /* 63 125 250 500 1 2 4 8 16 */
  142292. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142293. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142294. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142295. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142296. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142297. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142298. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142299. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142300. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142301. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142302. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142303. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142304. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142305. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142306. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142307. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142308. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142309. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142310. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142311. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142312. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142313. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142314. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142315. };
  142316. /* noise bias (transition block) */
  142317. static noise3 _psy_noisebias_trans[12]={
  142318. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142319. /* -1 */
  142320. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142321. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142322. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142323. /* 0
  142324. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142325. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142326. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142327. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142328. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142329. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142330. /* 1
  142331. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142332. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142333. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142334. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142335. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142336. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142337. /* 2
  142338. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142339. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142340. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142341. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142342. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142343. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142344. /* 3
  142345. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142346. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142347. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142348. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142349. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142350. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142351. /* 4
  142352. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142353. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142354. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142355. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142356. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142357. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142358. /* 5
  142359. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142360. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142361. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142362. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142363. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142364. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142365. /* 6
  142366. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142367. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142368. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142369. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142370. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142371. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142372. /* 7
  142373. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142374. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142375. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142376. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142377. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142378. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142379. /* 8
  142380. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142381. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142382. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142383. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142384. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142385. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142386. /* 9
  142387. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142388. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142389. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142390. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142391. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142392. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142393. /* 10 */
  142394. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142395. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142396. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142397. };
  142398. /* noise bias (long block) */
  142399. static noise3 _psy_noisebias_long[12]={
  142400. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142401. /* -1 */
  142402. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142403. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142404. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142405. /* 0 */
  142406. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142407. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142408. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142409. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142410. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142411. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142412. /* 1 */
  142413. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142414. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142415. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142416. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142417. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142418. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142419. /* 2 */
  142420. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142421. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142422. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142423. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142424. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142425. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142426. /* 3 */
  142427. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142428. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142429. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142430. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142431. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142432. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142433. /* 4 */
  142434. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142435. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142436. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142437. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142438. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142439. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142440. /* 5 */
  142441. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142442. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142443. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142444. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142445. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142446. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142447. /* 6 */
  142448. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142449. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142450. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142451. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142452. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142453. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142454. /* 7 */
  142455. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142456. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142457. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142458. /* 8 */
  142459. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142460. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142461. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142462. /* 9 */
  142463. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142464. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142465. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142466. /* 10 */
  142467. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142468. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142469. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142470. };
  142471. /* noise bias (impulse block) */
  142472. static noise3 _psy_noisebias_impulse[12]={
  142473. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142474. /* -1 */
  142475. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142476. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142477. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142478. /* 0 */
  142479. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142480. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142481. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142482. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142483. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142484. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142485. /* 1 */
  142486. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142487. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142488. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142489. /* 2 */
  142490. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142491. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142492. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142493. /* 3 */
  142494. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142495. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142496. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142497. /* 4 */
  142498. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142499. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142500. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142501. /* 5 */
  142502. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142503. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142504. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142505. /* 6
  142506. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142507. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142508. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142509. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142510. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142511. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142512. /* 7 */
  142513. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142514. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142515. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142516. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142517. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142518. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142519. /* 8 */
  142520. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142521. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142522. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142523. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142524. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142525. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142526. /* 9 */
  142527. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142528. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142529. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142530. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142531. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142532. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142533. /* 10 */
  142534. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142535. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142536. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142537. };
  142538. /* noise bias (padding block) */
  142539. static noise3 _psy_noisebias_padding[12]={
  142540. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142541. /* -1 */
  142542. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142543. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142544. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142545. /* 0 */
  142546. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142547. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142548. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142549. /* 1 */
  142550. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142551. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142552. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142553. /* 2 */
  142554. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142555. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142556. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142557. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142558. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142559. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142560. /* 3 */
  142561. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142562. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142563. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142564. /* 4 */
  142565. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142566. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142567. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142568. /* 5 */
  142569. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142570. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142571. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142572. /* 6 */
  142573. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142574. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142575. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142576. /* 7 */
  142577. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142578. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142579. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142580. /* 8 */
  142581. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142582. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142583. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142584. /* 9 */
  142585. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142586. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142587. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142588. /* 10 */
  142589. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142590. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142591. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142592. };
  142593. static noiseguard _psy_noiseguards_44[4]={
  142594. {3,3,15},
  142595. {3,3,15},
  142596. {10,10,100},
  142597. {10,10,100},
  142598. };
  142599. static int _psy_tone_suppress[12]={
  142600. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142601. };
  142602. static int _psy_tone_0dB[12]={
  142603. 90,90,95,95,95,95,105,105,105,105,105,105,
  142604. };
  142605. static int _psy_noise_suppress[12]={
  142606. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142607. };
  142608. static vorbis_info_psy _psy_info_template={
  142609. /* blockflag */
  142610. -1,
  142611. /* ath_adjatt, ath_maxatt */
  142612. -140.,-140.,
  142613. /* tonemask att boost/decay,suppr,curves */
  142614. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142615. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142616. 1, -0.f, .5f, .5f, 0,0,0,
  142617. /* noiseoffset*3, noisecompand, max_curve_dB */
  142618. {{-1},{-1},{-1}},{-1},105.f,
  142619. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142620. 0,0,-1,-1,0.,
  142621. };
  142622. /* ath ****************/
  142623. static int _psy_ath_floater[12]={
  142624. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142625. };
  142626. static int _psy_ath_abs[12]={
  142627. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142628. };
  142629. /* stereo setup. These don't map directly to quality level, there's
  142630. an additional indirection as several of the below may be used in a
  142631. single bitmanaged stream
  142632. ****************/
  142633. /* various stereo possibilities */
  142634. /* stereo mode by base quality level */
  142635. static adj_stereo _psy_stereo_modes_44[12]={
  142636. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142637. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142638. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142639. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142640. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142641. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142642. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142643. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142644. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142645. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142646. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142647. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142648. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142649. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142650. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142651. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142652. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142653. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142654. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142655. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142656. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142657. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142658. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142659. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142660. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142661. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142662. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142663. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142664. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142665. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142666. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142667. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142668. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142669. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142670. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142671. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142672. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142673. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142674. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142675. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142676. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142677. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142678. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142679. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142680. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142681. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142682. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142683. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142684. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142685. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142686. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142687. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142688. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142689. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142690. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142691. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142692. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142693. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142694. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142695. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142696. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142697. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142698. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142699. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142700. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142701. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142702. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142703. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142704. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142705. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142706. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142707. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142708. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142709. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142710. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142711. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142712. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142713. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142714. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142715. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142716. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142717. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142718. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142719. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142720. };
  142721. /* tone master attenuation by base quality mode and bitrate tweak */
  142722. static att3 _psy_tone_masteratt_44[12]={
  142723. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142724. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142725. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142726. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142727. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142728. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142729. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142730. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142731. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142732. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142733. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142734. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142735. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142736. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142737. };
  142738. /* lowpass by mode **************/
  142739. static double _psy_lowpass_44[12]={
  142740. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142741. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142742. };
  142743. /* noise normalization **********/
  142744. static int _noise_start_short_44[11]={
  142745. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142746. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142747. };
  142748. static int _noise_start_long_44[11]={
  142749. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142750. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142751. };
  142752. static int _noise_part_short_44[11]={
  142753. 8,8,8,8,8,8,8,8,8,8,8
  142754. };
  142755. static int _noise_part_long_44[11]={
  142756. 32,32,32,32,32,32,32,32,32,32,32
  142757. };
  142758. static double _noise_thresh_44[11]={
  142759. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142760. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142761. };
  142762. static double _noise_thresh_5only[2]={
  142763. .5,.5,
  142764. };
  142765. /*** End of inlined file: psych_44.h ***/
  142766. static double rate_mapping_44_stereo[12]={
  142767. 22500.,32000.,40000.,48000.,56000.,64000.,
  142768. 80000.,96000.,112000.,128000.,160000.,250001.
  142769. };
  142770. static double quality_mapping_44[12]={
  142771. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142772. };
  142773. static int blocksize_short_44[11]={
  142774. 512,256,256,256,256,256,256,256,256,256,256
  142775. };
  142776. static int blocksize_long_44[11]={
  142777. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142778. };
  142779. static double _psy_compand_short_mapping[12]={
  142780. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142781. };
  142782. static double _psy_compand_long_mapping[12]={
  142783. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142784. };
  142785. static double _global_mapping_44[12]={
  142786. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142787. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142788. };
  142789. static int _floor_short_mapping_44[11]={
  142790. 1,0,0,2,2,4,5,5,5,5,5
  142791. };
  142792. static int _floor_long_mapping_44[11]={
  142793. 8,7,7,7,7,7,7,7,7,7,7
  142794. };
  142795. ve_setup_data_template ve_setup_44_stereo={
  142796. 11,
  142797. rate_mapping_44_stereo,
  142798. quality_mapping_44,
  142799. 2,
  142800. 40000,
  142801. 50000,
  142802. blocksize_short_44,
  142803. blocksize_long_44,
  142804. _psy_tone_masteratt_44,
  142805. _psy_tone_0dB,
  142806. _psy_tone_suppress,
  142807. _vp_tonemask_adj_otherblock,
  142808. _vp_tonemask_adj_longblock,
  142809. _vp_tonemask_adj_otherblock,
  142810. _psy_noiseguards_44,
  142811. _psy_noisebias_impulse,
  142812. _psy_noisebias_padding,
  142813. _psy_noisebias_trans,
  142814. _psy_noisebias_long,
  142815. _psy_noise_suppress,
  142816. _psy_compand_44,
  142817. _psy_compand_short_mapping,
  142818. _psy_compand_long_mapping,
  142819. {_noise_start_short_44,_noise_start_long_44},
  142820. {_noise_part_short_44,_noise_part_long_44},
  142821. _noise_thresh_44,
  142822. _psy_ath_floater,
  142823. _psy_ath_abs,
  142824. _psy_lowpass_44,
  142825. _psy_global_44,
  142826. _global_mapping_44,
  142827. _psy_stereo_modes_44,
  142828. _floor_books,
  142829. _floor,
  142830. _floor_short_mapping_44,
  142831. _floor_long_mapping_44,
  142832. _mapres_template_44_stereo
  142833. };
  142834. /*** End of inlined file: setup_44.h ***/
  142835. /*** Start of inlined file: setup_44u.h ***/
  142836. /*** Start of inlined file: residue_44u.h ***/
  142837. /*** Start of inlined file: res_books_uncoupled.h ***/
  142838. static long _vq_quantlist__16u0__p1_0[] = {
  142839. 1,
  142840. 0,
  142841. 2,
  142842. };
  142843. static long _vq_lengthlist__16u0__p1_0[] = {
  142844. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142845. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142846. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142847. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142848. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142849. 12,
  142850. };
  142851. static float _vq_quantthresh__16u0__p1_0[] = {
  142852. -0.5, 0.5,
  142853. };
  142854. static long _vq_quantmap__16u0__p1_0[] = {
  142855. 1, 0, 2,
  142856. };
  142857. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142858. _vq_quantthresh__16u0__p1_0,
  142859. _vq_quantmap__16u0__p1_0,
  142860. 3,
  142861. 3
  142862. };
  142863. static static_codebook _16u0__p1_0 = {
  142864. 4, 81,
  142865. _vq_lengthlist__16u0__p1_0,
  142866. 1, -535822336, 1611661312, 2, 0,
  142867. _vq_quantlist__16u0__p1_0,
  142868. NULL,
  142869. &_vq_auxt__16u0__p1_0,
  142870. NULL,
  142871. 0
  142872. };
  142873. static long _vq_quantlist__16u0__p2_0[] = {
  142874. 1,
  142875. 0,
  142876. 2,
  142877. };
  142878. static long _vq_lengthlist__16u0__p2_0[] = {
  142879. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142880. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142881. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142882. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142883. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142884. 8,
  142885. };
  142886. static float _vq_quantthresh__16u0__p2_0[] = {
  142887. -0.5, 0.5,
  142888. };
  142889. static long _vq_quantmap__16u0__p2_0[] = {
  142890. 1, 0, 2,
  142891. };
  142892. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142893. _vq_quantthresh__16u0__p2_0,
  142894. _vq_quantmap__16u0__p2_0,
  142895. 3,
  142896. 3
  142897. };
  142898. static static_codebook _16u0__p2_0 = {
  142899. 4, 81,
  142900. _vq_lengthlist__16u0__p2_0,
  142901. 1, -535822336, 1611661312, 2, 0,
  142902. _vq_quantlist__16u0__p2_0,
  142903. NULL,
  142904. &_vq_auxt__16u0__p2_0,
  142905. NULL,
  142906. 0
  142907. };
  142908. static long _vq_quantlist__16u0__p3_0[] = {
  142909. 2,
  142910. 1,
  142911. 3,
  142912. 0,
  142913. 4,
  142914. };
  142915. static long _vq_lengthlist__16u0__p3_0[] = {
  142916. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142917. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142918. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142919. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142920. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142921. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142922. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142923. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142924. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142925. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142926. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142927. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142928. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142929. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142930. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142931. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142932. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142933. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142934. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142935. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142936. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142937. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142938. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142939. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142940. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142941. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142942. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142943. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142944. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142945. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142946. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142947. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142948. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142949. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142950. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142951. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142952. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142953. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142954. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142955. 18,
  142956. };
  142957. static float _vq_quantthresh__16u0__p3_0[] = {
  142958. -1.5, -0.5, 0.5, 1.5,
  142959. };
  142960. static long _vq_quantmap__16u0__p3_0[] = {
  142961. 3, 1, 0, 2, 4,
  142962. };
  142963. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142964. _vq_quantthresh__16u0__p3_0,
  142965. _vq_quantmap__16u0__p3_0,
  142966. 5,
  142967. 5
  142968. };
  142969. static static_codebook _16u0__p3_0 = {
  142970. 4, 625,
  142971. _vq_lengthlist__16u0__p3_0,
  142972. 1, -533725184, 1611661312, 3, 0,
  142973. _vq_quantlist__16u0__p3_0,
  142974. NULL,
  142975. &_vq_auxt__16u0__p3_0,
  142976. NULL,
  142977. 0
  142978. };
  142979. static long _vq_quantlist__16u0__p4_0[] = {
  142980. 2,
  142981. 1,
  142982. 3,
  142983. 0,
  142984. 4,
  142985. };
  142986. static long _vq_lengthlist__16u0__p4_0[] = {
  142987. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142988. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142989. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142990. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142991. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142992. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142993. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142994. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142995. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142996. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142997. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142998. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142999. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143000. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143001. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143002. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143003. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143004. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143005. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143006. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143007. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143008. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143009. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143010. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143011. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143012. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143013. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143014. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143015. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143016. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143017. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143018. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143019. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143020. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143021. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143022. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143023. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143024. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143025. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143026. 11,
  143027. };
  143028. static float _vq_quantthresh__16u0__p4_0[] = {
  143029. -1.5, -0.5, 0.5, 1.5,
  143030. };
  143031. static long _vq_quantmap__16u0__p4_0[] = {
  143032. 3, 1, 0, 2, 4,
  143033. };
  143034. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143035. _vq_quantthresh__16u0__p4_0,
  143036. _vq_quantmap__16u0__p4_0,
  143037. 5,
  143038. 5
  143039. };
  143040. static static_codebook _16u0__p4_0 = {
  143041. 4, 625,
  143042. _vq_lengthlist__16u0__p4_0,
  143043. 1, -533725184, 1611661312, 3, 0,
  143044. _vq_quantlist__16u0__p4_0,
  143045. NULL,
  143046. &_vq_auxt__16u0__p4_0,
  143047. NULL,
  143048. 0
  143049. };
  143050. static long _vq_quantlist__16u0__p5_0[] = {
  143051. 4,
  143052. 3,
  143053. 5,
  143054. 2,
  143055. 6,
  143056. 1,
  143057. 7,
  143058. 0,
  143059. 8,
  143060. };
  143061. static long _vq_lengthlist__16u0__p5_0[] = {
  143062. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143063. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143064. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143065. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143066. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143067. 12,
  143068. };
  143069. static float _vq_quantthresh__16u0__p5_0[] = {
  143070. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143071. };
  143072. static long _vq_quantmap__16u0__p5_0[] = {
  143073. 7, 5, 3, 1, 0, 2, 4, 6,
  143074. 8,
  143075. };
  143076. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143077. _vq_quantthresh__16u0__p5_0,
  143078. _vq_quantmap__16u0__p5_0,
  143079. 9,
  143080. 9
  143081. };
  143082. static static_codebook _16u0__p5_0 = {
  143083. 2, 81,
  143084. _vq_lengthlist__16u0__p5_0,
  143085. 1, -531628032, 1611661312, 4, 0,
  143086. _vq_quantlist__16u0__p5_0,
  143087. NULL,
  143088. &_vq_auxt__16u0__p5_0,
  143089. NULL,
  143090. 0
  143091. };
  143092. static long _vq_quantlist__16u0__p6_0[] = {
  143093. 6,
  143094. 5,
  143095. 7,
  143096. 4,
  143097. 8,
  143098. 3,
  143099. 9,
  143100. 2,
  143101. 10,
  143102. 1,
  143103. 11,
  143104. 0,
  143105. 12,
  143106. };
  143107. static long _vq_lengthlist__16u0__p6_0[] = {
  143108. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143109. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143110. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143111. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143112. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143113. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143114. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143115. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143116. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143117. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143118. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143119. };
  143120. static float _vq_quantthresh__16u0__p6_0[] = {
  143121. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143122. 12.5, 17.5, 22.5, 27.5,
  143123. };
  143124. static long _vq_quantmap__16u0__p6_0[] = {
  143125. 11, 9, 7, 5, 3, 1, 0, 2,
  143126. 4, 6, 8, 10, 12,
  143127. };
  143128. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143129. _vq_quantthresh__16u0__p6_0,
  143130. _vq_quantmap__16u0__p6_0,
  143131. 13,
  143132. 13
  143133. };
  143134. static static_codebook _16u0__p6_0 = {
  143135. 2, 169,
  143136. _vq_lengthlist__16u0__p6_0,
  143137. 1, -526516224, 1616117760, 4, 0,
  143138. _vq_quantlist__16u0__p6_0,
  143139. NULL,
  143140. &_vq_auxt__16u0__p6_0,
  143141. NULL,
  143142. 0
  143143. };
  143144. static long _vq_quantlist__16u0__p6_1[] = {
  143145. 2,
  143146. 1,
  143147. 3,
  143148. 0,
  143149. 4,
  143150. };
  143151. static long _vq_lengthlist__16u0__p6_1[] = {
  143152. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143153. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143154. };
  143155. static float _vq_quantthresh__16u0__p6_1[] = {
  143156. -1.5, -0.5, 0.5, 1.5,
  143157. };
  143158. static long _vq_quantmap__16u0__p6_1[] = {
  143159. 3, 1, 0, 2, 4,
  143160. };
  143161. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143162. _vq_quantthresh__16u0__p6_1,
  143163. _vq_quantmap__16u0__p6_1,
  143164. 5,
  143165. 5
  143166. };
  143167. static static_codebook _16u0__p6_1 = {
  143168. 2, 25,
  143169. _vq_lengthlist__16u0__p6_1,
  143170. 1, -533725184, 1611661312, 3, 0,
  143171. _vq_quantlist__16u0__p6_1,
  143172. NULL,
  143173. &_vq_auxt__16u0__p6_1,
  143174. NULL,
  143175. 0
  143176. };
  143177. static long _vq_quantlist__16u0__p7_0[] = {
  143178. 1,
  143179. 0,
  143180. 2,
  143181. };
  143182. static long _vq_lengthlist__16u0__p7_0[] = {
  143183. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143184. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143185. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143186. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143187. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143188. 7,
  143189. };
  143190. static float _vq_quantthresh__16u0__p7_0[] = {
  143191. -157.5, 157.5,
  143192. };
  143193. static long _vq_quantmap__16u0__p7_0[] = {
  143194. 1, 0, 2,
  143195. };
  143196. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143197. _vq_quantthresh__16u0__p7_0,
  143198. _vq_quantmap__16u0__p7_0,
  143199. 3,
  143200. 3
  143201. };
  143202. static static_codebook _16u0__p7_0 = {
  143203. 4, 81,
  143204. _vq_lengthlist__16u0__p7_0,
  143205. 1, -518803456, 1628680192, 2, 0,
  143206. _vq_quantlist__16u0__p7_0,
  143207. NULL,
  143208. &_vq_auxt__16u0__p7_0,
  143209. NULL,
  143210. 0
  143211. };
  143212. static long _vq_quantlist__16u0__p7_1[] = {
  143213. 7,
  143214. 6,
  143215. 8,
  143216. 5,
  143217. 9,
  143218. 4,
  143219. 10,
  143220. 3,
  143221. 11,
  143222. 2,
  143223. 12,
  143224. 1,
  143225. 13,
  143226. 0,
  143227. 14,
  143228. };
  143229. static long _vq_lengthlist__16u0__p7_1[] = {
  143230. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143231. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143232. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143233. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143234. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143235. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143236. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143240. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143242. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143243. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143244. 10,
  143245. };
  143246. static float _vq_quantthresh__16u0__p7_1[] = {
  143247. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143248. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143249. };
  143250. static long _vq_quantmap__16u0__p7_1[] = {
  143251. 13, 11, 9, 7, 5, 3, 1, 0,
  143252. 2, 4, 6, 8, 10, 12, 14,
  143253. };
  143254. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143255. _vq_quantthresh__16u0__p7_1,
  143256. _vq_quantmap__16u0__p7_1,
  143257. 15,
  143258. 15
  143259. };
  143260. static static_codebook _16u0__p7_1 = {
  143261. 2, 225,
  143262. _vq_lengthlist__16u0__p7_1,
  143263. 1, -520986624, 1620377600, 4, 0,
  143264. _vq_quantlist__16u0__p7_1,
  143265. NULL,
  143266. &_vq_auxt__16u0__p7_1,
  143267. NULL,
  143268. 0
  143269. };
  143270. static long _vq_quantlist__16u0__p7_2[] = {
  143271. 10,
  143272. 9,
  143273. 11,
  143274. 8,
  143275. 12,
  143276. 7,
  143277. 13,
  143278. 6,
  143279. 14,
  143280. 5,
  143281. 15,
  143282. 4,
  143283. 16,
  143284. 3,
  143285. 17,
  143286. 2,
  143287. 18,
  143288. 1,
  143289. 19,
  143290. 0,
  143291. 20,
  143292. };
  143293. static long _vq_lengthlist__16u0__p7_2[] = {
  143294. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143295. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143296. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143297. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143298. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143299. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143300. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143301. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143302. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143303. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143304. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143305. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143306. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143307. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143308. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143309. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143310. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143311. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143312. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143313. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143314. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143315. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143316. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143317. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143318. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143319. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143320. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143321. 10,10,12,11,10,11,11,11,10,
  143322. };
  143323. static float _vq_quantthresh__16u0__p7_2[] = {
  143324. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143325. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143326. 6.5, 7.5, 8.5, 9.5,
  143327. };
  143328. static long _vq_quantmap__16u0__p7_2[] = {
  143329. 19, 17, 15, 13, 11, 9, 7, 5,
  143330. 3, 1, 0, 2, 4, 6, 8, 10,
  143331. 12, 14, 16, 18, 20,
  143332. };
  143333. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143334. _vq_quantthresh__16u0__p7_2,
  143335. _vq_quantmap__16u0__p7_2,
  143336. 21,
  143337. 21
  143338. };
  143339. static static_codebook _16u0__p7_2 = {
  143340. 2, 441,
  143341. _vq_lengthlist__16u0__p7_2,
  143342. 1, -529268736, 1611661312, 5, 0,
  143343. _vq_quantlist__16u0__p7_2,
  143344. NULL,
  143345. &_vq_auxt__16u0__p7_2,
  143346. NULL,
  143347. 0
  143348. };
  143349. static long _huff_lengthlist__16u0__single[] = {
  143350. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143351. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143352. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143353. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143354. };
  143355. static static_codebook _huff_book__16u0__single = {
  143356. 2, 64,
  143357. _huff_lengthlist__16u0__single,
  143358. 0, 0, 0, 0, 0,
  143359. NULL,
  143360. NULL,
  143361. NULL,
  143362. NULL,
  143363. 0
  143364. };
  143365. static long _huff_lengthlist__16u1__long[] = {
  143366. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143367. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143368. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143369. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143370. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143371. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143372. 16,13,16,18,
  143373. };
  143374. static static_codebook _huff_book__16u1__long = {
  143375. 2, 100,
  143376. _huff_lengthlist__16u1__long,
  143377. 0, 0, 0, 0, 0,
  143378. NULL,
  143379. NULL,
  143380. NULL,
  143381. NULL,
  143382. 0
  143383. };
  143384. static long _vq_quantlist__16u1__p1_0[] = {
  143385. 1,
  143386. 0,
  143387. 2,
  143388. };
  143389. static long _vq_lengthlist__16u1__p1_0[] = {
  143390. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143391. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143392. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143393. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143394. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143395. 11,
  143396. };
  143397. static float _vq_quantthresh__16u1__p1_0[] = {
  143398. -0.5, 0.5,
  143399. };
  143400. static long _vq_quantmap__16u1__p1_0[] = {
  143401. 1, 0, 2,
  143402. };
  143403. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143404. _vq_quantthresh__16u1__p1_0,
  143405. _vq_quantmap__16u1__p1_0,
  143406. 3,
  143407. 3
  143408. };
  143409. static static_codebook _16u1__p1_0 = {
  143410. 4, 81,
  143411. _vq_lengthlist__16u1__p1_0,
  143412. 1, -535822336, 1611661312, 2, 0,
  143413. _vq_quantlist__16u1__p1_0,
  143414. NULL,
  143415. &_vq_auxt__16u1__p1_0,
  143416. NULL,
  143417. 0
  143418. };
  143419. static long _vq_quantlist__16u1__p2_0[] = {
  143420. 1,
  143421. 0,
  143422. 2,
  143423. };
  143424. static long _vq_lengthlist__16u1__p2_0[] = {
  143425. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143426. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143427. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143428. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143429. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143430. 8,
  143431. };
  143432. static float _vq_quantthresh__16u1__p2_0[] = {
  143433. -0.5, 0.5,
  143434. };
  143435. static long _vq_quantmap__16u1__p2_0[] = {
  143436. 1, 0, 2,
  143437. };
  143438. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143439. _vq_quantthresh__16u1__p2_0,
  143440. _vq_quantmap__16u1__p2_0,
  143441. 3,
  143442. 3
  143443. };
  143444. static static_codebook _16u1__p2_0 = {
  143445. 4, 81,
  143446. _vq_lengthlist__16u1__p2_0,
  143447. 1, -535822336, 1611661312, 2, 0,
  143448. _vq_quantlist__16u1__p2_0,
  143449. NULL,
  143450. &_vq_auxt__16u1__p2_0,
  143451. NULL,
  143452. 0
  143453. };
  143454. static long _vq_quantlist__16u1__p3_0[] = {
  143455. 2,
  143456. 1,
  143457. 3,
  143458. 0,
  143459. 4,
  143460. };
  143461. static long _vq_lengthlist__16u1__p3_0[] = {
  143462. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143463. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143464. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143465. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143466. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143467. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143468. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143469. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143470. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143471. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143472. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143473. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143474. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143475. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143476. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143477. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143478. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143479. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143480. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143481. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143482. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143483. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143484. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143485. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143486. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143487. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143488. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143489. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143490. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143491. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143492. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143493. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143494. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143495. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143496. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143497. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143498. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143499. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143500. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143501. 16,
  143502. };
  143503. static float _vq_quantthresh__16u1__p3_0[] = {
  143504. -1.5, -0.5, 0.5, 1.5,
  143505. };
  143506. static long _vq_quantmap__16u1__p3_0[] = {
  143507. 3, 1, 0, 2, 4,
  143508. };
  143509. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143510. _vq_quantthresh__16u1__p3_0,
  143511. _vq_quantmap__16u1__p3_0,
  143512. 5,
  143513. 5
  143514. };
  143515. static static_codebook _16u1__p3_0 = {
  143516. 4, 625,
  143517. _vq_lengthlist__16u1__p3_0,
  143518. 1, -533725184, 1611661312, 3, 0,
  143519. _vq_quantlist__16u1__p3_0,
  143520. NULL,
  143521. &_vq_auxt__16u1__p3_0,
  143522. NULL,
  143523. 0
  143524. };
  143525. static long _vq_quantlist__16u1__p4_0[] = {
  143526. 2,
  143527. 1,
  143528. 3,
  143529. 0,
  143530. 4,
  143531. };
  143532. static long _vq_lengthlist__16u1__p4_0[] = {
  143533. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143534. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143535. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143536. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143537. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143538. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143539. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143540. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143541. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143542. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143543. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143544. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143545. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143546. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143547. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143548. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143549. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143550. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143551. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143552. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143553. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143554. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143555. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143556. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143557. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143558. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143559. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143560. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143561. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143562. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143563. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143564. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143565. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143566. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143567. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143568. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143569. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143570. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143571. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143572. 11,
  143573. };
  143574. static float _vq_quantthresh__16u1__p4_0[] = {
  143575. -1.5, -0.5, 0.5, 1.5,
  143576. };
  143577. static long _vq_quantmap__16u1__p4_0[] = {
  143578. 3, 1, 0, 2, 4,
  143579. };
  143580. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143581. _vq_quantthresh__16u1__p4_0,
  143582. _vq_quantmap__16u1__p4_0,
  143583. 5,
  143584. 5
  143585. };
  143586. static static_codebook _16u1__p4_0 = {
  143587. 4, 625,
  143588. _vq_lengthlist__16u1__p4_0,
  143589. 1, -533725184, 1611661312, 3, 0,
  143590. _vq_quantlist__16u1__p4_0,
  143591. NULL,
  143592. &_vq_auxt__16u1__p4_0,
  143593. NULL,
  143594. 0
  143595. };
  143596. static long _vq_quantlist__16u1__p5_0[] = {
  143597. 4,
  143598. 3,
  143599. 5,
  143600. 2,
  143601. 6,
  143602. 1,
  143603. 7,
  143604. 0,
  143605. 8,
  143606. };
  143607. static long _vq_lengthlist__16u1__p5_0[] = {
  143608. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143609. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143610. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143611. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143612. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143613. 13,
  143614. };
  143615. static float _vq_quantthresh__16u1__p5_0[] = {
  143616. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143617. };
  143618. static long _vq_quantmap__16u1__p5_0[] = {
  143619. 7, 5, 3, 1, 0, 2, 4, 6,
  143620. 8,
  143621. };
  143622. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143623. _vq_quantthresh__16u1__p5_0,
  143624. _vq_quantmap__16u1__p5_0,
  143625. 9,
  143626. 9
  143627. };
  143628. static static_codebook _16u1__p5_0 = {
  143629. 2, 81,
  143630. _vq_lengthlist__16u1__p5_0,
  143631. 1, -531628032, 1611661312, 4, 0,
  143632. _vq_quantlist__16u1__p5_0,
  143633. NULL,
  143634. &_vq_auxt__16u1__p5_0,
  143635. NULL,
  143636. 0
  143637. };
  143638. static long _vq_quantlist__16u1__p6_0[] = {
  143639. 4,
  143640. 3,
  143641. 5,
  143642. 2,
  143643. 6,
  143644. 1,
  143645. 7,
  143646. 0,
  143647. 8,
  143648. };
  143649. static long _vq_lengthlist__16u1__p6_0[] = {
  143650. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143651. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143652. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143653. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143654. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143655. 11,
  143656. };
  143657. static float _vq_quantthresh__16u1__p6_0[] = {
  143658. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143659. };
  143660. static long _vq_quantmap__16u1__p6_0[] = {
  143661. 7, 5, 3, 1, 0, 2, 4, 6,
  143662. 8,
  143663. };
  143664. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143665. _vq_quantthresh__16u1__p6_0,
  143666. _vq_quantmap__16u1__p6_0,
  143667. 9,
  143668. 9
  143669. };
  143670. static static_codebook _16u1__p6_0 = {
  143671. 2, 81,
  143672. _vq_lengthlist__16u1__p6_0,
  143673. 1, -531628032, 1611661312, 4, 0,
  143674. _vq_quantlist__16u1__p6_0,
  143675. NULL,
  143676. &_vq_auxt__16u1__p6_0,
  143677. NULL,
  143678. 0
  143679. };
  143680. static long _vq_quantlist__16u1__p7_0[] = {
  143681. 1,
  143682. 0,
  143683. 2,
  143684. };
  143685. static long _vq_lengthlist__16u1__p7_0[] = {
  143686. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143687. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143688. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143689. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143690. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143691. 13,
  143692. };
  143693. static float _vq_quantthresh__16u1__p7_0[] = {
  143694. -5.5, 5.5,
  143695. };
  143696. static long _vq_quantmap__16u1__p7_0[] = {
  143697. 1, 0, 2,
  143698. };
  143699. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143700. _vq_quantthresh__16u1__p7_0,
  143701. _vq_quantmap__16u1__p7_0,
  143702. 3,
  143703. 3
  143704. };
  143705. static static_codebook _16u1__p7_0 = {
  143706. 4, 81,
  143707. _vq_lengthlist__16u1__p7_0,
  143708. 1, -529137664, 1618345984, 2, 0,
  143709. _vq_quantlist__16u1__p7_0,
  143710. NULL,
  143711. &_vq_auxt__16u1__p7_0,
  143712. NULL,
  143713. 0
  143714. };
  143715. static long _vq_quantlist__16u1__p7_1[] = {
  143716. 5,
  143717. 4,
  143718. 6,
  143719. 3,
  143720. 7,
  143721. 2,
  143722. 8,
  143723. 1,
  143724. 9,
  143725. 0,
  143726. 10,
  143727. };
  143728. static long _vq_lengthlist__16u1__p7_1[] = {
  143729. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143730. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143731. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143732. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143733. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143734. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143735. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143736. 8, 9, 9,10,10,10,10,10,10,
  143737. };
  143738. static float _vq_quantthresh__16u1__p7_1[] = {
  143739. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143740. 3.5, 4.5,
  143741. };
  143742. static long _vq_quantmap__16u1__p7_1[] = {
  143743. 9, 7, 5, 3, 1, 0, 2, 4,
  143744. 6, 8, 10,
  143745. };
  143746. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143747. _vq_quantthresh__16u1__p7_1,
  143748. _vq_quantmap__16u1__p7_1,
  143749. 11,
  143750. 11
  143751. };
  143752. static static_codebook _16u1__p7_1 = {
  143753. 2, 121,
  143754. _vq_lengthlist__16u1__p7_1,
  143755. 1, -531365888, 1611661312, 4, 0,
  143756. _vq_quantlist__16u1__p7_1,
  143757. NULL,
  143758. &_vq_auxt__16u1__p7_1,
  143759. NULL,
  143760. 0
  143761. };
  143762. static long _vq_quantlist__16u1__p8_0[] = {
  143763. 5,
  143764. 4,
  143765. 6,
  143766. 3,
  143767. 7,
  143768. 2,
  143769. 8,
  143770. 1,
  143771. 9,
  143772. 0,
  143773. 10,
  143774. };
  143775. static long _vq_lengthlist__16u1__p8_0[] = {
  143776. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143777. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143778. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143779. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143780. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143781. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143782. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143783. 13,14,14,15,15,16,16,15,16,
  143784. };
  143785. static float _vq_quantthresh__16u1__p8_0[] = {
  143786. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143787. 38.5, 49.5,
  143788. };
  143789. static long _vq_quantmap__16u1__p8_0[] = {
  143790. 9, 7, 5, 3, 1, 0, 2, 4,
  143791. 6, 8, 10,
  143792. };
  143793. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143794. _vq_quantthresh__16u1__p8_0,
  143795. _vq_quantmap__16u1__p8_0,
  143796. 11,
  143797. 11
  143798. };
  143799. static static_codebook _16u1__p8_0 = {
  143800. 2, 121,
  143801. _vq_lengthlist__16u1__p8_0,
  143802. 1, -524582912, 1618345984, 4, 0,
  143803. _vq_quantlist__16u1__p8_0,
  143804. NULL,
  143805. &_vq_auxt__16u1__p8_0,
  143806. NULL,
  143807. 0
  143808. };
  143809. static long _vq_quantlist__16u1__p8_1[] = {
  143810. 5,
  143811. 4,
  143812. 6,
  143813. 3,
  143814. 7,
  143815. 2,
  143816. 8,
  143817. 1,
  143818. 9,
  143819. 0,
  143820. 10,
  143821. };
  143822. static long _vq_lengthlist__16u1__p8_1[] = {
  143823. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143824. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143825. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143826. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143827. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143828. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143829. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143830. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143831. };
  143832. static float _vq_quantthresh__16u1__p8_1[] = {
  143833. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143834. 3.5, 4.5,
  143835. };
  143836. static long _vq_quantmap__16u1__p8_1[] = {
  143837. 9, 7, 5, 3, 1, 0, 2, 4,
  143838. 6, 8, 10,
  143839. };
  143840. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143841. _vq_quantthresh__16u1__p8_1,
  143842. _vq_quantmap__16u1__p8_1,
  143843. 11,
  143844. 11
  143845. };
  143846. static static_codebook _16u1__p8_1 = {
  143847. 2, 121,
  143848. _vq_lengthlist__16u1__p8_1,
  143849. 1, -531365888, 1611661312, 4, 0,
  143850. _vq_quantlist__16u1__p8_1,
  143851. NULL,
  143852. &_vq_auxt__16u1__p8_1,
  143853. NULL,
  143854. 0
  143855. };
  143856. static long _vq_quantlist__16u1__p9_0[] = {
  143857. 7,
  143858. 6,
  143859. 8,
  143860. 5,
  143861. 9,
  143862. 4,
  143863. 10,
  143864. 3,
  143865. 11,
  143866. 2,
  143867. 12,
  143868. 1,
  143869. 13,
  143870. 0,
  143871. 14,
  143872. };
  143873. static long _vq_lengthlist__16u1__p9_0[] = {
  143874. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143875. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143876. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143877. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143878. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143879. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143880. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143881. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143882. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143883. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143884. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143885. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143886. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143887. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143888. 8,
  143889. };
  143890. static float _vq_quantthresh__16u1__p9_0[] = {
  143891. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143892. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143893. };
  143894. static long _vq_quantmap__16u1__p9_0[] = {
  143895. 13, 11, 9, 7, 5, 3, 1, 0,
  143896. 2, 4, 6, 8, 10, 12, 14,
  143897. };
  143898. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143899. _vq_quantthresh__16u1__p9_0,
  143900. _vq_quantmap__16u1__p9_0,
  143901. 15,
  143902. 15
  143903. };
  143904. static static_codebook _16u1__p9_0 = {
  143905. 2, 225,
  143906. _vq_lengthlist__16u1__p9_0,
  143907. 1, -514071552, 1627381760, 4, 0,
  143908. _vq_quantlist__16u1__p9_0,
  143909. NULL,
  143910. &_vq_auxt__16u1__p9_0,
  143911. NULL,
  143912. 0
  143913. };
  143914. static long _vq_quantlist__16u1__p9_1[] = {
  143915. 7,
  143916. 6,
  143917. 8,
  143918. 5,
  143919. 9,
  143920. 4,
  143921. 10,
  143922. 3,
  143923. 11,
  143924. 2,
  143925. 12,
  143926. 1,
  143927. 13,
  143928. 0,
  143929. 14,
  143930. };
  143931. static long _vq_lengthlist__16u1__p9_1[] = {
  143932. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143933. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143934. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143935. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143936. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143937. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143938. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143939. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143940. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143941. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143942. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143943. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143944. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143945. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143946. 9,
  143947. };
  143948. static float _vq_quantthresh__16u1__p9_1[] = {
  143949. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143950. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143951. };
  143952. static long _vq_quantmap__16u1__p9_1[] = {
  143953. 13, 11, 9, 7, 5, 3, 1, 0,
  143954. 2, 4, 6, 8, 10, 12, 14,
  143955. };
  143956. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143957. _vq_quantthresh__16u1__p9_1,
  143958. _vq_quantmap__16u1__p9_1,
  143959. 15,
  143960. 15
  143961. };
  143962. static static_codebook _16u1__p9_1 = {
  143963. 2, 225,
  143964. _vq_lengthlist__16u1__p9_1,
  143965. 1, -522338304, 1620115456, 4, 0,
  143966. _vq_quantlist__16u1__p9_1,
  143967. NULL,
  143968. &_vq_auxt__16u1__p9_1,
  143969. NULL,
  143970. 0
  143971. };
  143972. static long _vq_quantlist__16u1__p9_2[] = {
  143973. 8,
  143974. 7,
  143975. 9,
  143976. 6,
  143977. 10,
  143978. 5,
  143979. 11,
  143980. 4,
  143981. 12,
  143982. 3,
  143983. 13,
  143984. 2,
  143985. 14,
  143986. 1,
  143987. 15,
  143988. 0,
  143989. 16,
  143990. };
  143991. static long _vq_lengthlist__16u1__p9_2[] = {
  143992. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143993. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143994. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143995. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143996. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143997. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143998. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143999. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144000. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144001. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144002. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144003. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144004. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144005. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144006. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144007. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144008. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144009. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144010. 10,
  144011. };
  144012. static float _vq_quantthresh__16u1__p9_2[] = {
  144013. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144014. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144015. };
  144016. static long _vq_quantmap__16u1__p9_2[] = {
  144017. 15, 13, 11, 9, 7, 5, 3, 1,
  144018. 0, 2, 4, 6, 8, 10, 12, 14,
  144019. 16,
  144020. };
  144021. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144022. _vq_quantthresh__16u1__p9_2,
  144023. _vq_quantmap__16u1__p9_2,
  144024. 17,
  144025. 17
  144026. };
  144027. static static_codebook _16u1__p9_2 = {
  144028. 2, 289,
  144029. _vq_lengthlist__16u1__p9_2,
  144030. 1, -529530880, 1611661312, 5, 0,
  144031. _vq_quantlist__16u1__p9_2,
  144032. NULL,
  144033. &_vq_auxt__16u1__p9_2,
  144034. NULL,
  144035. 0
  144036. };
  144037. static long _huff_lengthlist__16u1__short[] = {
  144038. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144039. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144040. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144041. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144042. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144043. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144044. 16,16,16,16,
  144045. };
  144046. static static_codebook _huff_book__16u1__short = {
  144047. 2, 100,
  144048. _huff_lengthlist__16u1__short,
  144049. 0, 0, 0, 0, 0,
  144050. NULL,
  144051. NULL,
  144052. NULL,
  144053. NULL,
  144054. 0
  144055. };
  144056. static long _huff_lengthlist__16u2__long[] = {
  144057. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144058. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144059. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144060. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144061. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144062. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144063. 13,14,18,18,
  144064. };
  144065. static static_codebook _huff_book__16u2__long = {
  144066. 2, 100,
  144067. _huff_lengthlist__16u2__long,
  144068. 0, 0, 0, 0, 0,
  144069. NULL,
  144070. NULL,
  144071. NULL,
  144072. NULL,
  144073. 0
  144074. };
  144075. static long _huff_lengthlist__16u2__short[] = {
  144076. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144077. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144078. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144079. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144080. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144081. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144082. 16,16,16,16,
  144083. };
  144084. static static_codebook _huff_book__16u2__short = {
  144085. 2, 100,
  144086. _huff_lengthlist__16u2__short,
  144087. 0, 0, 0, 0, 0,
  144088. NULL,
  144089. NULL,
  144090. NULL,
  144091. NULL,
  144092. 0
  144093. };
  144094. static long _vq_quantlist__16u2_p1_0[] = {
  144095. 1,
  144096. 0,
  144097. 2,
  144098. };
  144099. static long _vq_lengthlist__16u2_p1_0[] = {
  144100. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144101. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144102. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144103. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144104. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144105. 10,
  144106. };
  144107. static float _vq_quantthresh__16u2_p1_0[] = {
  144108. -0.5, 0.5,
  144109. };
  144110. static long _vq_quantmap__16u2_p1_0[] = {
  144111. 1, 0, 2,
  144112. };
  144113. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144114. _vq_quantthresh__16u2_p1_0,
  144115. _vq_quantmap__16u2_p1_0,
  144116. 3,
  144117. 3
  144118. };
  144119. static static_codebook _16u2_p1_0 = {
  144120. 4, 81,
  144121. _vq_lengthlist__16u2_p1_0,
  144122. 1, -535822336, 1611661312, 2, 0,
  144123. _vq_quantlist__16u2_p1_0,
  144124. NULL,
  144125. &_vq_auxt__16u2_p1_0,
  144126. NULL,
  144127. 0
  144128. };
  144129. static long _vq_quantlist__16u2_p2_0[] = {
  144130. 2,
  144131. 1,
  144132. 3,
  144133. 0,
  144134. 4,
  144135. };
  144136. static long _vq_lengthlist__16u2_p2_0[] = {
  144137. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144138. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144139. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144140. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144141. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144142. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144143. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144144. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144145. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144146. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144147. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144148. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144149. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144150. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144151. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144152. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144153. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144154. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144155. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144156. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144157. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144158. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144159. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144160. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144161. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144162. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144163. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144164. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144165. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144166. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144167. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144168. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144169. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144170. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144171. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144172. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144173. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144174. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144175. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144176. 13,
  144177. };
  144178. static float _vq_quantthresh__16u2_p2_0[] = {
  144179. -1.5, -0.5, 0.5, 1.5,
  144180. };
  144181. static long _vq_quantmap__16u2_p2_0[] = {
  144182. 3, 1, 0, 2, 4,
  144183. };
  144184. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144185. _vq_quantthresh__16u2_p2_0,
  144186. _vq_quantmap__16u2_p2_0,
  144187. 5,
  144188. 5
  144189. };
  144190. static static_codebook _16u2_p2_0 = {
  144191. 4, 625,
  144192. _vq_lengthlist__16u2_p2_0,
  144193. 1, -533725184, 1611661312, 3, 0,
  144194. _vq_quantlist__16u2_p2_0,
  144195. NULL,
  144196. &_vq_auxt__16u2_p2_0,
  144197. NULL,
  144198. 0
  144199. };
  144200. static long _vq_quantlist__16u2_p3_0[] = {
  144201. 4,
  144202. 3,
  144203. 5,
  144204. 2,
  144205. 6,
  144206. 1,
  144207. 7,
  144208. 0,
  144209. 8,
  144210. };
  144211. static long _vq_lengthlist__16u2_p3_0[] = {
  144212. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144213. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144214. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144215. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144216. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144217. 11,
  144218. };
  144219. static float _vq_quantthresh__16u2_p3_0[] = {
  144220. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144221. };
  144222. static long _vq_quantmap__16u2_p3_0[] = {
  144223. 7, 5, 3, 1, 0, 2, 4, 6,
  144224. 8,
  144225. };
  144226. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144227. _vq_quantthresh__16u2_p3_0,
  144228. _vq_quantmap__16u2_p3_0,
  144229. 9,
  144230. 9
  144231. };
  144232. static static_codebook _16u2_p3_0 = {
  144233. 2, 81,
  144234. _vq_lengthlist__16u2_p3_0,
  144235. 1, -531628032, 1611661312, 4, 0,
  144236. _vq_quantlist__16u2_p3_0,
  144237. NULL,
  144238. &_vq_auxt__16u2_p3_0,
  144239. NULL,
  144240. 0
  144241. };
  144242. static long _vq_quantlist__16u2_p4_0[] = {
  144243. 8,
  144244. 7,
  144245. 9,
  144246. 6,
  144247. 10,
  144248. 5,
  144249. 11,
  144250. 4,
  144251. 12,
  144252. 3,
  144253. 13,
  144254. 2,
  144255. 14,
  144256. 1,
  144257. 15,
  144258. 0,
  144259. 16,
  144260. };
  144261. static long _vq_lengthlist__16u2_p4_0[] = {
  144262. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144263. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144264. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144265. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144266. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144267. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144268. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144269. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144270. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144271. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144272. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144273. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144274. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144275. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144276. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144277. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144278. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144279. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144280. 14,
  144281. };
  144282. static float _vq_quantthresh__16u2_p4_0[] = {
  144283. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144284. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144285. };
  144286. static long _vq_quantmap__16u2_p4_0[] = {
  144287. 15, 13, 11, 9, 7, 5, 3, 1,
  144288. 0, 2, 4, 6, 8, 10, 12, 14,
  144289. 16,
  144290. };
  144291. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144292. _vq_quantthresh__16u2_p4_0,
  144293. _vq_quantmap__16u2_p4_0,
  144294. 17,
  144295. 17
  144296. };
  144297. static static_codebook _16u2_p4_0 = {
  144298. 2, 289,
  144299. _vq_lengthlist__16u2_p4_0,
  144300. 1, -529530880, 1611661312, 5, 0,
  144301. _vq_quantlist__16u2_p4_0,
  144302. NULL,
  144303. &_vq_auxt__16u2_p4_0,
  144304. NULL,
  144305. 0
  144306. };
  144307. static long _vq_quantlist__16u2_p5_0[] = {
  144308. 1,
  144309. 0,
  144310. 2,
  144311. };
  144312. static long _vq_lengthlist__16u2_p5_0[] = {
  144313. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144314. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144315. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144316. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144317. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144318. 10,
  144319. };
  144320. static float _vq_quantthresh__16u2_p5_0[] = {
  144321. -5.5, 5.5,
  144322. };
  144323. static long _vq_quantmap__16u2_p5_0[] = {
  144324. 1, 0, 2,
  144325. };
  144326. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144327. _vq_quantthresh__16u2_p5_0,
  144328. _vq_quantmap__16u2_p5_0,
  144329. 3,
  144330. 3
  144331. };
  144332. static static_codebook _16u2_p5_0 = {
  144333. 4, 81,
  144334. _vq_lengthlist__16u2_p5_0,
  144335. 1, -529137664, 1618345984, 2, 0,
  144336. _vq_quantlist__16u2_p5_0,
  144337. NULL,
  144338. &_vq_auxt__16u2_p5_0,
  144339. NULL,
  144340. 0
  144341. };
  144342. static long _vq_quantlist__16u2_p5_1[] = {
  144343. 5,
  144344. 4,
  144345. 6,
  144346. 3,
  144347. 7,
  144348. 2,
  144349. 8,
  144350. 1,
  144351. 9,
  144352. 0,
  144353. 10,
  144354. };
  144355. static long _vq_lengthlist__16u2_p5_1[] = {
  144356. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144357. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144358. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144359. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144360. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144361. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144362. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144363. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144364. };
  144365. static float _vq_quantthresh__16u2_p5_1[] = {
  144366. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144367. 3.5, 4.5,
  144368. };
  144369. static long _vq_quantmap__16u2_p5_1[] = {
  144370. 9, 7, 5, 3, 1, 0, 2, 4,
  144371. 6, 8, 10,
  144372. };
  144373. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144374. _vq_quantthresh__16u2_p5_1,
  144375. _vq_quantmap__16u2_p5_1,
  144376. 11,
  144377. 11
  144378. };
  144379. static static_codebook _16u2_p5_1 = {
  144380. 2, 121,
  144381. _vq_lengthlist__16u2_p5_1,
  144382. 1, -531365888, 1611661312, 4, 0,
  144383. _vq_quantlist__16u2_p5_1,
  144384. NULL,
  144385. &_vq_auxt__16u2_p5_1,
  144386. NULL,
  144387. 0
  144388. };
  144389. static long _vq_quantlist__16u2_p6_0[] = {
  144390. 6,
  144391. 5,
  144392. 7,
  144393. 4,
  144394. 8,
  144395. 3,
  144396. 9,
  144397. 2,
  144398. 10,
  144399. 1,
  144400. 11,
  144401. 0,
  144402. 12,
  144403. };
  144404. static long _vq_lengthlist__16u2_p6_0[] = {
  144405. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144406. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144407. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144408. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144409. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144410. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144411. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144412. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144413. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144414. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144415. 12,13,13,14,14,14,14,15,15,
  144416. };
  144417. static float _vq_quantthresh__16u2_p6_0[] = {
  144418. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144419. 12.5, 17.5, 22.5, 27.5,
  144420. };
  144421. static long _vq_quantmap__16u2_p6_0[] = {
  144422. 11, 9, 7, 5, 3, 1, 0, 2,
  144423. 4, 6, 8, 10, 12,
  144424. };
  144425. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144426. _vq_quantthresh__16u2_p6_0,
  144427. _vq_quantmap__16u2_p6_0,
  144428. 13,
  144429. 13
  144430. };
  144431. static static_codebook _16u2_p6_0 = {
  144432. 2, 169,
  144433. _vq_lengthlist__16u2_p6_0,
  144434. 1, -526516224, 1616117760, 4, 0,
  144435. _vq_quantlist__16u2_p6_0,
  144436. NULL,
  144437. &_vq_auxt__16u2_p6_0,
  144438. NULL,
  144439. 0
  144440. };
  144441. static long _vq_quantlist__16u2_p6_1[] = {
  144442. 2,
  144443. 1,
  144444. 3,
  144445. 0,
  144446. 4,
  144447. };
  144448. static long _vq_lengthlist__16u2_p6_1[] = {
  144449. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144450. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144451. };
  144452. static float _vq_quantthresh__16u2_p6_1[] = {
  144453. -1.5, -0.5, 0.5, 1.5,
  144454. };
  144455. static long _vq_quantmap__16u2_p6_1[] = {
  144456. 3, 1, 0, 2, 4,
  144457. };
  144458. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144459. _vq_quantthresh__16u2_p6_1,
  144460. _vq_quantmap__16u2_p6_1,
  144461. 5,
  144462. 5
  144463. };
  144464. static static_codebook _16u2_p6_1 = {
  144465. 2, 25,
  144466. _vq_lengthlist__16u2_p6_1,
  144467. 1, -533725184, 1611661312, 3, 0,
  144468. _vq_quantlist__16u2_p6_1,
  144469. NULL,
  144470. &_vq_auxt__16u2_p6_1,
  144471. NULL,
  144472. 0
  144473. };
  144474. static long _vq_quantlist__16u2_p7_0[] = {
  144475. 6,
  144476. 5,
  144477. 7,
  144478. 4,
  144479. 8,
  144480. 3,
  144481. 9,
  144482. 2,
  144483. 10,
  144484. 1,
  144485. 11,
  144486. 0,
  144487. 12,
  144488. };
  144489. static long _vq_lengthlist__16u2_p7_0[] = {
  144490. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144491. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144492. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144493. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144494. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144495. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144496. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144497. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144498. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144499. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144500. 12,13,13,13,14,14,14,15,14,
  144501. };
  144502. static float _vq_quantthresh__16u2_p7_0[] = {
  144503. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144504. 27.5, 38.5, 49.5, 60.5,
  144505. };
  144506. static long _vq_quantmap__16u2_p7_0[] = {
  144507. 11, 9, 7, 5, 3, 1, 0, 2,
  144508. 4, 6, 8, 10, 12,
  144509. };
  144510. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144511. _vq_quantthresh__16u2_p7_0,
  144512. _vq_quantmap__16u2_p7_0,
  144513. 13,
  144514. 13
  144515. };
  144516. static static_codebook _16u2_p7_0 = {
  144517. 2, 169,
  144518. _vq_lengthlist__16u2_p7_0,
  144519. 1, -523206656, 1618345984, 4, 0,
  144520. _vq_quantlist__16u2_p7_0,
  144521. NULL,
  144522. &_vq_auxt__16u2_p7_0,
  144523. NULL,
  144524. 0
  144525. };
  144526. static long _vq_quantlist__16u2_p7_1[] = {
  144527. 5,
  144528. 4,
  144529. 6,
  144530. 3,
  144531. 7,
  144532. 2,
  144533. 8,
  144534. 1,
  144535. 9,
  144536. 0,
  144537. 10,
  144538. };
  144539. static long _vq_lengthlist__16u2_p7_1[] = {
  144540. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144541. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144542. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144543. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144544. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144545. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144546. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144547. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144548. };
  144549. static float _vq_quantthresh__16u2_p7_1[] = {
  144550. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144551. 3.5, 4.5,
  144552. };
  144553. static long _vq_quantmap__16u2_p7_1[] = {
  144554. 9, 7, 5, 3, 1, 0, 2, 4,
  144555. 6, 8, 10,
  144556. };
  144557. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144558. _vq_quantthresh__16u2_p7_1,
  144559. _vq_quantmap__16u2_p7_1,
  144560. 11,
  144561. 11
  144562. };
  144563. static static_codebook _16u2_p7_1 = {
  144564. 2, 121,
  144565. _vq_lengthlist__16u2_p7_1,
  144566. 1, -531365888, 1611661312, 4, 0,
  144567. _vq_quantlist__16u2_p7_1,
  144568. NULL,
  144569. &_vq_auxt__16u2_p7_1,
  144570. NULL,
  144571. 0
  144572. };
  144573. static long _vq_quantlist__16u2_p8_0[] = {
  144574. 7,
  144575. 6,
  144576. 8,
  144577. 5,
  144578. 9,
  144579. 4,
  144580. 10,
  144581. 3,
  144582. 11,
  144583. 2,
  144584. 12,
  144585. 1,
  144586. 13,
  144587. 0,
  144588. 14,
  144589. };
  144590. static long _vq_lengthlist__16u2_p8_0[] = {
  144591. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144592. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144593. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144594. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144595. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144596. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144597. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144598. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144599. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144600. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144601. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144602. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144603. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144604. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144605. 14,
  144606. };
  144607. static float _vq_quantthresh__16u2_p8_0[] = {
  144608. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144609. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144610. };
  144611. static long _vq_quantmap__16u2_p8_0[] = {
  144612. 13, 11, 9, 7, 5, 3, 1, 0,
  144613. 2, 4, 6, 8, 10, 12, 14,
  144614. };
  144615. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144616. _vq_quantthresh__16u2_p8_0,
  144617. _vq_quantmap__16u2_p8_0,
  144618. 15,
  144619. 15
  144620. };
  144621. static static_codebook _16u2_p8_0 = {
  144622. 2, 225,
  144623. _vq_lengthlist__16u2_p8_0,
  144624. 1, -520986624, 1620377600, 4, 0,
  144625. _vq_quantlist__16u2_p8_0,
  144626. NULL,
  144627. &_vq_auxt__16u2_p8_0,
  144628. NULL,
  144629. 0
  144630. };
  144631. static long _vq_quantlist__16u2_p8_1[] = {
  144632. 10,
  144633. 9,
  144634. 11,
  144635. 8,
  144636. 12,
  144637. 7,
  144638. 13,
  144639. 6,
  144640. 14,
  144641. 5,
  144642. 15,
  144643. 4,
  144644. 16,
  144645. 3,
  144646. 17,
  144647. 2,
  144648. 18,
  144649. 1,
  144650. 19,
  144651. 0,
  144652. 20,
  144653. };
  144654. static long _vq_lengthlist__16u2_p8_1[] = {
  144655. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144656. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144657. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144658. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144659. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144660. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144661. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144662. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144663. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144664. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144665. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144666. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144667. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144668. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144669. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144670. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144671. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144672. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144673. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144674. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144675. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144676. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144677. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144678. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144680. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144681. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144682. 11,11,10,11,11,11,10,11,11,
  144683. };
  144684. static float _vq_quantthresh__16u2_p8_1[] = {
  144685. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144686. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144687. 6.5, 7.5, 8.5, 9.5,
  144688. };
  144689. static long _vq_quantmap__16u2_p8_1[] = {
  144690. 19, 17, 15, 13, 11, 9, 7, 5,
  144691. 3, 1, 0, 2, 4, 6, 8, 10,
  144692. 12, 14, 16, 18, 20,
  144693. };
  144694. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144695. _vq_quantthresh__16u2_p8_1,
  144696. _vq_quantmap__16u2_p8_1,
  144697. 21,
  144698. 21
  144699. };
  144700. static static_codebook _16u2_p8_1 = {
  144701. 2, 441,
  144702. _vq_lengthlist__16u2_p8_1,
  144703. 1, -529268736, 1611661312, 5, 0,
  144704. _vq_quantlist__16u2_p8_1,
  144705. NULL,
  144706. &_vq_auxt__16u2_p8_1,
  144707. NULL,
  144708. 0
  144709. };
  144710. static long _vq_quantlist__16u2_p9_0[] = {
  144711. 5586,
  144712. 4655,
  144713. 6517,
  144714. 3724,
  144715. 7448,
  144716. 2793,
  144717. 8379,
  144718. 1862,
  144719. 9310,
  144720. 931,
  144721. 10241,
  144722. 0,
  144723. 11172,
  144724. 5521,
  144725. 5651,
  144726. };
  144727. static long _vq_lengthlist__16u2_p9_0[] = {
  144728. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144731. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144732. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144733. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144735. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144736. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144737. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144738. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144739. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144740. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144741. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144742. 5,
  144743. };
  144744. static float _vq_quantthresh__16u2_p9_0[] = {
  144745. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144746. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144747. };
  144748. static long _vq_quantmap__16u2_p9_0[] = {
  144749. 11, 9, 7, 5, 3, 1, 13, 0,
  144750. 14, 2, 4, 6, 8, 10, 12,
  144751. };
  144752. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144753. _vq_quantthresh__16u2_p9_0,
  144754. _vq_quantmap__16u2_p9_0,
  144755. 15,
  144756. 15
  144757. };
  144758. static static_codebook _16u2_p9_0 = {
  144759. 2, 225,
  144760. _vq_lengthlist__16u2_p9_0,
  144761. 1, -510275072, 1611661312, 14, 0,
  144762. _vq_quantlist__16u2_p9_0,
  144763. NULL,
  144764. &_vq_auxt__16u2_p9_0,
  144765. NULL,
  144766. 0
  144767. };
  144768. static long _vq_quantlist__16u2_p9_1[] = {
  144769. 392,
  144770. 343,
  144771. 441,
  144772. 294,
  144773. 490,
  144774. 245,
  144775. 539,
  144776. 196,
  144777. 588,
  144778. 147,
  144779. 637,
  144780. 98,
  144781. 686,
  144782. 49,
  144783. 735,
  144784. 0,
  144785. 784,
  144786. 388,
  144787. 396,
  144788. };
  144789. static long _vq_lengthlist__16u2_p9_1[] = {
  144790. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144791. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144792. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144793. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144794. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144795. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144796. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144797. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144798. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144799. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144800. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144801. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144802. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144803. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144804. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144810. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144811. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144812. 11,11,11,11,11,11,11, 5, 4,
  144813. };
  144814. static float _vq_quantthresh__16u2_p9_1[] = {
  144815. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144816. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144817. 318.5, 367.5,
  144818. };
  144819. static long _vq_quantmap__16u2_p9_1[] = {
  144820. 15, 13, 11, 9, 7, 5, 3, 1,
  144821. 17, 0, 18, 2, 4, 6, 8, 10,
  144822. 12, 14, 16,
  144823. };
  144824. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144825. _vq_quantthresh__16u2_p9_1,
  144826. _vq_quantmap__16u2_p9_1,
  144827. 19,
  144828. 19
  144829. };
  144830. static static_codebook _16u2_p9_1 = {
  144831. 2, 361,
  144832. _vq_lengthlist__16u2_p9_1,
  144833. 1, -518488064, 1611661312, 10, 0,
  144834. _vq_quantlist__16u2_p9_1,
  144835. NULL,
  144836. &_vq_auxt__16u2_p9_1,
  144837. NULL,
  144838. 0
  144839. };
  144840. static long _vq_quantlist__16u2_p9_2[] = {
  144841. 24,
  144842. 23,
  144843. 25,
  144844. 22,
  144845. 26,
  144846. 21,
  144847. 27,
  144848. 20,
  144849. 28,
  144850. 19,
  144851. 29,
  144852. 18,
  144853. 30,
  144854. 17,
  144855. 31,
  144856. 16,
  144857. 32,
  144858. 15,
  144859. 33,
  144860. 14,
  144861. 34,
  144862. 13,
  144863. 35,
  144864. 12,
  144865. 36,
  144866. 11,
  144867. 37,
  144868. 10,
  144869. 38,
  144870. 9,
  144871. 39,
  144872. 8,
  144873. 40,
  144874. 7,
  144875. 41,
  144876. 6,
  144877. 42,
  144878. 5,
  144879. 43,
  144880. 4,
  144881. 44,
  144882. 3,
  144883. 45,
  144884. 2,
  144885. 46,
  144886. 1,
  144887. 47,
  144888. 0,
  144889. 48,
  144890. };
  144891. static long _vq_lengthlist__16u2_p9_2[] = {
  144892. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144893. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144894. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144895. 11,
  144896. };
  144897. static float _vq_quantthresh__16u2_p9_2[] = {
  144898. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144899. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144902. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144903. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144904. };
  144905. static long _vq_quantmap__16u2_p9_2[] = {
  144906. 47, 45, 43, 41, 39, 37, 35, 33,
  144907. 31, 29, 27, 25, 23, 21, 19, 17,
  144908. 15, 13, 11, 9, 7, 5, 3, 1,
  144909. 0, 2, 4, 6, 8, 10, 12, 14,
  144910. 16, 18, 20, 22, 24, 26, 28, 30,
  144911. 32, 34, 36, 38, 40, 42, 44, 46,
  144912. 48,
  144913. };
  144914. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144915. _vq_quantthresh__16u2_p9_2,
  144916. _vq_quantmap__16u2_p9_2,
  144917. 49,
  144918. 49
  144919. };
  144920. static static_codebook _16u2_p9_2 = {
  144921. 1, 49,
  144922. _vq_lengthlist__16u2_p9_2,
  144923. 1, -526909440, 1611661312, 6, 0,
  144924. _vq_quantlist__16u2_p9_2,
  144925. NULL,
  144926. &_vq_auxt__16u2_p9_2,
  144927. NULL,
  144928. 0
  144929. };
  144930. static long _vq_quantlist__8u0__p1_0[] = {
  144931. 1,
  144932. 0,
  144933. 2,
  144934. };
  144935. static long _vq_lengthlist__8u0__p1_0[] = {
  144936. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144937. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144938. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144939. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144940. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144941. 11,
  144942. };
  144943. static float _vq_quantthresh__8u0__p1_0[] = {
  144944. -0.5, 0.5,
  144945. };
  144946. static long _vq_quantmap__8u0__p1_0[] = {
  144947. 1, 0, 2,
  144948. };
  144949. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144950. _vq_quantthresh__8u0__p1_0,
  144951. _vq_quantmap__8u0__p1_0,
  144952. 3,
  144953. 3
  144954. };
  144955. static static_codebook _8u0__p1_0 = {
  144956. 4, 81,
  144957. _vq_lengthlist__8u0__p1_0,
  144958. 1, -535822336, 1611661312, 2, 0,
  144959. _vq_quantlist__8u0__p1_0,
  144960. NULL,
  144961. &_vq_auxt__8u0__p1_0,
  144962. NULL,
  144963. 0
  144964. };
  144965. static long _vq_quantlist__8u0__p2_0[] = {
  144966. 1,
  144967. 0,
  144968. 2,
  144969. };
  144970. static long _vq_lengthlist__8u0__p2_0[] = {
  144971. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144972. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144973. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144974. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144975. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144976. 8,
  144977. };
  144978. static float _vq_quantthresh__8u0__p2_0[] = {
  144979. -0.5, 0.5,
  144980. };
  144981. static long _vq_quantmap__8u0__p2_0[] = {
  144982. 1, 0, 2,
  144983. };
  144984. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144985. _vq_quantthresh__8u0__p2_0,
  144986. _vq_quantmap__8u0__p2_0,
  144987. 3,
  144988. 3
  144989. };
  144990. static static_codebook _8u0__p2_0 = {
  144991. 4, 81,
  144992. _vq_lengthlist__8u0__p2_0,
  144993. 1, -535822336, 1611661312, 2, 0,
  144994. _vq_quantlist__8u0__p2_0,
  144995. NULL,
  144996. &_vq_auxt__8u0__p2_0,
  144997. NULL,
  144998. 0
  144999. };
  145000. static long _vq_quantlist__8u0__p3_0[] = {
  145001. 2,
  145002. 1,
  145003. 3,
  145004. 0,
  145005. 4,
  145006. };
  145007. static long _vq_lengthlist__8u0__p3_0[] = {
  145008. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145009. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145010. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145011. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145012. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145013. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145014. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145015. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145016. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145017. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145018. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145019. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145020. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145021. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145022. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145023. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145024. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145025. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145026. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145027. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145028. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145029. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145030. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145031. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145032. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145033. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145034. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145035. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145036. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145037. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145038. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145039. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145040. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145041. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145042. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145043. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145044. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145045. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145046. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145047. 16,
  145048. };
  145049. static float _vq_quantthresh__8u0__p3_0[] = {
  145050. -1.5, -0.5, 0.5, 1.5,
  145051. };
  145052. static long _vq_quantmap__8u0__p3_0[] = {
  145053. 3, 1, 0, 2, 4,
  145054. };
  145055. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145056. _vq_quantthresh__8u0__p3_0,
  145057. _vq_quantmap__8u0__p3_0,
  145058. 5,
  145059. 5
  145060. };
  145061. static static_codebook _8u0__p3_0 = {
  145062. 4, 625,
  145063. _vq_lengthlist__8u0__p3_0,
  145064. 1, -533725184, 1611661312, 3, 0,
  145065. _vq_quantlist__8u0__p3_0,
  145066. NULL,
  145067. &_vq_auxt__8u0__p3_0,
  145068. NULL,
  145069. 0
  145070. };
  145071. static long _vq_quantlist__8u0__p4_0[] = {
  145072. 2,
  145073. 1,
  145074. 3,
  145075. 0,
  145076. 4,
  145077. };
  145078. static long _vq_lengthlist__8u0__p4_0[] = {
  145079. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145080. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145081. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145082. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145083. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145084. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145085. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145086. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145087. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145088. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145089. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145090. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145091. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145092. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145093. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145094. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145095. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145096. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145097. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145098. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145099. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145100. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145101. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145102. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145103. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145104. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145105. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145106. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145107. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145108. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145109. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145110. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145111. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145112. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145113. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145114. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145115. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145116. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145117. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145118. 12,
  145119. };
  145120. static float _vq_quantthresh__8u0__p4_0[] = {
  145121. -1.5, -0.5, 0.5, 1.5,
  145122. };
  145123. static long _vq_quantmap__8u0__p4_0[] = {
  145124. 3, 1, 0, 2, 4,
  145125. };
  145126. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145127. _vq_quantthresh__8u0__p4_0,
  145128. _vq_quantmap__8u0__p4_0,
  145129. 5,
  145130. 5
  145131. };
  145132. static static_codebook _8u0__p4_0 = {
  145133. 4, 625,
  145134. _vq_lengthlist__8u0__p4_0,
  145135. 1, -533725184, 1611661312, 3, 0,
  145136. _vq_quantlist__8u0__p4_0,
  145137. NULL,
  145138. &_vq_auxt__8u0__p4_0,
  145139. NULL,
  145140. 0
  145141. };
  145142. static long _vq_quantlist__8u0__p5_0[] = {
  145143. 4,
  145144. 3,
  145145. 5,
  145146. 2,
  145147. 6,
  145148. 1,
  145149. 7,
  145150. 0,
  145151. 8,
  145152. };
  145153. static long _vq_lengthlist__8u0__p5_0[] = {
  145154. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145155. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145156. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145157. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145158. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145159. 12,
  145160. };
  145161. static float _vq_quantthresh__8u0__p5_0[] = {
  145162. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145163. };
  145164. static long _vq_quantmap__8u0__p5_0[] = {
  145165. 7, 5, 3, 1, 0, 2, 4, 6,
  145166. 8,
  145167. };
  145168. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145169. _vq_quantthresh__8u0__p5_0,
  145170. _vq_quantmap__8u0__p5_0,
  145171. 9,
  145172. 9
  145173. };
  145174. static static_codebook _8u0__p5_0 = {
  145175. 2, 81,
  145176. _vq_lengthlist__8u0__p5_0,
  145177. 1, -531628032, 1611661312, 4, 0,
  145178. _vq_quantlist__8u0__p5_0,
  145179. NULL,
  145180. &_vq_auxt__8u0__p5_0,
  145181. NULL,
  145182. 0
  145183. };
  145184. static long _vq_quantlist__8u0__p6_0[] = {
  145185. 6,
  145186. 5,
  145187. 7,
  145188. 4,
  145189. 8,
  145190. 3,
  145191. 9,
  145192. 2,
  145193. 10,
  145194. 1,
  145195. 11,
  145196. 0,
  145197. 12,
  145198. };
  145199. static long _vq_lengthlist__8u0__p6_0[] = {
  145200. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145201. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145202. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145203. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145204. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145205. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145206. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145207. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145208. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145209. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145210. 16, 0,15, 0,17, 0, 0, 0, 0,
  145211. };
  145212. static float _vq_quantthresh__8u0__p6_0[] = {
  145213. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145214. 12.5, 17.5, 22.5, 27.5,
  145215. };
  145216. static long _vq_quantmap__8u0__p6_0[] = {
  145217. 11, 9, 7, 5, 3, 1, 0, 2,
  145218. 4, 6, 8, 10, 12,
  145219. };
  145220. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145221. _vq_quantthresh__8u0__p6_0,
  145222. _vq_quantmap__8u0__p6_0,
  145223. 13,
  145224. 13
  145225. };
  145226. static static_codebook _8u0__p6_0 = {
  145227. 2, 169,
  145228. _vq_lengthlist__8u0__p6_0,
  145229. 1, -526516224, 1616117760, 4, 0,
  145230. _vq_quantlist__8u0__p6_0,
  145231. NULL,
  145232. &_vq_auxt__8u0__p6_0,
  145233. NULL,
  145234. 0
  145235. };
  145236. static long _vq_quantlist__8u0__p6_1[] = {
  145237. 2,
  145238. 1,
  145239. 3,
  145240. 0,
  145241. 4,
  145242. };
  145243. static long _vq_lengthlist__8u0__p6_1[] = {
  145244. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145245. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145246. };
  145247. static float _vq_quantthresh__8u0__p6_1[] = {
  145248. -1.5, -0.5, 0.5, 1.5,
  145249. };
  145250. static long _vq_quantmap__8u0__p6_1[] = {
  145251. 3, 1, 0, 2, 4,
  145252. };
  145253. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145254. _vq_quantthresh__8u0__p6_1,
  145255. _vq_quantmap__8u0__p6_1,
  145256. 5,
  145257. 5
  145258. };
  145259. static static_codebook _8u0__p6_1 = {
  145260. 2, 25,
  145261. _vq_lengthlist__8u0__p6_1,
  145262. 1, -533725184, 1611661312, 3, 0,
  145263. _vq_quantlist__8u0__p6_1,
  145264. NULL,
  145265. &_vq_auxt__8u0__p6_1,
  145266. NULL,
  145267. 0
  145268. };
  145269. static long _vq_quantlist__8u0__p7_0[] = {
  145270. 1,
  145271. 0,
  145272. 2,
  145273. };
  145274. static long _vq_lengthlist__8u0__p7_0[] = {
  145275. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145276. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145277. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145278. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145279. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145280. 7,
  145281. };
  145282. static float _vq_quantthresh__8u0__p7_0[] = {
  145283. -157.5, 157.5,
  145284. };
  145285. static long _vq_quantmap__8u0__p7_0[] = {
  145286. 1, 0, 2,
  145287. };
  145288. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145289. _vq_quantthresh__8u0__p7_0,
  145290. _vq_quantmap__8u0__p7_0,
  145291. 3,
  145292. 3
  145293. };
  145294. static static_codebook _8u0__p7_0 = {
  145295. 4, 81,
  145296. _vq_lengthlist__8u0__p7_0,
  145297. 1, -518803456, 1628680192, 2, 0,
  145298. _vq_quantlist__8u0__p7_0,
  145299. NULL,
  145300. &_vq_auxt__8u0__p7_0,
  145301. NULL,
  145302. 0
  145303. };
  145304. static long _vq_quantlist__8u0__p7_1[] = {
  145305. 7,
  145306. 6,
  145307. 8,
  145308. 5,
  145309. 9,
  145310. 4,
  145311. 10,
  145312. 3,
  145313. 11,
  145314. 2,
  145315. 12,
  145316. 1,
  145317. 13,
  145318. 0,
  145319. 14,
  145320. };
  145321. static long _vq_lengthlist__8u0__p7_1[] = {
  145322. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145323. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145324. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145325. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145326. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145327. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145328. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145329. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145330. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145331. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145332. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145333. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145334. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145335. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145336. 10,
  145337. };
  145338. static float _vq_quantthresh__8u0__p7_1[] = {
  145339. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145340. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145341. };
  145342. static long _vq_quantmap__8u0__p7_1[] = {
  145343. 13, 11, 9, 7, 5, 3, 1, 0,
  145344. 2, 4, 6, 8, 10, 12, 14,
  145345. };
  145346. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145347. _vq_quantthresh__8u0__p7_1,
  145348. _vq_quantmap__8u0__p7_1,
  145349. 15,
  145350. 15
  145351. };
  145352. static static_codebook _8u0__p7_1 = {
  145353. 2, 225,
  145354. _vq_lengthlist__8u0__p7_1,
  145355. 1, -520986624, 1620377600, 4, 0,
  145356. _vq_quantlist__8u0__p7_1,
  145357. NULL,
  145358. &_vq_auxt__8u0__p7_1,
  145359. NULL,
  145360. 0
  145361. };
  145362. static long _vq_quantlist__8u0__p7_2[] = {
  145363. 10,
  145364. 9,
  145365. 11,
  145366. 8,
  145367. 12,
  145368. 7,
  145369. 13,
  145370. 6,
  145371. 14,
  145372. 5,
  145373. 15,
  145374. 4,
  145375. 16,
  145376. 3,
  145377. 17,
  145378. 2,
  145379. 18,
  145380. 1,
  145381. 19,
  145382. 0,
  145383. 20,
  145384. };
  145385. static long _vq_lengthlist__8u0__p7_2[] = {
  145386. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145387. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145388. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145389. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145390. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145391. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145392. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145393. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145394. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145395. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145396. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145397. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145398. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145399. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145400. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145401. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145402. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145403. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145404. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145405. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145406. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145407. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145408. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145409. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145410. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145411. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145412. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145413. 11,12,11,11,11,10,10,11,11,
  145414. };
  145415. static float _vq_quantthresh__8u0__p7_2[] = {
  145416. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145417. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145418. 6.5, 7.5, 8.5, 9.5,
  145419. };
  145420. static long _vq_quantmap__8u0__p7_2[] = {
  145421. 19, 17, 15, 13, 11, 9, 7, 5,
  145422. 3, 1, 0, 2, 4, 6, 8, 10,
  145423. 12, 14, 16, 18, 20,
  145424. };
  145425. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145426. _vq_quantthresh__8u0__p7_2,
  145427. _vq_quantmap__8u0__p7_2,
  145428. 21,
  145429. 21
  145430. };
  145431. static static_codebook _8u0__p7_2 = {
  145432. 2, 441,
  145433. _vq_lengthlist__8u0__p7_2,
  145434. 1, -529268736, 1611661312, 5, 0,
  145435. _vq_quantlist__8u0__p7_2,
  145436. NULL,
  145437. &_vq_auxt__8u0__p7_2,
  145438. NULL,
  145439. 0
  145440. };
  145441. static long _huff_lengthlist__8u0__single[] = {
  145442. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145443. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145444. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145445. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145446. };
  145447. static static_codebook _huff_book__8u0__single = {
  145448. 2, 64,
  145449. _huff_lengthlist__8u0__single,
  145450. 0, 0, 0, 0, 0,
  145451. NULL,
  145452. NULL,
  145453. NULL,
  145454. NULL,
  145455. 0
  145456. };
  145457. static long _vq_quantlist__8u1__p1_0[] = {
  145458. 1,
  145459. 0,
  145460. 2,
  145461. };
  145462. static long _vq_lengthlist__8u1__p1_0[] = {
  145463. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145464. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145465. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145466. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145467. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145468. 10,
  145469. };
  145470. static float _vq_quantthresh__8u1__p1_0[] = {
  145471. -0.5, 0.5,
  145472. };
  145473. static long _vq_quantmap__8u1__p1_0[] = {
  145474. 1, 0, 2,
  145475. };
  145476. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145477. _vq_quantthresh__8u1__p1_0,
  145478. _vq_quantmap__8u1__p1_0,
  145479. 3,
  145480. 3
  145481. };
  145482. static static_codebook _8u1__p1_0 = {
  145483. 4, 81,
  145484. _vq_lengthlist__8u1__p1_0,
  145485. 1, -535822336, 1611661312, 2, 0,
  145486. _vq_quantlist__8u1__p1_0,
  145487. NULL,
  145488. &_vq_auxt__8u1__p1_0,
  145489. NULL,
  145490. 0
  145491. };
  145492. static long _vq_quantlist__8u1__p2_0[] = {
  145493. 1,
  145494. 0,
  145495. 2,
  145496. };
  145497. static long _vq_lengthlist__8u1__p2_0[] = {
  145498. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145499. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145500. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145501. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145502. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145503. 7,
  145504. };
  145505. static float _vq_quantthresh__8u1__p2_0[] = {
  145506. -0.5, 0.5,
  145507. };
  145508. static long _vq_quantmap__8u1__p2_0[] = {
  145509. 1, 0, 2,
  145510. };
  145511. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145512. _vq_quantthresh__8u1__p2_0,
  145513. _vq_quantmap__8u1__p2_0,
  145514. 3,
  145515. 3
  145516. };
  145517. static static_codebook _8u1__p2_0 = {
  145518. 4, 81,
  145519. _vq_lengthlist__8u1__p2_0,
  145520. 1, -535822336, 1611661312, 2, 0,
  145521. _vq_quantlist__8u1__p2_0,
  145522. NULL,
  145523. &_vq_auxt__8u1__p2_0,
  145524. NULL,
  145525. 0
  145526. };
  145527. static long _vq_quantlist__8u1__p3_0[] = {
  145528. 2,
  145529. 1,
  145530. 3,
  145531. 0,
  145532. 4,
  145533. };
  145534. static long _vq_lengthlist__8u1__p3_0[] = {
  145535. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145536. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145537. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145538. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145539. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145540. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145541. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145542. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145543. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145544. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145545. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145546. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145547. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145548. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145549. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145550. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145551. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145552. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145553. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145554. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145555. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145556. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145557. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145558. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145559. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145560. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145561. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145562. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145563. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145564. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145565. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145566. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145567. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145568. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145569. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145570. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145571. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145572. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145573. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145574. 16,
  145575. };
  145576. static float _vq_quantthresh__8u1__p3_0[] = {
  145577. -1.5, -0.5, 0.5, 1.5,
  145578. };
  145579. static long _vq_quantmap__8u1__p3_0[] = {
  145580. 3, 1, 0, 2, 4,
  145581. };
  145582. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145583. _vq_quantthresh__8u1__p3_0,
  145584. _vq_quantmap__8u1__p3_0,
  145585. 5,
  145586. 5
  145587. };
  145588. static static_codebook _8u1__p3_0 = {
  145589. 4, 625,
  145590. _vq_lengthlist__8u1__p3_0,
  145591. 1, -533725184, 1611661312, 3, 0,
  145592. _vq_quantlist__8u1__p3_0,
  145593. NULL,
  145594. &_vq_auxt__8u1__p3_0,
  145595. NULL,
  145596. 0
  145597. };
  145598. static long _vq_quantlist__8u1__p4_0[] = {
  145599. 2,
  145600. 1,
  145601. 3,
  145602. 0,
  145603. 4,
  145604. };
  145605. static long _vq_lengthlist__8u1__p4_0[] = {
  145606. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145607. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145608. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145609. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145610. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145611. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145612. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145613. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145614. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145615. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145616. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145617. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145618. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145619. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145620. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145621. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145622. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145623. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145624. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145625. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145626. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145627. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145628. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145629. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145630. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145631. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145632. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145633. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145634. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145635. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145636. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145637. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145638. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145639. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145640. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145641. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145642. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145643. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145644. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145645. 10,
  145646. };
  145647. static float _vq_quantthresh__8u1__p4_0[] = {
  145648. -1.5, -0.5, 0.5, 1.5,
  145649. };
  145650. static long _vq_quantmap__8u1__p4_0[] = {
  145651. 3, 1, 0, 2, 4,
  145652. };
  145653. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145654. _vq_quantthresh__8u1__p4_0,
  145655. _vq_quantmap__8u1__p4_0,
  145656. 5,
  145657. 5
  145658. };
  145659. static static_codebook _8u1__p4_0 = {
  145660. 4, 625,
  145661. _vq_lengthlist__8u1__p4_0,
  145662. 1, -533725184, 1611661312, 3, 0,
  145663. _vq_quantlist__8u1__p4_0,
  145664. NULL,
  145665. &_vq_auxt__8u1__p4_0,
  145666. NULL,
  145667. 0
  145668. };
  145669. static long _vq_quantlist__8u1__p5_0[] = {
  145670. 4,
  145671. 3,
  145672. 5,
  145673. 2,
  145674. 6,
  145675. 1,
  145676. 7,
  145677. 0,
  145678. 8,
  145679. };
  145680. static long _vq_lengthlist__8u1__p5_0[] = {
  145681. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145682. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145683. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145684. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145685. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145686. 13,
  145687. };
  145688. static float _vq_quantthresh__8u1__p5_0[] = {
  145689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145690. };
  145691. static long _vq_quantmap__8u1__p5_0[] = {
  145692. 7, 5, 3, 1, 0, 2, 4, 6,
  145693. 8,
  145694. };
  145695. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145696. _vq_quantthresh__8u1__p5_0,
  145697. _vq_quantmap__8u1__p5_0,
  145698. 9,
  145699. 9
  145700. };
  145701. static static_codebook _8u1__p5_0 = {
  145702. 2, 81,
  145703. _vq_lengthlist__8u1__p5_0,
  145704. 1, -531628032, 1611661312, 4, 0,
  145705. _vq_quantlist__8u1__p5_0,
  145706. NULL,
  145707. &_vq_auxt__8u1__p5_0,
  145708. NULL,
  145709. 0
  145710. };
  145711. static long _vq_quantlist__8u1__p6_0[] = {
  145712. 4,
  145713. 3,
  145714. 5,
  145715. 2,
  145716. 6,
  145717. 1,
  145718. 7,
  145719. 0,
  145720. 8,
  145721. };
  145722. static long _vq_lengthlist__8u1__p6_0[] = {
  145723. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145724. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145725. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145726. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145727. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145728. 10,
  145729. };
  145730. static float _vq_quantthresh__8u1__p6_0[] = {
  145731. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145732. };
  145733. static long _vq_quantmap__8u1__p6_0[] = {
  145734. 7, 5, 3, 1, 0, 2, 4, 6,
  145735. 8,
  145736. };
  145737. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145738. _vq_quantthresh__8u1__p6_0,
  145739. _vq_quantmap__8u1__p6_0,
  145740. 9,
  145741. 9
  145742. };
  145743. static static_codebook _8u1__p6_0 = {
  145744. 2, 81,
  145745. _vq_lengthlist__8u1__p6_0,
  145746. 1, -531628032, 1611661312, 4, 0,
  145747. _vq_quantlist__8u1__p6_0,
  145748. NULL,
  145749. &_vq_auxt__8u1__p6_0,
  145750. NULL,
  145751. 0
  145752. };
  145753. static long _vq_quantlist__8u1__p7_0[] = {
  145754. 1,
  145755. 0,
  145756. 2,
  145757. };
  145758. static long _vq_lengthlist__8u1__p7_0[] = {
  145759. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145760. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145761. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145762. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145763. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145764. 11,
  145765. };
  145766. static float _vq_quantthresh__8u1__p7_0[] = {
  145767. -5.5, 5.5,
  145768. };
  145769. static long _vq_quantmap__8u1__p7_0[] = {
  145770. 1, 0, 2,
  145771. };
  145772. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145773. _vq_quantthresh__8u1__p7_0,
  145774. _vq_quantmap__8u1__p7_0,
  145775. 3,
  145776. 3
  145777. };
  145778. static static_codebook _8u1__p7_0 = {
  145779. 4, 81,
  145780. _vq_lengthlist__8u1__p7_0,
  145781. 1, -529137664, 1618345984, 2, 0,
  145782. _vq_quantlist__8u1__p7_0,
  145783. NULL,
  145784. &_vq_auxt__8u1__p7_0,
  145785. NULL,
  145786. 0
  145787. };
  145788. static long _vq_quantlist__8u1__p7_1[] = {
  145789. 5,
  145790. 4,
  145791. 6,
  145792. 3,
  145793. 7,
  145794. 2,
  145795. 8,
  145796. 1,
  145797. 9,
  145798. 0,
  145799. 10,
  145800. };
  145801. static long _vq_lengthlist__8u1__p7_1[] = {
  145802. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145803. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145804. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145805. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145806. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145807. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145808. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145809. 9, 9, 9, 9, 9,10,10,10,10,
  145810. };
  145811. static float _vq_quantthresh__8u1__p7_1[] = {
  145812. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145813. 3.5, 4.5,
  145814. };
  145815. static long _vq_quantmap__8u1__p7_1[] = {
  145816. 9, 7, 5, 3, 1, 0, 2, 4,
  145817. 6, 8, 10,
  145818. };
  145819. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145820. _vq_quantthresh__8u1__p7_1,
  145821. _vq_quantmap__8u1__p7_1,
  145822. 11,
  145823. 11
  145824. };
  145825. static static_codebook _8u1__p7_1 = {
  145826. 2, 121,
  145827. _vq_lengthlist__8u1__p7_1,
  145828. 1, -531365888, 1611661312, 4, 0,
  145829. _vq_quantlist__8u1__p7_1,
  145830. NULL,
  145831. &_vq_auxt__8u1__p7_1,
  145832. NULL,
  145833. 0
  145834. };
  145835. static long _vq_quantlist__8u1__p8_0[] = {
  145836. 5,
  145837. 4,
  145838. 6,
  145839. 3,
  145840. 7,
  145841. 2,
  145842. 8,
  145843. 1,
  145844. 9,
  145845. 0,
  145846. 10,
  145847. };
  145848. static long _vq_lengthlist__8u1__p8_0[] = {
  145849. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145850. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145851. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145852. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145853. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145854. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145855. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145856. 12,13,13,14,14,15,15,15,15,
  145857. };
  145858. static float _vq_quantthresh__8u1__p8_0[] = {
  145859. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145860. 38.5, 49.5,
  145861. };
  145862. static long _vq_quantmap__8u1__p8_0[] = {
  145863. 9, 7, 5, 3, 1, 0, 2, 4,
  145864. 6, 8, 10,
  145865. };
  145866. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145867. _vq_quantthresh__8u1__p8_0,
  145868. _vq_quantmap__8u1__p8_0,
  145869. 11,
  145870. 11
  145871. };
  145872. static static_codebook _8u1__p8_0 = {
  145873. 2, 121,
  145874. _vq_lengthlist__8u1__p8_0,
  145875. 1, -524582912, 1618345984, 4, 0,
  145876. _vq_quantlist__8u1__p8_0,
  145877. NULL,
  145878. &_vq_auxt__8u1__p8_0,
  145879. NULL,
  145880. 0
  145881. };
  145882. static long _vq_quantlist__8u1__p8_1[] = {
  145883. 5,
  145884. 4,
  145885. 6,
  145886. 3,
  145887. 7,
  145888. 2,
  145889. 8,
  145890. 1,
  145891. 9,
  145892. 0,
  145893. 10,
  145894. };
  145895. static long _vq_lengthlist__8u1__p8_1[] = {
  145896. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145897. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145898. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145899. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145900. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145901. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145902. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145903. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145904. };
  145905. static float _vq_quantthresh__8u1__p8_1[] = {
  145906. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145907. 3.5, 4.5,
  145908. };
  145909. static long _vq_quantmap__8u1__p8_1[] = {
  145910. 9, 7, 5, 3, 1, 0, 2, 4,
  145911. 6, 8, 10,
  145912. };
  145913. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145914. _vq_quantthresh__8u1__p8_1,
  145915. _vq_quantmap__8u1__p8_1,
  145916. 11,
  145917. 11
  145918. };
  145919. static static_codebook _8u1__p8_1 = {
  145920. 2, 121,
  145921. _vq_lengthlist__8u1__p8_1,
  145922. 1, -531365888, 1611661312, 4, 0,
  145923. _vq_quantlist__8u1__p8_1,
  145924. NULL,
  145925. &_vq_auxt__8u1__p8_1,
  145926. NULL,
  145927. 0
  145928. };
  145929. static long _vq_quantlist__8u1__p9_0[] = {
  145930. 7,
  145931. 6,
  145932. 8,
  145933. 5,
  145934. 9,
  145935. 4,
  145936. 10,
  145937. 3,
  145938. 11,
  145939. 2,
  145940. 12,
  145941. 1,
  145942. 13,
  145943. 0,
  145944. 14,
  145945. };
  145946. static long _vq_lengthlist__8u1__p9_0[] = {
  145947. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145948. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145949. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145950. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145951. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145959. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145960. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145961. 10,
  145962. };
  145963. static float _vq_quantthresh__8u1__p9_0[] = {
  145964. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145965. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145966. };
  145967. static long _vq_quantmap__8u1__p9_0[] = {
  145968. 13, 11, 9, 7, 5, 3, 1, 0,
  145969. 2, 4, 6, 8, 10, 12, 14,
  145970. };
  145971. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145972. _vq_quantthresh__8u1__p9_0,
  145973. _vq_quantmap__8u1__p9_0,
  145974. 15,
  145975. 15
  145976. };
  145977. static static_codebook _8u1__p9_0 = {
  145978. 2, 225,
  145979. _vq_lengthlist__8u1__p9_0,
  145980. 1, -514071552, 1627381760, 4, 0,
  145981. _vq_quantlist__8u1__p9_0,
  145982. NULL,
  145983. &_vq_auxt__8u1__p9_0,
  145984. NULL,
  145985. 0
  145986. };
  145987. static long _vq_quantlist__8u1__p9_1[] = {
  145988. 7,
  145989. 6,
  145990. 8,
  145991. 5,
  145992. 9,
  145993. 4,
  145994. 10,
  145995. 3,
  145996. 11,
  145997. 2,
  145998. 12,
  145999. 1,
  146000. 13,
  146001. 0,
  146002. 14,
  146003. };
  146004. static long _vq_lengthlist__8u1__p9_1[] = {
  146005. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146006. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146007. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146008. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146009. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146010. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146011. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146012. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146013. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146014. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146015. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146016. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146017. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146018. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146019. 13,
  146020. };
  146021. static float _vq_quantthresh__8u1__p9_1[] = {
  146022. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146023. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146024. };
  146025. static long _vq_quantmap__8u1__p9_1[] = {
  146026. 13, 11, 9, 7, 5, 3, 1, 0,
  146027. 2, 4, 6, 8, 10, 12, 14,
  146028. };
  146029. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146030. _vq_quantthresh__8u1__p9_1,
  146031. _vq_quantmap__8u1__p9_1,
  146032. 15,
  146033. 15
  146034. };
  146035. static static_codebook _8u1__p9_1 = {
  146036. 2, 225,
  146037. _vq_lengthlist__8u1__p9_1,
  146038. 1, -522338304, 1620115456, 4, 0,
  146039. _vq_quantlist__8u1__p9_1,
  146040. NULL,
  146041. &_vq_auxt__8u1__p9_1,
  146042. NULL,
  146043. 0
  146044. };
  146045. static long _vq_quantlist__8u1__p9_2[] = {
  146046. 8,
  146047. 7,
  146048. 9,
  146049. 6,
  146050. 10,
  146051. 5,
  146052. 11,
  146053. 4,
  146054. 12,
  146055. 3,
  146056. 13,
  146057. 2,
  146058. 14,
  146059. 1,
  146060. 15,
  146061. 0,
  146062. 16,
  146063. };
  146064. static long _vq_lengthlist__8u1__p9_2[] = {
  146065. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146066. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146067. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146068. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146069. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146070. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146071. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146072. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146073. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146074. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146075. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146076. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146077. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146078. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146079. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146080. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146081. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146082. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146083. 10,
  146084. };
  146085. static float _vq_quantthresh__8u1__p9_2[] = {
  146086. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146087. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146088. };
  146089. static long _vq_quantmap__8u1__p9_2[] = {
  146090. 15, 13, 11, 9, 7, 5, 3, 1,
  146091. 0, 2, 4, 6, 8, 10, 12, 14,
  146092. 16,
  146093. };
  146094. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146095. _vq_quantthresh__8u1__p9_2,
  146096. _vq_quantmap__8u1__p9_2,
  146097. 17,
  146098. 17
  146099. };
  146100. static static_codebook _8u1__p9_2 = {
  146101. 2, 289,
  146102. _vq_lengthlist__8u1__p9_2,
  146103. 1, -529530880, 1611661312, 5, 0,
  146104. _vq_quantlist__8u1__p9_2,
  146105. NULL,
  146106. &_vq_auxt__8u1__p9_2,
  146107. NULL,
  146108. 0
  146109. };
  146110. static long _huff_lengthlist__8u1__single[] = {
  146111. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146112. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146113. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146114. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146115. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146116. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146117. 13, 8, 8,15,
  146118. };
  146119. static static_codebook _huff_book__8u1__single = {
  146120. 2, 100,
  146121. _huff_lengthlist__8u1__single,
  146122. 0, 0, 0, 0, 0,
  146123. NULL,
  146124. NULL,
  146125. NULL,
  146126. NULL,
  146127. 0
  146128. };
  146129. static long _huff_lengthlist__44u0__long[] = {
  146130. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146131. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146132. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146133. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146134. };
  146135. static static_codebook _huff_book__44u0__long = {
  146136. 2, 64,
  146137. _huff_lengthlist__44u0__long,
  146138. 0, 0, 0, 0, 0,
  146139. NULL,
  146140. NULL,
  146141. NULL,
  146142. NULL,
  146143. 0
  146144. };
  146145. static long _vq_quantlist__44u0__p1_0[] = {
  146146. 1,
  146147. 0,
  146148. 2,
  146149. };
  146150. static long _vq_lengthlist__44u0__p1_0[] = {
  146151. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146152. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146153. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146154. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146155. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146156. 13,
  146157. };
  146158. static float _vq_quantthresh__44u0__p1_0[] = {
  146159. -0.5, 0.5,
  146160. };
  146161. static long _vq_quantmap__44u0__p1_0[] = {
  146162. 1, 0, 2,
  146163. };
  146164. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146165. _vq_quantthresh__44u0__p1_0,
  146166. _vq_quantmap__44u0__p1_0,
  146167. 3,
  146168. 3
  146169. };
  146170. static static_codebook _44u0__p1_0 = {
  146171. 4, 81,
  146172. _vq_lengthlist__44u0__p1_0,
  146173. 1, -535822336, 1611661312, 2, 0,
  146174. _vq_quantlist__44u0__p1_0,
  146175. NULL,
  146176. &_vq_auxt__44u0__p1_0,
  146177. NULL,
  146178. 0
  146179. };
  146180. static long _vq_quantlist__44u0__p2_0[] = {
  146181. 1,
  146182. 0,
  146183. 2,
  146184. };
  146185. static long _vq_lengthlist__44u0__p2_0[] = {
  146186. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146187. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146188. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146189. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146190. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146191. 9,
  146192. };
  146193. static float _vq_quantthresh__44u0__p2_0[] = {
  146194. -0.5, 0.5,
  146195. };
  146196. static long _vq_quantmap__44u0__p2_0[] = {
  146197. 1, 0, 2,
  146198. };
  146199. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146200. _vq_quantthresh__44u0__p2_0,
  146201. _vq_quantmap__44u0__p2_0,
  146202. 3,
  146203. 3
  146204. };
  146205. static static_codebook _44u0__p2_0 = {
  146206. 4, 81,
  146207. _vq_lengthlist__44u0__p2_0,
  146208. 1, -535822336, 1611661312, 2, 0,
  146209. _vq_quantlist__44u0__p2_0,
  146210. NULL,
  146211. &_vq_auxt__44u0__p2_0,
  146212. NULL,
  146213. 0
  146214. };
  146215. static long _vq_quantlist__44u0__p3_0[] = {
  146216. 2,
  146217. 1,
  146218. 3,
  146219. 0,
  146220. 4,
  146221. };
  146222. static long _vq_lengthlist__44u0__p3_0[] = {
  146223. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146224. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146225. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146226. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146227. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146228. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146229. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146230. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146231. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146232. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146233. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146234. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146235. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146236. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146237. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146238. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146239. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146240. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146241. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146242. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146243. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146244. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146245. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146246. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146247. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146248. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146249. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146250. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146251. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146252. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146253. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146254. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146255. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146256. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146257. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146258. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146259. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146260. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146261. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146262. 19,
  146263. };
  146264. static float _vq_quantthresh__44u0__p3_0[] = {
  146265. -1.5, -0.5, 0.5, 1.5,
  146266. };
  146267. static long _vq_quantmap__44u0__p3_0[] = {
  146268. 3, 1, 0, 2, 4,
  146269. };
  146270. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146271. _vq_quantthresh__44u0__p3_0,
  146272. _vq_quantmap__44u0__p3_0,
  146273. 5,
  146274. 5
  146275. };
  146276. static static_codebook _44u0__p3_0 = {
  146277. 4, 625,
  146278. _vq_lengthlist__44u0__p3_0,
  146279. 1, -533725184, 1611661312, 3, 0,
  146280. _vq_quantlist__44u0__p3_0,
  146281. NULL,
  146282. &_vq_auxt__44u0__p3_0,
  146283. NULL,
  146284. 0
  146285. };
  146286. static long _vq_quantlist__44u0__p4_0[] = {
  146287. 2,
  146288. 1,
  146289. 3,
  146290. 0,
  146291. 4,
  146292. };
  146293. static long _vq_lengthlist__44u0__p4_0[] = {
  146294. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146295. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146296. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146297. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146298. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146299. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146300. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146301. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146302. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146303. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146304. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146305. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146306. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146307. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146308. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146309. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146310. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146311. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146312. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146313. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146314. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146315. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146316. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146317. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146318. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146319. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146320. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146321. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146322. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146323. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146324. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146325. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146326. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146327. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146328. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146329. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146330. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146331. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146332. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146333. 12,
  146334. };
  146335. static float _vq_quantthresh__44u0__p4_0[] = {
  146336. -1.5, -0.5, 0.5, 1.5,
  146337. };
  146338. static long _vq_quantmap__44u0__p4_0[] = {
  146339. 3, 1, 0, 2, 4,
  146340. };
  146341. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146342. _vq_quantthresh__44u0__p4_0,
  146343. _vq_quantmap__44u0__p4_0,
  146344. 5,
  146345. 5
  146346. };
  146347. static static_codebook _44u0__p4_0 = {
  146348. 4, 625,
  146349. _vq_lengthlist__44u0__p4_0,
  146350. 1, -533725184, 1611661312, 3, 0,
  146351. _vq_quantlist__44u0__p4_0,
  146352. NULL,
  146353. &_vq_auxt__44u0__p4_0,
  146354. NULL,
  146355. 0
  146356. };
  146357. static long _vq_quantlist__44u0__p5_0[] = {
  146358. 4,
  146359. 3,
  146360. 5,
  146361. 2,
  146362. 6,
  146363. 1,
  146364. 7,
  146365. 0,
  146366. 8,
  146367. };
  146368. static long _vq_lengthlist__44u0__p5_0[] = {
  146369. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146370. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146371. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146372. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146373. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146374. 12,
  146375. };
  146376. static float _vq_quantthresh__44u0__p5_0[] = {
  146377. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146378. };
  146379. static long _vq_quantmap__44u0__p5_0[] = {
  146380. 7, 5, 3, 1, 0, 2, 4, 6,
  146381. 8,
  146382. };
  146383. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146384. _vq_quantthresh__44u0__p5_0,
  146385. _vq_quantmap__44u0__p5_0,
  146386. 9,
  146387. 9
  146388. };
  146389. static static_codebook _44u0__p5_0 = {
  146390. 2, 81,
  146391. _vq_lengthlist__44u0__p5_0,
  146392. 1, -531628032, 1611661312, 4, 0,
  146393. _vq_quantlist__44u0__p5_0,
  146394. NULL,
  146395. &_vq_auxt__44u0__p5_0,
  146396. NULL,
  146397. 0
  146398. };
  146399. static long _vq_quantlist__44u0__p6_0[] = {
  146400. 6,
  146401. 5,
  146402. 7,
  146403. 4,
  146404. 8,
  146405. 3,
  146406. 9,
  146407. 2,
  146408. 10,
  146409. 1,
  146410. 11,
  146411. 0,
  146412. 12,
  146413. };
  146414. static long _vq_lengthlist__44u0__p6_0[] = {
  146415. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146416. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146417. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146418. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146419. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146420. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146421. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146422. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146423. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146424. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146425. 15,17,16,17,18,17,17,18, 0,
  146426. };
  146427. static float _vq_quantthresh__44u0__p6_0[] = {
  146428. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146429. 12.5, 17.5, 22.5, 27.5,
  146430. };
  146431. static long _vq_quantmap__44u0__p6_0[] = {
  146432. 11, 9, 7, 5, 3, 1, 0, 2,
  146433. 4, 6, 8, 10, 12,
  146434. };
  146435. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146436. _vq_quantthresh__44u0__p6_0,
  146437. _vq_quantmap__44u0__p6_0,
  146438. 13,
  146439. 13
  146440. };
  146441. static static_codebook _44u0__p6_0 = {
  146442. 2, 169,
  146443. _vq_lengthlist__44u0__p6_0,
  146444. 1, -526516224, 1616117760, 4, 0,
  146445. _vq_quantlist__44u0__p6_0,
  146446. NULL,
  146447. &_vq_auxt__44u0__p6_0,
  146448. NULL,
  146449. 0
  146450. };
  146451. static long _vq_quantlist__44u0__p6_1[] = {
  146452. 2,
  146453. 1,
  146454. 3,
  146455. 0,
  146456. 4,
  146457. };
  146458. static long _vq_lengthlist__44u0__p6_1[] = {
  146459. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146460. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146461. };
  146462. static float _vq_quantthresh__44u0__p6_1[] = {
  146463. -1.5, -0.5, 0.5, 1.5,
  146464. };
  146465. static long _vq_quantmap__44u0__p6_1[] = {
  146466. 3, 1, 0, 2, 4,
  146467. };
  146468. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146469. _vq_quantthresh__44u0__p6_1,
  146470. _vq_quantmap__44u0__p6_1,
  146471. 5,
  146472. 5
  146473. };
  146474. static static_codebook _44u0__p6_1 = {
  146475. 2, 25,
  146476. _vq_lengthlist__44u0__p6_1,
  146477. 1, -533725184, 1611661312, 3, 0,
  146478. _vq_quantlist__44u0__p6_1,
  146479. NULL,
  146480. &_vq_auxt__44u0__p6_1,
  146481. NULL,
  146482. 0
  146483. };
  146484. static long _vq_quantlist__44u0__p7_0[] = {
  146485. 2,
  146486. 1,
  146487. 3,
  146488. 0,
  146489. 4,
  146490. };
  146491. static long _vq_lengthlist__44u0__p7_0[] = {
  146492. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146495. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146499. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146522. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146523. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146530. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146531. 10,
  146532. };
  146533. static float _vq_quantthresh__44u0__p7_0[] = {
  146534. -253.5, -84.5, 84.5, 253.5,
  146535. };
  146536. static long _vq_quantmap__44u0__p7_0[] = {
  146537. 3, 1, 0, 2, 4,
  146538. };
  146539. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146540. _vq_quantthresh__44u0__p7_0,
  146541. _vq_quantmap__44u0__p7_0,
  146542. 5,
  146543. 5
  146544. };
  146545. static static_codebook _44u0__p7_0 = {
  146546. 4, 625,
  146547. _vq_lengthlist__44u0__p7_0,
  146548. 1, -518709248, 1626677248, 3, 0,
  146549. _vq_quantlist__44u0__p7_0,
  146550. NULL,
  146551. &_vq_auxt__44u0__p7_0,
  146552. NULL,
  146553. 0
  146554. };
  146555. static long _vq_quantlist__44u0__p7_1[] = {
  146556. 6,
  146557. 5,
  146558. 7,
  146559. 4,
  146560. 8,
  146561. 3,
  146562. 9,
  146563. 2,
  146564. 10,
  146565. 1,
  146566. 11,
  146567. 0,
  146568. 12,
  146569. };
  146570. static long _vq_lengthlist__44u0__p7_1[] = {
  146571. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146572. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146573. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146574. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146575. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146576. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146577. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146578. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146579. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146580. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146581. 15,15,15,15,15,15,15,15,15,
  146582. };
  146583. static float _vq_quantthresh__44u0__p7_1[] = {
  146584. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146585. 32.5, 45.5, 58.5, 71.5,
  146586. };
  146587. static long _vq_quantmap__44u0__p7_1[] = {
  146588. 11, 9, 7, 5, 3, 1, 0, 2,
  146589. 4, 6, 8, 10, 12,
  146590. };
  146591. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146592. _vq_quantthresh__44u0__p7_1,
  146593. _vq_quantmap__44u0__p7_1,
  146594. 13,
  146595. 13
  146596. };
  146597. static static_codebook _44u0__p7_1 = {
  146598. 2, 169,
  146599. _vq_lengthlist__44u0__p7_1,
  146600. 1, -523010048, 1618608128, 4, 0,
  146601. _vq_quantlist__44u0__p7_1,
  146602. NULL,
  146603. &_vq_auxt__44u0__p7_1,
  146604. NULL,
  146605. 0
  146606. };
  146607. static long _vq_quantlist__44u0__p7_2[] = {
  146608. 6,
  146609. 5,
  146610. 7,
  146611. 4,
  146612. 8,
  146613. 3,
  146614. 9,
  146615. 2,
  146616. 10,
  146617. 1,
  146618. 11,
  146619. 0,
  146620. 12,
  146621. };
  146622. static long _vq_lengthlist__44u0__p7_2[] = {
  146623. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146624. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146625. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146626. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146627. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146628. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146629. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146630. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146631. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146632. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146633. 9, 9, 9,10, 9, 9,10,10, 9,
  146634. };
  146635. static float _vq_quantthresh__44u0__p7_2[] = {
  146636. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146637. 2.5, 3.5, 4.5, 5.5,
  146638. };
  146639. static long _vq_quantmap__44u0__p7_2[] = {
  146640. 11, 9, 7, 5, 3, 1, 0, 2,
  146641. 4, 6, 8, 10, 12,
  146642. };
  146643. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146644. _vq_quantthresh__44u0__p7_2,
  146645. _vq_quantmap__44u0__p7_2,
  146646. 13,
  146647. 13
  146648. };
  146649. static static_codebook _44u0__p7_2 = {
  146650. 2, 169,
  146651. _vq_lengthlist__44u0__p7_2,
  146652. 1, -531103744, 1611661312, 4, 0,
  146653. _vq_quantlist__44u0__p7_2,
  146654. NULL,
  146655. &_vq_auxt__44u0__p7_2,
  146656. NULL,
  146657. 0
  146658. };
  146659. static long _huff_lengthlist__44u0__short[] = {
  146660. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146661. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146662. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146663. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146664. };
  146665. static static_codebook _huff_book__44u0__short = {
  146666. 2, 64,
  146667. _huff_lengthlist__44u0__short,
  146668. 0, 0, 0, 0, 0,
  146669. NULL,
  146670. NULL,
  146671. NULL,
  146672. NULL,
  146673. 0
  146674. };
  146675. static long _huff_lengthlist__44u1__long[] = {
  146676. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146677. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146678. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146679. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146680. };
  146681. static static_codebook _huff_book__44u1__long = {
  146682. 2, 64,
  146683. _huff_lengthlist__44u1__long,
  146684. 0, 0, 0, 0, 0,
  146685. NULL,
  146686. NULL,
  146687. NULL,
  146688. NULL,
  146689. 0
  146690. };
  146691. static long _vq_quantlist__44u1__p1_0[] = {
  146692. 1,
  146693. 0,
  146694. 2,
  146695. };
  146696. static long _vq_lengthlist__44u1__p1_0[] = {
  146697. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146698. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146699. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146700. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146701. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146702. 13,
  146703. };
  146704. static float _vq_quantthresh__44u1__p1_0[] = {
  146705. -0.5, 0.5,
  146706. };
  146707. static long _vq_quantmap__44u1__p1_0[] = {
  146708. 1, 0, 2,
  146709. };
  146710. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146711. _vq_quantthresh__44u1__p1_0,
  146712. _vq_quantmap__44u1__p1_0,
  146713. 3,
  146714. 3
  146715. };
  146716. static static_codebook _44u1__p1_0 = {
  146717. 4, 81,
  146718. _vq_lengthlist__44u1__p1_0,
  146719. 1, -535822336, 1611661312, 2, 0,
  146720. _vq_quantlist__44u1__p1_0,
  146721. NULL,
  146722. &_vq_auxt__44u1__p1_0,
  146723. NULL,
  146724. 0
  146725. };
  146726. static long _vq_quantlist__44u1__p2_0[] = {
  146727. 1,
  146728. 0,
  146729. 2,
  146730. };
  146731. static long _vq_lengthlist__44u1__p2_0[] = {
  146732. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146733. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146734. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146735. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146736. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146737. 9,
  146738. };
  146739. static float _vq_quantthresh__44u1__p2_0[] = {
  146740. -0.5, 0.5,
  146741. };
  146742. static long _vq_quantmap__44u1__p2_0[] = {
  146743. 1, 0, 2,
  146744. };
  146745. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146746. _vq_quantthresh__44u1__p2_0,
  146747. _vq_quantmap__44u1__p2_0,
  146748. 3,
  146749. 3
  146750. };
  146751. static static_codebook _44u1__p2_0 = {
  146752. 4, 81,
  146753. _vq_lengthlist__44u1__p2_0,
  146754. 1, -535822336, 1611661312, 2, 0,
  146755. _vq_quantlist__44u1__p2_0,
  146756. NULL,
  146757. &_vq_auxt__44u1__p2_0,
  146758. NULL,
  146759. 0
  146760. };
  146761. static long _vq_quantlist__44u1__p3_0[] = {
  146762. 2,
  146763. 1,
  146764. 3,
  146765. 0,
  146766. 4,
  146767. };
  146768. static long _vq_lengthlist__44u1__p3_0[] = {
  146769. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146770. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146771. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146772. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146773. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146774. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146775. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146776. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146777. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146778. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146779. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146780. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146781. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146782. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146783. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146784. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146785. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146786. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146787. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146788. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146789. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146790. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146791. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146792. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146793. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146794. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146795. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146796. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146797. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146798. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146799. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146800. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146801. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146802. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146803. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146804. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146805. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146806. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146807. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146808. 19,
  146809. };
  146810. static float _vq_quantthresh__44u1__p3_0[] = {
  146811. -1.5, -0.5, 0.5, 1.5,
  146812. };
  146813. static long _vq_quantmap__44u1__p3_0[] = {
  146814. 3, 1, 0, 2, 4,
  146815. };
  146816. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146817. _vq_quantthresh__44u1__p3_0,
  146818. _vq_quantmap__44u1__p3_0,
  146819. 5,
  146820. 5
  146821. };
  146822. static static_codebook _44u1__p3_0 = {
  146823. 4, 625,
  146824. _vq_lengthlist__44u1__p3_0,
  146825. 1, -533725184, 1611661312, 3, 0,
  146826. _vq_quantlist__44u1__p3_0,
  146827. NULL,
  146828. &_vq_auxt__44u1__p3_0,
  146829. NULL,
  146830. 0
  146831. };
  146832. static long _vq_quantlist__44u1__p4_0[] = {
  146833. 2,
  146834. 1,
  146835. 3,
  146836. 0,
  146837. 4,
  146838. };
  146839. static long _vq_lengthlist__44u1__p4_0[] = {
  146840. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146841. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146842. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146843. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146844. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146845. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146846. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146847. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146848. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146849. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146850. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146851. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146852. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146853. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146854. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146855. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146856. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146857. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146858. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146859. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146860. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146861. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146862. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146863. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146864. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146865. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146866. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146867. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146868. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146869. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146870. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146871. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146872. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146873. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146874. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146875. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146876. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146877. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146878. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146879. 12,
  146880. };
  146881. static float _vq_quantthresh__44u1__p4_0[] = {
  146882. -1.5, -0.5, 0.5, 1.5,
  146883. };
  146884. static long _vq_quantmap__44u1__p4_0[] = {
  146885. 3, 1, 0, 2, 4,
  146886. };
  146887. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146888. _vq_quantthresh__44u1__p4_0,
  146889. _vq_quantmap__44u1__p4_0,
  146890. 5,
  146891. 5
  146892. };
  146893. static static_codebook _44u1__p4_0 = {
  146894. 4, 625,
  146895. _vq_lengthlist__44u1__p4_0,
  146896. 1, -533725184, 1611661312, 3, 0,
  146897. _vq_quantlist__44u1__p4_0,
  146898. NULL,
  146899. &_vq_auxt__44u1__p4_0,
  146900. NULL,
  146901. 0
  146902. };
  146903. static long _vq_quantlist__44u1__p5_0[] = {
  146904. 4,
  146905. 3,
  146906. 5,
  146907. 2,
  146908. 6,
  146909. 1,
  146910. 7,
  146911. 0,
  146912. 8,
  146913. };
  146914. static long _vq_lengthlist__44u1__p5_0[] = {
  146915. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146916. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146917. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146918. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146919. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146920. 12,
  146921. };
  146922. static float _vq_quantthresh__44u1__p5_0[] = {
  146923. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146924. };
  146925. static long _vq_quantmap__44u1__p5_0[] = {
  146926. 7, 5, 3, 1, 0, 2, 4, 6,
  146927. 8,
  146928. };
  146929. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146930. _vq_quantthresh__44u1__p5_0,
  146931. _vq_quantmap__44u1__p5_0,
  146932. 9,
  146933. 9
  146934. };
  146935. static static_codebook _44u1__p5_0 = {
  146936. 2, 81,
  146937. _vq_lengthlist__44u1__p5_0,
  146938. 1, -531628032, 1611661312, 4, 0,
  146939. _vq_quantlist__44u1__p5_0,
  146940. NULL,
  146941. &_vq_auxt__44u1__p5_0,
  146942. NULL,
  146943. 0
  146944. };
  146945. static long _vq_quantlist__44u1__p6_0[] = {
  146946. 6,
  146947. 5,
  146948. 7,
  146949. 4,
  146950. 8,
  146951. 3,
  146952. 9,
  146953. 2,
  146954. 10,
  146955. 1,
  146956. 11,
  146957. 0,
  146958. 12,
  146959. };
  146960. static long _vq_lengthlist__44u1__p6_0[] = {
  146961. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146962. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146963. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146964. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146965. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146966. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146967. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146968. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146969. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146970. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146971. 15,17,16,17,18,17,17,18, 0,
  146972. };
  146973. static float _vq_quantthresh__44u1__p6_0[] = {
  146974. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146975. 12.5, 17.5, 22.5, 27.5,
  146976. };
  146977. static long _vq_quantmap__44u1__p6_0[] = {
  146978. 11, 9, 7, 5, 3, 1, 0, 2,
  146979. 4, 6, 8, 10, 12,
  146980. };
  146981. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146982. _vq_quantthresh__44u1__p6_0,
  146983. _vq_quantmap__44u1__p6_0,
  146984. 13,
  146985. 13
  146986. };
  146987. static static_codebook _44u1__p6_0 = {
  146988. 2, 169,
  146989. _vq_lengthlist__44u1__p6_0,
  146990. 1, -526516224, 1616117760, 4, 0,
  146991. _vq_quantlist__44u1__p6_0,
  146992. NULL,
  146993. &_vq_auxt__44u1__p6_0,
  146994. NULL,
  146995. 0
  146996. };
  146997. static long _vq_quantlist__44u1__p6_1[] = {
  146998. 2,
  146999. 1,
  147000. 3,
  147001. 0,
  147002. 4,
  147003. };
  147004. static long _vq_lengthlist__44u1__p6_1[] = {
  147005. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147006. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147007. };
  147008. static float _vq_quantthresh__44u1__p6_1[] = {
  147009. -1.5, -0.5, 0.5, 1.5,
  147010. };
  147011. static long _vq_quantmap__44u1__p6_1[] = {
  147012. 3, 1, 0, 2, 4,
  147013. };
  147014. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147015. _vq_quantthresh__44u1__p6_1,
  147016. _vq_quantmap__44u1__p6_1,
  147017. 5,
  147018. 5
  147019. };
  147020. static static_codebook _44u1__p6_1 = {
  147021. 2, 25,
  147022. _vq_lengthlist__44u1__p6_1,
  147023. 1, -533725184, 1611661312, 3, 0,
  147024. _vq_quantlist__44u1__p6_1,
  147025. NULL,
  147026. &_vq_auxt__44u1__p6_1,
  147027. NULL,
  147028. 0
  147029. };
  147030. static long _vq_quantlist__44u1__p7_0[] = {
  147031. 3,
  147032. 2,
  147033. 4,
  147034. 1,
  147035. 5,
  147036. 0,
  147037. 6,
  147038. };
  147039. static long _vq_lengthlist__44u1__p7_0[] = {
  147040. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147041. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147042. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147043. 8,
  147044. };
  147045. static float _vq_quantthresh__44u1__p7_0[] = {
  147046. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147047. };
  147048. static long _vq_quantmap__44u1__p7_0[] = {
  147049. 5, 3, 1, 0, 2, 4, 6,
  147050. };
  147051. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147052. _vq_quantthresh__44u1__p7_0,
  147053. _vq_quantmap__44u1__p7_0,
  147054. 7,
  147055. 7
  147056. };
  147057. static static_codebook _44u1__p7_0 = {
  147058. 2, 49,
  147059. _vq_lengthlist__44u1__p7_0,
  147060. 1, -518017024, 1626677248, 3, 0,
  147061. _vq_quantlist__44u1__p7_0,
  147062. NULL,
  147063. &_vq_auxt__44u1__p7_0,
  147064. NULL,
  147065. 0
  147066. };
  147067. static long _vq_quantlist__44u1__p7_1[] = {
  147068. 6,
  147069. 5,
  147070. 7,
  147071. 4,
  147072. 8,
  147073. 3,
  147074. 9,
  147075. 2,
  147076. 10,
  147077. 1,
  147078. 11,
  147079. 0,
  147080. 12,
  147081. };
  147082. static long _vq_lengthlist__44u1__p7_1[] = {
  147083. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147084. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147085. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147086. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147087. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147088. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147089. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147090. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147091. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147092. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147093. 15,15,15,15,15,15,15,15,15,
  147094. };
  147095. static float _vq_quantthresh__44u1__p7_1[] = {
  147096. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147097. 32.5, 45.5, 58.5, 71.5,
  147098. };
  147099. static long _vq_quantmap__44u1__p7_1[] = {
  147100. 11, 9, 7, 5, 3, 1, 0, 2,
  147101. 4, 6, 8, 10, 12,
  147102. };
  147103. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147104. _vq_quantthresh__44u1__p7_1,
  147105. _vq_quantmap__44u1__p7_1,
  147106. 13,
  147107. 13
  147108. };
  147109. static static_codebook _44u1__p7_1 = {
  147110. 2, 169,
  147111. _vq_lengthlist__44u1__p7_1,
  147112. 1, -523010048, 1618608128, 4, 0,
  147113. _vq_quantlist__44u1__p7_1,
  147114. NULL,
  147115. &_vq_auxt__44u1__p7_1,
  147116. NULL,
  147117. 0
  147118. };
  147119. static long _vq_quantlist__44u1__p7_2[] = {
  147120. 6,
  147121. 5,
  147122. 7,
  147123. 4,
  147124. 8,
  147125. 3,
  147126. 9,
  147127. 2,
  147128. 10,
  147129. 1,
  147130. 11,
  147131. 0,
  147132. 12,
  147133. };
  147134. static long _vq_lengthlist__44u1__p7_2[] = {
  147135. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147136. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147137. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147138. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147139. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147140. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147141. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147142. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147143. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147144. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147145. 9, 9, 9,10, 9, 9,10,10, 9,
  147146. };
  147147. static float _vq_quantthresh__44u1__p7_2[] = {
  147148. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147149. 2.5, 3.5, 4.5, 5.5,
  147150. };
  147151. static long _vq_quantmap__44u1__p7_2[] = {
  147152. 11, 9, 7, 5, 3, 1, 0, 2,
  147153. 4, 6, 8, 10, 12,
  147154. };
  147155. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147156. _vq_quantthresh__44u1__p7_2,
  147157. _vq_quantmap__44u1__p7_2,
  147158. 13,
  147159. 13
  147160. };
  147161. static static_codebook _44u1__p7_2 = {
  147162. 2, 169,
  147163. _vq_lengthlist__44u1__p7_2,
  147164. 1, -531103744, 1611661312, 4, 0,
  147165. _vq_quantlist__44u1__p7_2,
  147166. NULL,
  147167. &_vq_auxt__44u1__p7_2,
  147168. NULL,
  147169. 0
  147170. };
  147171. static long _huff_lengthlist__44u1__short[] = {
  147172. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147173. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147174. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147175. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147176. };
  147177. static static_codebook _huff_book__44u1__short = {
  147178. 2, 64,
  147179. _huff_lengthlist__44u1__short,
  147180. 0, 0, 0, 0, 0,
  147181. NULL,
  147182. NULL,
  147183. NULL,
  147184. NULL,
  147185. 0
  147186. };
  147187. static long _huff_lengthlist__44u2__long[] = {
  147188. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147189. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147190. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147191. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147192. };
  147193. static static_codebook _huff_book__44u2__long = {
  147194. 2, 64,
  147195. _huff_lengthlist__44u2__long,
  147196. 0, 0, 0, 0, 0,
  147197. NULL,
  147198. NULL,
  147199. NULL,
  147200. NULL,
  147201. 0
  147202. };
  147203. static long _vq_quantlist__44u2__p1_0[] = {
  147204. 1,
  147205. 0,
  147206. 2,
  147207. };
  147208. static long _vq_lengthlist__44u2__p1_0[] = {
  147209. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147210. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147211. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147212. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147213. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147214. 13,
  147215. };
  147216. static float _vq_quantthresh__44u2__p1_0[] = {
  147217. -0.5, 0.5,
  147218. };
  147219. static long _vq_quantmap__44u2__p1_0[] = {
  147220. 1, 0, 2,
  147221. };
  147222. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147223. _vq_quantthresh__44u2__p1_0,
  147224. _vq_quantmap__44u2__p1_0,
  147225. 3,
  147226. 3
  147227. };
  147228. static static_codebook _44u2__p1_0 = {
  147229. 4, 81,
  147230. _vq_lengthlist__44u2__p1_0,
  147231. 1, -535822336, 1611661312, 2, 0,
  147232. _vq_quantlist__44u2__p1_0,
  147233. NULL,
  147234. &_vq_auxt__44u2__p1_0,
  147235. NULL,
  147236. 0
  147237. };
  147238. static long _vq_quantlist__44u2__p2_0[] = {
  147239. 1,
  147240. 0,
  147241. 2,
  147242. };
  147243. static long _vq_lengthlist__44u2__p2_0[] = {
  147244. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147245. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147246. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147247. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147248. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147249. 9,
  147250. };
  147251. static float _vq_quantthresh__44u2__p2_0[] = {
  147252. -0.5, 0.5,
  147253. };
  147254. static long _vq_quantmap__44u2__p2_0[] = {
  147255. 1, 0, 2,
  147256. };
  147257. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147258. _vq_quantthresh__44u2__p2_0,
  147259. _vq_quantmap__44u2__p2_0,
  147260. 3,
  147261. 3
  147262. };
  147263. static static_codebook _44u2__p2_0 = {
  147264. 4, 81,
  147265. _vq_lengthlist__44u2__p2_0,
  147266. 1, -535822336, 1611661312, 2, 0,
  147267. _vq_quantlist__44u2__p2_0,
  147268. NULL,
  147269. &_vq_auxt__44u2__p2_0,
  147270. NULL,
  147271. 0
  147272. };
  147273. static long _vq_quantlist__44u2__p3_0[] = {
  147274. 2,
  147275. 1,
  147276. 3,
  147277. 0,
  147278. 4,
  147279. };
  147280. static long _vq_lengthlist__44u2__p3_0[] = {
  147281. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147282. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147283. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147284. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147285. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147286. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147287. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147288. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147289. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147290. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147291. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147292. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147293. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147294. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147295. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147296. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147297. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147298. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147299. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147300. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147301. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147302. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147303. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147304. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147305. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147306. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147307. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147308. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147309. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147310. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147311. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147312. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147313. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147314. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147315. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147316. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147317. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147318. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147319. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147320. 0,
  147321. };
  147322. static float _vq_quantthresh__44u2__p3_0[] = {
  147323. -1.5, -0.5, 0.5, 1.5,
  147324. };
  147325. static long _vq_quantmap__44u2__p3_0[] = {
  147326. 3, 1, 0, 2, 4,
  147327. };
  147328. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147329. _vq_quantthresh__44u2__p3_0,
  147330. _vq_quantmap__44u2__p3_0,
  147331. 5,
  147332. 5
  147333. };
  147334. static static_codebook _44u2__p3_0 = {
  147335. 4, 625,
  147336. _vq_lengthlist__44u2__p3_0,
  147337. 1, -533725184, 1611661312, 3, 0,
  147338. _vq_quantlist__44u2__p3_0,
  147339. NULL,
  147340. &_vq_auxt__44u2__p3_0,
  147341. NULL,
  147342. 0
  147343. };
  147344. static long _vq_quantlist__44u2__p4_0[] = {
  147345. 2,
  147346. 1,
  147347. 3,
  147348. 0,
  147349. 4,
  147350. };
  147351. static long _vq_lengthlist__44u2__p4_0[] = {
  147352. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147353. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147354. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147355. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147356. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147357. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147358. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147359. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147360. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147361. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147362. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147363. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147364. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147365. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147366. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147367. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147368. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147369. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147370. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147371. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147372. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147373. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147374. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147375. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147376. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147377. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147378. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147379. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147380. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147381. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147382. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147383. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147384. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147385. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147386. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147387. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147388. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147389. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147390. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147391. 13,
  147392. };
  147393. static float _vq_quantthresh__44u2__p4_0[] = {
  147394. -1.5, -0.5, 0.5, 1.5,
  147395. };
  147396. static long _vq_quantmap__44u2__p4_0[] = {
  147397. 3, 1, 0, 2, 4,
  147398. };
  147399. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147400. _vq_quantthresh__44u2__p4_0,
  147401. _vq_quantmap__44u2__p4_0,
  147402. 5,
  147403. 5
  147404. };
  147405. static static_codebook _44u2__p4_0 = {
  147406. 4, 625,
  147407. _vq_lengthlist__44u2__p4_0,
  147408. 1, -533725184, 1611661312, 3, 0,
  147409. _vq_quantlist__44u2__p4_0,
  147410. NULL,
  147411. &_vq_auxt__44u2__p4_0,
  147412. NULL,
  147413. 0
  147414. };
  147415. static long _vq_quantlist__44u2__p5_0[] = {
  147416. 4,
  147417. 3,
  147418. 5,
  147419. 2,
  147420. 6,
  147421. 1,
  147422. 7,
  147423. 0,
  147424. 8,
  147425. };
  147426. static long _vq_lengthlist__44u2__p5_0[] = {
  147427. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147428. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147429. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147430. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147431. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147432. 13,
  147433. };
  147434. static float _vq_quantthresh__44u2__p5_0[] = {
  147435. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147436. };
  147437. static long _vq_quantmap__44u2__p5_0[] = {
  147438. 7, 5, 3, 1, 0, 2, 4, 6,
  147439. 8,
  147440. };
  147441. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147442. _vq_quantthresh__44u2__p5_0,
  147443. _vq_quantmap__44u2__p5_0,
  147444. 9,
  147445. 9
  147446. };
  147447. static static_codebook _44u2__p5_0 = {
  147448. 2, 81,
  147449. _vq_lengthlist__44u2__p5_0,
  147450. 1, -531628032, 1611661312, 4, 0,
  147451. _vq_quantlist__44u2__p5_0,
  147452. NULL,
  147453. &_vq_auxt__44u2__p5_0,
  147454. NULL,
  147455. 0
  147456. };
  147457. static long _vq_quantlist__44u2__p6_0[] = {
  147458. 6,
  147459. 5,
  147460. 7,
  147461. 4,
  147462. 8,
  147463. 3,
  147464. 9,
  147465. 2,
  147466. 10,
  147467. 1,
  147468. 11,
  147469. 0,
  147470. 12,
  147471. };
  147472. static long _vq_lengthlist__44u2__p6_0[] = {
  147473. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147474. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147475. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147476. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147477. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147478. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147479. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147480. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147481. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147482. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147483. 15,17,17,16,18,17,18, 0, 0,
  147484. };
  147485. static float _vq_quantthresh__44u2__p6_0[] = {
  147486. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147487. 12.5, 17.5, 22.5, 27.5,
  147488. };
  147489. static long _vq_quantmap__44u2__p6_0[] = {
  147490. 11, 9, 7, 5, 3, 1, 0, 2,
  147491. 4, 6, 8, 10, 12,
  147492. };
  147493. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147494. _vq_quantthresh__44u2__p6_0,
  147495. _vq_quantmap__44u2__p6_0,
  147496. 13,
  147497. 13
  147498. };
  147499. static static_codebook _44u2__p6_0 = {
  147500. 2, 169,
  147501. _vq_lengthlist__44u2__p6_0,
  147502. 1, -526516224, 1616117760, 4, 0,
  147503. _vq_quantlist__44u2__p6_0,
  147504. NULL,
  147505. &_vq_auxt__44u2__p6_0,
  147506. NULL,
  147507. 0
  147508. };
  147509. static long _vq_quantlist__44u2__p6_1[] = {
  147510. 2,
  147511. 1,
  147512. 3,
  147513. 0,
  147514. 4,
  147515. };
  147516. static long _vq_lengthlist__44u2__p6_1[] = {
  147517. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147518. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147519. };
  147520. static float _vq_quantthresh__44u2__p6_1[] = {
  147521. -1.5, -0.5, 0.5, 1.5,
  147522. };
  147523. static long _vq_quantmap__44u2__p6_1[] = {
  147524. 3, 1, 0, 2, 4,
  147525. };
  147526. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147527. _vq_quantthresh__44u2__p6_1,
  147528. _vq_quantmap__44u2__p6_1,
  147529. 5,
  147530. 5
  147531. };
  147532. static static_codebook _44u2__p6_1 = {
  147533. 2, 25,
  147534. _vq_lengthlist__44u2__p6_1,
  147535. 1, -533725184, 1611661312, 3, 0,
  147536. _vq_quantlist__44u2__p6_1,
  147537. NULL,
  147538. &_vq_auxt__44u2__p6_1,
  147539. NULL,
  147540. 0
  147541. };
  147542. static long _vq_quantlist__44u2__p7_0[] = {
  147543. 4,
  147544. 3,
  147545. 5,
  147546. 2,
  147547. 6,
  147548. 1,
  147549. 7,
  147550. 0,
  147551. 8,
  147552. };
  147553. static long _vq_lengthlist__44u2__p7_0[] = {
  147554. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147555. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147559. 11,
  147560. };
  147561. static float _vq_quantthresh__44u2__p7_0[] = {
  147562. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147563. };
  147564. static long _vq_quantmap__44u2__p7_0[] = {
  147565. 7, 5, 3, 1, 0, 2, 4, 6,
  147566. 8,
  147567. };
  147568. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147569. _vq_quantthresh__44u2__p7_0,
  147570. _vq_quantmap__44u2__p7_0,
  147571. 9,
  147572. 9
  147573. };
  147574. static static_codebook _44u2__p7_0 = {
  147575. 2, 81,
  147576. _vq_lengthlist__44u2__p7_0,
  147577. 1, -516612096, 1626677248, 4, 0,
  147578. _vq_quantlist__44u2__p7_0,
  147579. NULL,
  147580. &_vq_auxt__44u2__p7_0,
  147581. NULL,
  147582. 0
  147583. };
  147584. static long _vq_quantlist__44u2__p7_1[] = {
  147585. 6,
  147586. 5,
  147587. 7,
  147588. 4,
  147589. 8,
  147590. 3,
  147591. 9,
  147592. 2,
  147593. 10,
  147594. 1,
  147595. 11,
  147596. 0,
  147597. 12,
  147598. };
  147599. static long _vq_lengthlist__44u2__p7_1[] = {
  147600. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147601. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147602. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147603. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147604. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147605. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147606. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147607. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147608. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147609. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147610. 14,14,14,17,15,17,17,17,17,
  147611. };
  147612. static float _vq_quantthresh__44u2__p7_1[] = {
  147613. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147614. 32.5, 45.5, 58.5, 71.5,
  147615. };
  147616. static long _vq_quantmap__44u2__p7_1[] = {
  147617. 11, 9, 7, 5, 3, 1, 0, 2,
  147618. 4, 6, 8, 10, 12,
  147619. };
  147620. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147621. _vq_quantthresh__44u2__p7_1,
  147622. _vq_quantmap__44u2__p7_1,
  147623. 13,
  147624. 13
  147625. };
  147626. static static_codebook _44u2__p7_1 = {
  147627. 2, 169,
  147628. _vq_lengthlist__44u2__p7_1,
  147629. 1, -523010048, 1618608128, 4, 0,
  147630. _vq_quantlist__44u2__p7_1,
  147631. NULL,
  147632. &_vq_auxt__44u2__p7_1,
  147633. NULL,
  147634. 0
  147635. };
  147636. static long _vq_quantlist__44u2__p7_2[] = {
  147637. 6,
  147638. 5,
  147639. 7,
  147640. 4,
  147641. 8,
  147642. 3,
  147643. 9,
  147644. 2,
  147645. 10,
  147646. 1,
  147647. 11,
  147648. 0,
  147649. 12,
  147650. };
  147651. static long _vq_lengthlist__44u2__p7_2[] = {
  147652. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147653. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147654. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147655. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147656. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147657. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147658. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147659. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147660. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147661. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147662. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147663. };
  147664. static float _vq_quantthresh__44u2__p7_2[] = {
  147665. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147666. 2.5, 3.5, 4.5, 5.5,
  147667. };
  147668. static long _vq_quantmap__44u2__p7_2[] = {
  147669. 11, 9, 7, 5, 3, 1, 0, 2,
  147670. 4, 6, 8, 10, 12,
  147671. };
  147672. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147673. _vq_quantthresh__44u2__p7_2,
  147674. _vq_quantmap__44u2__p7_2,
  147675. 13,
  147676. 13
  147677. };
  147678. static static_codebook _44u2__p7_2 = {
  147679. 2, 169,
  147680. _vq_lengthlist__44u2__p7_2,
  147681. 1, -531103744, 1611661312, 4, 0,
  147682. _vq_quantlist__44u2__p7_2,
  147683. NULL,
  147684. &_vq_auxt__44u2__p7_2,
  147685. NULL,
  147686. 0
  147687. };
  147688. static long _huff_lengthlist__44u2__short[] = {
  147689. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147690. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147691. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147692. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147693. };
  147694. static static_codebook _huff_book__44u2__short = {
  147695. 2, 64,
  147696. _huff_lengthlist__44u2__short,
  147697. 0, 0, 0, 0, 0,
  147698. NULL,
  147699. NULL,
  147700. NULL,
  147701. NULL,
  147702. 0
  147703. };
  147704. static long _huff_lengthlist__44u3__long[] = {
  147705. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147706. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147707. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147708. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147709. };
  147710. static static_codebook _huff_book__44u3__long = {
  147711. 2, 64,
  147712. _huff_lengthlist__44u3__long,
  147713. 0, 0, 0, 0, 0,
  147714. NULL,
  147715. NULL,
  147716. NULL,
  147717. NULL,
  147718. 0
  147719. };
  147720. static long _vq_quantlist__44u3__p1_0[] = {
  147721. 1,
  147722. 0,
  147723. 2,
  147724. };
  147725. static long _vq_lengthlist__44u3__p1_0[] = {
  147726. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147727. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147728. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147729. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147730. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147731. 13,
  147732. };
  147733. static float _vq_quantthresh__44u3__p1_0[] = {
  147734. -0.5, 0.5,
  147735. };
  147736. static long _vq_quantmap__44u3__p1_0[] = {
  147737. 1, 0, 2,
  147738. };
  147739. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147740. _vq_quantthresh__44u3__p1_0,
  147741. _vq_quantmap__44u3__p1_0,
  147742. 3,
  147743. 3
  147744. };
  147745. static static_codebook _44u3__p1_0 = {
  147746. 4, 81,
  147747. _vq_lengthlist__44u3__p1_0,
  147748. 1, -535822336, 1611661312, 2, 0,
  147749. _vq_quantlist__44u3__p1_0,
  147750. NULL,
  147751. &_vq_auxt__44u3__p1_0,
  147752. NULL,
  147753. 0
  147754. };
  147755. static long _vq_quantlist__44u3__p2_0[] = {
  147756. 1,
  147757. 0,
  147758. 2,
  147759. };
  147760. static long _vq_lengthlist__44u3__p2_0[] = {
  147761. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147762. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147763. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147764. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147765. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147766. 9,
  147767. };
  147768. static float _vq_quantthresh__44u3__p2_0[] = {
  147769. -0.5, 0.5,
  147770. };
  147771. static long _vq_quantmap__44u3__p2_0[] = {
  147772. 1, 0, 2,
  147773. };
  147774. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147775. _vq_quantthresh__44u3__p2_0,
  147776. _vq_quantmap__44u3__p2_0,
  147777. 3,
  147778. 3
  147779. };
  147780. static static_codebook _44u3__p2_0 = {
  147781. 4, 81,
  147782. _vq_lengthlist__44u3__p2_0,
  147783. 1, -535822336, 1611661312, 2, 0,
  147784. _vq_quantlist__44u3__p2_0,
  147785. NULL,
  147786. &_vq_auxt__44u3__p2_0,
  147787. NULL,
  147788. 0
  147789. };
  147790. static long _vq_quantlist__44u3__p3_0[] = {
  147791. 2,
  147792. 1,
  147793. 3,
  147794. 0,
  147795. 4,
  147796. };
  147797. static long _vq_lengthlist__44u3__p3_0[] = {
  147798. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147799. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147800. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147801. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147802. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147803. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147804. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147805. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147806. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147807. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147808. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147809. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147810. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147811. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147812. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147813. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147814. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147815. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147816. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147817. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147818. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147819. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147820. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147821. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147822. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147823. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147824. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147825. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147826. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147827. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147828. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147829. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147830. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147831. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147832. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147833. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147834. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147835. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147836. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147837. 0,
  147838. };
  147839. static float _vq_quantthresh__44u3__p3_0[] = {
  147840. -1.5, -0.5, 0.5, 1.5,
  147841. };
  147842. static long _vq_quantmap__44u3__p3_0[] = {
  147843. 3, 1, 0, 2, 4,
  147844. };
  147845. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147846. _vq_quantthresh__44u3__p3_0,
  147847. _vq_quantmap__44u3__p3_0,
  147848. 5,
  147849. 5
  147850. };
  147851. static static_codebook _44u3__p3_0 = {
  147852. 4, 625,
  147853. _vq_lengthlist__44u3__p3_0,
  147854. 1, -533725184, 1611661312, 3, 0,
  147855. _vq_quantlist__44u3__p3_0,
  147856. NULL,
  147857. &_vq_auxt__44u3__p3_0,
  147858. NULL,
  147859. 0
  147860. };
  147861. static long _vq_quantlist__44u3__p4_0[] = {
  147862. 2,
  147863. 1,
  147864. 3,
  147865. 0,
  147866. 4,
  147867. };
  147868. static long _vq_lengthlist__44u3__p4_0[] = {
  147869. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147870. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147871. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147872. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147873. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147874. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147875. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147876. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147877. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147878. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147879. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147880. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147881. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147882. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147883. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147884. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147885. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147886. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147887. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147888. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147889. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147890. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147891. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147892. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147893. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147894. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147895. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147896. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147897. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147898. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147899. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147900. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147901. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147902. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147903. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147904. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147905. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147906. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147907. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147908. 13,
  147909. };
  147910. static float _vq_quantthresh__44u3__p4_0[] = {
  147911. -1.5, -0.5, 0.5, 1.5,
  147912. };
  147913. static long _vq_quantmap__44u3__p4_0[] = {
  147914. 3, 1, 0, 2, 4,
  147915. };
  147916. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147917. _vq_quantthresh__44u3__p4_0,
  147918. _vq_quantmap__44u3__p4_0,
  147919. 5,
  147920. 5
  147921. };
  147922. static static_codebook _44u3__p4_0 = {
  147923. 4, 625,
  147924. _vq_lengthlist__44u3__p4_0,
  147925. 1, -533725184, 1611661312, 3, 0,
  147926. _vq_quantlist__44u3__p4_0,
  147927. NULL,
  147928. &_vq_auxt__44u3__p4_0,
  147929. NULL,
  147930. 0
  147931. };
  147932. static long _vq_quantlist__44u3__p5_0[] = {
  147933. 4,
  147934. 3,
  147935. 5,
  147936. 2,
  147937. 6,
  147938. 1,
  147939. 7,
  147940. 0,
  147941. 8,
  147942. };
  147943. static long _vq_lengthlist__44u3__p5_0[] = {
  147944. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147945. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147946. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147947. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147948. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147949. 12,
  147950. };
  147951. static float _vq_quantthresh__44u3__p5_0[] = {
  147952. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147953. };
  147954. static long _vq_quantmap__44u3__p5_0[] = {
  147955. 7, 5, 3, 1, 0, 2, 4, 6,
  147956. 8,
  147957. };
  147958. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147959. _vq_quantthresh__44u3__p5_0,
  147960. _vq_quantmap__44u3__p5_0,
  147961. 9,
  147962. 9
  147963. };
  147964. static static_codebook _44u3__p5_0 = {
  147965. 2, 81,
  147966. _vq_lengthlist__44u3__p5_0,
  147967. 1, -531628032, 1611661312, 4, 0,
  147968. _vq_quantlist__44u3__p5_0,
  147969. NULL,
  147970. &_vq_auxt__44u3__p5_0,
  147971. NULL,
  147972. 0
  147973. };
  147974. static long _vq_quantlist__44u3__p6_0[] = {
  147975. 6,
  147976. 5,
  147977. 7,
  147978. 4,
  147979. 8,
  147980. 3,
  147981. 9,
  147982. 2,
  147983. 10,
  147984. 1,
  147985. 11,
  147986. 0,
  147987. 12,
  147988. };
  147989. static long _vq_lengthlist__44u3__p6_0[] = {
  147990. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147991. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147992. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147993. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147994. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147995. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147996. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147997. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147998. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147999. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148000. 15,16,16,16,17,18,16,20,18,
  148001. };
  148002. static float _vq_quantthresh__44u3__p6_0[] = {
  148003. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148004. 12.5, 17.5, 22.5, 27.5,
  148005. };
  148006. static long _vq_quantmap__44u3__p6_0[] = {
  148007. 11, 9, 7, 5, 3, 1, 0, 2,
  148008. 4, 6, 8, 10, 12,
  148009. };
  148010. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148011. _vq_quantthresh__44u3__p6_0,
  148012. _vq_quantmap__44u3__p6_0,
  148013. 13,
  148014. 13
  148015. };
  148016. static static_codebook _44u3__p6_0 = {
  148017. 2, 169,
  148018. _vq_lengthlist__44u3__p6_0,
  148019. 1, -526516224, 1616117760, 4, 0,
  148020. _vq_quantlist__44u3__p6_0,
  148021. NULL,
  148022. &_vq_auxt__44u3__p6_0,
  148023. NULL,
  148024. 0
  148025. };
  148026. static long _vq_quantlist__44u3__p6_1[] = {
  148027. 2,
  148028. 1,
  148029. 3,
  148030. 0,
  148031. 4,
  148032. };
  148033. static long _vq_lengthlist__44u3__p6_1[] = {
  148034. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148035. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148036. };
  148037. static float _vq_quantthresh__44u3__p6_1[] = {
  148038. -1.5, -0.5, 0.5, 1.5,
  148039. };
  148040. static long _vq_quantmap__44u3__p6_1[] = {
  148041. 3, 1, 0, 2, 4,
  148042. };
  148043. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148044. _vq_quantthresh__44u3__p6_1,
  148045. _vq_quantmap__44u3__p6_1,
  148046. 5,
  148047. 5
  148048. };
  148049. static static_codebook _44u3__p6_1 = {
  148050. 2, 25,
  148051. _vq_lengthlist__44u3__p6_1,
  148052. 1, -533725184, 1611661312, 3, 0,
  148053. _vq_quantlist__44u3__p6_1,
  148054. NULL,
  148055. &_vq_auxt__44u3__p6_1,
  148056. NULL,
  148057. 0
  148058. };
  148059. static long _vq_quantlist__44u3__p7_0[] = {
  148060. 4,
  148061. 3,
  148062. 5,
  148063. 2,
  148064. 6,
  148065. 1,
  148066. 7,
  148067. 0,
  148068. 8,
  148069. };
  148070. static long _vq_lengthlist__44u3__p7_0[] = {
  148071. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148072. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148073. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148074. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148076. 9,
  148077. };
  148078. static float _vq_quantthresh__44u3__p7_0[] = {
  148079. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148080. };
  148081. static long _vq_quantmap__44u3__p7_0[] = {
  148082. 7, 5, 3, 1, 0, 2, 4, 6,
  148083. 8,
  148084. };
  148085. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148086. _vq_quantthresh__44u3__p7_0,
  148087. _vq_quantmap__44u3__p7_0,
  148088. 9,
  148089. 9
  148090. };
  148091. static static_codebook _44u3__p7_0 = {
  148092. 2, 81,
  148093. _vq_lengthlist__44u3__p7_0,
  148094. 1, -515907584, 1627381760, 4, 0,
  148095. _vq_quantlist__44u3__p7_0,
  148096. NULL,
  148097. &_vq_auxt__44u3__p7_0,
  148098. NULL,
  148099. 0
  148100. };
  148101. static long _vq_quantlist__44u3__p7_1[] = {
  148102. 7,
  148103. 6,
  148104. 8,
  148105. 5,
  148106. 9,
  148107. 4,
  148108. 10,
  148109. 3,
  148110. 11,
  148111. 2,
  148112. 12,
  148113. 1,
  148114. 13,
  148115. 0,
  148116. 14,
  148117. };
  148118. static long _vq_lengthlist__44u3__p7_1[] = {
  148119. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148120. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148121. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148122. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148123. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148124. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148125. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148126. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148127. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148128. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148129. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148130. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148131. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148132. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148133. 17,
  148134. };
  148135. static float _vq_quantthresh__44u3__p7_1[] = {
  148136. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148137. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148138. };
  148139. static long _vq_quantmap__44u3__p7_1[] = {
  148140. 13, 11, 9, 7, 5, 3, 1, 0,
  148141. 2, 4, 6, 8, 10, 12, 14,
  148142. };
  148143. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148144. _vq_quantthresh__44u3__p7_1,
  148145. _vq_quantmap__44u3__p7_1,
  148146. 15,
  148147. 15
  148148. };
  148149. static static_codebook _44u3__p7_1 = {
  148150. 2, 225,
  148151. _vq_lengthlist__44u3__p7_1,
  148152. 1, -522338304, 1620115456, 4, 0,
  148153. _vq_quantlist__44u3__p7_1,
  148154. NULL,
  148155. &_vq_auxt__44u3__p7_1,
  148156. NULL,
  148157. 0
  148158. };
  148159. static long _vq_quantlist__44u3__p7_2[] = {
  148160. 8,
  148161. 7,
  148162. 9,
  148163. 6,
  148164. 10,
  148165. 5,
  148166. 11,
  148167. 4,
  148168. 12,
  148169. 3,
  148170. 13,
  148171. 2,
  148172. 14,
  148173. 1,
  148174. 15,
  148175. 0,
  148176. 16,
  148177. };
  148178. static long _vq_lengthlist__44u3__p7_2[] = {
  148179. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148180. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148181. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148182. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148183. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148184. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148185. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148186. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148187. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148188. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148189. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148190. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148191. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148192. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148193. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148196. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148197. 11,
  148198. };
  148199. static float _vq_quantthresh__44u3__p7_2[] = {
  148200. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148201. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148202. };
  148203. static long _vq_quantmap__44u3__p7_2[] = {
  148204. 15, 13, 11, 9, 7, 5, 3, 1,
  148205. 0, 2, 4, 6, 8, 10, 12, 14,
  148206. 16,
  148207. };
  148208. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148209. _vq_quantthresh__44u3__p7_2,
  148210. _vq_quantmap__44u3__p7_2,
  148211. 17,
  148212. 17
  148213. };
  148214. static static_codebook _44u3__p7_2 = {
  148215. 2, 289,
  148216. _vq_lengthlist__44u3__p7_2,
  148217. 1, -529530880, 1611661312, 5, 0,
  148218. _vq_quantlist__44u3__p7_2,
  148219. NULL,
  148220. &_vq_auxt__44u3__p7_2,
  148221. NULL,
  148222. 0
  148223. };
  148224. static long _huff_lengthlist__44u3__short[] = {
  148225. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148226. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148227. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148228. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148229. };
  148230. static static_codebook _huff_book__44u3__short = {
  148231. 2, 64,
  148232. _huff_lengthlist__44u3__short,
  148233. 0, 0, 0, 0, 0,
  148234. NULL,
  148235. NULL,
  148236. NULL,
  148237. NULL,
  148238. 0
  148239. };
  148240. static long _huff_lengthlist__44u4__long[] = {
  148241. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148242. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148243. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148244. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148245. };
  148246. static static_codebook _huff_book__44u4__long = {
  148247. 2, 64,
  148248. _huff_lengthlist__44u4__long,
  148249. 0, 0, 0, 0, 0,
  148250. NULL,
  148251. NULL,
  148252. NULL,
  148253. NULL,
  148254. 0
  148255. };
  148256. static long _vq_quantlist__44u4__p1_0[] = {
  148257. 1,
  148258. 0,
  148259. 2,
  148260. };
  148261. static long _vq_lengthlist__44u4__p1_0[] = {
  148262. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148263. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148264. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148265. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148266. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148267. 13,
  148268. };
  148269. static float _vq_quantthresh__44u4__p1_0[] = {
  148270. -0.5, 0.5,
  148271. };
  148272. static long _vq_quantmap__44u4__p1_0[] = {
  148273. 1, 0, 2,
  148274. };
  148275. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148276. _vq_quantthresh__44u4__p1_0,
  148277. _vq_quantmap__44u4__p1_0,
  148278. 3,
  148279. 3
  148280. };
  148281. static static_codebook _44u4__p1_0 = {
  148282. 4, 81,
  148283. _vq_lengthlist__44u4__p1_0,
  148284. 1, -535822336, 1611661312, 2, 0,
  148285. _vq_quantlist__44u4__p1_0,
  148286. NULL,
  148287. &_vq_auxt__44u4__p1_0,
  148288. NULL,
  148289. 0
  148290. };
  148291. static long _vq_quantlist__44u4__p2_0[] = {
  148292. 1,
  148293. 0,
  148294. 2,
  148295. };
  148296. static long _vq_lengthlist__44u4__p2_0[] = {
  148297. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148298. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148299. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148300. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148301. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148302. 9,
  148303. };
  148304. static float _vq_quantthresh__44u4__p2_0[] = {
  148305. -0.5, 0.5,
  148306. };
  148307. static long _vq_quantmap__44u4__p2_0[] = {
  148308. 1, 0, 2,
  148309. };
  148310. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148311. _vq_quantthresh__44u4__p2_0,
  148312. _vq_quantmap__44u4__p2_0,
  148313. 3,
  148314. 3
  148315. };
  148316. static static_codebook _44u4__p2_0 = {
  148317. 4, 81,
  148318. _vq_lengthlist__44u4__p2_0,
  148319. 1, -535822336, 1611661312, 2, 0,
  148320. _vq_quantlist__44u4__p2_0,
  148321. NULL,
  148322. &_vq_auxt__44u4__p2_0,
  148323. NULL,
  148324. 0
  148325. };
  148326. static long _vq_quantlist__44u4__p3_0[] = {
  148327. 2,
  148328. 1,
  148329. 3,
  148330. 0,
  148331. 4,
  148332. };
  148333. static long _vq_lengthlist__44u4__p3_0[] = {
  148334. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148335. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148336. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148337. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148338. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148339. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148340. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148341. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148342. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148343. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148344. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148345. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148346. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148347. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148348. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148349. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148350. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148351. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148352. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148353. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148354. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148355. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148356. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148357. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148358. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148359. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148360. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148361. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148362. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148363. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148364. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148365. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148366. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148367. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148368. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148369. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148370. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148371. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148372. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148373. 0,
  148374. };
  148375. static float _vq_quantthresh__44u4__p3_0[] = {
  148376. -1.5, -0.5, 0.5, 1.5,
  148377. };
  148378. static long _vq_quantmap__44u4__p3_0[] = {
  148379. 3, 1, 0, 2, 4,
  148380. };
  148381. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148382. _vq_quantthresh__44u4__p3_0,
  148383. _vq_quantmap__44u4__p3_0,
  148384. 5,
  148385. 5
  148386. };
  148387. static static_codebook _44u4__p3_0 = {
  148388. 4, 625,
  148389. _vq_lengthlist__44u4__p3_0,
  148390. 1, -533725184, 1611661312, 3, 0,
  148391. _vq_quantlist__44u4__p3_0,
  148392. NULL,
  148393. &_vq_auxt__44u4__p3_0,
  148394. NULL,
  148395. 0
  148396. };
  148397. static long _vq_quantlist__44u4__p4_0[] = {
  148398. 2,
  148399. 1,
  148400. 3,
  148401. 0,
  148402. 4,
  148403. };
  148404. static long _vq_lengthlist__44u4__p4_0[] = {
  148405. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148406. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148407. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148408. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148409. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148410. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148411. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148412. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148413. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148414. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148415. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148416. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148417. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148418. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148419. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148420. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148421. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148422. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148423. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148424. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148425. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148426. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148427. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148428. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148429. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148430. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148431. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148432. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148433. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148434. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148435. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148436. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148437. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148438. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148439. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148440. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148441. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148442. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148443. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148444. 13,
  148445. };
  148446. static float _vq_quantthresh__44u4__p4_0[] = {
  148447. -1.5, -0.5, 0.5, 1.5,
  148448. };
  148449. static long _vq_quantmap__44u4__p4_0[] = {
  148450. 3, 1, 0, 2, 4,
  148451. };
  148452. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148453. _vq_quantthresh__44u4__p4_0,
  148454. _vq_quantmap__44u4__p4_0,
  148455. 5,
  148456. 5
  148457. };
  148458. static static_codebook _44u4__p4_0 = {
  148459. 4, 625,
  148460. _vq_lengthlist__44u4__p4_0,
  148461. 1, -533725184, 1611661312, 3, 0,
  148462. _vq_quantlist__44u4__p4_0,
  148463. NULL,
  148464. &_vq_auxt__44u4__p4_0,
  148465. NULL,
  148466. 0
  148467. };
  148468. static long _vq_quantlist__44u4__p5_0[] = {
  148469. 4,
  148470. 3,
  148471. 5,
  148472. 2,
  148473. 6,
  148474. 1,
  148475. 7,
  148476. 0,
  148477. 8,
  148478. };
  148479. static long _vq_lengthlist__44u4__p5_0[] = {
  148480. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148481. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148482. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148483. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148484. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148485. 12,
  148486. };
  148487. static float _vq_quantthresh__44u4__p5_0[] = {
  148488. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148489. };
  148490. static long _vq_quantmap__44u4__p5_0[] = {
  148491. 7, 5, 3, 1, 0, 2, 4, 6,
  148492. 8,
  148493. };
  148494. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148495. _vq_quantthresh__44u4__p5_0,
  148496. _vq_quantmap__44u4__p5_0,
  148497. 9,
  148498. 9
  148499. };
  148500. static static_codebook _44u4__p5_0 = {
  148501. 2, 81,
  148502. _vq_lengthlist__44u4__p5_0,
  148503. 1, -531628032, 1611661312, 4, 0,
  148504. _vq_quantlist__44u4__p5_0,
  148505. NULL,
  148506. &_vq_auxt__44u4__p5_0,
  148507. NULL,
  148508. 0
  148509. };
  148510. static long _vq_quantlist__44u4__p6_0[] = {
  148511. 6,
  148512. 5,
  148513. 7,
  148514. 4,
  148515. 8,
  148516. 3,
  148517. 9,
  148518. 2,
  148519. 10,
  148520. 1,
  148521. 11,
  148522. 0,
  148523. 12,
  148524. };
  148525. static long _vq_lengthlist__44u4__p6_0[] = {
  148526. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148527. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148528. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148529. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148530. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148531. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148532. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148533. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148534. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148535. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148536. 16,16,16,17,17,18,17,20,21,
  148537. };
  148538. static float _vq_quantthresh__44u4__p6_0[] = {
  148539. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148540. 12.5, 17.5, 22.5, 27.5,
  148541. };
  148542. static long _vq_quantmap__44u4__p6_0[] = {
  148543. 11, 9, 7, 5, 3, 1, 0, 2,
  148544. 4, 6, 8, 10, 12,
  148545. };
  148546. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148547. _vq_quantthresh__44u4__p6_0,
  148548. _vq_quantmap__44u4__p6_0,
  148549. 13,
  148550. 13
  148551. };
  148552. static static_codebook _44u4__p6_0 = {
  148553. 2, 169,
  148554. _vq_lengthlist__44u4__p6_0,
  148555. 1, -526516224, 1616117760, 4, 0,
  148556. _vq_quantlist__44u4__p6_0,
  148557. NULL,
  148558. &_vq_auxt__44u4__p6_0,
  148559. NULL,
  148560. 0
  148561. };
  148562. static long _vq_quantlist__44u4__p6_1[] = {
  148563. 2,
  148564. 1,
  148565. 3,
  148566. 0,
  148567. 4,
  148568. };
  148569. static long _vq_lengthlist__44u4__p6_1[] = {
  148570. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148571. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148572. };
  148573. static float _vq_quantthresh__44u4__p6_1[] = {
  148574. -1.5, -0.5, 0.5, 1.5,
  148575. };
  148576. static long _vq_quantmap__44u4__p6_1[] = {
  148577. 3, 1, 0, 2, 4,
  148578. };
  148579. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148580. _vq_quantthresh__44u4__p6_1,
  148581. _vq_quantmap__44u4__p6_1,
  148582. 5,
  148583. 5
  148584. };
  148585. static static_codebook _44u4__p6_1 = {
  148586. 2, 25,
  148587. _vq_lengthlist__44u4__p6_1,
  148588. 1, -533725184, 1611661312, 3, 0,
  148589. _vq_quantlist__44u4__p6_1,
  148590. NULL,
  148591. &_vq_auxt__44u4__p6_1,
  148592. NULL,
  148593. 0
  148594. };
  148595. static long _vq_quantlist__44u4__p7_0[] = {
  148596. 6,
  148597. 5,
  148598. 7,
  148599. 4,
  148600. 8,
  148601. 3,
  148602. 9,
  148603. 2,
  148604. 10,
  148605. 1,
  148606. 11,
  148607. 0,
  148608. 12,
  148609. };
  148610. static long _vq_lengthlist__44u4__p7_0[] = {
  148611. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148612. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148613. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148614. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148615. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148616. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148621. 11,11,11,11,11,11,11,11,11,
  148622. };
  148623. static float _vq_quantthresh__44u4__p7_0[] = {
  148624. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148625. 637.5, 892.5, 1147.5, 1402.5,
  148626. };
  148627. static long _vq_quantmap__44u4__p7_0[] = {
  148628. 11, 9, 7, 5, 3, 1, 0, 2,
  148629. 4, 6, 8, 10, 12,
  148630. };
  148631. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148632. _vq_quantthresh__44u4__p7_0,
  148633. _vq_quantmap__44u4__p7_0,
  148634. 13,
  148635. 13
  148636. };
  148637. static static_codebook _44u4__p7_0 = {
  148638. 2, 169,
  148639. _vq_lengthlist__44u4__p7_0,
  148640. 1, -514332672, 1627381760, 4, 0,
  148641. _vq_quantlist__44u4__p7_0,
  148642. NULL,
  148643. &_vq_auxt__44u4__p7_0,
  148644. NULL,
  148645. 0
  148646. };
  148647. static long _vq_quantlist__44u4__p7_1[] = {
  148648. 7,
  148649. 6,
  148650. 8,
  148651. 5,
  148652. 9,
  148653. 4,
  148654. 10,
  148655. 3,
  148656. 11,
  148657. 2,
  148658. 12,
  148659. 1,
  148660. 13,
  148661. 0,
  148662. 14,
  148663. };
  148664. static long _vq_lengthlist__44u4__p7_1[] = {
  148665. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148666. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148667. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148668. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148669. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148670. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148671. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148672. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148673. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148674. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148675. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148676. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148677. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148678. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148679. 16,
  148680. };
  148681. static float _vq_quantthresh__44u4__p7_1[] = {
  148682. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148683. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148684. };
  148685. static long _vq_quantmap__44u4__p7_1[] = {
  148686. 13, 11, 9, 7, 5, 3, 1, 0,
  148687. 2, 4, 6, 8, 10, 12, 14,
  148688. };
  148689. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148690. _vq_quantthresh__44u4__p7_1,
  148691. _vq_quantmap__44u4__p7_1,
  148692. 15,
  148693. 15
  148694. };
  148695. static static_codebook _44u4__p7_1 = {
  148696. 2, 225,
  148697. _vq_lengthlist__44u4__p7_1,
  148698. 1, -522338304, 1620115456, 4, 0,
  148699. _vq_quantlist__44u4__p7_1,
  148700. NULL,
  148701. &_vq_auxt__44u4__p7_1,
  148702. NULL,
  148703. 0
  148704. };
  148705. static long _vq_quantlist__44u4__p7_2[] = {
  148706. 8,
  148707. 7,
  148708. 9,
  148709. 6,
  148710. 10,
  148711. 5,
  148712. 11,
  148713. 4,
  148714. 12,
  148715. 3,
  148716. 13,
  148717. 2,
  148718. 14,
  148719. 1,
  148720. 15,
  148721. 0,
  148722. 16,
  148723. };
  148724. static long _vq_lengthlist__44u4__p7_2[] = {
  148725. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148726. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148727. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148728. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148729. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148730. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148731. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148732. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148733. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148734. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148735. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148736. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148737. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148738. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148739. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148740. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148741. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148742. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148743. 10,
  148744. };
  148745. static float _vq_quantthresh__44u4__p7_2[] = {
  148746. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148747. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148748. };
  148749. static long _vq_quantmap__44u4__p7_2[] = {
  148750. 15, 13, 11, 9, 7, 5, 3, 1,
  148751. 0, 2, 4, 6, 8, 10, 12, 14,
  148752. 16,
  148753. };
  148754. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148755. _vq_quantthresh__44u4__p7_2,
  148756. _vq_quantmap__44u4__p7_2,
  148757. 17,
  148758. 17
  148759. };
  148760. static static_codebook _44u4__p7_2 = {
  148761. 2, 289,
  148762. _vq_lengthlist__44u4__p7_2,
  148763. 1, -529530880, 1611661312, 5, 0,
  148764. _vq_quantlist__44u4__p7_2,
  148765. NULL,
  148766. &_vq_auxt__44u4__p7_2,
  148767. NULL,
  148768. 0
  148769. };
  148770. static long _huff_lengthlist__44u4__short[] = {
  148771. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148772. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148773. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148774. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148775. };
  148776. static static_codebook _huff_book__44u4__short = {
  148777. 2, 64,
  148778. _huff_lengthlist__44u4__short,
  148779. 0, 0, 0, 0, 0,
  148780. NULL,
  148781. NULL,
  148782. NULL,
  148783. NULL,
  148784. 0
  148785. };
  148786. static long _huff_lengthlist__44u5__long[] = {
  148787. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148788. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148789. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148790. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148791. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148792. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148793. 14, 8, 7, 8,
  148794. };
  148795. static static_codebook _huff_book__44u5__long = {
  148796. 2, 100,
  148797. _huff_lengthlist__44u5__long,
  148798. 0, 0, 0, 0, 0,
  148799. NULL,
  148800. NULL,
  148801. NULL,
  148802. NULL,
  148803. 0
  148804. };
  148805. static long _vq_quantlist__44u5__p1_0[] = {
  148806. 1,
  148807. 0,
  148808. 2,
  148809. };
  148810. static long _vq_lengthlist__44u5__p1_0[] = {
  148811. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148812. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148813. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148814. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148815. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148816. 12,
  148817. };
  148818. static float _vq_quantthresh__44u5__p1_0[] = {
  148819. -0.5, 0.5,
  148820. };
  148821. static long _vq_quantmap__44u5__p1_0[] = {
  148822. 1, 0, 2,
  148823. };
  148824. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148825. _vq_quantthresh__44u5__p1_0,
  148826. _vq_quantmap__44u5__p1_0,
  148827. 3,
  148828. 3
  148829. };
  148830. static static_codebook _44u5__p1_0 = {
  148831. 4, 81,
  148832. _vq_lengthlist__44u5__p1_0,
  148833. 1, -535822336, 1611661312, 2, 0,
  148834. _vq_quantlist__44u5__p1_0,
  148835. NULL,
  148836. &_vq_auxt__44u5__p1_0,
  148837. NULL,
  148838. 0
  148839. };
  148840. static long _vq_quantlist__44u5__p2_0[] = {
  148841. 1,
  148842. 0,
  148843. 2,
  148844. };
  148845. static long _vq_lengthlist__44u5__p2_0[] = {
  148846. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148847. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148848. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148849. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148850. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148851. 9,
  148852. };
  148853. static float _vq_quantthresh__44u5__p2_0[] = {
  148854. -0.5, 0.5,
  148855. };
  148856. static long _vq_quantmap__44u5__p2_0[] = {
  148857. 1, 0, 2,
  148858. };
  148859. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148860. _vq_quantthresh__44u5__p2_0,
  148861. _vq_quantmap__44u5__p2_0,
  148862. 3,
  148863. 3
  148864. };
  148865. static static_codebook _44u5__p2_0 = {
  148866. 4, 81,
  148867. _vq_lengthlist__44u5__p2_0,
  148868. 1, -535822336, 1611661312, 2, 0,
  148869. _vq_quantlist__44u5__p2_0,
  148870. NULL,
  148871. &_vq_auxt__44u5__p2_0,
  148872. NULL,
  148873. 0
  148874. };
  148875. static long _vq_quantlist__44u5__p3_0[] = {
  148876. 2,
  148877. 1,
  148878. 3,
  148879. 0,
  148880. 4,
  148881. };
  148882. static long _vq_lengthlist__44u5__p3_0[] = {
  148883. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148884. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148885. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148886. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148887. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148888. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148889. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148890. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148891. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148892. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148893. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148894. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148895. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148896. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148897. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148898. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148899. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148900. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148901. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148902. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148903. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148904. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148905. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148906. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148907. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148908. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148909. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148910. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148911. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148912. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148913. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148914. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148915. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148916. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148917. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148918. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148919. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148920. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148921. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148922. 0,
  148923. };
  148924. static float _vq_quantthresh__44u5__p3_0[] = {
  148925. -1.5, -0.5, 0.5, 1.5,
  148926. };
  148927. static long _vq_quantmap__44u5__p3_0[] = {
  148928. 3, 1, 0, 2, 4,
  148929. };
  148930. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148931. _vq_quantthresh__44u5__p3_0,
  148932. _vq_quantmap__44u5__p3_0,
  148933. 5,
  148934. 5
  148935. };
  148936. static static_codebook _44u5__p3_0 = {
  148937. 4, 625,
  148938. _vq_lengthlist__44u5__p3_0,
  148939. 1, -533725184, 1611661312, 3, 0,
  148940. _vq_quantlist__44u5__p3_0,
  148941. NULL,
  148942. &_vq_auxt__44u5__p3_0,
  148943. NULL,
  148944. 0
  148945. };
  148946. static long _vq_quantlist__44u5__p4_0[] = {
  148947. 2,
  148948. 1,
  148949. 3,
  148950. 0,
  148951. 4,
  148952. };
  148953. static long _vq_lengthlist__44u5__p4_0[] = {
  148954. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148955. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148956. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148957. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148958. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148959. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148960. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148961. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148962. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148963. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148964. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148965. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148966. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148967. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148968. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148969. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148970. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148971. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148972. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148973. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148974. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148975. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148976. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148977. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148978. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148979. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148980. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148981. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148982. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148983. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148984. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148985. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148986. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148987. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148988. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148989. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148990. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148991. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148992. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148993. 12,
  148994. };
  148995. static float _vq_quantthresh__44u5__p4_0[] = {
  148996. -1.5, -0.5, 0.5, 1.5,
  148997. };
  148998. static long _vq_quantmap__44u5__p4_0[] = {
  148999. 3, 1, 0, 2, 4,
  149000. };
  149001. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149002. _vq_quantthresh__44u5__p4_0,
  149003. _vq_quantmap__44u5__p4_0,
  149004. 5,
  149005. 5
  149006. };
  149007. static static_codebook _44u5__p4_0 = {
  149008. 4, 625,
  149009. _vq_lengthlist__44u5__p4_0,
  149010. 1, -533725184, 1611661312, 3, 0,
  149011. _vq_quantlist__44u5__p4_0,
  149012. NULL,
  149013. &_vq_auxt__44u5__p4_0,
  149014. NULL,
  149015. 0
  149016. };
  149017. static long _vq_quantlist__44u5__p5_0[] = {
  149018. 4,
  149019. 3,
  149020. 5,
  149021. 2,
  149022. 6,
  149023. 1,
  149024. 7,
  149025. 0,
  149026. 8,
  149027. };
  149028. static long _vq_lengthlist__44u5__p5_0[] = {
  149029. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149030. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149031. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149032. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149033. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149034. 14,
  149035. };
  149036. static float _vq_quantthresh__44u5__p5_0[] = {
  149037. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149038. };
  149039. static long _vq_quantmap__44u5__p5_0[] = {
  149040. 7, 5, 3, 1, 0, 2, 4, 6,
  149041. 8,
  149042. };
  149043. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149044. _vq_quantthresh__44u5__p5_0,
  149045. _vq_quantmap__44u5__p5_0,
  149046. 9,
  149047. 9
  149048. };
  149049. static static_codebook _44u5__p5_0 = {
  149050. 2, 81,
  149051. _vq_lengthlist__44u5__p5_0,
  149052. 1, -531628032, 1611661312, 4, 0,
  149053. _vq_quantlist__44u5__p5_0,
  149054. NULL,
  149055. &_vq_auxt__44u5__p5_0,
  149056. NULL,
  149057. 0
  149058. };
  149059. static long _vq_quantlist__44u5__p6_0[] = {
  149060. 4,
  149061. 3,
  149062. 5,
  149063. 2,
  149064. 6,
  149065. 1,
  149066. 7,
  149067. 0,
  149068. 8,
  149069. };
  149070. static long _vq_lengthlist__44u5__p6_0[] = {
  149071. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149072. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149073. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149074. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149075. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149076. 11,
  149077. };
  149078. static float _vq_quantthresh__44u5__p6_0[] = {
  149079. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149080. };
  149081. static long _vq_quantmap__44u5__p6_0[] = {
  149082. 7, 5, 3, 1, 0, 2, 4, 6,
  149083. 8,
  149084. };
  149085. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149086. _vq_quantthresh__44u5__p6_0,
  149087. _vq_quantmap__44u5__p6_0,
  149088. 9,
  149089. 9
  149090. };
  149091. static static_codebook _44u5__p6_0 = {
  149092. 2, 81,
  149093. _vq_lengthlist__44u5__p6_0,
  149094. 1, -531628032, 1611661312, 4, 0,
  149095. _vq_quantlist__44u5__p6_0,
  149096. NULL,
  149097. &_vq_auxt__44u5__p6_0,
  149098. NULL,
  149099. 0
  149100. };
  149101. static long _vq_quantlist__44u5__p7_0[] = {
  149102. 1,
  149103. 0,
  149104. 2,
  149105. };
  149106. static long _vq_lengthlist__44u5__p7_0[] = {
  149107. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149108. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149109. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149110. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149111. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149112. 12,
  149113. };
  149114. static float _vq_quantthresh__44u5__p7_0[] = {
  149115. -5.5, 5.5,
  149116. };
  149117. static long _vq_quantmap__44u5__p7_0[] = {
  149118. 1, 0, 2,
  149119. };
  149120. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149121. _vq_quantthresh__44u5__p7_0,
  149122. _vq_quantmap__44u5__p7_0,
  149123. 3,
  149124. 3
  149125. };
  149126. static static_codebook _44u5__p7_0 = {
  149127. 4, 81,
  149128. _vq_lengthlist__44u5__p7_0,
  149129. 1, -529137664, 1618345984, 2, 0,
  149130. _vq_quantlist__44u5__p7_0,
  149131. NULL,
  149132. &_vq_auxt__44u5__p7_0,
  149133. NULL,
  149134. 0
  149135. };
  149136. static long _vq_quantlist__44u5__p7_1[] = {
  149137. 5,
  149138. 4,
  149139. 6,
  149140. 3,
  149141. 7,
  149142. 2,
  149143. 8,
  149144. 1,
  149145. 9,
  149146. 0,
  149147. 10,
  149148. };
  149149. static long _vq_lengthlist__44u5__p7_1[] = {
  149150. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149151. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149152. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149153. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149154. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149155. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149156. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149157. 9, 9, 9, 9, 9,10,10,10,10,
  149158. };
  149159. static float _vq_quantthresh__44u5__p7_1[] = {
  149160. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149161. 3.5, 4.5,
  149162. };
  149163. static long _vq_quantmap__44u5__p7_1[] = {
  149164. 9, 7, 5, 3, 1, 0, 2, 4,
  149165. 6, 8, 10,
  149166. };
  149167. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149168. _vq_quantthresh__44u5__p7_1,
  149169. _vq_quantmap__44u5__p7_1,
  149170. 11,
  149171. 11
  149172. };
  149173. static static_codebook _44u5__p7_1 = {
  149174. 2, 121,
  149175. _vq_lengthlist__44u5__p7_1,
  149176. 1, -531365888, 1611661312, 4, 0,
  149177. _vq_quantlist__44u5__p7_1,
  149178. NULL,
  149179. &_vq_auxt__44u5__p7_1,
  149180. NULL,
  149181. 0
  149182. };
  149183. static long _vq_quantlist__44u5__p8_0[] = {
  149184. 5,
  149185. 4,
  149186. 6,
  149187. 3,
  149188. 7,
  149189. 2,
  149190. 8,
  149191. 1,
  149192. 9,
  149193. 0,
  149194. 10,
  149195. };
  149196. static long _vq_lengthlist__44u5__p8_0[] = {
  149197. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149198. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149199. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149200. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149201. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149202. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149203. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149204. 12,13,13,14,14,14,14,15,15,
  149205. };
  149206. static float _vq_quantthresh__44u5__p8_0[] = {
  149207. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149208. 38.5, 49.5,
  149209. };
  149210. static long _vq_quantmap__44u5__p8_0[] = {
  149211. 9, 7, 5, 3, 1, 0, 2, 4,
  149212. 6, 8, 10,
  149213. };
  149214. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149215. _vq_quantthresh__44u5__p8_0,
  149216. _vq_quantmap__44u5__p8_0,
  149217. 11,
  149218. 11
  149219. };
  149220. static static_codebook _44u5__p8_0 = {
  149221. 2, 121,
  149222. _vq_lengthlist__44u5__p8_0,
  149223. 1, -524582912, 1618345984, 4, 0,
  149224. _vq_quantlist__44u5__p8_0,
  149225. NULL,
  149226. &_vq_auxt__44u5__p8_0,
  149227. NULL,
  149228. 0
  149229. };
  149230. static long _vq_quantlist__44u5__p8_1[] = {
  149231. 5,
  149232. 4,
  149233. 6,
  149234. 3,
  149235. 7,
  149236. 2,
  149237. 8,
  149238. 1,
  149239. 9,
  149240. 0,
  149241. 10,
  149242. };
  149243. static long _vq_lengthlist__44u5__p8_1[] = {
  149244. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149245. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149246. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149247. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149248. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149249. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149250. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149251. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149252. };
  149253. static float _vq_quantthresh__44u5__p8_1[] = {
  149254. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149255. 3.5, 4.5,
  149256. };
  149257. static long _vq_quantmap__44u5__p8_1[] = {
  149258. 9, 7, 5, 3, 1, 0, 2, 4,
  149259. 6, 8, 10,
  149260. };
  149261. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149262. _vq_quantthresh__44u5__p8_1,
  149263. _vq_quantmap__44u5__p8_1,
  149264. 11,
  149265. 11
  149266. };
  149267. static static_codebook _44u5__p8_1 = {
  149268. 2, 121,
  149269. _vq_lengthlist__44u5__p8_1,
  149270. 1, -531365888, 1611661312, 4, 0,
  149271. _vq_quantlist__44u5__p8_1,
  149272. NULL,
  149273. &_vq_auxt__44u5__p8_1,
  149274. NULL,
  149275. 0
  149276. };
  149277. static long _vq_quantlist__44u5__p9_0[] = {
  149278. 6,
  149279. 5,
  149280. 7,
  149281. 4,
  149282. 8,
  149283. 3,
  149284. 9,
  149285. 2,
  149286. 10,
  149287. 1,
  149288. 11,
  149289. 0,
  149290. 12,
  149291. };
  149292. static long _vq_lengthlist__44u5__p9_0[] = {
  149293. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149294. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149295. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149296. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149297. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149298. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149299. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149300. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149301. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149302. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149303. 12,12,12,12,12,12,12,12,12,
  149304. };
  149305. static float _vq_quantthresh__44u5__p9_0[] = {
  149306. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149307. 637.5, 892.5, 1147.5, 1402.5,
  149308. };
  149309. static long _vq_quantmap__44u5__p9_0[] = {
  149310. 11, 9, 7, 5, 3, 1, 0, 2,
  149311. 4, 6, 8, 10, 12,
  149312. };
  149313. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149314. _vq_quantthresh__44u5__p9_0,
  149315. _vq_quantmap__44u5__p9_0,
  149316. 13,
  149317. 13
  149318. };
  149319. static static_codebook _44u5__p9_0 = {
  149320. 2, 169,
  149321. _vq_lengthlist__44u5__p9_0,
  149322. 1, -514332672, 1627381760, 4, 0,
  149323. _vq_quantlist__44u5__p9_0,
  149324. NULL,
  149325. &_vq_auxt__44u5__p9_0,
  149326. NULL,
  149327. 0
  149328. };
  149329. static long _vq_quantlist__44u5__p9_1[] = {
  149330. 7,
  149331. 6,
  149332. 8,
  149333. 5,
  149334. 9,
  149335. 4,
  149336. 10,
  149337. 3,
  149338. 11,
  149339. 2,
  149340. 12,
  149341. 1,
  149342. 13,
  149343. 0,
  149344. 14,
  149345. };
  149346. static long _vq_lengthlist__44u5__p9_1[] = {
  149347. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149348. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149349. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149350. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149351. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149352. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149353. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149354. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149355. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149356. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149357. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149358. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149359. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149360. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149361. 14,
  149362. };
  149363. static float _vq_quantthresh__44u5__p9_1[] = {
  149364. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149365. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149366. };
  149367. static long _vq_quantmap__44u5__p9_1[] = {
  149368. 13, 11, 9, 7, 5, 3, 1, 0,
  149369. 2, 4, 6, 8, 10, 12, 14,
  149370. };
  149371. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149372. _vq_quantthresh__44u5__p9_1,
  149373. _vq_quantmap__44u5__p9_1,
  149374. 15,
  149375. 15
  149376. };
  149377. static static_codebook _44u5__p9_1 = {
  149378. 2, 225,
  149379. _vq_lengthlist__44u5__p9_1,
  149380. 1, -522338304, 1620115456, 4, 0,
  149381. _vq_quantlist__44u5__p9_1,
  149382. NULL,
  149383. &_vq_auxt__44u5__p9_1,
  149384. NULL,
  149385. 0
  149386. };
  149387. static long _vq_quantlist__44u5__p9_2[] = {
  149388. 8,
  149389. 7,
  149390. 9,
  149391. 6,
  149392. 10,
  149393. 5,
  149394. 11,
  149395. 4,
  149396. 12,
  149397. 3,
  149398. 13,
  149399. 2,
  149400. 14,
  149401. 1,
  149402. 15,
  149403. 0,
  149404. 16,
  149405. };
  149406. static long _vq_lengthlist__44u5__p9_2[] = {
  149407. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149408. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149409. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149410. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149411. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149412. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149413. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149414. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149415. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149416. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149417. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149418. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149419. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149420. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149421. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149422. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149423. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149424. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149425. 10,
  149426. };
  149427. static float _vq_quantthresh__44u5__p9_2[] = {
  149428. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149429. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149430. };
  149431. static long _vq_quantmap__44u5__p9_2[] = {
  149432. 15, 13, 11, 9, 7, 5, 3, 1,
  149433. 0, 2, 4, 6, 8, 10, 12, 14,
  149434. 16,
  149435. };
  149436. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149437. _vq_quantthresh__44u5__p9_2,
  149438. _vq_quantmap__44u5__p9_2,
  149439. 17,
  149440. 17
  149441. };
  149442. static static_codebook _44u5__p9_2 = {
  149443. 2, 289,
  149444. _vq_lengthlist__44u5__p9_2,
  149445. 1, -529530880, 1611661312, 5, 0,
  149446. _vq_quantlist__44u5__p9_2,
  149447. NULL,
  149448. &_vq_auxt__44u5__p9_2,
  149449. NULL,
  149450. 0
  149451. };
  149452. static long _huff_lengthlist__44u5__short[] = {
  149453. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149454. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149455. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149456. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149457. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149458. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149459. 6, 8,15,17,
  149460. };
  149461. static static_codebook _huff_book__44u5__short = {
  149462. 2, 100,
  149463. _huff_lengthlist__44u5__short,
  149464. 0, 0, 0, 0, 0,
  149465. NULL,
  149466. NULL,
  149467. NULL,
  149468. NULL,
  149469. 0
  149470. };
  149471. static long _huff_lengthlist__44u6__long[] = {
  149472. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149473. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149474. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149475. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149476. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149477. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149478. 13, 8, 7, 7,
  149479. };
  149480. static static_codebook _huff_book__44u6__long = {
  149481. 2, 100,
  149482. _huff_lengthlist__44u6__long,
  149483. 0, 0, 0, 0, 0,
  149484. NULL,
  149485. NULL,
  149486. NULL,
  149487. NULL,
  149488. 0
  149489. };
  149490. static long _vq_quantlist__44u6__p1_0[] = {
  149491. 1,
  149492. 0,
  149493. 2,
  149494. };
  149495. static long _vq_lengthlist__44u6__p1_0[] = {
  149496. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149497. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149498. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149499. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149500. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149501. 12,
  149502. };
  149503. static float _vq_quantthresh__44u6__p1_0[] = {
  149504. -0.5, 0.5,
  149505. };
  149506. static long _vq_quantmap__44u6__p1_0[] = {
  149507. 1, 0, 2,
  149508. };
  149509. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149510. _vq_quantthresh__44u6__p1_0,
  149511. _vq_quantmap__44u6__p1_0,
  149512. 3,
  149513. 3
  149514. };
  149515. static static_codebook _44u6__p1_0 = {
  149516. 4, 81,
  149517. _vq_lengthlist__44u6__p1_0,
  149518. 1, -535822336, 1611661312, 2, 0,
  149519. _vq_quantlist__44u6__p1_0,
  149520. NULL,
  149521. &_vq_auxt__44u6__p1_0,
  149522. NULL,
  149523. 0
  149524. };
  149525. static long _vq_quantlist__44u6__p2_0[] = {
  149526. 1,
  149527. 0,
  149528. 2,
  149529. };
  149530. static long _vq_lengthlist__44u6__p2_0[] = {
  149531. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149532. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149533. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149534. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149535. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149536. 9,
  149537. };
  149538. static float _vq_quantthresh__44u6__p2_0[] = {
  149539. -0.5, 0.5,
  149540. };
  149541. static long _vq_quantmap__44u6__p2_0[] = {
  149542. 1, 0, 2,
  149543. };
  149544. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149545. _vq_quantthresh__44u6__p2_0,
  149546. _vq_quantmap__44u6__p2_0,
  149547. 3,
  149548. 3
  149549. };
  149550. static static_codebook _44u6__p2_0 = {
  149551. 4, 81,
  149552. _vq_lengthlist__44u6__p2_0,
  149553. 1, -535822336, 1611661312, 2, 0,
  149554. _vq_quantlist__44u6__p2_0,
  149555. NULL,
  149556. &_vq_auxt__44u6__p2_0,
  149557. NULL,
  149558. 0
  149559. };
  149560. static long _vq_quantlist__44u6__p3_0[] = {
  149561. 2,
  149562. 1,
  149563. 3,
  149564. 0,
  149565. 4,
  149566. };
  149567. static long _vq_lengthlist__44u6__p3_0[] = {
  149568. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149569. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149570. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149571. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149572. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149573. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149574. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149575. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149576. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149577. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149578. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149579. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149580. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149581. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149582. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149583. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149584. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149585. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149586. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149587. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149588. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149589. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149590. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149591. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149592. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149593. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149594. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149595. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149596. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149597. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149598. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149599. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149600. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149601. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149602. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149603. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149604. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149605. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149606. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149607. 19,
  149608. };
  149609. static float _vq_quantthresh__44u6__p3_0[] = {
  149610. -1.5, -0.5, 0.5, 1.5,
  149611. };
  149612. static long _vq_quantmap__44u6__p3_0[] = {
  149613. 3, 1, 0, 2, 4,
  149614. };
  149615. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149616. _vq_quantthresh__44u6__p3_0,
  149617. _vq_quantmap__44u6__p3_0,
  149618. 5,
  149619. 5
  149620. };
  149621. static static_codebook _44u6__p3_0 = {
  149622. 4, 625,
  149623. _vq_lengthlist__44u6__p3_0,
  149624. 1, -533725184, 1611661312, 3, 0,
  149625. _vq_quantlist__44u6__p3_0,
  149626. NULL,
  149627. &_vq_auxt__44u6__p3_0,
  149628. NULL,
  149629. 0
  149630. };
  149631. static long _vq_quantlist__44u6__p4_0[] = {
  149632. 2,
  149633. 1,
  149634. 3,
  149635. 0,
  149636. 4,
  149637. };
  149638. static long _vq_lengthlist__44u6__p4_0[] = {
  149639. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149640. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149641. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149642. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149643. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149644. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149645. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149646. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149647. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149648. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149649. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149650. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149651. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149652. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149653. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149654. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149655. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149656. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149657. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149658. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149659. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149660. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149661. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149662. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149663. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149664. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149665. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149666. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149667. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149668. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149669. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149670. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149671. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149672. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149673. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149674. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149675. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149676. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149677. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149678. 13,
  149679. };
  149680. static float _vq_quantthresh__44u6__p4_0[] = {
  149681. -1.5, -0.5, 0.5, 1.5,
  149682. };
  149683. static long _vq_quantmap__44u6__p4_0[] = {
  149684. 3, 1, 0, 2, 4,
  149685. };
  149686. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149687. _vq_quantthresh__44u6__p4_0,
  149688. _vq_quantmap__44u6__p4_0,
  149689. 5,
  149690. 5
  149691. };
  149692. static static_codebook _44u6__p4_0 = {
  149693. 4, 625,
  149694. _vq_lengthlist__44u6__p4_0,
  149695. 1, -533725184, 1611661312, 3, 0,
  149696. _vq_quantlist__44u6__p4_0,
  149697. NULL,
  149698. &_vq_auxt__44u6__p4_0,
  149699. NULL,
  149700. 0
  149701. };
  149702. static long _vq_quantlist__44u6__p5_0[] = {
  149703. 4,
  149704. 3,
  149705. 5,
  149706. 2,
  149707. 6,
  149708. 1,
  149709. 7,
  149710. 0,
  149711. 8,
  149712. };
  149713. static long _vq_lengthlist__44u6__p5_0[] = {
  149714. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149715. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149716. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149717. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149718. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149719. 14,
  149720. };
  149721. static float _vq_quantthresh__44u6__p5_0[] = {
  149722. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149723. };
  149724. static long _vq_quantmap__44u6__p5_0[] = {
  149725. 7, 5, 3, 1, 0, 2, 4, 6,
  149726. 8,
  149727. };
  149728. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149729. _vq_quantthresh__44u6__p5_0,
  149730. _vq_quantmap__44u6__p5_0,
  149731. 9,
  149732. 9
  149733. };
  149734. static static_codebook _44u6__p5_0 = {
  149735. 2, 81,
  149736. _vq_lengthlist__44u6__p5_0,
  149737. 1, -531628032, 1611661312, 4, 0,
  149738. _vq_quantlist__44u6__p5_0,
  149739. NULL,
  149740. &_vq_auxt__44u6__p5_0,
  149741. NULL,
  149742. 0
  149743. };
  149744. static long _vq_quantlist__44u6__p6_0[] = {
  149745. 4,
  149746. 3,
  149747. 5,
  149748. 2,
  149749. 6,
  149750. 1,
  149751. 7,
  149752. 0,
  149753. 8,
  149754. };
  149755. static long _vq_lengthlist__44u6__p6_0[] = {
  149756. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149757. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149758. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149759. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149760. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149761. 12,
  149762. };
  149763. static float _vq_quantthresh__44u6__p6_0[] = {
  149764. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149765. };
  149766. static long _vq_quantmap__44u6__p6_0[] = {
  149767. 7, 5, 3, 1, 0, 2, 4, 6,
  149768. 8,
  149769. };
  149770. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149771. _vq_quantthresh__44u6__p6_0,
  149772. _vq_quantmap__44u6__p6_0,
  149773. 9,
  149774. 9
  149775. };
  149776. static static_codebook _44u6__p6_0 = {
  149777. 2, 81,
  149778. _vq_lengthlist__44u6__p6_0,
  149779. 1, -531628032, 1611661312, 4, 0,
  149780. _vq_quantlist__44u6__p6_0,
  149781. NULL,
  149782. &_vq_auxt__44u6__p6_0,
  149783. NULL,
  149784. 0
  149785. };
  149786. static long _vq_quantlist__44u6__p7_0[] = {
  149787. 1,
  149788. 0,
  149789. 2,
  149790. };
  149791. static long _vq_lengthlist__44u6__p7_0[] = {
  149792. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149793. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149794. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149795. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149796. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149797. 10,
  149798. };
  149799. static float _vq_quantthresh__44u6__p7_0[] = {
  149800. -5.5, 5.5,
  149801. };
  149802. static long _vq_quantmap__44u6__p7_0[] = {
  149803. 1, 0, 2,
  149804. };
  149805. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149806. _vq_quantthresh__44u6__p7_0,
  149807. _vq_quantmap__44u6__p7_0,
  149808. 3,
  149809. 3
  149810. };
  149811. static static_codebook _44u6__p7_0 = {
  149812. 4, 81,
  149813. _vq_lengthlist__44u6__p7_0,
  149814. 1, -529137664, 1618345984, 2, 0,
  149815. _vq_quantlist__44u6__p7_0,
  149816. NULL,
  149817. &_vq_auxt__44u6__p7_0,
  149818. NULL,
  149819. 0
  149820. };
  149821. static long _vq_quantlist__44u6__p7_1[] = {
  149822. 5,
  149823. 4,
  149824. 6,
  149825. 3,
  149826. 7,
  149827. 2,
  149828. 8,
  149829. 1,
  149830. 9,
  149831. 0,
  149832. 10,
  149833. };
  149834. static long _vq_lengthlist__44u6__p7_1[] = {
  149835. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149836. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149837. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149838. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149839. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149840. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149841. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149842. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149843. };
  149844. static float _vq_quantthresh__44u6__p7_1[] = {
  149845. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149846. 3.5, 4.5,
  149847. };
  149848. static long _vq_quantmap__44u6__p7_1[] = {
  149849. 9, 7, 5, 3, 1, 0, 2, 4,
  149850. 6, 8, 10,
  149851. };
  149852. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149853. _vq_quantthresh__44u6__p7_1,
  149854. _vq_quantmap__44u6__p7_1,
  149855. 11,
  149856. 11
  149857. };
  149858. static static_codebook _44u6__p7_1 = {
  149859. 2, 121,
  149860. _vq_lengthlist__44u6__p7_1,
  149861. 1, -531365888, 1611661312, 4, 0,
  149862. _vq_quantlist__44u6__p7_1,
  149863. NULL,
  149864. &_vq_auxt__44u6__p7_1,
  149865. NULL,
  149866. 0
  149867. };
  149868. static long _vq_quantlist__44u6__p8_0[] = {
  149869. 5,
  149870. 4,
  149871. 6,
  149872. 3,
  149873. 7,
  149874. 2,
  149875. 8,
  149876. 1,
  149877. 9,
  149878. 0,
  149879. 10,
  149880. };
  149881. static long _vq_lengthlist__44u6__p8_0[] = {
  149882. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149883. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149884. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149885. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149886. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149887. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149888. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149889. 12,13,13,14,14,14,15,15,15,
  149890. };
  149891. static float _vq_quantthresh__44u6__p8_0[] = {
  149892. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149893. 38.5, 49.5,
  149894. };
  149895. static long _vq_quantmap__44u6__p8_0[] = {
  149896. 9, 7, 5, 3, 1, 0, 2, 4,
  149897. 6, 8, 10,
  149898. };
  149899. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149900. _vq_quantthresh__44u6__p8_0,
  149901. _vq_quantmap__44u6__p8_0,
  149902. 11,
  149903. 11
  149904. };
  149905. static static_codebook _44u6__p8_0 = {
  149906. 2, 121,
  149907. _vq_lengthlist__44u6__p8_0,
  149908. 1, -524582912, 1618345984, 4, 0,
  149909. _vq_quantlist__44u6__p8_0,
  149910. NULL,
  149911. &_vq_auxt__44u6__p8_0,
  149912. NULL,
  149913. 0
  149914. };
  149915. static long _vq_quantlist__44u6__p8_1[] = {
  149916. 5,
  149917. 4,
  149918. 6,
  149919. 3,
  149920. 7,
  149921. 2,
  149922. 8,
  149923. 1,
  149924. 9,
  149925. 0,
  149926. 10,
  149927. };
  149928. static long _vq_lengthlist__44u6__p8_1[] = {
  149929. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149930. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149931. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149932. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149933. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149934. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149935. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149936. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149937. };
  149938. static float _vq_quantthresh__44u6__p8_1[] = {
  149939. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149940. 3.5, 4.5,
  149941. };
  149942. static long _vq_quantmap__44u6__p8_1[] = {
  149943. 9, 7, 5, 3, 1, 0, 2, 4,
  149944. 6, 8, 10,
  149945. };
  149946. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149947. _vq_quantthresh__44u6__p8_1,
  149948. _vq_quantmap__44u6__p8_1,
  149949. 11,
  149950. 11
  149951. };
  149952. static static_codebook _44u6__p8_1 = {
  149953. 2, 121,
  149954. _vq_lengthlist__44u6__p8_1,
  149955. 1, -531365888, 1611661312, 4, 0,
  149956. _vq_quantlist__44u6__p8_1,
  149957. NULL,
  149958. &_vq_auxt__44u6__p8_1,
  149959. NULL,
  149960. 0
  149961. };
  149962. static long _vq_quantlist__44u6__p9_0[] = {
  149963. 7,
  149964. 6,
  149965. 8,
  149966. 5,
  149967. 9,
  149968. 4,
  149969. 10,
  149970. 3,
  149971. 11,
  149972. 2,
  149973. 12,
  149974. 1,
  149975. 13,
  149976. 0,
  149977. 14,
  149978. };
  149979. static long _vq_lengthlist__44u6__p9_0[] = {
  149980. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149981. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149982. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149983. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149984. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149985. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149986. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149987. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149988. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149989. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149990. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149991. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149992. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149993. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149994. 14,
  149995. };
  149996. static float _vq_quantthresh__44u6__p9_0[] = {
  149997. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149998. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149999. };
  150000. static long _vq_quantmap__44u6__p9_0[] = {
  150001. 13, 11, 9, 7, 5, 3, 1, 0,
  150002. 2, 4, 6, 8, 10, 12, 14,
  150003. };
  150004. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150005. _vq_quantthresh__44u6__p9_0,
  150006. _vq_quantmap__44u6__p9_0,
  150007. 15,
  150008. 15
  150009. };
  150010. static static_codebook _44u6__p9_0 = {
  150011. 2, 225,
  150012. _vq_lengthlist__44u6__p9_0,
  150013. 1, -514071552, 1627381760, 4, 0,
  150014. _vq_quantlist__44u6__p9_0,
  150015. NULL,
  150016. &_vq_auxt__44u6__p9_0,
  150017. NULL,
  150018. 0
  150019. };
  150020. static long _vq_quantlist__44u6__p9_1[] = {
  150021. 7,
  150022. 6,
  150023. 8,
  150024. 5,
  150025. 9,
  150026. 4,
  150027. 10,
  150028. 3,
  150029. 11,
  150030. 2,
  150031. 12,
  150032. 1,
  150033. 13,
  150034. 0,
  150035. 14,
  150036. };
  150037. static long _vq_lengthlist__44u6__p9_1[] = {
  150038. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150039. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150040. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150041. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150042. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150043. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150044. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150045. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150046. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150047. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150048. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150049. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150050. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150051. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150052. 13,
  150053. };
  150054. static float _vq_quantthresh__44u6__p9_1[] = {
  150055. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150056. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150057. };
  150058. static long _vq_quantmap__44u6__p9_1[] = {
  150059. 13, 11, 9, 7, 5, 3, 1, 0,
  150060. 2, 4, 6, 8, 10, 12, 14,
  150061. };
  150062. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150063. _vq_quantthresh__44u6__p9_1,
  150064. _vq_quantmap__44u6__p9_1,
  150065. 15,
  150066. 15
  150067. };
  150068. static static_codebook _44u6__p9_1 = {
  150069. 2, 225,
  150070. _vq_lengthlist__44u6__p9_1,
  150071. 1, -522338304, 1620115456, 4, 0,
  150072. _vq_quantlist__44u6__p9_1,
  150073. NULL,
  150074. &_vq_auxt__44u6__p9_1,
  150075. NULL,
  150076. 0
  150077. };
  150078. static long _vq_quantlist__44u6__p9_2[] = {
  150079. 8,
  150080. 7,
  150081. 9,
  150082. 6,
  150083. 10,
  150084. 5,
  150085. 11,
  150086. 4,
  150087. 12,
  150088. 3,
  150089. 13,
  150090. 2,
  150091. 14,
  150092. 1,
  150093. 15,
  150094. 0,
  150095. 16,
  150096. };
  150097. static long _vq_lengthlist__44u6__p9_2[] = {
  150098. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150099. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150100. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150101. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150102. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150103. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150104. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150105. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150106. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150107. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150108. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150109. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150110. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150111. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150112. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150113. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150114. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150115. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150116. 10,
  150117. };
  150118. static float _vq_quantthresh__44u6__p9_2[] = {
  150119. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150120. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150121. };
  150122. static long _vq_quantmap__44u6__p9_2[] = {
  150123. 15, 13, 11, 9, 7, 5, 3, 1,
  150124. 0, 2, 4, 6, 8, 10, 12, 14,
  150125. 16,
  150126. };
  150127. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150128. _vq_quantthresh__44u6__p9_2,
  150129. _vq_quantmap__44u6__p9_2,
  150130. 17,
  150131. 17
  150132. };
  150133. static static_codebook _44u6__p9_2 = {
  150134. 2, 289,
  150135. _vq_lengthlist__44u6__p9_2,
  150136. 1, -529530880, 1611661312, 5, 0,
  150137. _vq_quantlist__44u6__p9_2,
  150138. NULL,
  150139. &_vq_auxt__44u6__p9_2,
  150140. NULL,
  150141. 0
  150142. };
  150143. static long _huff_lengthlist__44u6__short[] = {
  150144. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150145. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150146. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150147. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150148. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150149. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150150. 7, 6, 9,16,
  150151. };
  150152. static static_codebook _huff_book__44u6__short = {
  150153. 2, 100,
  150154. _huff_lengthlist__44u6__short,
  150155. 0, 0, 0, 0, 0,
  150156. NULL,
  150157. NULL,
  150158. NULL,
  150159. NULL,
  150160. 0
  150161. };
  150162. static long _huff_lengthlist__44u7__long[] = {
  150163. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150164. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150165. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150166. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150167. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150168. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150169. 12, 8, 6, 7,
  150170. };
  150171. static static_codebook _huff_book__44u7__long = {
  150172. 2, 100,
  150173. _huff_lengthlist__44u7__long,
  150174. 0, 0, 0, 0, 0,
  150175. NULL,
  150176. NULL,
  150177. NULL,
  150178. NULL,
  150179. 0
  150180. };
  150181. static long _vq_quantlist__44u7__p1_0[] = {
  150182. 1,
  150183. 0,
  150184. 2,
  150185. };
  150186. static long _vq_lengthlist__44u7__p1_0[] = {
  150187. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150188. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150189. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150190. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150191. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150192. 12,
  150193. };
  150194. static float _vq_quantthresh__44u7__p1_0[] = {
  150195. -0.5, 0.5,
  150196. };
  150197. static long _vq_quantmap__44u7__p1_0[] = {
  150198. 1, 0, 2,
  150199. };
  150200. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150201. _vq_quantthresh__44u7__p1_0,
  150202. _vq_quantmap__44u7__p1_0,
  150203. 3,
  150204. 3
  150205. };
  150206. static static_codebook _44u7__p1_0 = {
  150207. 4, 81,
  150208. _vq_lengthlist__44u7__p1_0,
  150209. 1, -535822336, 1611661312, 2, 0,
  150210. _vq_quantlist__44u7__p1_0,
  150211. NULL,
  150212. &_vq_auxt__44u7__p1_0,
  150213. NULL,
  150214. 0
  150215. };
  150216. static long _vq_quantlist__44u7__p2_0[] = {
  150217. 1,
  150218. 0,
  150219. 2,
  150220. };
  150221. static long _vq_lengthlist__44u7__p2_0[] = {
  150222. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150223. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150224. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150225. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150226. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150227. 9,
  150228. };
  150229. static float _vq_quantthresh__44u7__p2_0[] = {
  150230. -0.5, 0.5,
  150231. };
  150232. static long _vq_quantmap__44u7__p2_0[] = {
  150233. 1, 0, 2,
  150234. };
  150235. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150236. _vq_quantthresh__44u7__p2_0,
  150237. _vq_quantmap__44u7__p2_0,
  150238. 3,
  150239. 3
  150240. };
  150241. static static_codebook _44u7__p2_0 = {
  150242. 4, 81,
  150243. _vq_lengthlist__44u7__p2_0,
  150244. 1, -535822336, 1611661312, 2, 0,
  150245. _vq_quantlist__44u7__p2_0,
  150246. NULL,
  150247. &_vq_auxt__44u7__p2_0,
  150248. NULL,
  150249. 0
  150250. };
  150251. static long _vq_quantlist__44u7__p3_0[] = {
  150252. 2,
  150253. 1,
  150254. 3,
  150255. 0,
  150256. 4,
  150257. };
  150258. static long _vq_lengthlist__44u7__p3_0[] = {
  150259. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150260. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150261. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150262. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150263. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150264. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150265. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150266. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150267. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150268. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150269. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150270. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150271. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150272. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150273. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150274. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150275. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150276. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150277. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150278. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150279. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150280. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150281. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150282. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150283. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150284. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150285. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150286. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150287. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150288. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150289. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150290. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150291. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150292. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150293. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150294. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150295. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150296. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150297. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150298. 0,
  150299. };
  150300. static float _vq_quantthresh__44u7__p3_0[] = {
  150301. -1.5, -0.5, 0.5, 1.5,
  150302. };
  150303. static long _vq_quantmap__44u7__p3_0[] = {
  150304. 3, 1, 0, 2, 4,
  150305. };
  150306. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150307. _vq_quantthresh__44u7__p3_0,
  150308. _vq_quantmap__44u7__p3_0,
  150309. 5,
  150310. 5
  150311. };
  150312. static static_codebook _44u7__p3_0 = {
  150313. 4, 625,
  150314. _vq_lengthlist__44u7__p3_0,
  150315. 1, -533725184, 1611661312, 3, 0,
  150316. _vq_quantlist__44u7__p3_0,
  150317. NULL,
  150318. &_vq_auxt__44u7__p3_0,
  150319. NULL,
  150320. 0
  150321. };
  150322. static long _vq_quantlist__44u7__p4_0[] = {
  150323. 2,
  150324. 1,
  150325. 3,
  150326. 0,
  150327. 4,
  150328. };
  150329. static long _vq_lengthlist__44u7__p4_0[] = {
  150330. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150331. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150332. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150333. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150334. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150335. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150336. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150337. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150338. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150339. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150340. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150341. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150342. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150343. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150344. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150345. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150346. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150347. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150348. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150349. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150350. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150351. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150352. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150353. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150354. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150355. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150356. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150357. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150358. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150359. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150360. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150361. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150362. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150363. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150364. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150365. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150366. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150367. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150368. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150369. 14,
  150370. };
  150371. static float _vq_quantthresh__44u7__p4_0[] = {
  150372. -1.5, -0.5, 0.5, 1.5,
  150373. };
  150374. static long _vq_quantmap__44u7__p4_0[] = {
  150375. 3, 1, 0, 2, 4,
  150376. };
  150377. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150378. _vq_quantthresh__44u7__p4_0,
  150379. _vq_quantmap__44u7__p4_0,
  150380. 5,
  150381. 5
  150382. };
  150383. static static_codebook _44u7__p4_0 = {
  150384. 4, 625,
  150385. _vq_lengthlist__44u7__p4_0,
  150386. 1, -533725184, 1611661312, 3, 0,
  150387. _vq_quantlist__44u7__p4_0,
  150388. NULL,
  150389. &_vq_auxt__44u7__p4_0,
  150390. NULL,
  150391. 0
  150392. };
  150393. static long _vq_quantlist__44u7__p5_0[] = {
  150394. 4,
  150395. 3,
  150396. 5,
  150397. 2,
  150398. 6,
  150399. 1,
  150400. 7,
  150401. 0,
  150402. 8,
  150403. };
  150404. static long _vq_lengthlist__44u7__p5_0[] = {
  150405. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150406. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150407. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150408. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150409. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150410. 14,
  150411. };
  150412. static float _vq_quantthresh__44u7__p5_0[] = {
  150413. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150414. };
  150415. static long _vq_quantmap__44u7__p5_0[] = {
  150416. 7, 5, 3, 1, 0, 2, 4, 6,
  150417. 8,
  150418. };
  150419. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150420. _vq_quantthresh__44u7__p5_0,
  150421. _vq_quantmap__44u7__p5_0,
  150422. 9,
  150423. 9
  150424. };
  150425. static static_codebook _44u7__p5_0 = {
  150426. 2, 81,
  150427. _vq_lengthlist__44u7__p5_0,
  150428. 1, -531628032, 1611661312, 4, 0,
  150429. _vq_quantlist__44u7__p5_0,
  150430. NULL,
  150431. &_vq_auxt__44u7__p5_0,
  150432. NULL,
  150433. 0
  150434. };
  150435. static long _vq_quantlist__44u7__p6_0[] = {
  150436. 4,
  150437. 3,
  150438. 5,
  150439. 2,
  150440. 6,
  150441. 1,
  150442. 7,
  150443. 0,
  150444. 8,
  150445. };
  150446. static long _vq_lengthlist__44u7__p6_0[] = {
  150447. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150448. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150449. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150450. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150451. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150452. 12,
  150453. };
  150454. static float _vq_quantthresh__44u7__p6_0[] = {
  150455. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150456. };
  150457. static long _vq_quantmap__44u7__p6_0[] = {
  150458. 7, 5, 3, 1, 0, 2, 4, 6,
  150459. 8,
  150460. };
  150461. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150462. _vq_quantthresh__44u7__p6_0,
  150463. _vq_quantmap__44u7__p6_0,
  150464. 9,
  150465. 9
  150466. };
  150467. static static_codebook _44u7__p6_0 = {
  150468. 2, 81,
  150469. _vq_lengthlist__44u7__p6_0,
  150470. 1, -531628032, 1611661312, 4, 0,
  150471. _vq_quantlist__44u7__p6_0,
  150472. NULL,
  150473. &_vq_auxt__44u7__p6_0,
  150474. NULL,
  150475. 0
  150476. };
  150477. static long _vq_quantlist__44u7__p7_0[] = {
  150478. 1,
  150479. 0,
  150480. 2,
  150481. };
  150482. static long _vq_lengthlist__44u7__p7_0[] = {
  150483. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150484. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150485. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150486. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150487. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150488. 10,
  150489. };
  150490. static float _vq_quantthresh__44u7__p7_0[] = {
  150491. -5.5, 5.5,
  150492. };
  150493. static long _vq_quantmap__44u7__p7_0[] = {
  150494. 1, 0, 2,
  150495. };
  150496. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150497. _vq_quantthresh__44u7__p7_0,
  150498. _vq_quantmap__44u7__p7_0,
  150499. 3,
  150500. 3
  150501. };
  150502. static static_codebook _44u7__p7_0 = {
  150503. 4, 81,
  150504. _vq_lengthlist__44u7__p7_0,
  150505. 1, -529137664, 1618345984, 2, 0,
  150506. _vq_quantlist__44u7__p7_0,
  150507. NULL,
  150508. &_vq_auxt__44u7__p7_0,
  150509. NULL,
  150510. 0
  150511. };
  150512. static long _vq_quantlist__44u7__p7_1[] = {
  150513. 5,
  150514. 4,
  150515. 6,
  150516. 3,
  150517. 7,
  150518. 2,
  150519. 8,
  150520. 1,
  150521. 9,
  150522. 0,
  150523. 10,
  150524. };
  150525. static long _vq_lengthlist__44u7__p7_1[] = {
  150526. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150527. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150528. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150529. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150530. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150531. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150532. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150533. 8, 9, 9, 9, 9, 9,10,10,10,
  150534. };
  150535. static float _vq_quantthresh__44u7__p7_1[] = {
  150536. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150537. 3.5, 4.5,
  150538. };
  150539. static long _vq_quantmap__44u7__p7_1[] = {
  150540. 9, 7, 5, 3, 1, 0, 2, 4,
  150541. 6, 8, 10,
  150542. };
  150543. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150544. _vq_quantthresh__44u7__p7_1,
  150545. _vq_quantmap__44u7__p7_1,
  150546. 11,
  150547. 11
  150548. };
  150549. static static_codebook _44u7__p7_1 = {
  150550. 2, 121,
  150551. _vq_lengthlist__44u7__p7_1,
  150552. 1, -531365888, 1611661312, 4, 0,
  150553. _vq_quantlist__44u7__p7_1,
  150554. NULL,
  150555. &_vq_auxt__44u7__p7_1,
  150556. NULL,
  150557. 0
  150558. };
  150559. static long _vq_quantlist__44u7__p8_0[] = {
  150560. 5,
  150561. 4,
  150562. 6,
  150563. 3,
  150564. 7,
  150565. 2,
  150566. 8,
  150567. 1,
  150568. 9,
  150569. 0,
  150570. 10,
  150571. };
  150572. static long _vq_lengthlist__44u7__p8_0[] = {
  150573. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150574. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150575. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150576. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150577. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150578. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150579. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150580. 12,13,13,14,14,15,15,15,16,
  150581. };
  150582. static float _vq_quantthresh__44u7__p8_0[] = {
  150583. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150584. 38.5, 49.5,
  150585. };
  150586. static long _vq_quantmap__44u7__p8_0[] = {
  150587. 9, 7, 5, 3, 1, 0, 2, 4,
  150588. 6, 8, 10,
  150589. };
  150590. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150591. _vq_quantthresh__44u7__p8_0,
  150592. _vq_quantmap__44u7__p8_0,
  150593. 11,
  150594. 11
  150595. };
  150596. static static_codebook _44u7__p8_0 = {
  150597. 2, 121,
  150598. _vq_lengthlist__44u7__p8_0,
  150599. 1, -524582912, 1618345984, 4, 0,
  150600. _vq_quantlist__44u7__p8_0,
  150601. NULL,
  150602. &_vq_auxt__44u7__p8_0,
  150603. NULL,
  150604. 0
  150605. };
  150606. static long _vq_quantlist__44u7__p8_1[] = {
  150607. 5,
  150608. 4,
  150609. 6,
  150610. 3,
  150611. 7,
  150612. 2,
  150613. 8,
  150614. 1,
  150615. 9,
  150616. 0,
  150617. 10,
  150618. };
  150619. static long _vq_lengthlist__44u7__p8_1[] = {
  150620. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150621. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150622. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150623. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150624. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150625. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150626. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150627. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150628. };
  150629. static float _vq_quantthresh__44u7__p8_1[] = {
  150630. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150631. 3.5, 4.5,
  150632. };
  150633. static long _vq_quantmap__44u7__p8_1[] = {
  150634. 9, 7, 5, 3, 1, 0, 2, 4,
  150635. 6, 8, 10,
  150636. };
  150637. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150638. _vq_quantthresh__44u7__p8_1,
  150639. _vq_quantmap__44u7__p8_1,
  150640. 11,
  150641. 11
  150642. };
  150643. static static_codebook _44u7__p8_1 = {
  150644. 2, 121,
  150645. _vq_lengthlist__44u7__p8_1,
  150646. 1, -531365888, 1611661312, 4, 0,
  150647. _vq_quantlist__44u7__p8_1,
  150648. NULL,
  150649. &_vq_auxt__44u7__p8_1,
  150650. NULL,
  150651. 0
  150652. };
  150653. static long _vq_quantlist__44u7__p9_0[] = {
  150654. 5,
  150655. 4,
  150656. 6,
  150657. 3,
  150658. 7,
  150659. 2,
  150660. 8,
  150661. 1,
  150662. 9,
  150663. 0,
  150664. 10,
  150665. };
  150666. static long _vq_lengthlist__44u7__p9_0[] = {
  150667. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150668. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150670. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150671. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150673. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150674. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150675. };
  150676. static float _vq_quantthresh__44u7__p9_0[] = {
  150677. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150678. 2229.5, 2866.5,
  150679. };
  150680. static long _vq_quantmap__44u7__p9_0[] = {
  150681. 9, 7, 5, 3, 1, 0, 2, 4,
  150682. 6, 8, 10,
  150683. };
  150684. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150685. _vq_quantthresh__44u7__p9_0,
  150686. _vq_quantmap__44u7__p9_0,
  150687. 11,
  150688. 11
  150689. };
  150690. static static_codebook _44u7__p9_0 = {
  150691. 2, 121,
  150692. _vq_lengthlist__44u7__p9_0,
  150693. 1, -512171520, 1630791680, 4, 0,
  150694. _vq_quantlist__44u7__p9_0,
  150695. NULL,
  150696. &_vq_auxt__44u7__p9_0,
  150697. NULL,
  150698. 0
  150699. };
  150700. static long _vq_quantlist__44u7__p9_1[] = {
  150701. 6,
  150702. 5,
  150703. 7,
  150704. 4,
  150705. 8,
  150706. 3,
  150707. 9,
  150708. 2,
  150709. 10,
  150710. 1,
  150711. 11,
  150712. 0,
  150713. 12,
  150714. };
  150715. static long _vq_lengthlist__44u7__p9_1[] = {
  150716. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150717. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150718. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150719. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150720. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150721. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150722. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150723. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150724. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150725. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150726. 15,15,15,15,17,17,16,17,16,
  150727. };
  150728. static float _vq_quantthresh__44u7__p9_1[] = {
  150729. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150730. 122.5, 171.5, 220.5, 269.5,
  150731. };
  150732. static long _vq_quantmap__44u7__p9_1[] = {
  150733. 11, 9, 7, 5, 3, 1, 0, 2,
  150734. 4, 6, 8, 10, 12,
  150735. };
  150736. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150737. _vq_quantthresh__44u7__p9_1,
  150738. _vq_quantmap__44u7__p9_1,
  150739. 13,
  150740. 13
  150741. };
  150742. static static_codebook _44u7__p9_1 = {
  150743. 2, 169,
  150744. _vq_lengthlist__44u7__p9_1,
  150745. 1, -518889472, 1622704128, 4, 0,
  150746. _vq_quantlist__44u7__p9_1,
  150747. NULL,
  150748. &_vq_auxt__44u7__p9_1,
  150749. NULL,
  150750. 0
  150751. };
  150752. static long _vq_quantlist__44u7__p9_2[] = {
  150753. 24,
  150754. 23,
  150755. 25,
  150756. 22,
  150757. 26,
  150758. 21,
  150759. 27,
  150760. 20,
  150761. 28,
  150762. 19,
  150763. 29,
  150764. 18,
  150765. 30,
  150766. 17,
  150767. 31,
  150768. 16,
  150769. 32,
  150770. 15,
  150771. 33,
  150772. 14,
  150773. 34,
  150774. 13,
  150775. 35,
  150776. 12,
  150777. 36,
  150778. 11,
  150779. 37,
  150780. 10,
  150781. 38,
  150782. 9,
  150783. 39,
  150784. 8,
  150785. 40,
  150786. 7,
  150787. 41,
  150788. 6,
  150789. 42,
  150790. 5,
  150791. 43,
  150792. 4,
  150793. 44,
  150794. 3,
  150795. 45,
  150796. 2,
  150797. 46,
  150798. 1,
  150799. 47,
  150800. 0,
  150801. 48,
  150802. };
  150803. static long _vq_lengthlist__44u7__p9_2[] = {
  150804. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150805. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150806. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150807. 8,
  150808. };
  150809. static float _vq_quantthresh__44u7__p9_2[] = {
  150810. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150811. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150812. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150813. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150814. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150815. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150816. };
  150817. static long _vq_quantmap__44u7__p9_2[] = {
  150818. 47, 45, 43, 41, 39, 37, 35, 33,
  150819. 31, 29, 27, 25, 23, 21, 19, 17,
  150820. 15, 13, 11, 9, 7, 5, 3, 1,
  150821. 0, 2, 4, 6, 8, 10, 12, 14,
  150822. 16, 18, 20, 22, 24, 26, 28, 30,
  150823. 32, 34, 36, 38, 40, 42, 44, 46,
  150824. 48,
  150825. };
  150826. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150827. _vq_quantthresh__44u7__p9_2,
  150828. _vq_quantmap__44u7__p9_2,
  150829. 49,
  150830. 49
  150831. };
  150832. static static_codebook _44u7__p9_2 = {
  150833. 1, 49,
  150834. _vq_lengthlist__44u7__p9_2,
  150835. 1, -526909440, 1611661312, 6, 0,
  150836. _vq_quantlist__44u7__p9_2,
  150837. NULL,
  150838. &_vq_auxt__44u7__p9_2,
  150839. NULL,
  150840. 0
  150841. };
  150842. static long _huff_lengthlist__44u7__short[] = {
  150843. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150844. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150845. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150846. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150847. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150848. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150849. 6, 8, 5, 9,
  150850. };
  150851. static static_codebook _huff_book__44u7__short = {
  150852. 2, 100,
  150853. _huff_lengthlist__44u7__short,
  150854. 0, 0, 0, 0, 0,
  150855. NULL,
  150856. NULL,
  150857. NULL,
  150858. NULL,
  150859. 0
  150860. };
  150861. static long _huff_lengthlist__44u8__long[] = {
  150862. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150863. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150864. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150865. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150866. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150867. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150868. 10, 8, 8, 9,
  150869. };
  150870. static static_codebook _huff_book__44u8__long = {
  150871. 2, 100,
  150872. _huff_lengthlist__44u8__long,
  150873. 0, 0, 0, 0, 0,
  150874. NULL,
  150875. NULL,
  150876. NULL,
  150877. NULL,
  150878. 0
  150879. };
  150880. static long _huff_lengthlist__44u8__short[] = {
  150881. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150882. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150883. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150884. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150885. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150886. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150887. 10,10,15,17,
  150888. };
  150889. static static_codebook _huff_book__44u8__short = {
  150890. 2, 100,
  150891. _huff_lengthlist__44u8__short,
  150892. 0, 0, 0, 0, 0,
  150893. NULL,
  150894. NULL,
  150895. NULL,
  150896. NULL,
  150897. 0
  150898. };
  150899. static long _vq_quantlist__44u8_p1_0[] = {
  150900. 1,
  150901. 0,
  150902. 2,
  150903. };
  150904. static long _vq_lengthlist__44u8_p1_0[] = {
  150905. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150906. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150907. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150908. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150909. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150910. 10,
  150911. };
  150912. static float _vq_quantthresh__44u8_p1_0[] = {
  150913. -0.5, 0.5,
  150914. };
  150915. static long _vq_quantmap__44u8_p1_0[] = {
  150916. 1, 0, 2,
  150917. };
  150918. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150919. _vq_quantthresh__44u8_p1_0,
  150920. _vq_quantmap__44u8_p1_0,
  150921. 3,
  150922. 3
  150923. };
  150924. static static_codebook _44u8_p1_0 = {
  150925. 4, 81,
  150926. _vq_lengthlist__44u8_p1_0,
  150927. 1, -535822336, 1611661312, 2, 0,
  150928. _vq_quantlist__44u8_p1_0,
  150929. NULL,
  150930. &_vq_auxt__44u8_p1_0,
  150931. NULL,
  150932. 0
  150933. };
  150934. static long _vq_quantlist__44u8_p2_0[] = {
  150935. 2,
  150936. 1,
  150937. 3,
  150938. 0,
  150939. 4,
  150940. };
  150941. static long _vq_lengthlist__44u8_p2_0[] = {
  150942. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150943. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150944. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150945. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150946. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150947. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150948. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150949. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150950. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150951. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150952. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150953. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150954. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150955. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150956. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150957. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150958. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150959. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150960. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150961. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150962. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150963. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150964. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150965. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150966. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150967. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150968. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150969. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150970. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150971. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150972. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150973. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150974. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150975. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150976. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150977. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150978. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150979. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150980. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150981. 14,
  150982. };
  150983. static float _vq_quantthresh__44u8_p2_0[] = {
  150984. -1.5, -0.5, 0.5, 1.5,
  150985. };
  150986. static long _vq_quantmap__44u8_p2_0[] = {
  150987. 3, 1, 0, 2, 4,
  150988. };
  150989. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150990. _vq_quantthresh__44u8_p2_0,
  150991. _vq_quantmap__44u8_p2_0,
  150992. 5,
  150993. 5
  150994. };
  150995. static static_codebook _44u8_p2_0 = {
  150996. 4, 625,
  150997. _vq_lengthlist__44u8_p2_0,
  150998. 1, -533725184, 1611661312, 3, 0,
  150999. _vq_quantlist__44u8_p2_0,
  151000. NULL,
  151001. &_vq_auxt__44u8_p2_0,
  151002. NULL,
  151003. 0
  151004. };
  151005. static long _vq_quantlist__44u8_p3_0[] = {
  151006. 4,
  151007. 3,
  151008. 5,
  151009. 2,
  151010. 6,
  151011. 1,
  151012. 7,
  151013. 0,
  151014. 8,
  151015. };
  151016. static long _vq_lengthlist__44u8_p3_0[] = {
  151017. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151018. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151019. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151020. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151021. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151022. 12,
  151023. };
  151024. static float _vq_quantthresh__44u8_p3_0[] = {
  151025. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151026. };
  151027. static long _vq_quantmap__44u8_p3_0[] = {
  151028. 7, 5, 3, 1, 0, 2, 4, 6,
  151029. 8,
  151030. };
  151031. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151032. _vq_quantthresh__44u8_p3_0,
  151033. _vq_quantmap__44u8_p3_0,
  151034. 9,
  151035. 9
  151036. };
  151037. static static_codebook _44u8_p3_0 = {
  151038. 2, 81,
  151039. _vq_lengthlist__44u8_p3_0,
  151040. 1, -531628032, 1611661312, 4, 0,
  151041. _vq_quantlist__44u8_p3_0,
  151042. NULL,
  151043. &_vq_auxt__44u8_p3_0,
  151044. NULL,
  151045. 0
  151046. };
  151047. static long _vq_quantlist__44u8_p4_0[] = {
  151048. 8,
  151049. 7,
  151050. 9,
  151051. 6,
  151052. 10,
  151053. 5,
  151054. 11,
  151055. 4,
  151056. 12,
  151057. 3,
  151058. 13,
  151059. 2,
  151060. 14,
  151061. 1,
  151062. 15,
  151063. 0,
  151064. 16,
  151065. };
  151066. static long _vq_lengthlist__44u8_p4_0[] = {
  151067. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151068. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151069. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151070. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151071. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151072. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151073. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151074. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151075. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151076. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151077. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151078. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151079. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151080. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151081. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151082. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151083. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151084. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151085. 14,
  151086. };
  151087. static float _vq_quantthresh__44u8_p4_0[] = {
  151088. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151089. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151090. };
  151091. static long _vq_quantmap__44u8_p4_0[] = {
  151092. 15, 13, 11, 9, 7, 5, 3, 1,
  151093. 0, 2, 4, 6, 8, 10, 12, 14,
  151094. 16,
  151095. };
  151096. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151097. _vq_quantthresh__44u8_p4_0,
  151098. _vq_quantmap__44u8_p4_0,
  151099. 17,
  151100. 17
  151101. };
  151102. static static_codebook _44u8_p4_0 = {
  151103. 2, 289,
  151104. _vq_lengthlist__44u8_p4_0,
  151105. 1, -529530880, 1611661312, 5, 0,
  151106. _vq_quantlist__44u8_p4_0,
  151107. NULL,
  151108. &_vq_auxt__44u8_p4_0,
  151109. NULL,
  151110. 0
  151111. };
  151112. static long _vq_quantlist__44u8_p5_0[] = {
  151113. 1,
  151114. 0,
  151115. 2,
  151116. };
  151117. static long _vq_lengthlist__44u8_p5_0[] = {
  151118. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151119. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151120. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151121. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151122. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151123. 10,
  151124. };
  151125. static float _vq_quantthresh__44u8_p5_0[] = {
  151126. -5.5, 5.5,
  151127. };
  151128. static long _vq_quantmap__44u8_p5_0[] = {
  151129. 1, 0, 2,
  151130. };
  151131. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151132. _vq_quantthresh__44u8_p5_0,
  151133. _vq_quantmap__44u8_p5_0,
  151134. 3,
  151135. 3
  151136. };
  151137. static static_codebook _44u8_p5_0 = {
  151138. 4, 81,
  151139. _vq_lengthlist__44u8_p5_0,
  151140. 1, -529137664, 1618345984, 2, 0,
  151141. _vq_quantlist__44u8_p5_0,
  151142. NULL,
  151143. &_vq_auxt__44u8_p5_0,
  151144. NULL,
  151145. 0
  151146. };
  151147. static long _vq_quantlist__44u8_p5_1[] = {
  151148. 5,
  151149. 4,
  151150. 6,
  151151. 3,
  151152. 7,
  151153. 2,
  151154. 8,
  151155. 1,
  151156. 9,
  151157. 0,
  151158. 10,
  151159. };
  151160. static long _vq_lengthlist__44u8_p5_1[] = {
  151161. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151162. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151163. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151164. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151165. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151166. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151167. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151168. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151169. };
  151170. static float _vq_quantthresh__44u8_p5_1[] = {
  151171. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151172. 3.5, 4.5,
  151173. };
  151174. static long _vq_quantmap__44u8_p5_1[] = {
  151175. 9, 7, 5, 3, 1, 0, 2, 4,
  151176. 6, 8, 10,
  151177. };
  151178. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151179. _vq_quantthresh__44u8_p5_1,
  151180. _vq_quantmap__44u8_p5_1,
  151181. 11,
  151182. 11
  151183. };
  151184. static static_codebook _44u8_p5_1 = {
  151185. 2, 121,
  151186. _vq_lengthlist__44u8_p5_1,
  151187. 1, -531365888, 1611661312, 4, 0,
  151188. _vq_quantlist__44u8_p5_1,
  151189. NULL,
  151190. &_vq_auxt__44u8_p5_1,
  151191. NULL,
  151192. 0
  151193. };
  151194. static long _vq_quantlist__44u8_p6_0[] = {
  151195. 6,
  151196. 5,
  151197. 7,
  151198. 4,
  151199. 8,
  151200. 3,
  151201. 9,
  151202. 2,
  151203. 10,
  151204. 1,
  151205. 11,
  151206. 0,
  151207. 12,
  151208. };
  151209. static long _vq_lengthlist__44u8_p6_0[] = {
  151210. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151211. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151212. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151213. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151214. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151215. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151216. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151217. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151218. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151219. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151220. 11,11,11,11,11,12,11,12,12,
  151221. };
  151222. static float _vq_quantthresh__44u8_p6_0[] = {
  151223. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151224. 12.5, 17.5, 22.5, 27.5,
  151225. };
  151226. static long _vq_quantmap__44u8_p6_0[] = {
  151227. 11, 9, 7, 5, 3, 1, 0, 2,
  151228. 4, 6, 8, 10, 12,
  151229. };
  151230. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151231. _vq_quantthresh__44u8_p6_0,
  151232. _vq_quantmap__44u8_p6_0,
  151233. 13,
  151234. 13
  151235. };
  151236. static static_codebook _44u8_p6_0 = {
  151237. 2, 169,
  151238. _vq_lengthlist__44u8_p6_0,
  151239. 1, -526516224, 1616117760, 4, 0,
  151240. _vq_quantlist__44u8_p6_0,
  151241. NULL,
  151242. &_vq_auxt__44u8_p6_0,
  151243. NULL,
  151244. 0
  151245. };
  151246. static long _vq_quantlist__44u8_p6_1[] = {
  151247. 2,
  151248. 1,
  151249. 3,
  151250. 0,
  151251. 4,
  151252. };
  151253. static long _vq_lengthlist__44u8_p6_1[] = {
  151254. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151255. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151256. };
  151257. static float _vq_quantthresh__44u8_p6_1[] = {
  151258. -1.5, -0.5, 0.5, 1.5,
  151259. };
  151260. static long _vq_quantmap__44u8_p6_1[] = {
  151261. 3, 1, 0, 2, 4,
  151262. };
  151263. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151264. _vq_quantthresh__44u8_p6_1,
  151265. _vq_quantmap__44u8_p6_1,
  151266. 5,
  151267. 5
  151268. };
  151269. static static_codebook _44u8_p6_1 = {
  151270. 2, 25,
  151271. _vq_lengthlist__44u8_p6_1,
  151272. 1, -533725184, 1611661312, 3, 0,
  151273. _vq_quantlist__44u8_p6_1,
  151274. NULL,
  151275. &_vq_auxt__44u8_p6_1,
  151276. NULL,
  151277. 0
  151278. };
  151279. static long _vq_quantlist__44u8_p7_0[] = {
  151280. 6,
  151281. 5,
  151282. 7,
  151283. 4,
  151284. 8,
  151285. 3,
  151286. 9,
  151287. 2,
  151288. 10,
  151289. 1,
  151290. 11,
  151291. 0,
  151292. 12,
  151293. };
  151294. static long _vq_lengthlist__44u8_p7_0[] = {
  151295. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151296. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151297. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151298. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151299. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151300. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151301. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151302. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151303. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151304. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151305. 13,13,14,14,14,15,15,15,16,
  151306. };
  151307. static float _vq_quantthresh__44u8_p7_0[] = {
  151308. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151309. 27.5, 38.5, 49.5, 60.5,
  151310. };
  151311. static long _vq_quantmap__44u8_p7_0[] = {
  151312. 11, 9, 7, 5, 3, 1, 0, 2,
  151313. 4, 6, 8, 10, 12,
  151314. };
  151315. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151316. _vq_quantthresh__44u8_p7_0,
  151317. _vq_quantmap__44u8_p7_0,
  151318. 13,
  151319. 13
  151320. };
  151321. static static_codebook _44u8_p7_0 = {
  151322. 2, 169,
  151323. _vq_lengthlist__44u8_p7_0,
  151324. 1, -523206656, 1618345984, 4, 0,
  151325. _vq_quantlist__44u8_p7_0,
  151326. NULL,
  151327. &_vq_auxt__44u8_p7_0,
  151328. NULL,
  151329. 0
  151330. };
  151331. static long _vq_quantlist__44u8_p7_1[] = {
  151332. 5,
  151333. 4,
  151334. 6,
  151335. 3,
  151336. 7,
  151337. 2,
  151338. 8,
  151339. 1,
  151340. 9,
  151341. 0,
  151342. 10,
  151343. };
  151344. static long _vq_lengthlist__44u8_p7_1[] = {
  151345. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151346. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151347. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151348. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151349. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151350. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151351. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151352. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151353. };
  151354. static float _vq_quantthresh__44u8_p7_1[] = {
  151355. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151356. 3.5, 4.5,
  151357. };
  151358. static long _vq_quantmap__44u8_p7_1[] = {
  151359. 9, 7, 5, 3, 1, 0, 2, 4,
  151360. 6, 8, 10,
  151361. };
  151362. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151363. _vq_quantthresh__44u8_p7_1,
  151364. _vq_quantmap__44u8_p7_1,
  151365. 11,
  151366. 11
  151367. };
  151368. static static_codebook _44u8_p7_1 = {
  151369. 2, 121,
  151370. _vq_lengthlist__44u8_p7_1,
  151371. 1, -531365888, 1611661312, 4, 0,
  151372. _vq_quantlist__44u8_p7_1,
  151373. NULL,
  151374. &_vq_auxt__44u8_p7_1,
  151375. NULL,
  151376. 0
  151377. };
  151378. static long _vq_quantlist__44u8_p8_0[] = {
  151379. 7,
  151380. 6,
  151381. 8,
  151382. 5,
  151383. 9,
  151384. 4,
  151385. 10,
  151386. 3,
  151387. 11,
  151388. 2,
  151389. 12,
  151390. 1,
  151391. 13,
  151392. 0,
  151393. 14,
  151394. };
  151395. static long _vq_lengthlist__44u8_p8_0[] = {
  151396. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151397. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151398. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151399. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151400. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151401. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151402. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151403. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151404. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151405. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151406. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151407. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151408. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151409. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151410. 17,
  151411. };
  151412. static float _vq_quantthresh__44u8_p8_0[] = {
  151413. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151414. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151415. };
  151416. static long _vq_quantmap__44u8_p8_0[] = {
  151417. 13, 11, 9, 7, 5, 3, 1, 0,
  151418. 2, 4, 6, 8, 10, 12, 14,
  151419. };
  151420. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151421. _vq_quantthresh__44u8_p8_0,
  151422. _vq_quantmap__44u8_p8_0,
  151423. 15,
  151424. 15
  151425. };
  151426. static static_codebook _44u8_p8_0 = {
  151427. 2, 225,
  151428. _vq_lengthlist__44u8_p8_0,
  151429. 1, -520986624, 1620377600, 4, 0,
  151430. _vq_quantlist__44u8_p8_0,
  151431. NULL,
  151432. &_vq_auxt__44u8_p8_0,
  151433. NULL,
  151434. 0
  151435. };
  151436. static long _vq_quantlist__44u8_p8_1[] = {
  151437. 10,
  151438. 9,
  151439. 11,
  151440. 8,
  151441. 12,
  151442. 7,
  151443. 13,
  151444. 6,
  151445. 14,
  151446. 5,
  151447. 15,
  151448. 4,
  151449. 16,
  151450. 3,
  151451. 17,
  151452. 2,
  151453. 18,
  151454. 1,
  151455. 19,
  151456. 0,
  151457. 20,
  151458. };
  151459. static long _vq_lengthlist__44u8_p8_1[] = {
  151460. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151461. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151462. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151463. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151464. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151465. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151466. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151467. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151468. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151469. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151470. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151471. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151472. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151473. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151474. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151475. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151476. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151477. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151478. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151479. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151480. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151481. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151482. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151483. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151484. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151485. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151486. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151487. 10,10,10,10,10,10,10,10,10,
  151488. };
  151489. static float _vq_quantthresh__44u8_p8_1[] = {
  151490. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151491. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151492. 6.5, 7.5, 8.5, 9.5,
  151493. };
  151494. static long _vq_quantmap__44u8_p8_1[] = {
  151495. 19, 17, 15, 13, 11, 9, 7, 5,
  151496. 3, 1, 0, 2, 4, 6, 8, 10,
  151497. 12, 14, 16, 18, 20,
  151498. };
  151499. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151500. _vq_quantthresh__44u8_p8_1,
  151501. _vq_quantmap__44u8_p8_1,
  151502. 21,
  151503. 21
  151504. };
  151505. static static_codebook _44u8_p8_1 = {
  151506. 2, 441,
  151507. _vq_lengthlist__44u8_p8_1,
  151508. 1, -529268736, 1611661312, 5, 0,
  151509. _vq_quantlist__44u8_p8_1,
  151510. NULL,
  151511. &_vq_auxt__44u8_p8_1,
  151512. NULL,
  151513. 0
  151514. };
  151515. static long _vq_quantlist__44u8_p9_0[] = {
  151516. 4,
  151517. 3,
  151518. 5,
  151519. 2,
  151520. 6,
  151521. 1,
  151522. 7,
  151523. 0,
  151524. 8,
  151525. };
  151526. static long _vq_lengthlist__44u8_p9_0[] = {
  151527. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151528. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151530. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151531. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151532. 8,
  151533. };
  151534. static float _vq_quantthresh__44u8_p9_0[] = {
  151535. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151536. };
  151537. static long _vq_quantmap__44u8_p9_0[] = {
  151538. 7, 5, 3, 1, 0, 2, 4, 6,
  151539. 8,
  151540. };
  151541. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151542. _vq_quantthresh__44u8_p9_0,
  151543. _vq_quantmap__44u8_p9_0,
  151544. 9,
  151545. 9
  151546. };
  151547. static static_codebook _44u8_p9_0 = {
  151548. 2, 81,
  151549. _vq_lengthlist__44u8_p9_0,
  151550. 1, -511895552, 1631393792, 4, 0,
  151551. _vq_quantlist__44u8_p9_0,
  151552. NULL,
  151553. &_vq_auxt__44u8_p9_0,
  151554. NULL,
  151555. 0
  151556. };
  151557. static long _vq_quantlist__44u8_p9_1[] = {
  151558. 9,
  151559. 8,
  151560. 10,
  151561. 7,
  151562. 11,
  151563. 6,
  151564. 12,
  151565. 5,
  151566. 13,
  151567. 4,
  151568. 14,
  151569. 3,
  151570. 15,
  151571. 2,
  151572. 16,
  151573. 1,
  151574. 17,
  151575. 0,
  151576. 18,
  151577. };
  151578. static long _vq_lengthlist__44u8_p9_1[] = {
  151579. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151580. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151581. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151582. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151583. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151584. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151585. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151586. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151587. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151588. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151589. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151590. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151591. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151592. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151593. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151594. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151595. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151596. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151597. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151598. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151599. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151600. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151601. 16,15,16,16,16,16,16,16,16,
  151602. };
  151603. static float _vq_quantthresh__44u8_p9_1[] = {
  151604. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151605. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151606. 367.5, 416.5,
  151607. };
  151608. static long _vq_quantmap__44u8_p9_1[] = {
  151609. 17, 15, 13, 11, 9, 7, 5, 3,
  151610. 1, 0, 2, 4, 6, 8, 10, 12,
  151611. 14, 16, 18,
  151612. };
  151613. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151614. _vq_quantthresh__44u8_p9_1,
  151615. _vq_quantmap__44u8_p9_1,
  151616. 19,
  151617. 19
  151618. };
  151619. static static_codebook _44u8_p9_1 = {
  151620. 2, 361,
  151621. _vq_lengthlist__44u8_p9_1,
  151622. 1, -518287360, 1622704128, 5, 0,
  151623. _vq_quantlist__44u8_p9_1,
  151624. NULL,
  151625. &_vq_auxt__44u8_p9_1,
  151626. NULL,
  151627. 0
  151628. };
  151629. static long _vq_quantlist__44u8_p9_2[] = {
  151630. 24,
  151631. 23,
  151632. 25,
  151633. 22,
  151634. 26,
  151635. 21,
  151636. 27,
  151637. 20,
  151638. 28,
  151639. 19,
  151640. 29,
  151641. 18,
  151642. 30,
  151643. 17,
  151644. 31,
  151645. 16,
  151646. 32,
  151647. 15,
  151648. 33,
  151649. 14,
  151650. 34,
  151651. 13,
  151652. 35,
  151653. 12,
  151654. 36,
  151655. 11,
  151656. 37,
  151657. 10,
  151658. 38,
  151659. 9,
  151660. 39,
  151661. 8,
  151662. 40,
  151663. 7,
  151664. 41,
  151665. 6,
  151666. 42,
  151667. 5,
  151668. 43,
  151669. 4,
  151670. 44,
  151671. 3,
  151672. 45,
  151673. 2,
  151674. 46,
  151675. 1,
  151676. 47,
  151677. 0,
  151678. 48,
  151679. };
  151680. static long _vq_lengthlist__44u8_p9_2[] = {
  151681. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151682. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151683. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151684. 7,
  151685. };
  151686. static float _vq_quantthresh__44u8_p9_2[] = {
  151687. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151688. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151689. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151690. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151691. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151692. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151693. };
  151694. static long _vq_quantmap__44u8_p9_2[] = {
  151695. 47, 45, 43, 41, 39, 37, 35, 33,
  151696. 31, 29, 27, 25, 23, 21, 19, 17,
  151697. 15, 13, 11, 9, 7, 5, 3, 1,
  151698. 0, 2, 4, 6, 8, 10, 12, 14,
  151699. 16, 18, 20, 22, 24, 26, 28, 30,
  151700. 32, 34, 36, 38, 40, 42, 44, 46,
  151701. 48,
  151702. };
  151703. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151704. _vq_quantthresh__44u8_p9_2,
  151705. _vq_quantmap__44u8_p9_2,
  151706. 49,
  151707. 49
  151708. };
  151709. static static_codebook _44u8_p9_2 = {
  151710. 1, 49,
  151711. _vq_lengthlist__44u8_p9_2,
  151712. 1, -526909440, 1611661312, 6, 0,
  151713. _vq_quantlist__44u8_p9_2,
  151714. NULL,
  151715. &_vq_auxt__44u8_p9_2,
  151716. NULL,
  151717. 0
  151718. };
  151719. static long _huff_lengthlist__44u9__long[] = {
  151720. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151721. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151722. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151723. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151724. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151725. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151726. 10, 8, 8, 9,
  151727. };
  151728. static static_codebook _huff_book__44u9__long = {
  151729. 2, 100,
  151730. _huff_lengthlist__44u9__long,
  151731. 0, 0, 0, 0, 0,
  151732. NULL,
  151733. NULL,
  151734. NULL,
  151735. NULL,
  151736. 0
  151737. };
  151738. static long _huff_lengthlist__44u9__short[] = {
  151739. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151740. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151741. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151742. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151743. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151744. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151745. 9, 9,12,15,
  151746. };
  151747. static static_codebook _huff_book__44u9__short = {
  151748. 2, 100,
  151749. _huff_lengthlist__44u9__short,
  151750. 0, 0, 0, 0, 0,
  151751. NULL,
  151752. NULL,
  151753. NULL,
  151754. NULL,
  151755. 0
  151756. };
  151757. static long _vq_quantlist__44u9_p1_0[] = {
  151758. 1,
  151759. 0,
  151760. 2,
  151761. };
  151762. static long _vq_lengthlist__44u9_p1_0[] = {
  151763. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151764. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151765. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151766. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151767. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151768. 10,
  151769. };
  151770. static float _vq_quantthresh__44u9_p1_0[] = {
  151771. -0.5, 0.5,
  151772. };
  151773. static long _vq_quantmap__44u9_p1_0[] = {
  151774. 1, 0, 2,
  151775. };
  151776. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151777. _vq_quantthresh__44u9_p1_0,
  151778. _vq_quantmap__44u9_p1_0,
  151779. 3,
  151780. 3
  151781. };
  151782. static static_codebook _44u9_p1_0 = {
  151783. 4, 81,
  151784. _vq_lengthlist__44u9_p1_0,
  151785. 1, -535822336, 1611661312, 2, 0,
  151786. _vq_quantlist__44u9_p1_0,
  151787. NULL,
  151788. &_vq_auxt__44u9_p1_0,
  151789. NULL,
  151790. 0
  151791. };
  151792. static long _vq_quantlist__44u9_p2_0[] = {
  151793. 2,
  151794. 1,
  151795. 3,
  151796. 0,
  151797. 4,
  151798. };
  151799. static long _vq_lengthlist__44u9_p2_0[] = {
  151800. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151801. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151802. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151803. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151804. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151805. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151806. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151807. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151808. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151809. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151810. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151811. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151812. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151813. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151814. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151815. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151816. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151817. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151818. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151819. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151820. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151821. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151822. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151823. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151824. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151825. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151826. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151827. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151828. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151829. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151830. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151831. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151832. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151833. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151834. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151835. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151836. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151837. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151838. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151839. 14,
  151840. };
  151841. static float _vq_quantthresh__44u9_p2_0[] = {
  151842. -1.5, -0.5, 0.5, 1.5,
  151843. };
  151844. static long _vq_quantmap__44u9_p2_0[] = {
  151845. 3, 1, 0, 2, 4,
  151846. };
  151847. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151848. _vq_quantthresh__44u9_p2_0,
  151849. _vq_quantmap__44u9_p2_0,
  151850. 5,
  151851. 5
  151852. };
  151853. static static_codebook _44u9_p2_0 = {
  151854. 4, 625,
  151855. _vq_lengthlist__44u9_p2_0,
  151856. 1, -533725184, 1611661312, 3, 0,
  151857. _vq_quantlist__44u9_p2_0,
  151858. NULL,
  151859. &_vq_auxt__44u9_p2_0,
  151860. NULL,
  151861. 0
  151862. };
  151863. static long _vq_quantlist__44u9_p3_0[] = {
  151864. 4,
  151865. 3,
  151866. 5,
  151867. 2,
  151868. 6,
  151869. 1,
  151870. 7,
  151871. 0,
  151872. 8,
  151873. };
  151874. static long _vq_lengthlist__44u9_p3_0[] = {
  151875. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151876. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151877. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151878. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151879. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151880. 11,
  151881. };
  151882. static float _vq_quantthresh__44u9_p3_0[] = {
  151883. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151884. };
  151885. static long _vq_quantmap__44u9_p3_0[] = {
  151886. 7, 5, 3, 1, 0, 2, 4, 6,
  151887. 8,
  151888. };
  151889. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151890. _vq_quantthresh__44u9_p3_0,
  151891. _vq_quantmap__44u9_p3_0,
  151892. 9,
  151893. 9
  151894. };
  151895. static static_codebook _44u9_p3_0 = {
  151896. 2, 81,
  151897. _vq_lengthlist__44u9_p3_0,
  151898. 1, -531628032, 1611661312, 4, 0,
  151899. _vq_quantlist__44u9_p3_0,
  151900. NULL,
  151901. &_vq_auxt__44u9_p3_0,
  151902. NULL,
  151903. 0
  151904. };
  151905. static long _vq_quantlist__44u9_p4_0[] = {
  151906. 8,
  151907. 7,
  151908. 9,
  151909. 6,
  151910. 10,
  151911. 5,
  151912. 11,
  151913. 4,
  151914. 12,
  151915. 3,
  151916. 13,
  151917. 2,
  151918. 14,
  151919. 1,
  151920. 15,
  151921. 0,
  151922. 16,
  151923. };
  151924. static long _vq_lengthlist__44u9_p4_0[] = {
  151925. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151926. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151927. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151928. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151929. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151930. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151931. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151932. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151933. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151934. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151935. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151936. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151937. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151938. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151939. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151940. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151941. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151942. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151943. 14,
  151944. };
  151945. static float _vq_quantthresh__44u9_p4_0[] = {
  151946. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151947. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151948. };
  151949. static long _vq_quantmap__44u9_p4_0[] = {
  151950. 15, 13, 11, 9, 7, 5, 3, 1,
  151951. 0, 2, 4, 6, 8, 10, 12, 14,
  151952. 16,
  151953. };
  151954. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151955. _vq_quantthresh__44u9_p4_0,
  151956. _vq_quantmap__44u9_p4_0,
  151957. 17,
  151958. 17
  151959. };
  151960. static static_codebook _44u9_p4_0 = {
  151961. 2, 289,
  151962. _vq_lengthlist__44u9_p4_0,
  151963. 1, -529530880, 1611661312, 5, 0,
  151964. _vq_quantlist__44u9_p4_0,
  151965. NULL,
  151966. &_vq_auxt__44u9_p4_0,
  151967. NULL,
  151968. 0
  151969. };
  151970. static long _vq_quantlist__44u9_p5_0[] = {
  151971. 1,
  151972. 0,
  151973. 2,
  151974. };
  151975. static long _vq_lengthlist__44u9_p5_0[] = {
  151976. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151977. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151978. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151979. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151980. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151981. 10,
  151982. };
  151983. static float _vq_quantthresh__44u9_p5_0[] = {
  151984. -5.5, 5.5,
  151985. };
  151986. static long _vq_quantmap__44u9_p5_0[] = {
  151987. 1, 0, 2,
  151988. };
  151989. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151990. _vq_quantthresh__44u9_p5_0,
  151991. _vq_quantmap__44u9_p5_0,
  151992. 3,
  151993. 3
  151994. };
  151995. static static_codebook _44u9_p5_0 = {
  151996. 4, 81,
  151997. _vq_lengthlist__44u9_p5_0,
  151998. 1, -529137664, 1618345984, 2, 0,
  151999. _vq_quantlist__44u9_p5_0,
  152000. NULL,
  152001. &_vq_auxt__44u9_p5_0,
  152002. NULL,
  152003. 0
  152004. };
  152005. static long _vq_quantlist__44u9_p5_1[] = {
  152006. 5,
  152007. 4,
  152008. 6,
  152009. 3,
  152010. 7,
  152011. 2,
  152012. 8,
  152013. 1,
  152014. 9,
  152015. 0,
  152016. 10,
  152017. };
  152018. static long _vq_lengthlist__44u9_p5_1[] = {
  152019. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152020. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152021. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152022. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152023. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152024. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152025. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152026. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152027. };
  152028. static float _vq_quantthresh__44u9_p5_1[] = {
  152029. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152030. 3.5, 4.5,
  152031. };
  152032. static long _vq_quantmap__44u9_p5_1[] = {
  152033. 9, 7, 5, 3, 1, 0, 2, 4,
  152034. 6, 8, 10,
  152035. };
  152036. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152037. _vq_quantthresh__44u9_p5_1,
  152038. _vq_quantmap__44u9_p5_1,
  152039. 11,
  152040. 11
  152041. };
  152042. static static_codebook _44u9_p5_1 = {
  152043. 2, 121,
  152044. _vq_lengthlist__44u9_p5_1,
  152045. 1, -531365888, 1611661312, 4, 0,
  152046. _vq_quantlist__44u9_p5_1,
  152047. NULL,
  152048. &_vq_auxt__44u9_p5_1,
  152049. NULL,
  152050. 0
  152051. };
  152052. static long _vq_quantlist__44u9_p6_0[] = {
  152053. 6,
  152054. 5,
  152055. 7,
  152056. 4,
  152057. 8,
  152058. 3,
  152059. 9,
  152060. 2,
  152061. 10,
  152062. 1,
  152063. 11,
  152064. 0,
  152065. 12,
  152066. };
  152067. static long _vq_lengthlist__44u9_p6_0[] = {
  152068. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152069. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152070. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152071. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152072. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152073. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152074. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152075. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152076. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152077. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152078. 10,11,11,11,11,12,11,12,12,
  152079. };
  152080. static float _vq_quantthresh__44u9_p6_0[] = {
  152081. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152082. 12.5, 17.5, 22.5, 27.5,
  152083. };
  152084. static long _vq_quantmap__44u9_p6_0[] = {
  152085. 11, 9, 7, 5, 3, 1, 0, 2,
  152086. 4, 6, 8, 10, 12,
  152087. };
  152088. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152089. _vq_quantthresh__44u9_p6_0,
  152090. _vq_quantmap__44u9_p6_0,
  152091. 13,
  152092. 13
  152093. };
  152094. static static_codebook _44u9_p6_0 = {
  152095. 2, 169,
  152096. _vq_lengthlist__44u9_p6_0,
  152097. 1, -526516224, 1616117760, 4, 0,
  152098. _vq_quantlist__44u9_p6_0,
  152099. NULL,
  152100. &_vq_auxt__44u9_p6_0,
  152101. NULL,
  152102. 0
  152103. };
  152104. static long _vq_quantlist__44u9_p6_1[] = {
  152105. 2,
  152106. 1,
  152107. 3,
  152108. 0,
  152109. 4,
  152110. };
  152111. static long _vq_lengthlist__44u9_p6_1[] = {
  152112. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152113. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152114. };
  152115. static float _vq_quantthresh__44u9_p6_1[] = {
  152116. -1.5, -0.5, 0.5, 1.5,
  152117. };
  152118. static long _vq_quantmap__44u9_p6_1[] = {
  152119. 3, 1, 0, 2, 4,
  152120. };
  152121. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152122. _vq_quantthresh__44u9_p6_1,
  152123. _vq_quantmap__44u9_p6_1,
  152124. 5,
  152125. 5
  152126. };
  152127. static static_codebook _44u9_p6_1 = {
  152128. 2, 25,
  152129. _vq_lengthlist__44u9_p6_1,
  152130. 1, -533725184, 1611661312, 3, 0,
  152131. _vq_quantlist__44u9_p6_1,
  152132. NULL,
  152133. &_vq_auxt__44u9_p6_1,
  152134. NULL,
  152135. 0
  152136. };
  152137. static long _vq_quantlist__44u9_p7_0[] = {
  152138. 6,
  152139. 5,
  152140. 7,
  152141. 4,
  152142. 8,
  152143. 3,
  152144. 9,
  152145. 2,
  152146. 10,
  152147. 1,
  152148. 11,
  152149. 0,
  152150. 12,
  152151. };
  152152. static long _vq_lengthlist__44u9_p7_0[] = {
  152153. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152154. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152155. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152156. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152157. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152158. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152159. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152160. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152161. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152162. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152163. 12,13,13,14,14,14,15,15,15,
  152164. };
  152165. static float _vq_quantthresh__44u9_p7_0[] = {
  152166. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152167. 27.5, 38.5, 49.5, 60.5,
  152168. };
  152169. static long _vq_quantmap__44u9_p7_0[] = {
  152170. 11, 9, 7, 5, 3, 1, 0, 2,
  152171. 4, 6, 8, 10, 12,
  152172. };
  152173. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152174. _vq_quantthresh__44u9_p7_0,
  152175. _vq_quantmap__44u9_p7_0,
  152176. 13,
  152177. 13
  152178. };
  152179. static static_codebook _44u9_p7_0 = {
  152180. 2, 169,
  152181. _vq_lengthlist__44u9_p7_0,
  152182. 1, -523206656, 1618345984, 4, 0,
  152183. _vq_quantlist__44u9_p7_0,
  152184. NULL,
  152185. &_vq_auxt__44u9_p7_0,
  152186. NULL,
  152187. 0
  152188. };
  152189. static long _vq_quantlist__44u9_p7_1[] = {
  152190. 5,
  152191. 4,
  152192. 6,
  152193. 3,
  152194. 7,
  152195. 2,
  152196. 8,
  152197. 1,
  152198. 9,
  152199. 0,
  152200. 10,
  152201. };
  152202. static long _vq_lengthlist__44u9_p7_1[] = {
  152203. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152204. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152205. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152206. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152207. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152208. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152209. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152210. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152211. };
  152212. static float _vq_quantthresh__44u9_p7_1[] = {
  152213. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152214. 3.5, 4.5,
  152215. };
  152216. static long _vq_quantmap__44u9_p7_1[] = {
  152217. 9, 7, 5, 3, 1, 0, 2, 4,
  152218. 6, 8, 10,
  152219. };
  152220. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152221. _vq_quantthresh__44u9_p7_1,
  152222. _vq_quantmap__44u9_p7_1,
  152223. 11,
  152224. 11
  152225. };
  152226. static static_codebook _44u9_p7_1 = {
  152227. 2, 121,
  152228. _vq_lengthlist__44u9_p7_1,
  152229. 1, -531365888, 1611661312, 4, 0,
  152230. _vq_quantlist__44u9_p7_1,
  152231. NULL,
  152232. &_vq_auxt__44u9_p7_1,
  152233. NULL,
  152234. 0
  152235. };
  152236. static long _vq_quantlist__44u9_p8_0[] = {
  152237. 7,
  152238. 6,
  152239. 8,
  152240. 5,
  152241. 9,
  152242. 4,
  152243. 10,
  152244. 3,
  152245. 11,
  152246. 2,
  152247. 12,
  152248. 1,
  152249. 13,
  152250. 0,
  152251. 14,
  152252. };
  152253. static long _vq_lengthlist__44u9_p8_0[] = {
  152254. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152255. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152256. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152257. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152258. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152259. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152260. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152261. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152262. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152263. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152264. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152265. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152266. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152267. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152268. 15,
  152269. };
  152270. static float _vq_quantthresh__44u9_p8_0[] = {
  152271. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152272. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152273. };
  152274. static long _vq_quantmap__44u9_p8_0[] = {
  152275. 13, 11, 9, 7, 5, 3, 1, 0,
  152276. 2, 4, 6, 8, 10, 12, 14,
  152277. };
  152278. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152279. _vq_quantthresh__44u9_p8_0,
  152280. _vq_quantmap__44u9_p8_0,
  152281. 15,
  152282. 15
  152283. };
  152284. static static_codebook _44u9_p8_0 = {
  152285. 2, 225,
  152286. _vq_lengthlist__44u9_p8_0,
  152287. 1, -520986624, 1620377600, 4, 0,
  152288. _vq_quantlist__44u9_p8_0,
  152289. NULL,
  152290. &_vq_auxt__44u9_p8_0,
  152291. NULL,
  152292. 0
  152293. };
  152294. static long _vq_quantlist__44u9_p8_1[] = {
  152295. 10,
  152296. 9,
  152297. 11,
  152298. 8,
  152299. 12,
  152300. 7,
  152301. 13,
  152302. 6,
  152303. 14,
  152304. 5,
  152305. 15,
  152306. 4,
  152307. 16,
  152308. 3,
  152309. 17,
  152310. 2,
  152311. 18,
  152312. 1,
  152313. 19,
  152314. 0,
  152315. 20,
  152316. };
  152317. static long _vq_lengthlist__44u9_p8_1[] = {
  152318. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152319. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152320. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152321. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152322. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152323. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152324. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152325. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152326. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152327. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152328. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152329. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152330. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152331. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152332. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152333. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152334. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152335. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152336. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152337. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152338. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152339. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152340. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152341. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152343. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152344. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152345. 10,10,10,10,10,10,10,10,10,
  152346. };
  152347. static float _vq_quantthresh__44u9_p8_1[] = {
  152348. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152349. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152350. 6.5, 7.5, 8.5, 9.5,
  152351. };
  152352. static long _vq_quantmap__44u9_p8_1[] = {
  152353. 19, 17, 15, 13, 11, 9, 7, 5,
  152354. 3, 1, 0, 2, 4, 6, 8, 10,
  152355. 12, 14, 16, 18, 20,
  152356. };
  152357. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152358. _vq_quantthresh__44u9_p8_1,
  152359. _vq_quantmap__44u9_p8_1,
  152360. 21,
  152361. 21
  152362. };
  152363. static static_codebook _44u9_p8_1 = {
  152364. 2, 441,
  152365. _vq_lengthlist__44u9_p8_1,
  152366. 1, -529268736, 1611661312, 5, 0,
  152367. _vq_quantlist__44u9_p8_1,
  152368. NULL,
  152369. &_vq_auxt__44u9_p8_1,
  152370. NULL,
  152371. 0
  152372. };
  152373. static long _vq_quantlist__44u9_p9_0[] = {
  152374. 7,
  152375. 6,
  152376. 8,
  152377. 5,
  152378. 9,
  152379. 4,
  152380. 10,
  152381. 3,
  152382. 11,
  152383. 2,
  152384. 12,
  152385. 1,
  152386. 13,
  152387. 0,
  152388. 14,
  152389. };
  152390. static long _vq_lengthlist__44u9_p9_0[] = {
  152391. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152392. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152393. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152395. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152398. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152399. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152401. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152402. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152403. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152404. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152405. 10,
  152406. };
  152407. static float _vq_quantthresh__44u9_p9_0[] = {
  152408. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152409. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152410. };
  152411. static long _vq_quantmap__44u9_p9_0[] = {
  152412. 13, 11, 9, 7, 5, 3, 1, 0,
  152413. 2, 4, 6, 8, 10, 12, 14,
  152414. };
  152415. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152416. _vq_quantthresh__44u9_p9_0,
  152417. _vq_quantmap__44u9_p9_0,
  152418. 15,
  152419. 15
  152420. };
  152421. static static_codebook _44u9_p9_0 = {
  152422. 2, 225,
  152423. _vq_lengthlist__44u9_p9_0,
  152424. 1, -510036736, 1631393792, 4, 0,
  152425. _vq_quantlist__44u9_p9_0,
  152426. NULL,
  152427. &_vq_auxt__44u9_p9_0,
  152428. NULL,
  152429. 0
  152430. };
  152431. static long _vq_quantlist__44u9_p9_1[] = {
  152432. 9,
  152433. 8,
  152434. 10,
  152435. 7,
  152436. 11,
  152437. 6,
  152438. 12,
  152439. 5,
  152440. 13,
  152441. 4,
  152442. 14,
  152443. 3,
  152444. 15,
  152445. 2,
  152446. 16,
  152447. 1,
  152448. 17,
  152449. 0,
  152450. 18,
  152451. };
  152452. static long _vq_lengthlist__44u9_p9_1[] = {
  152453. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152454. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152455. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152456. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152457. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152458. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152459. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152460. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152461. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152462. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152463. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152464. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152465. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152466. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152467. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152468. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152469. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152470. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152471. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152472. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152473. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152474. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152475. 17,17,15,17,15,17,16,16,17,
  152476. };
  152477. static float _vq_quantthresh__44u9_p9_1[] = {
  152478. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152479. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152480. 367.5, 416.5,
  152481. };
  152482. static long _vq_quantmap__44u9_p9_1[] = {
  152483. 17, 15, 13, 11, 9, 7, 5, 3,
  152484. 1, 0, 2, 4, 6, 8, 10, 12,
  152485. 14, 16, 18,
  152486. };
  152487. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152488. _vq_quantthresh__44u9_p9_1,
  152489. _vq_quantmap__44u9_p9_1,
  152490. 19,
  152491. 19
  152492. };
  152493. static static_codebook _44u9_p9_1 = {
  152494. 2, 361,
  152495. _vq_lengthlist__44u9_p9_1,
  152496. 1, -518287360, 1622704128, 5, 0,
  152497. _vq_quantlist__44u9_p9_1,
  152498. NULL,
  152499. &_vq_auxt__44u9_p9_1,
  152500. NULL,
  152501. 0
  152502. };
  152503. static long _vq_quantlist__44u9_p9_2[] = {
  152504. 24,
  152505. 23,
  152506. 25,
  152507. 22,
  152508. 26,
  152509. 21,
  152510. 27,
  152511. 20,
  152512. 28,
  152513. 19,
  152514. 29,
  152515. 18,
  152516. 30,
  152517. 17,
  152518. 31,
  152519. 16,
  152520. 32,
  152521. 15,
  152522. 33,
  152523. 14,
  152524. 34,
  152525. 13,
  152526. 35,
  152527. 12,
  152528. 36,
  152529. 11,
  152530. 37,
  152531. 10,
  152532. 38,
  152533. 9,
  152534. 39,
  152535. 8,
  152536. 40,
  152537. 7,
  152538. 41,
  152539. 6,
  152540. 42,
  152541. 5,
  152542. 43,
  152543. 4,
  152544. 44,
  152545. 3,
  152546. 45,
  152547. 2,
  152548. 46,
  152549. 1,
  152550. 47,
  152551. 0,
  152552. 48,
  152553. };
  152554. static long _vq_lengthlist__44u9_p9_2[] = {
  152555. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152556. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152557. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152558. 7,
  152559. };
  152560. static float _vq_quantthresh__44u9_p9_2[] = {
  152561. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152562. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152563. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152564. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152565. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152566. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152567. };
  152568. static long _vq_quantmap__44u9_p9_2[] = {
  152569. 47, 45, 43, 41, 39, 37, 35, 33,
  152570. 31, 29, 27, 25, 23, 21, 19, 17,
  152571. 15, 13, 11, 9, 7, 5, 3, 1,
  152572. 0, 2, 4, 6, 8, 10, 12, 14,
  152573. 16, 18, 20, 22, 24, 26, 28, 30,
  152574. 32, 34, 36, 38, 40, 42, 44, 46,
  152575. 48,
  152576. };
  152577. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152578. _vq_quantthresh__44u9_p9_2,
  152579. _vq_quantmap__44u9_p9_2,
  152580. 49,
  152581. 49
  152582. };
  152583. static static_codebook _44u9_p9_2 = {
  152584. 1, 49,
  152585. _vq_lengthlist__44u9_p9_2,
  152586. 1, -526909440, 1611661312, 6, 0,
  152587. _vq_quantlist__44u9_p9_2,
  152588. NULL,
  152589. &_vq_auxt__44u9_p9_2,
  152590. NULL,
  152591. 0
  152592. };
  152593. static long _huff_lengthlist__44un1__long[] = {
  152594. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152595. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152596. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152597. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152598. };
  152599. static static_codebook _huff_book__44un1__long = {
  152600. 2, 64,
  152601. _huff_lengthlist__44un1__long,
  152602. 0, 0, 0, 0, 0,
  152603. NULL,
  152604. NULL,
  152605. NULL,
  152606. NULL,
  152607. 0
  152608. };
  152609. static long _vq_quantlist__44un1__p1_0[] = {
  152610. 1,
  152611. 0,
  152612. 2,
  152613. };
  152614. static long _vq_lengthlist__44un1__p1_0[] = {
  152615. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152616. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152617. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152618. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152619. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152620. 12,
  152621. };
  152622. static float _vq_quantthresh__44un1__p1_0[] = {
  152623. -0.5, 0.5,
  152624. };
  152625. static long _vq_quantmap__44un1__p1_0[] = {
  152626. 1, 0, 2,
  152627. };
  152628. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152629. _vq_quantthresh__44un1__p1_0,
  152630. _vq_quantmap__44un1__p1_0,
  152631. 3,
  152632. 3
  152633. };
  152634. static static_codebook _44un1__p1_0 = {
  152635. 4, 81,
  152636. _vq_lengthlist__44un1__p1_0,
  152637. 1, -535822336, 1611661312, 2, 0,
  152638. _vq_quantlist__44un1__p1_0,
  152639. NULL,
  152640. &_vq_auxt__44un1__p1_0,
  152641. NULL,
  152642. 0
  152643. };
  152644. static long _vq_quantlist__44un1__p2_0[] = {
  152645. 1,
  152646. 0,
  152647. 2,
  152648. };
  152649. static long _vq_lengthlist__44un1__p2_0[] = {
  152650. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152651. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152652. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152653. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152654. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152655. 8,
  152656. };
  152657. static float _vq_quantthresh__44un1__p2_0[] = {
  152658. -0.5, 0.5,
  152659. };
  152660. static long _vq_quantmap__44un1__p2_0[] = {
  152661. 1, 0, 2,
  152662. };
  152663. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152664. _vq_quantthresh__44un1__p2_0,
  152665. _vq_quantmap__44un1__p2_0,
  152666. 3,
  152667. 3
  152668. };
  152669. static static_codebook _44un1__p2_0 = {
  152670. 4, 81,
  152671. _vq_lengthlist__44un1__p2_0,
  152672. 1, -535822336, 1611661312, 2, 0,
  152673. _vq_quantlist__44un1__p2_0,
  152674. NULL,
  152675. &_vq_auxt__44un1__p2_0,
  152676. NULL,
  152677. 0
  152678. };
  152679. static long _vq_quantlist__44un1__p3_0[] = {
  152680. 2,
  152681. 1,
  152682. 3,
  152683. 0,
  152684. 4,
  152685. };
  152686. static long _vq_lengthlist__44un1__p3_0[] = {
  152687. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152688. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152689. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152690. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152691. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152692. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152693. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152694. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152695. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152696. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152697. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152698. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152699. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152700. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152701. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152702. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152703. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152704. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152705. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152706. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152707. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152708. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152709. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152710. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152711. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152712. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152713. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152714. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152715. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152716. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152717. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152718. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152719. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152720. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152721. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152722. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152723. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152724. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152725. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152726. 17,
  152727. };
  152728. static float _vq_quantthresh__44un1__p3_0[] = {
  152729. -1.5, -0.5, 0.5, 1.5,
  152730. };
  152731. static long _vq_quantmap__44un1__p3_0[] = {
  152732. 3, 1, 0, 2, 4,
  152733. };
  152734. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152735. _vq_quantthresh__44un1__p3_0,
  152736. _vq_quantmap__44un1__p3_0,
  152737. 5,
  152738. 5
  152739. };
  152740. static static_codebook _44un1__p3_0 = {
  152741. 4, 625,
  152742. _vq_lengthlist__44un1__p3_0,
  152743. 1, -533725184, 1611661312, 3, 0,
  152744. _vq_quantlist__44un1__p3_0,
  152745. NULL,
  152746. &_vq_auxt__44un1__p3_0,
  152747. NULL,
  152748. 0
  152749. };
  152750. static long _vq_quantlist__44un1__p4_0[] = {
  152751. 2,
  152752. 1,
  152753. 3,
  152754. 0,
  152755. 4,
  152756. };
  152757. static long _vq_lengthlist__44un1__p4_0[] = {
  152758. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152759. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152760. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152761. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152762. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152763. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152764. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152765. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152766. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152767. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152768. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152769. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152770. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152771. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152772. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152773. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152774. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152775. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152776. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152777. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152778. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152779. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152780. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152781. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152782. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152783. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152784. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152785. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152786. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152787. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152788. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152789. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152790. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152791. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152792. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152793. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152794. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152795. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152796. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152797. 12,
  152798. };
  152799. static float _vq_quantthresh__44un1__p4_0[] = {
  152800. -1.5, -0.5, 0.5, 1.5,
  152801. };
  152802. static long _vq_quantmap__44un1__p4_0[] = {
  152803. 3, 1, 0, 2, 4,
  152804. };
  152805. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152806. _vq_quantthresh__44un1__p4_0,
  152807. _vq_quantmap__44un1__p4_0,
  152808. 5,
  152809. 5
  152810. };
  152811. static static_codebook _44un1__p4_0 = {
  152812. 4, 625,
  152813. _vq_lengthlist__44un1__p4_0,
  152814. 1, -533725184, 1611661312, 3, 0,
  152815. _vq_quantlist__44un1__p4_0,
  152816. NULL,
  152817. &_vq_auxt__44un1__p4_0,
  152818. NULL,
  152819. 0
  152820. };
  152821. static long _vq_quantlist__44un1__p5_0[] = {
  152822. 4,
  152823. 3,
  152824. 5,
  152825. 2,
  152826. 6,
  152827. 1,
  152828. 7,
  152829. 0,
  152830. 8,
  152831. };
  152832. static long _vq_lengthlist__44un1__p5_0[] = {
  152833. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152834. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152835. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152836. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152837. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152838. 12,
  152839. };
  152840. static float _vq_quantthresh__44un1__p5_0[] = {
  152841. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152842. };
  152843. static long _vq_quantmap__44un1__p5_0[] = {
  152844. 7, 5, 3, 1, 0, 2, 4, 6,
  152845. 8,
  152846. };
  152847. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152848. _vq_quantthresh__44un1__p5_0,
  152849. _vq_quantmap__44un1__p5_0,
  152850. 9,
  152851. 9
  152852. };
  152853. static static_codebook _44un1__p5_0 = {
  152854. 2, 81,
  152855. _vq_lengthlist__44un1__p5_0,
  152856. 1, -531628032, 1611661312, 4, 0,
  152857. _vq_quantlist__44un1__p5_0,
  152858. NULL,
  152859. &_vq_auxt__44un1__p5_0,
  152860. NULL,
  152861. 0
  152862. };
  152863. static long _vq_quantlist__44un1__p6_0[] = {
  152864. 6,
  152865. 5,
  152866. 7,
  152867. 4,
  152868. 8,
  152869. 3,
  152870. 9,
  152871. 2,
  152872. 10,
  152873. 1,
  152874. 11,
  152875. 0,
  152876. 12,
  152877. };
  152878. static long _vq_lengthlist__44un1__p6_0[] = {
  152879. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152880. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152881. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152882. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152883. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152884. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152885. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152886. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152887. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152888. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152889. 16, 0,15,18,18, 0,16, 0, 0,
  152890. };
  152891. static float _vq_quantthresh__44un1__p6_0[] = {
  152892. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152893. 12.5, 17.5, 22.5, 27.5,
  152894. };
  152895. static long _vq_quantmap__44un1__p6_0[] = {
  152896. 11, 9, 7, 5, 3, 1, 0, 2,
  152897. 4, 6, 8, 10, 12,
  152898. };
  152899. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152900. _vq_quantthresh__44un1__p6_0,
  152901. _vq_quantmap__44un1__p6_0,
  152902. 13,
  152903. 13
  152904. };
  152905. static static_codebook _44un1__p6_0 = {
  152906. 2, 169,
  152907. _vq_lengthlist__44un1__p6_0,
  152908. 1, -526516224, 1616117760, 4, 0,
  152909. _vq_quantlist__44un1__p6_0,
  152910. NULL,
  152911. &_vq_auxt__44un1__p6_0,
  152912. NULL,
  152913. 0
  152914. };
  152915. static long _vq_quantlist__44un1__p6_1[] = {
  152916. 2,
  152917. 1,
  152918. 3,
  152919. 0,
  152920. 4,
  152921. };
  152922. static long _vq_lengthlist__44un1__p6_1[] = {
  152923. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152924. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152925. };
  152926. static float _vq_quantthresh__44un1__p6_1[] = {
  152927. -1.5, -0.5, 0.5, 1.5,
  152928. };
  152929. static long _vq_quantmap__44un1__p6_1[] = {
  152930. 3, 1, 0, 2, 4,
  152931. };
  152932. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152933. _vq_quantthresh__44un1__p6_1,
  152934. _vq_quantmap__44un1__p6_1,
  152935. 5,
  152936. 5
  152937. };
  152938. static static_codebook _44un1__p6_1 = {
  152939. 2, 25,
  152940. _vq_lengthlist__44un1__p6_1,
  152941. 1, -533725184, 1611661312, 3, 0,
  152942. _vq_quantlist__44un1__p6_1,
  152943. NULL,
  152944. &_vq_auxt__44un1__p6_1,
  152945. NULL,
  152946. 0
  152947. };
  152948. static long _vq_quantlist__44un1__p7_0[] = {
  152949. 2,
  152950. 1,
  152951. 3,
  152952. 0,
  152953. 4,
  152954. };
  152955. static long _vq_lengthlist__44un1__p7_0[] = {
  152956. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152957. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152959. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152960. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152963. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152964. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152966. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152968. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152969. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152970. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152971. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152972. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152973. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152975. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152976. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152977. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152978. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152979. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152981. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152982. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152985. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152987. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152989. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152990. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152992. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152993. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152994. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152995. 10,
  152996. };
  152997. static float _vq_quantthresh__44un1__p7_0[] = {
  152998. -253.5, -84.5, 84.5, 253.5,
  152999. };
  153000. static long _vq_quantmap__44un1__p7_0[] = {
  153001. 3, 1, 0, 2, 4,
  153002. };
  153003. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153004. _vq_quantthresh__44un1__p7_0,
  153005. _vq_quantmap__44un1__p7_0,
  153006. 5,
  153007. 5
  153008. };
  153009. static static_codebook _44un1__p7_0 = {
  153010. 4, 625,
  153011. _vq_lengthlist__44un1__p7_0,
  153012. 1, -518709248, 1626677248, 3, 0,
  153013. _vq_quantlist__44un1__p7_0,
  153014. NULL,
  153015. &_vq_auxt__44un1__p7_0,
  153016. NULL,
  153017. 0
  153018. };
  153019. static long _vq_quantlist__44un1__p7_1[] = {
  153020. 6,
  153021. 5,
  153022. 7,
  153023. 4,
  153024. 8,
  153025. 3,
  153026. 9,
  153027. 2,
  153028. 10,
  153029. 1,
  153030. 11,
  153031. 0,
  153032. 12,
  153033. };
  153034. static long _vq_lengthlist__44un1__p7_1[] = {
  153035. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153036. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153037. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153038. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153039. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153040. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153041. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153042. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153043. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153044. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153045. 12,13,13,12,13,13,14,14,14,
  153046. };
  153047. static float _vq_quantthresh__44un1__p7_1[] = {
  153048. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153049. 32.5, 45.5, 58.5, 71.5,
  153050. };
  153051. static long _vq_quantmap__44un1__p7_1[] = {
  153052. 11, 9, 7, 5, 3, 1, 0, 2,
  153053. 4, 6, 8, 10, 12,
  153054. };
  153055. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153056. _vq_quantthresh__44un1__p7_1,
  153057. _vq_quantmap__44un1__p7_1,
  153058. 13,
  153059. 13
  153060. };
  153061. static static_codebook _44un1__p7_1 = {
  153062. 2, 169,
  153063. _vq_lengthlist__44un1__p7_1,
  153064. 1, -523010048, 1618608128, 4, 0,
  153065. _vq_quantlist__44un1__p7_1,
  153066. NULL,
  153067. &_vq_auxt__44un1__p7_1,
  153068. NULL,
  153069. 0
  153070. };
  153071. static long _vq_quantlist__44un1__p7_2[] = {
  153072. 6,
  153073. 5,
  153074. 7,
  153075. 4,
  153076. 8,
  153077. 3,
  153078. 9,
  153079. 2,
  153080. 10,
  153081. 1,
  153082. 11,
  153083. 0,
  153084. 12,
  153085. };
  153086. static long _vq_lengthlist__44un1__p7_2[] = {
  153087. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153088. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153089. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153090. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153091. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153092. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153093. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153094. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153095. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153096. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153097. 9, 9, 9,10,10,10,10,10,10,
  153098. };
  153099. static float _vq_quantthresh__44un1__p7_2[] = {
  153100. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153101. 2.5, 3.5, 4.5, 5.5,
  153102. };
  153103. static long _vq_quantmap__44un1__p7_2[] = {
  153104. 11, 9, 7, 5, 3, 1, 0, 2,
  153105. 4, 6, 8, 10, 12,
  153106. };
  153107. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153108. _vq_quantthresh__44un1__p7_2,
  153109. _vq_quantmap__44un1__p7_2,
  153110. 13,
  153111. 13
  153112. };
  153113. static static_codebook _44un1__p7_2 = {
  153114. 2, 169,
  153115. _vq_lengthlist__44un1__p7_2,
  153116. 1, -531103744, 1611661312, 4, 0,
  153117. _vq_quantlist__44un1__p7_2,
  153118. NULL,
  153119. &_vq_auxt__44un1__p7_2,
  153120. NULL,
  153121. 0
  153122. };
  153123. static long _huff_lengthlist__44un1__short[] = {
  153124. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153125. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153126. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153127. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153128. };
  153129. static static_codebook _huff_book__44un1__short = {
  153130. 2, 64,
  153131. _huff_lengthlist__44un1__short,
  153132. 0, 0, 0, 0, 0,
  153133. NULL,
  153134. NULL,
  153135. NULL,
  153136. NULL,
  153137. 0
  153138. };
  153139. /*** End of inlined file: res_books_uncoupled.h ***/
  153140. /***** residue backends *********************************************/
  153141. static vorbis_info_residue0 _residue_44_low_un={
  153142. 0,-1, -1, 8,-1,
  153143. {0},
  153144. {-1},
  153145. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153146. { -1, 25, -1, 45, -1, -1, -1}
  153147. };
  153148. static vorbis_info_residue0 _residue_44_mid_un={
  153149. 0,-1, -1, 10,-1,
  153150. /* 0 1 2 3 4 5 6 7 8 9 */
  153151. {0},
  153152. {-1},
  153153. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153154. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153155. };
  153156. static vorbis_info_residue0 _residue_44_hi_un={
  153157. 0,-1, -1, 10,-1,
  153158. /* 0 1 2 3 4 5 6 7 8 9 */
  153159. {0},
  153160. {-1},
  153161. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153162. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153163. };
  153164. /* mapping conventions:
  153165. only one submap (this would change for efficient 5.1 support for example)*/
  153166. /* Four psychoacoustic profiles are used, one for each blocktype */
  153167. static vorbis_info_mapping0 _map_nominal_u[2]={
  153168. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153169. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153170. };
  153171. static static_bookblock _resbook_44u_n1={
  153172. {
  153173. {0},
  153174. {0,0,&_44un1__p1_0},
  153175. {0,0,&_44un1__p2_0},
  153176. {0,0,&_44un1__p3_0},
  153177. {0,0,&_44un1__p4_0},
  153178. {0,0,&_44un1__p5_0},
  153179. {&_44un1__p6_0,&_44un1__p6_1},
  153180. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153181. }
  153182. };
  153183. static static_bookblock _resbook_44u_0={
  153184. {
  153185. {0},
  153186. {0,0,&_44u0__p1_0},
  153187. {0,0,&_44u0__p2_0},
  153188. {0,0,&_44u0__p3_0},
  153189. {0,0,&_44u0__p4_0},
  153190. {0,0,&_44u0__p5_0},
  153191. {&_44u0__p6_0,&_44u0__p6_1},
  153192. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153193. }
  153194. };
  153195. static static_bookblock _resbook_44u_1={
  153196. {
  153197. {0},
  153198. {0,0,&_44u1__p1_0},
  153199. {0,0,&_44u1__p2_0},
  153200. {0,0,&_44u1__p3_0},
  153201. {0,0,&_44u1__p4_0},
  153202. {0,0,&_44u1__p5_0},
  153203. {&_44u1__p6_0,&_44u1__p6_1},
  153204. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153205. }
  153206. };
  153207. static static_bookblock _resbook_44u_2={
  153208. {
  153209. {0},
  153210. {0,0,&_44u2__p1_0},
  153211. {0,0,&_44u2__p2_0},
  153212. {0,0,&_44u2__p3_0},
  153213. {0,0,&_44u2__p4_0},
  153214. {0,0,&_44u2__p5_0},
  153215. {&_44u2__p6_0,&_44u2__p6_1},
  153216. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153217. }
  153218. };
  153219. static static_bookblock _resbook_44u_3={
  153220. {
  153221. {0},
  153222. {0,0,&_44u3__p1_0},
  153223. {0,0,&_44u3__p2_0},
  153224. {0,0,&_44u3__p3_0},
  153225. {0,0,&_44u3__p4_0},
  153226. {0,0,&_44u3__p5_0},
  153227. {&_44u3__p6_0,&_44u3__p6_1},
  153228. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153229. }
  153230. };
  153231. static static_bookblock _resbook_44u_4={
  153232. {
  153233. {0},
  153234. {0,0,&_44u4__p1_0},
  153235. {0,0,&_44u4__p2_0},
  153236. {0,0,&_44u4__p3_0},
  153237. {0,0,&_44u4__p4_0},
  153238. {0,0,&_44u4__p5_0},
  153239. {&_44u4__p6_0,&_44u4__p6_1},
  153240. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153241. }
  153242. };
  153243. static static_bookblock _resbook_44u_5={
  153244. {
  153245. {0},
  153246. {0,0,&_44u5__p1_0},
  153247. {0,0,&_44u5__p2_0},
  153248. {0,0,&_44u5__p3_0},
  153249. {0,0,&_44u5__p4_0},
  153250. {0,0,&_44u5__p5_0},
  153251. {0,0,&_44u5__p6_0},
  153252. {&_44u5__p7_0,&_44u5__p7_1},
  153253. {&_44u5__p8_0,&_44u5__p8_1},
  153254. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153255. }
  153256. };
  153257. static static_bookblock _resbook_44u_6={
  153258. {
  153259. {0},
  153260. {0,0,&_44u6__p1_0},
  153261. {0,0,&_44u6__p2_0},
  153262. {0,0,&_44u6__p3_0},
  153263. {0,0,&_44u6__p4_0},
  153264. {0,0,&_44u6__p5_0},
  153265. {0,0,&_44u6__p6_0},
  153266. {&_44u6__p7_0,&_44u6__p7_1},
  153267. {&_44u6__p8_0,&_44u6__p8_1},
  153268. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153269. }
  153270. };
  153271. static static_bookblock _resbook_44u_7={
  153272. {
  153273. {0},
  153274. {0,0,&_44u7__p1_0},
  153275. {0,0,&_44u7__p2_0},
  153276. {0,0,&_44u7__p3_0},
  153277. {0,0,&_44u7__p4_0},
  153278. {0,0,&_44u7__p5_0},
  153279. {0,0,&_44u7__p6_0},
  153280. {&_44u7__p7_0,&_44u7__p7_1},
  153281. {&_44u7__p8_0,&_44u7__p8_1},
  153282. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153283. }
  153284. };
  153285. static static_bookblock _resbook_44u_8={
  153286. {
  153287. {0},
  153288. {0,0,&_44u8_p1_0},
  153289. {0,0,&_44u8_p2_0},
  153290. {0,0,&_44u8_p3_0},
  153291. {0,0,&_44u8_p4_0},
  153292. {&_44u8_p5_0,&_44u8_p5_1},
  153293. {&_44u8_p6_0,&_44u8_p6_1},
  153294. {&_44u8_p7_0,&_44u8_p7_1},
  153295. {&_44u8_p8_0,&_44u8_p8_1},
  153296. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153297. }
  153298. };
  153299. static static_bookblock _resbook_44u_9={
  153300. {
  153301. {0},
  153302. {0,0,&_44u9_p1_0},
  153303. {0,0,&_44u9_p2_0},
  153304. {0,0,&_44u9_p3_0},
  153305. {0,0,&_44u9_p4_0},
  153306. {&_44u9_p5_0,&_44u9_p5_1},
  153307. {&_44u9_p6_0,&_44u9_p6_1},
  153308. {&_44u9_p7_0,&_44u9_p7_1},
  153309. {&_44u9_p8_0,&_44u9_p8_1},
  153310. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153311. }
  153312. };
  153313. static vorbis_residue_template _res_44u_n1[]={
  153314. {1,0, &_residue_44_low_un,
  153315. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153316. &_resbook_44u_n1,&_resbook_44u_n1},
  153317. {1,0, &_residue_44_low_un,
  153318. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153319. &_resbook_44u_n1,&_resbook_44u_n1}
  153320. };
  153321. static vorbis_residue_template _res_44u_0[]={
  153322. {1,0, &_residue_44_low_un,
  153323. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153324. &_resbook_44u_0,&_resbook_44u_0},
  153325. {1,0, &_residue_44_low_un,
  153326. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153327. &_resbook_44u_0,&_resbook_44u_0}
  153328. };
  153329. static vorbis_residue_template _res_44u_1[]={
  153330. {1,0, &_residue_44_low_un,
  153331. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153332. &_resbook_44u_1,&_resbook_44u_1},
  153333. {1,0, &_residue_44_low_un,
  153334. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153335. &_resbook_44u_1,&_resbook_44u_1}
  153336. };
  153337. static vorbis_residue_template _res_44u_2[]={
  153338. {1,0, &_residue_44_low_un,
  153339. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153340. &_resbook_44u_2,&_resbook_44u_2},
  153341. {1,0, &_residue_44_low_un,
  153342. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153343. &_resbook_44u_2,&_resbook_44u_2}
  153344. };
  153345. static vorbis_residue_template _res_44u_3[]={
  153346. {1,0, &_residue_44_low_un,
  153347. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153348. &_resbook_44u_3,&_resbook_44u_3},
  153349. {1,0, &_residue_44_low_un,
  153350. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153351. &_resbook_44u_3,&_resbook_44u_3}
  153352. };
  153353. static vorbis_residue_template _res_44u_4[]={
  153354. {1,0, &_residue_44_low_un,
  153355. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153356. &_resbook_44u_4,&_resbook_44u_4},
  153357. {1,0, &_residue_44_low_un,
  153358. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153359. &_resbook_44u_4,&_resbook_44u_4}
  153360. };
  153361. static vorbis_residue_template _res_44u_5[]={
  153362. {1,0, &_residue_44_mid_un,
  153363. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153364. &_resbook_44u_5,&_resbook_44u_5},
  153365. {1,0, &_residue_44_mid_un,
  153366. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153367. &_resbook_44u_5,&_resbook_44u_5}
  153368. };
  153369. static vorbis_residue_template _res_44u_6[]={
  153370. {1,0, &_residue_44_mid_un,
  153371. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153372. &_resbook_44u_6,&_resbook_44u_6},
  153373. {1,0, &_residue_44_mid_un,
  153374. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153375. &_resbook_44u_6,&_resbook_44u_6}
  153376. };
  153377. static vorbis_residue_template _res_44u_7[]={
  153378. {1,0, &_residue_44_mid_un,
  153379. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153380. &_resbook_44u_7,&_resbook_44u_7},
  153381. {1,0, &_residue_44_mid_un,
  153382. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153383. &_resbook_44u_7,&_resbook_44u_7}
  153384. };
  153385. static vorbis_residue_template _res_44u_8[]={
  153386. {1,0, &_residue_44_hi_un,
  153387. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153388. &_resbook_44u_8,&_resbook_44u_8},
  153389. {1,0, &_residue_44_hi_un,
  153390. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153391. &_resbook_44u_8,&_resbook_44u_8}
  153392. };
  153393. static vorbis_residue_template _res_44u_9[]={
  153394. {1,0, &_residue_44_hi_un,
  153395. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153396. &_resbook_44u_9,&_resbook_44u_9},
  153397. {1,0, &_residue_44_hi_un,
  153398. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153399. &_resbook_44u_9,&_resbook_44u_9}
  153400. };
  153401. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153402. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153403. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153404. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153405. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153406. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153407. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153408. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153409. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153410. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153411. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153412. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153413. };
  153414. /*** End of inlined file: residue_44u.h ***/
  153415. static double rate_mapping_44_un[12]={
  153416. 32000.,48000.,60000.,70000.,80000.,86000.,
  153417. 96000.,110000.,120000.,140000.,160000.,240001.
  153418. };
  153419. ve_setup_data_template ve_setup_44_uncoupled={
  153420. 11,
  153421. rate_mapping_44_un,
  153422. quality_mapping_44,
  153423. -1,
  153424. 40000,
  153425. 50000,
  153426. blocksize_short_44,
  153427. blocksize_long_44,
  153428. _psy_tone_masteratt_44,
  153429. _psy_tone_0dB,
  153430. _psy_tone_suppress,
  153431. _vp_tonemask_adj_otherblock,
  153432. _vp_tonemask_adj_longblock,
  153433. _vp_tonemask_adj_otherblock,
  153434. _psy_noiseguards_44,
  153435. _psy_noisebias_impulse,
  153436. _psy_noisebias_padding,
  153437. _psy_noisebias_trans,
  153438. _psy_noisebias_long,
  153439. _psy_noise_suppress,
  153440. _psy_compand_44,
  153441. _psy_compand_short_mapping,
  153442. _psy_compand_long_mapping,
  153443. {_noise_start_short_44,_noise_start_long_44},
  153444. {_noise_part_short_44,_noise_part_long_44},
  153445. _noise_thresh_44,
  153446. _psy_ath_floater,
  153447. _psy_ath_abs,
  153448. _psy_lowpass_44,
  153449. _psy_global_44,
  153450. _global_mapping_44,
  153451. NULL,
  153452. _floor_books,
  153453. _floor,
  153454. _floor_short_mapping_44,
  153455. _floor_long_mapping_44,
  153456. _mapres_template_44_uncoupled
  153457. };
  153458. /*** End of inlined file: setup_44u.h ***/
  153459. /*** Start of inlined file: setup_32.h ***/
  153460. static double rate_mapping_32[12]={
  153461. 18000.,28000.,35000.,45000.,56000.,60000.,
  153462. 75000.,90000.,100000.,115000.,150000.,190000.,
  153463. };
  153464. static double rate_mapping_32_un[12]={
  153465. 30000.,42000.,52000.,64000.,72000.,78000.,
  153466. 86000.,92000.,110000.,120000.,140000.,190000.,
  153467. };
  153468. static double _psy_lowpass_32[12]={
  153469. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153470. };
  153471. ve_setup_data_template ve_setup_32_stereo={
  153472. 11,
  153473. rate_mapping_32,
  153474. quality_mapping_44,
  153475. 2,
  153476. 26000,
  153477. 40000,
  153478. blocksize_short_44,
  153479. blocksize_long_44,
  153480. _psy_tone_masteratt_44,
  153481. _psy_tone_0dB,
  153482. _psy_tone_suppress,
  153483. _vp_tonemask_adj_otherblock,
  153484. _vp_tonemask_adj_longblock,
  153485. _vp_tonemask_adj_otherblock,
  153486. _psy_noiseguards_44,
  153487. _psy_noisebias_impulse,
  153488. _psy_noisebias_padding,
  153489. _psy_noisebias_trans,
  153490. _psy_noisebias_long,
  153491. _psy_noise_suppress,
  153492. _psy_compand_44,
  153493. _psy_compand_short_mapping,
  153494. _psy_compand_long_mapping,
  153495. {_noise_start_short_44,_noise_start_long_44},
  153496. {_noise_part_short_44,_noise_part_long_44},
  153497. _noise_thresh_44,
  153498. _psy_ath_floater,
  153499. _psy_ath_abs,
  153500. _psy_lowpass_32,
  153501. _psy_global_44,
  153502. _global_mapping_44,
  153503. _psy_stereo_modes_44,
  153504. _floor_books,
  153505. _floor,
  153506. _floor_short_mapping_44,
  153507. _floor_long_mapping_44,
  153508. _mapres_template_44_stereo
  153509. };
  153510. ve_setup_data_template ve_setup_32_uncoupled={
  153511. 11,
  153512. rate_mapping_32_un,
  153513. quality_mapping_44,
  153514. -1,
  153515. 26000,
  153516. 40000,
  153517. blocksize_short_44,
  153518. blocksize_long_44,
  153519. _psy_tone_masteratt_44,
  153520. _psy_tone_0dB,
  153521. _psy_tone_suppress,
  153522. _vp_tonemask_adj_otherblock,
  153523. _vp_tonemask_adj_longblock,
  153524. _vp_tonemask_adj_otherblock,
  153525. _psy_noiseguards_44,
  153526. _psy_noisebias_impulse,
  153527. _psy_noisebias_padding,
  153528. _psy_noisebias_trans,
  153529. _psy_noisebias_long,
  153530. _psy_noise_suppress,
  153531. _psy_compand_44,
  153532. _psy_compand_short_mapping,
  153533. _psy_compand_long_mapping,
  153534. {_noise_start_short_44,_noise_start_long_44},
  153535. {_noise_part_short_44,_noise_part_long_44},
  153536. _noise_thresh_44,
  153537. _psy_ath_floater,
  153538. _psy_ath_abs,
  153539. _psy_lowpass_32,
  153540. _psy_global_44,
  153541. _global_mapping_44,
  153542. NULL,
  153543. _floor_books,
  153544. _floor,
  153545. _floor_short_mapping_44,
  153546. _floor_long_mapping_44,
  153547. _mapres_template_44_uncoupled
  153548. };
  153549. /*** End of inlined file: setup_32.h ***/
  153550. /*** Start of inlined file: setup_8.h ***/
  153551. /*** Start of inlined file: psych_8.h ***/
  153552. static att3 _psy_tone_masteratt_8[3]={
  153553. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153554. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153555. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153556. };
  153557. static vp_adjblock _vp_tonemask_adj_8[3]={
  153558. /* adjust for mode zero */
  153559. /* 63 125 250 500 1 2 4 8 16 */
  153560. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153561. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153562. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153563. };
  153564. static noise3 _psy_noisebias_8[3]={
  153565. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153566. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153567. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153568. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153569. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153570. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153571. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153572. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153573. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153574. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153575. };
  153576. /* stereo mode by base quality level */
  153577. static adj_stereo _psy_stereo_modes_8[3]={
  153578. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153579. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153580. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153581. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153582. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153583. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153584. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153585. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153586. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153587. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153588. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153589. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153590. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153591. };
  153592. static noiseguard _psy_noiseguards_8[2]={
  153593. {10,10,-1},
  153594. {10,10,-1},
  153595. };
  153596. static compandblock _psy_compand_8[2]={
  153597. {{
  153598. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153599. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153600. 12,12,13,13,14,14,15, 15, /* 23dB */
  153601. 16,16,17,17,17,18,18, 19, /* 31dB */
  153602. 19,19,20,21,22,23,24, 25, /* 39dB */
  153603. }},
  153604. {{
  153605. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153606. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153607. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153608. 9,10,11,12,13,14,15, 16, /* 31dB */
  153609. 17,18,19,20,21,22,23, 24, /* 39dB */
  153610. }},
  153611. };
  153612. static double _psy_lowpass_8[3]={3.,4.,4.};
  153613. static int _noise_start_8[2]={
  153614. 64,64,
  153615. };
  153616. static int _noise_part_8[2]={
  153617. 8,8,
  153618. };
  153619. static int _psy_ath_floater_8[3]={
  153620. -100,-100,-105,
  153621. };
  153622. static int _psy_ath_abs_8[3]={
  153623. -130,-130,-140,
  153624. };
  153625. /*** End of inlined file: psych_8.h ***/
  153626. /*** Start of inlined file: residue_8.h ***/
  153627. /***** residue backends *********************************************/
  153628. static static_bookblock _resbook_8s_0={
  153629. {
  153630. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153631. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153632. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153633. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153634. }
  153635. };
  153636. static static_bookblock _resbook_8s_1={
  153637. {
  153638. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153639. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153640. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153641. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153642. }
  153643. };
  153644. static vorbis_residue_template _res_8s_0[]={
  153645. {2,0, &_residue_44_mid,
  153646. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153647. &_resbook_8s_0,&_resbook_8s_0},
  153648. };
  153649. static vorbis_residue_template _res_8s_1[]={
  153650. {2,0, &_residue_44_mid,
  153651. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153652. &_resbook_8s_1,&_resbook_8s_1},
  153653. };
  153654. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153655. { _map_nominal, _res_8s_0 }, /* 0 */
  153656. { _map_nominal, _res_8s_1 }, /* 1 */
  153657. };
  153658. static static_bookblock _resbook_8u_0={
  153659. {
  153660. {0},
  153661. {0,0,&_8u0__p1_0},
  153662. {0,0,&_8u0__p2_0},
  153663. {0,0,&_8u0__p3_0},
  153664. {0,0,&_8u0__p4_0},
  153665. {0,0,&_8u0__p5_0},
  153666. {&_8u0__p6_0,&_8u0__p6_1},
  153667. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153668. }
  153669. };
  153670. static static_bookblock _resbook_8u_1={
  153671. {
  153672. {0},
  153673. {0,0,&_8u1__p1_0},
  153674. {0,0,&_8u1__p2_0},
  153675. {0,0,&_8u1__p3_0},
  153676. {0,0,&_8u1__p4_0},
  153677. {0,0,&_8u1__p5_0},
  153678. {0,0,&_8u1__p6_0},
  153679. {&_8u1__p7_0,&_8u1__p7_1},
  153680. {&_8u1__p8_0,&_8u1__p8_1},
  153681. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153682. }
  153683. };
  153684. static vorbis_residue_template _res_8u_0[]={
  153685. {1,0, &_residue_44_low_un,
  153686. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153687. &_resbook_8u_0,&_resbook_8u_0},
  153688. };
  153689. static vorbis_residue_template _res_8u_1[]={
  153690. {1,0, &_residue_44_mid_un,
  153691. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153692. &_resbook_8u_1,&_resbook_8u_1},
  153693. };
  153694. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153695. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153696. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153697. };
  153698. /*** End of inlined file: residue_8.h ***/
  153699. static int blocksize_8[2]={
  153700. 512,512
  153701. };
  153702. static int _floor_mapping_8[2]={
  153703. 6,6,
  153704. };
  153705. static double rate_mapping_8[3]={
  153706. 6000.,9000.,32000.,
  153707. };
  153708. static double rate_mapping_8_uncoupled[3]={
  153709. 8000.,14000.,42000.,
  153710. };
  153711. static double quality_mapping_8[3]={
  153712. -.1,.0,1.
  153713. };
  153714. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153715. static double _global_mapping_8[3]={ 1., 2., 3. };
  153716. ve_setup_data_template ve_setup_8_stereo={
  153717. 2,
  153718. rate_mapping_8,
  153719. quality_mapping_8,
  153720. 2,
  153721. 8000,
  153722. 9000,
  153723. blocksize_8,
  153724. blocksize_8,
  153725. _psy_tone_masteratt_8,
  153726. _psy_tone_0dB,
  153727. _psy_tone_suppress,
  153728. _vp_tonemask_adj_8,
  153729. NULL,
  153730. _vp_tonemask_adj_8,
  153731. _psy_noiseguards_8,
  153732. _psy_noisebias_8,
  153733. _psy_noisebias_8,
  153734. NULL,
  153735. NULL,
  153736. _psy_noise_suppress,
  153737. _psy_compand_8,
  153738. _psy_compand_8_mapping,
  153739. NULL,
  153740. {_noise_start_8,_noise_start_8},
  153741. {_noise_part_8,_noise_part_8},
  153742. _noise_thresh_5only,
  153743. _psy_ath_floater_8,
  153744. _psy_ath_abs_8,
  153745. _psy_lowpass_8,
  153746. _psy_global_44,
  153747. _global_mapping_8,
  153748. _psy_stereo_modes_8,
  153749. _floor_books,
  153750. _floor,
  153751. _floor_mapping_8,
  153752. NULL,
  153753. _mapres_template_8_stereo
  153754. };
  153755. ve_setup_data_template ve_setup_8_uncoupled={
  153756. 2,
  153757. rate_mapping_8_uncoupled,
  153758. quality_mapping_8,
  153759. -1,
  153760. 8000,
  153761. 9000,
  153762. blocksize_8,
  153763. blocksize_8,
  153764. _psy_tone_masteratt_8,
  153765. _psy_tone_0dB,
  153766. _psy_tone_suppress,
  153767. _vp_tonemask_adj_8,
  153768. NULL,
  153769. _vp_tonemask_adj_8,
  153770. _psy_noiseguards_8,
  153771. _psy_noisebias_8,
  153772. _psy_noisebias_8,
  153773. NULL,
  153774. NULL,
  153775. _psy_noise_suppress,
  153776. _psy_compand_8,
  153777. _psy_compand_8_mapping,
  153778. NULL,
  153779. {_noise_start_8,_noise_start_8},
  153780. {_noise_part_8,_noise_part_8},
  153781. _noise_thresh_5only,
  153782. _psy_ath_floater_8,
  153783. _psy_ath_abs_8,
  153784. _psy_lowpass_8,
  153785. _psy_global_44,
  153786. _global_mapping_8,
  153787. _psy_stereo_modes_8,
  153788. _floor_books,
  153789. _floor,
  153790. _floor_mapping_8,
  153791. NULL,
  153792. _mapres_template_8_uncoupled
  153793. };
  153794. /*** End of inlined file: setup_8.h ***/
  153795. /*** Start of inlined file: setup_11.h ***/
  153796. /*** Start of inlined file: psych_11.h ***/
  153797. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153798. static att3 _psy_tone_masteratt_11[3]={
  153799. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153800. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153801. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153802. };
  153803. static vp_adjblock _vp_tonemask_adj_11[3]={
  153804. /* adjust for mode zero */
  153805. /* 63 125 250 500 1 2 4 8 16 */
  153806. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153807. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153808. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153809. };
  153810. static noise3 _psy_noisebias_11[3]={
  153811. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153812. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153813. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153814. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153815. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153816. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153817. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153818. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153819. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153820. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153821. };
  153822. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153823. /*** End of inlined file: psych_11.h ***/
  153824. static int blocksize_11[2]={
  153825. 512,512
  153826. };
  153827. static int _floor_mapping_11[2]={
  153828. 6,6,
  153829. };
  153830. static double rate_mapping_11[3]={
  153831. 8000.,13000.,44000.,
  153832. };
  153833. static double rate_mapping_11_uncoupled[3]={
  153834. 12000.,20000.,50000.,
  153835. };
  153836. static double quality_mapping_11[3]={
  153837. -.1,.0,1.
  153838. };
  153839. ve_setup_data_template ve_setup_11_stereo={
  153840. 2,
  153841. rate_mapping_11,
  153842. quality_mapping_11,
  153843. 2,
  153844. 9000,
  153845. 15000,
  153846. blocksize_11,
  153847. blocksize_11,
  153848. _psy_tone_masteratt_11,
  153849. _psy_tone_0dB,
  153850. _psy_tone_suppress,
  153851. _vp_tonemask_adj_11,
  153852. NULL,
  153853. _vp_tonemask_adj_11,
  153854. _psy_noiseguards_8,
  153855. _psy_noisebias_11,
  153856. _psy_noisebias_11,
  153857. NULL,
  153858. NULL,
  153859. _psy_noise_suppress,
  153860. _psy_compand_8,
  153861. _psy_compand_8_mapping,
  153862. NULL,
  153863. {_noise_start_8,_noise_start_8},
  153864. {_noise_part_8,_noise_part_8},
  153865. _noise_thresh_11,
  153866. _psy_ath_floater_8,
  153867. _psy_ath_abs_8,
  153868. _psy_lowpass_11,
  153869. _psy_global_44,
  153870. _global_mapping_8,
  153871. _psy_stereo_modes_8,
  153872. _floor_books,
  153873. _floor,
  153874. _floor_mapping_11,
  153875. NULL,
  153876. _mapres_template_8_stereo
  153877. };
  153878. ve_setup_data_template ve_setup_11_uncoupled={
  153879. 2,
  153880. rate_mapping_11_uncoupled,
  153881. quality_mapping_11,
  153882. -1,
  153883. 9000,
  153884. 15000,
  153885. blocksize_11,
  153886. blocksize_11,
  153887. _psy_tone_masteratt_11,
  153888. _psy_tone_0dB,
  153889. _psy_tone_suppress,
  153890. _vp_tonemask_adj_11,
  153891. NULL,
  153892. _vp_tonemask_adj_11,
  153893. _psy_noiseguards_8,
  153894. _psy_noisebias_11,
  153895. _psy_noisebias_11,
  153896. NULL,
  153897. NULL,
  153898. _psy_noise_suppress,
  153899. _psy_compand_8,
  153900. _psy_compand_8_mapping,
  153901. NULL,
  153902. {_noise_start_8,_noise_start_8},
  153903. {_noise_part_8,_noise_part_8},
  153904. _noise_thresh_11,
  153905. _psy_ath_floater_8,
  153906. _psy_ath_abs_8,
  153907. _psy_lowpass_11,
  153908. _psy_global_44,
  153909. _global_mapping_8,
  153910. _psy_stereo_modes_8,
  153911. _floor_books,
  153912. _floor,
  153913. _floor_mapping_11,
  153914. NULL,
  153915. _mapres_template_8_uncoupled
  153916. };
  153917. /*** End of inlined file: setup_11.h ***/
  153918. /*** Start of inlined file: setup_16.h ***/
  153919. /*** Start of inlined file: psych_16.h ***/
  153920. /* stereo mode by base quality level */
  153921. static adj_stereo _psy_stereo_modes_16[4]={
  153922. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153923. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153924. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153925. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153926. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153927. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153928. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153929. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153930. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153931. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153932. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153933. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153934. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153935. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153936. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153937. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153938. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153939. };
  153940. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153941. static att3 _psy_tone_masteratt_16[4]={
  153942. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153943. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153944. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153945. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153946. };
  153947. static vp_adjblock _vp_tonemask_adj_16[4]={
  153948. /* adjust for mode zero */
  153949. /* 63 125 250 500 1 2 4 8 16 */
  153950. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153951. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153952. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153953. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153954. };
  153955. static noise3 _psy_noisebias_16_short[4]={
  153956. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153957. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153958. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153959. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153960. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153961. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153962. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153963. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153964. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153965. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153966. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153967. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153968. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153969. };
  153970. static noise3 _psy_noisebias_16_impulse[4]={
  153971. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153972. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153973. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153974. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153975. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153976. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153977. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153978. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153979. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153980. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153981. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153982. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153983. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153984. };
  153985. static noise3 _psy_noisebias_16[4]={
  153986. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153987. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153988. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153989. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153990. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153991. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153992. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153993. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153994. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153995. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153996. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153997. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153998. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153999. };
  154000. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154001. static int _noise_start_16[3]={ 256,256,9999 };
  154002. static int _noise_part_16[4]={ 8,8,8,8 };
  154003. static int _psy_ath_floater_16[4]={
  154004. -100,-100,-100,-105,
  154005. };
  154006. static int _psy_ath_abs_16[4]={
  154007. -130,-130,-130,-140,
  154008. };
  154009. /*** End of inlined file: psych_16.h ***/
  154010. /*** Start of inlined file: residue_16.h ***/
  154011. /***** residue backends *********************************************/
  154012. static static_bookblock _resbook_16s_0={
  154013. {
  154014. {0},
  154015. {0,0,&_16c0_s_p1_0},
  154016. {0,0,&_16c0_s_p2_0},
  154017. {0,0,&_16c0_s_p3_0},
  154018. {0,0,&_16c0_s_p4_0},
  154019. {0,0,&_16c0_s_p5_0},
  154020. {0,0,&_16c0_s_p6_0},
  154021. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154022. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154023. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154024. }
  154025. };
  154026. static static_bookblock _resbook_16s_1={
  154027. {
  154028. {0},
  154029. {0,0,&_16c1_s_p1_0},
  154030. {0,0,&_16c1_s_p2_0},
  154031. {0,0,&_16c1_s_p3_0},
  154032. {0,0,&_16c1_s_p4_0},
  154033. {0,0,&_16c1_s_p5_0},
  154034. {0,0,&_16c1_s_p6_0},
  154035. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154036. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154037. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154038. }
  154039. };
  154040. static static_bookblock _resbook_16s_2={
  154041. {
  154042. {0},
  154043. {0,0,&_16c2_s_p1_0},
  154044. {0,0,&_16c2_s_p2_0},
  154045. {0,0,&_16c2_s_p3_0},
  154046. {0,0,&_16c2_s_p4_0},
  154047. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154048. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154049. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154050. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154051. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154052. }
  154053. };
  154054. static vorbis_residue_template _res_16s_0[]={
  154055. {2,0, &_residue_44_mid,
  154056. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154057. &_resbook_16s_0,&_resbook_16s_0},
  154058. };
  154059. static vorbis_residue_template _res_16s_1[]={
  154060. {2,0, &_residue_44_mid,
  154061. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154062. &_resbook_16s_1,&_resbook_16s_1},
  154063. {2,0, &_residue_44_mid,
  154064. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154065. &_resbook_16s_1,&_resbook_16s_1}
  154066. };
  154067. static vorbis_residue_template _res_16s_2[]={
  154068. {2,0, &_residue_44_high,
  154069. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154070. &_resbook_16s_2,&_resbook_16s_2},
  154071. {2,0, &_residue_44_high,
  154072. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154073. &_resbook_16s_2,&_resbook_16s_2}
  154074. };
  154075. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154076. { _map_nominal, _res_16s_0 }, /* 0 */
  154077. { _map_nominal, _res_16s_1 }, /* 1 */
  154078. { _map_nominal, _res_16s_2 }, /* 2 */
  154079. };
  154080. static static_bookblock _resbook_16u_0={
  154081. {
  154082. {0},
  154083. {0,0,&_16u0__p1_0},
  154084. {0,0,&_16u0__p2_0},
  154085. {0,0,&_16u0__p3_0},
  154086. {0,0,&_16u0__p4_0},
  154087. {0,0,&_16u0__p5_0},
  154088. {&_16u0__p6_0,&_16u0__p6_1},
  154089. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154090. }
  154091. };
  154092. static static_bookblock _resbook_16u_1={
  154093. {
  154094. {0},
  154095. {0,0,&_16u1__p1_0},
  154096. {0,0,&_16u1__p2_0},
  154097. {0,0,&_16u1__p3_0},
  154098. {0,0,&_16u1__p4_0},
  154099. {0,0,&_16u1__p5_0},
  154100. {0,0,&_16u1__p6_0},
  154101. {&_16u1__p7_0,&_16u1__p7_1},
  154102. {&_16u1__p8_0,&_16u1__p8_1},
  154103. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154104. }
  154105. };
  154106. static static_bookblock _resbook_16u_2={
  154107. {
  154108. {0},
  154109. {0,0,&_16u2_p1_0},
  154110. {0,0,&_16u2_p2_0},
  154111. {0,0,&_16u2_p3_0},
  154112. {0,0,&_16u2_p4_0},
  154113. {&_16u2_p5_0,&_16u2_p5_1},
  154114. {&_16u2_p6_0,&_16u2_p6_1},
  154115. {&_16u2_p7_0,&_16u2_p7_1},
  154116. {&_16u2_p8_0,&_16u2_p8_1},
  154117. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154118. }
  154119. };
  154120. static vorbis_residue_template _res_16u_0[]={
  154121. {1,0, &_residue_44_low_un,
  154122. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154123. &_resbook_16u_0,&_resbook_16u_0},
  154124. };
  154125. static vorbis_residue_template _res_16u_1[]={
  154126. {1,0, &_residue_44_mid_un,
  154127. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154128. &_resbook_16u_1,&_resbook_16u_1},
  154129. {1,0, &_residue_44_mid_un,
  154130. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154131. &_resbook_16u_1,&_resbook_16u_1}
  154132. };
  154133. static vorbis_residue_template _res_16u_2[]={
  154134. {1,0, &_residue_44_hi_un,
  154135. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154136. &_resbook_16u_2,&_resbook_16u_2},
  154137. {1,0, &_residue_44_hi_un,
  154138. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154139. &_resbook_16u_2,&_resbook_16u_2}
  154140. };
  154141. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154142. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154143. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154144. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154145. };
  154146. /*** End of inlined file: residue_16.h ***/
  154147. static int blocksize_16_short[3]={
  154148. 1024,512,512
  154149. };
  154150. static int blocksize_16_long[3]={
  154151. 1024,1024,1024
  154152. };
  154153. static int _floor_mapping_16_short[3]={
  154154. 9,3,3
  154155. };
  154156. static int _floor_mapping_16[3]={
  154157. 9,9,9
  154158. };
  154159. static double rate_mapping_16[4]={
  154160. 12000.,20000.,44000.,86000.
  154161. };
  154162. static double rate_mapping_16_uncoupled[4]={
  154163. 16000.,28000.,64000.,100000.
  154164. };
  154165. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154166. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154167. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154168. ve_setup_data_template ve_setup_16_stereo={
  154169. 3,
  154170. rate_mapping_16,
  154171. quality_mapping_16,
  154172. 2,
  154173. 15000,
  154174. 19000,
  154175. blocksize_16_short,
  154176. blocksize_16_long,
  154177. _psy_tone_masteratt_16,
  154178. _psy_tone_0dB,
  154179. _psy_tone_suppress,
  154180. _vp_tonemask_adj_16,
  154181. _vp_tonemask_adj_16,
  154182. _vp_tonemask_adj_16,
  154183. _psy_noiseguards_8,
  154184. _psy_noisebias_16_impulse,
  154185. _psy_noisebias_16_short,
  154186. _psy_noisebias_16_short,
  154187. _psy_noisebias_16,
  154188. _psy_noise_suppress,
  154189. _psy_compand_8,
  154190. _psy_compand_16_mapping,
  154191. _psy_compand_16_mapping,
  154192. {_noise_start_16,_noise_start_16},
  154193. { _noise_part_16, _noise_part_16},
  154194. _noise_thresh_16,
  154195. _psy_ath_floater_16,
  154196. _psy_ath_abs_16,
  154197. _psy_lowpass_16,
  154198. _psy_global_44,
  154199. _global_mapping_16,
  154200. _psy_stereo_modes_16,
  154201. _floor_books,
  154202. _floor,
  154203. _floor_mapping_16_short,
  154204. _floor_mapping_16,
  154205. _mapres_template_16_stereo
  154206. };
  154207. ve_setup_data_template ve_setup_16_uncoupled={
  154208. 3,
  154209. rate_mapping_16_uncoupled,
  154210. quality_mapping_16,
  154211. -1,
  154212. 15000,
  154213. 19000,
  154214. blocksize_16_short,
  154215. blocksize_16_long,
  154216. _psy_tone_masteratt_16,
  154217. _psy_tone_0dB,
  154218. _psy_tone_suppress,
  154219. _vp_tonemask_adj_16,
  154220. _vp_tonemask_adj_16,
  154221. _vp_tonemask_adj_16,
  154222. _psy_noiseguards_8,
  154223. _psy_noisebias_16_impulse,
  154224. _psy_noisebias_16_short,
  154225. _psy_noisebias_16_short,
  154226. _psy_noisebias_16,
  154227. _psy_noise_suppress,
  154228. _psy_compand_8,
  154229. _psy_compand_16_mapping,
  154230. _psy_compand_16_mapping,
  154231. {_noise_start_16,_noise_start_16},
  154232. { _noise_part_16, _noise_part_16},
  154233. _noise_thresh_16,
  154234. _psy_ath_floater_16,
  154235. _psy_ath_abs_16,
  154236. _psy_lowpass_16,
  154237. _psy_global_44,
  154238. _global_mapping_16,
  154239. _psy_stereo_modes_16,
  154240. _floor_books,
  154241. _floor,
  154242. _floor_mapping_16_short,
  154243. _floor_mapping_16,
  154244. _mapres_template_16_uncoupled
  154245. };
  154246. /*** End of inlined file: setup_16.h ***/
  154247. /*** Start of inlined file: setup_22.h ***/
  154248. static double rate_mapping_22[4]={
  154249. 15000.,20000.,44000.,86000.
  154250. };
  154251. static double rate_mapping_22_uncoupled[4]={
  154252. 16000.,28000.,50000.,90000.
  154253. };
  154254. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154255. ve_setup_data_template ve_setup_22_stereo={
  154256. 3,
  154257. rate_mapping_22,
  154258. quality_mapping_16,
  154259. 2,
  154260. 19000,
  154261. 26000,
  154262. blocksize_16_short,
  154263. blocksize_16_long,
  154264. _psy_tone_masteratt_16,
  154265. _psy_tone_0dB,
  154266. _psy_tone_suppress,
  154267. _vp_tonemask_adj_16,
  154268. _vp_tonemask_adj_16,
  154269. _vp_tonemask_adj_16,
  154270. _psy_noiseguards_8,
  154271. _psy_noisebias_16_impulse,
  154272. _psy_noisebias_16_short,
  154273. _psy_noisebias_16_short,
  154274. _psy_noisebias_16,
  154275. _psy_noise_suppress,
  154276. _psy_compand_8,
  154277. _psy_compand_8_mapping,
  154278. _psy_compand_8_mapping,
  154279. {_noise_start_16,_noise_start_16},
  154280. { _noise_part_16, _noise_part_16},
  154281. _noise_thresh_16,
  154282. _psy_ath_floater_16,
  154283. _psy_ath_abs_16,
  154284. _psy_lowpass_22,
  154285. _psy_global_44,
  154286. _global_mapping_16,
  154287. _psy_stereo_modes_16,
  154288. _floor_books,
  154289. _floor,
  154290. _floor_mapping_16_short,
  154291. _floor_mapping_16,
  154292. _mapres_template_16_stereo
  154293. };
  154294. ve_setup_data_template ve_setup_22_uncoupled={
  154295. 3,
  154296. rate_mapping_22_uncoupled,
  154297. quality_mapping_16,
  154298. -1,
  154299. 19000,
  154300. 26000,
  154301. blocksize_16_short,
  154302. blocksize_16_long,
  154303. _psy_tone_masteratt_16,
  154304. _psy_tone_0dB,
  154305. _psy_tone_suppress,
  154306. _vp_tonemask_adj_16,
  154307. _vp_tonemask_adj_16,
  154308. _vp_tonemask_adj_16,
  154309. _psy_noiseguards_8,
  154310. _psy_noisebias_16_impulse,
  154311. _psy_noisebias_16_short,
  154312. _psy_noisebias_16_short,
  154313. _psy_noisebias_16,
  154314. _psy_noise_suppress,
  154315. _psy_compand_8,
  154316. _psy_compand_8_mapping,
  154317. _psy_compand_8_mapping,
  154318. {_noise_start_16,_noise_start_16},
  154319. { _noise_part_16, _noise_part_16},
  154320. _noise_thresh_16,
  154321. _psy_ath_floater_16,
  154322. _psy_ath_abs_16,
  154323. _psy_lowpass_22,
  154324. _psy_global_44,
  154325. _global_mapping_16,
  154326. _psy_stereo_modes_16,
  154327. _floor_books,
  154328. _floor,
  154329. _floor_mapping_16_short,
  154330. _floor_mapping_16,
  154331. _mapres_template_16_uncoupled
  154332. };
  154333. /*** End of inlined file: setup_22.h ***/
  154334. /*** Start of inlined file: setup_X.h ***/
  154335. static double rate_mapping_X[12]={
  154336. -1.,-1.,-1.,-1.,-1.,-1.,
  154337. -1.,-1.,-1.,-1.,-1.,-1.
  154338. };
  154339. ve_setup_data_template ve_setup_X_stereo={
  154340. 11,
  154341. rate_mapping_X,
  154342. quality_mapping_44,
  154343. 2,
  154344. 50000,
  154345. 200000,
  154346. blocksize_short_44,
  154347. blocksize_long_44,
  154348. _psy_tone_masteratt_44,
  154349. _psy_tone_0dB,
  154350. _psy_tone_suppress,
  154351. _vp_tonemask_adj_otherblock,
  154352. _vp_tonemask_adj_longblock,
  154353. _vp_tonemask_adj_otherblock,
  154354. _psy_noiseguards_44,
  154355. _psy_noisebias_impulse,
  154356. _psy_noisebias_padding,
  154357. _psy_noisebias_trans,
  154358. _psy_noisebias_long,
  154359. _psy_noise_suppress,
  154360. _psy_compand_44,
  154361. _psy_compand_short_mapping,
  154362. _psy_compand_long_mapping,
  154363. {_noise_start_short_44,_noise_start_long_44},
  154364. {_noise_part_short_44,_noise_part_long_44},
  154365. _noise_thresh_44,
  154366. _psy_ath_floater,
  154367. _psy_ath_abs,
  154368. _psy_lowpass_44,
  154369. _psy_global_44,
  154370. _global_mapping_44,
  154371. _psy_stereo_modes_44,
  154372. _floor_books,
  154373. _floor,
  154374. _floor_short_mapping_44,
  154375. _floor_long_mapping_44,
  154376. _mapres_template_44_stereo
  154377. };
  154378. ve_setup_data_template ve_setup_X_uncoupled={
  154379. 11,
  154380. rate_mapping_X,
  154381. quality_mapping_44,
  154382. -1,
  154383. 50000,
  154384. 200000,
  154385. blocksize_short_44,
  154386. blocksize_long_44,
  154387. _psy_tone_masteratt_44,
  154388. _psy_tone_0dB,
  154389. _psy_tone_suppress,
  154390. _vp_tonemask_adj_otherblock,
  154391. _vp_tonemask_adj_longblock,
  154392. _vp_tonemask_adj_otherblock,
  154393. _psy_noiseguards_44,
  154394. _psy_noisebias_impulse,
  154395. _psy_noisebias_padding,
  154396. _psy_noisebias_trans,
  154397. _psy_noisebias_long,
  154398. _psy_noise_suppress,
  154399. _psy_compand_44,
  154400. _psy_compand_short_mapping,
  154401. _psy_compand_long_mapping,
  154402. {_noise_start_short_44,_noise_start_long_44},
  154403. {_noise_part_short_44,_noise_part_long_44},
  154404. _noise_thresh_44,
  154405. _psy_ath_floater,
  154406. _psy_ath_abs,
  154407. _psy_lowpass_44,
  154408. _psy_global_44,
  154409. _global_mapping_44,
  154410. NULL,
  154411. _floor_books,
  154412. _floor,
  154413. _floor_short_mapping_44,
  154414. _floor_long_mapping_44,
  154415. _mapres_template_44_uncoupled
  154416. };
  154417. ve_setup_data_template ve_setup_XX_stereo={
  154418. 2,
  154419. rate_mapping_X,
  154420. quality_mapping_8,
  154421. 2,
  154422. 0,
  154423. 8000,
  154424. blocksize_8,
  154425. blocksize_8,
  154426. _psy_tone_masteratt_8,
  154427. _psy_tone_0dB,
  154428. _psy_tone_suppress,
  154429. _vp_tonemask_adj_8,
  154430. NULL,
  154431. _vp_tonemask_adj_8,
  154432. _psy_noiseguards_8,
  154433. _psy_noisebias_8,
  154434. _psy_noisebias_8,
  154435. NULL,
  154436. NULL,
  154437. _psy_noise_suppress,
  154438. _psy_compand_8,
  154439. _psy_compand_8_mapping,
  154440. NULL,
  154441. {_noise_start_8,_noise_start_8},
  154442. {_noise_part_8,_noise_part_8},
  154443. _noise_thresh_5only,
  154444. _psy_ath_floater_8,
  154445. _psy_ath_abs_8,
  154446. _psy_lowpass_8,
  154447. _psy_global_44,
  154448. _global_mapping_8,
  154449. _psy_stereo_modes_8,
  154450. _floor_books,
  154451. _floor,
  154452. _floor_mapping_8,
  154453. NULL,
  154454. _mapres_template_8_stereo
  154455. };
  154456. ve_setup_data_template ve_setup_XX_uncoupled={
  154457. 2,
  154458. rate_mapping_X,
  154459. quality_mapping_8,
  154460. -1,
  154461. 0,
  154462. 8000,
  154463. blocksize_8,
  154464. blocksize_8,
  154465. _psy_tone_masteratt_8,
  154466. _psy_tone_0dB,
  154467. _psy_tone_suppress,
  154468. _vp_tonemask_adj_8,
  154469. NULL,
  154470. _vp_tonemask_adj_8,
  154471. _psy_noiseguards_8,
  154472. _psy_noisebias_8,
  154473. _psy_noisebias_8,
  154474. NULL,
  154475. NULL,
  154476. _psy_noise_suppress,
  154477. _psy_compand_8,
  154478. _psy_compand_8_mapping,
  154479. NULL,
  154480. {_noise_start_8,_noise_start_8},
  154481. {_noise_part_8,_noise_part_8},
  154482. _noise_thresh_5only,
  154483. _psy_ath_floater_8,
  154484. _psy_ath_abs_8,
  154485. _psy_lowpass_8,
  154486. _psy_global_44,
  154487. _global_mapping_8,
  154488. _psy_stereo_modes_8,
  154489. _floor_books,
  154490. _floor,
  154491. _floor_mapping_8,
  154492. NULL,
  154493. _mapres_template_8_uncoupled
  154494. };
  154495. /*** End of inlined file: setup_X.h ***/
  154496. static ve_setup_data_template *setup_list[]={
  154497. &ve_setup_44_stereo,
  154498. &ve_setup_44_uncoupled,
  154499. &ve_setup_32_stereo,
  154500. &ve_setup_32_uncoupled,
  154501. &ve_setup_22_stereo,
  154502. &ve_setup_22_uncoupled,
  154503. &ve_setup_16_stereo,
  154504. &ve_setup_16_uncoupled,
  154505. &ve_setup_11_stereo,
  154506. &ve_setup_11_uncoupled,
  154507. &ve_setup_8_stereo,
  154508. &ve_setup_8_uncoupled,
  154509. &ve_setup_X_stereo,
  154510. &ve_setup_X_uncoupled,
  154511. &ve_setup_XX_stereo,
  154512. &ve_setup_XX_uncoupled,
  154513. 0
  154514. };
  154515. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154516. if(vi && vi->codec_setup){
  154517. vi->version=0;
  154518. vi->channels=ch;
  154519. vi->rate=rate;
  154520. return(0);
  154521. }
  154522. return(OV_EINVAL);
  154523. }
  154524. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154525. static_codebook ***books,
  154526. vorbis_info_floor1 *in,
  154527. int *x){
  154528. int i,k,is=s;
  154529. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154530. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154531. memcpy(f,in+x[is],sizeof(*f));
  154532. /* fill in the lowpass field, even if it's temporary */
  154533. f->n=ci->blocksizes[block]>>1;
  154534. /* books */
  154535. {
  154536. int partitions=f->partitions;
  154537. int maxclass=-1;
  154538. int maxbook=-1;
  154539. for(i=0;i<partitions;i++)
  154540. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154541. for(i=0;i<=maxclass;i++){
  154542. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154543. f->class_book[i]+=ci->books;
  154544. for(k=0;k<(1<<f->class_subs[i]);k++){
  154545. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154546. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154547. }
  154548. }
  154549. for(i=0;i<=maxbook;i++)
  154550. ci->book_param[ci->books++]=books[x[is]][i];
  154551. }
  154552. /* for now, we're only using floor 1 */
  154553. ci->floor_type[ci->floors]=1;
  154554. ci->floor_param[ci->floors]=f;
  154555. ci->floors++;
  154556. return;
  154557. }
  154558. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154559. vorbis_info_psy_global *in,
  154560. double *x){
  154561. int i,is=s;
  154562. double ds=s-is;
  154563. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154564. vorbis_info_psy_global *g=&ci->psy_g_param;
  154565. memcpy(g,in+(int)x[is],sizeof(*g));
  154566. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154567. is=(int)ds;
  154568. ds-=is;
  154569. if(ds==0 && is>0){
  154570. is--;
  154571. ds=1.;
  154572. }
  154573. /* interpolate the trigger threshholds */
  154574. for(i=0;i<4;i++){
  154575. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154576. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154577. }
  154578. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154579. return;
  154580. }
  154581. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154582. highlevel_encode_setup *hi,
  154583. adj_stereo *p){
  154584. float s=hi->stereo_point_setting;
  154585. int i,is=s;
  154586. double ds=s-is;
  154587. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154588. vorbis_info_psy_global *g=&ci->psy_g_param;
  154589. if(p){
  154590. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154591. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154592. if(hi->managed){
  154593. /* interpolate the kHz threshholds */
  154594. for(i=0;i<PACKETBLOBS;i++){
  154595. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154596. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154597. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154598. g->coupling_pkHz[i]=kHz;
  154599. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154600. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154601. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154602. }
  154603. }else{
  154604. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154605. for(i=0;i<PACKETBLOBS;i++){
  154606. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154607. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154608. g->coupling_pkHz[i]=kHz;
  154609. }
  154610. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154611. for(i=0;i<PACKETBLOBS;i++){
  154612. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154613. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154614. }
  154615. }
  154616. }else{
  154617. for(i=0;i<PACKETBLOBS;i++){
  154618. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154619. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154620. }
  154621. }
  154622. return;
  154623. }
  154624. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154625. int *nn_start,
  154626. int *nn_partition,
  154627. double *nn_thresh,
  154628. int block){
  154629. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154630. vorbis_info_psy *p=ci->psy_param[block];
  154631. highlevel_encode_setup *hi=&ci->hi;
  154632. int is=s;
  154633. if(block>=ci->psys)
  154634. ci->psys=block+1;
  154635. if(!p){
  154636. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154637. ci->psy_param[block]=p;
  154638. }
  154639. memcpy(p,&_psy_info_template,sizeof(*p));
  154640. p->blockflag=block>>1;
  154641. if(hi->noise_normalize_p){
  154642. p->normal_channel_p=1;
  154643. p->normal_point_p=1;
  154644. p->normal_start=nn_start[is];
  154645. p->normal_partition=nn_partition[is];
  154646. p->normal_thresh=nn_thresh[is];
  154647. }
  154648. return;
  154649. }
  154650. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154651. att3 *att,
  154652. int *max,
  154653. vp_adjblock *in){
  154654. int i,is=s;
  154655. double ds=s-is;
  154656. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154657. vorbis_info_psy *p=ci->psy_param[block];
  154658. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154659. filling the values in here */
  154660. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154661. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154662. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154663. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154664. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154665. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154666. for(i=0;i<P_BANDS;i++)
  154667. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154668. return;
  154669. }
  154670. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154671. compandblock *in, double *x){
  154672. int i,is=s;
  154673. double ds=s-is;
  154674. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154675. vorbis_info_psy *p=ci->psy_param[block];
  154676. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154677. is=(int)ds;
  154678. ds-=is;
  154679. if(ds==0 && is>0){
  154680. is--;
  154681. ds=1.;
  154682. }
  154683. /* interpolate the compander settings */
  154684. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154685. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154686. return;
  154687. }
  154688. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154689. int *suppress){
  154690. int is=s;
  154691. double ds=s-is;
  154692. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154693. vorbis_info_psy *p=ci->psy_param[block];
  154694. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154695. return;
  154696. }
  154697. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154698. int *suppress,
  154699. noise3 *in,
  154700. noiseguard *guard,
  154701. double userbias){
  154702. int i,is=s,j;
  154703. double ds=s-is;
  154704. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154705. vorbis_info_psy *p=ci->psy_param[block];
  154706. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154707. p->noisewindowlomin=guard[block].lo;
  154708. p->noisewindowhimin=guard[block].hi;
  154709. p->noisewindowfixed=guard[block].fixed;
  154710. for(j=0;j<P_NOISECURVES;j++)
  154711. for(i=0;i<P_BANDS;i++)
  154712. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154713. /* impulse blocks may take a user specified bias to boost the
  154714. nominal/high noise encoding depth */
  154715. for(j=0;j<P_NOISECURVES;j++){
  154716. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154717. for(i=0;i<P_BANDS;i++){
  154718. p->noiseoff[j][i]+=userbias;
  154719. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154720. }
  154721. }
  154722. return;
  154723. }
  154724. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154725. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154726. vorbis_info_psy *p=ci->psy_param[block];
  154727. p->ath_adjatt=ci->hi.ath_floating_dB;
  154728. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154729. return;
  154730. }
  154731. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154732. int i;
  154733. for(i=0;i<ci->books;i++)
  154734. if(ci->book_param[i]==book)return(i);
  154735. return(ci->books++);
  154736. }
  154737. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154738. int *shortb,int *longb){
  154739. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154740. int is=s;
  154741. int blockshort=shortb[is];
  154742. int blocklong=longb[is];
  154743. ci->blocksizes[0]=blockshort;
  154744. ci->blocksizes[1]=blocklong;
  154745. }
  154746. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154747. int number, int block,
  154748. vorbis_residue_template *res){
  154749. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154750. int i,n;
  154751. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154752. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154753. memcpy(r,res->res,sizeof(*r));
  154754. if(ci->residues<=number)ci->residues=number+1;
  154755. switch(ci->blocksizes[block]){
  154756. case 64:case 128:case 256:
  154757. r->grouping=16;
  154758. break;
  154759. default:
  154760. r->grouping=32;
  154761. break;
  154762. }
  154763. ci->residue_type[number]=res->res_type;
  154764. /* to be adjusted by lowpass/pointlimit later */
  154765. n=r->end=ci->blocksizes[block]>>1;
  154766. if(res->res_type==2)
  154767. n=r->end*=vi->channels;
  154768. /* fill in all the books */
  154769. {
  154770. int booklist=0,k;
  154771. if(ci->hi.managed){
  154772. for(i=0;i<r->partitions;i++)
  154773. for(k=0;k<3;k++)
  154774. if(res->books_base_managed->books[i][k])
  154775. r->secondstages[i]|=(1<<k);
  154776. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154777. ci->book_param[r->groupbook]=res->book_aux_managed;
  154778. for(i=0;i<r->partitions;i++){
  154779. for(k=0;k<3;k++){
  154780. if(res->books_base_managed->books[i][k]){
  154781. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154782. r->booklist[booklist++]=bookid;
  154783. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154784. }
  154785. }
  154786. }
  154787. }else{
  154788. for(i=0;i<r->partitions;i++)
  154789. for(k=0;k<3;k++)
  154790. if(res->books_base->books[i][k])
  154791. r->secondstages[i]|=(1<<k);
  154792. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154793. ci->book_param[r->groupbook]=res->book_aux;
  154794. for(i=0;i<r->partitions;i++){
  154795. for(k=0;k<3;k++){
  154796. if(res->books_base->books[i][k]){
  154797. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154798. r->booklist[booklist++]=bookid;
  154799. ci->book_param[bookid]=res->books_base->books[i][k];
  154800. }
  154801. }
  154802. }
  154803. }
  154804. }
  154805. /* lowpass setup/pointlimit */
  154806. {
  154807. double freq=ci->hi.lowpass_kHz*1000.;
  154808. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154809. double nyq=vi->rate/2.;
  154810. long blocksize=ci->blocksizes[block]>>1;
  154811. /* lowpass needs to be set in the floor and the residue. */
  154812. if(freq>nyq)freq=nyq;
  154813. /* in the floor, the granularity can be very fine; it doesn't alter
  154814. the encoding structure, only the samples used to fit the floor
  154815. approximation */
  154816. f->n=freq/nyq*blocksize;
  154817. /* this res may by limited by the maximum pointlimit of the mode,
  154818. not the lowpass. the floor is always lowpass limited. */
  154819. if(res->limit_type){
  154820. if(ci->hi.managed)
  154821. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154822. else
  154823. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154824. if(freq>nyq)freq=nyq;
  154825. }
  154826. /* in the residue, we're constrained, physically, by partition
  154827. boundaries. We still lowpass 'wherever', but we have to round up
  154828. here to next boundary, or the vorbis spec will round it *down* to
  154829. previous boundary in encode/decode */
  154830. if(ci->residue_type[block]==2)
  154831. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154832. r->grouping;
  154833. else
  154834. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154835. r->grouping;
  154836. }
  154837. }
  154838. /* we assume two maps in this encoder */
  154839. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154840. vorbis_mapping_template *maps){
  154841. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154842. int i,j,is=s,modes=2;
  154843. vorbis_info_mapping0 *map=maps[is].map;
  154844. vorbis_info_mode *mode=_mode_template;
  154845. vorbis_residue_template *res=maps[is].res;
  154846. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154847. for(i=0;i<modes;i++){
  154848. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154849. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154850. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154851. if(i>=ci->modes)ci->modes=i+1;
  154852. ci->map_type[i]=0;
  154853. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154854. if(i>=ci->maps)ci->maps=i+1;
  154855. for(j=0;j<map[i].submaps;j++)
  154856. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154857. ,res+map[i].residuesubmap[j]);
  154858. }
  154859. }
  154860. static double setting_to_approx_bitrate(vorbis_info *vi){
  154861. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154862. highlevel_encode_setup *hi=&ci->hi;
  154863. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154864. int is=hi->base_setting;
  154865. double ds=hi->base_setting-is;
  154866. int ch=vi->channels;
  154867. double *r=setup->rate_mapping;
  154868. if(r==NULL)
  154869. return(-1);
  154870. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154871. }
  154872. static void get_setup_template(vorbis_info *vi,
  154873. long ch,long srate,
  154874. double req,int q_or_bitrate){
  154875. int i=0,j;
  154876. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154877. highlevel_encode_setup *hi=&ci->hi;
  154878. if(q_or_bitrate)req/=ch;
  154879. while(setup_list[i]){
  154880. if(setup_list[i]->coupling_restriction==-1 ||
  154881. setup_list[i]->coupling_restriction==ch){
  154882. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154883. srate<=setup_list[i]->samplerate_max_restriction){
  154884. int mappings=setup_list[i]->mappings;
  154885. double *map=(q_or_bitrate?
  154886. setup_list[i]->rate_mapping:
  154887. setup_list[i]->quality_mapping);
  154888. /* the template matches. Does the requested quality mode
  154889. fall within this template's modes? */
  154890. if(req<map[0]){++i;continue;}
  154891. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154892. for(j=0;j<mappings;j++)
  154893. if(req>=map[j] && req<map[j+1])break;
  154894. /* an all-points match */
  154895. hi->setup=setup_list[i];
  154896. if(j==mappings)
  154897. hi->base_setting=j-.001;
  154898. else{
  154899. float low=map[j];
  154900. float high=map[j+1];
  154901. float del=(req-low)/(high-low);
  154902. hi->base_setting=j+del;
  154903. }
  154904. return;
  154905. }
  154906. }
  154907. i++;
  154908. }
  154909. hi->setup=NULL;
  154910. }
  154911. /* encoders will need to use vorbis_info_init beforehand and call
  154912. vorbis_info clear when all done */
  154913. /* two interfaces; this, more detailed one, and later a convenience
  154914. layer on top */
  154915. /* the final setup call */
  154916. int vorbis_encode_setup_init(vorbis_info *vi){
  154917. int i0=0,singleblock=0;
  154918. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154919. ve_setup_data_template *setup=NULL;
  154920. highlevel_encode_setup *hi=&ci->hi;
  154921. if(ci==NULL)return(OV_EINVAL);
  154922. if(!hi->impulse_block_p)i0=1;
  154923. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154924. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154925. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154926. /* again, bound this to avoid the app shooting itself int he foot
  154927. too badly */
  154928. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154929. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154930. /* get the appropriate setup template; matches the fetch in previous
  154931. stages */
  154932. setup=(ve_setup_data_template *)hi->setup;
  154933. if(setup==NULL)return(OV_EINVAL);
  154934. hi->set_in_stone=1;
  154935. /* choose block sizes from configured sizes as well as paying
  154936. attention to long_block_p and short_block_p. If the configured
  154937. short and long blocks are the same length, we set long_block_p
  154938. and unset short_block_p */
  154939. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154940. setup->blocksize_short,
  154941. setup->blocksize_long);
  154942. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154943. /* floor setup; choose proper floor params. Allocated on the floor
  154944. stack in order; if we alloc only long floor, it's 0 */
  154945. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154946. setup->floor_books,
  154947. setup->floor_params,
  154948. setup->floor_short_mapping);
  154949. if(!singleblock)
  154950. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154951. setup->floor_books,
  154952. setup->floor_params,
  154953. setup->floor_long_mapping);
  154954. /* setup of [mostly] short block detection and stereo*/
  154955. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154956. setup->global_params,
  154957. setup->global_mapping);
  154958. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154959. /* basic psych setup and noise normalization */
  154960. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154961. setup->psy_noise_normal_start[0],
  154962. setup->psy_noise_normal_partition[0],
  154963. setup->psy_noise_normal_thresh,
  154964. 0);
  154965. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154966. setup->psy_noise_normal_start[0],
  154967. setup->psy_noise_normal_partition[0],
  154968. setup->psy_noise_normal_thresh,
  154969. 1);
  154970. if(!singleblock){
  154971. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154972. setup->psy_noise_normal_start[1],
  154973. setup->psy_noise_normal_partition[1],
  154974. setup->psy_noise_normal_thresh,
  154975. 2);
  154976. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154977. setup->psy_noise_normal_start[1],
  154978. setup->psy_noise_normal_partition[1],
  154979. setup->psy_noise_normal_thresh,
  154980. 3);
  154981. }
  154982. /* tone masking setup */
  154983. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154984. setup->psy_tone_masteratt,
  154985. setup->psy_tone_0dB,
  154986. setup->psy_tone_adj_impulse);
  154987. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154988. setup->psy_tone_masteratt,
  154989. setup->psy_tone_0dB,
  154990. setup->psy_tone_adj_other);
  154991. if(!singleblock){
  154992. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154993. setup->psy_tone_masteratt,
  154994. setup->psy_tone_0dB,
  154995. setup->psy_tone_adj_other);
  154996. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154997. setup->psy_tone_masteratt,
  154998. setup->psy_tone_0dB,
  154999. setup->psy_tone_adj_long);
  155000. }
  155001. /* noise companding setup */
  155002. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155003. setup->psy_noise_compand,
  155004. setup->psy_noise_compand_short_mapping);
  155005. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155006. setup->psy_noise_compand,
  155007. setup->psy_noise_compand_short_mapping);
  155008. if(!singleblock){
  155009. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155010. setup->psy_noise_compand,
  155011. setup->psy_noise_compand_long_mapping);
  155012. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155013. setup->psy_noise_compand,
  155014. setup->psy_noise_compand_long_mapping);
  155015. }
  155016. /* peak guarding setup */
  155017. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155018. setup->psy_tone_dBsuppress);
  155019. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155020. setup->psy_tone_dBsuppress);
  155021. if(!singleblock){
  155022. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155023. setup->psy_tone_dBsuppress);
  155024. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155025. setup->psy_tone_dBsuppress);
  155026. }
  155027. /* noise bias setup */
  155028. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155029. setup->psy_noise_dBsuppress,
  155030. setup->psy_noise_bias_impulse,
  155031. setup->psy_noiseguards,
  155032. (i0==0?hi->impulse_noisetune:0.));
  155033. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155034. setup->psy_noise_dBsuppress,
  155035. setup->psy_noise_bias_padding,
  155036. setup->psy_noiseguards,0.);
  155037. if(!singleblock){
  155038. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155039. setup->psy_noise_dBsuppress,
  155040. setup->psy_noise_bias_trans,
  155041. setup->psy_noiseguards,0.);
  155042. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155043. setup->psy_noise_dBsuppress,
  155044. setup->psy_noise_bias_long,
  155045. setup->psy_noiseguards,0.);
  155046. }
  155047. vorbis_encode_ath_setup(vi,0);
  155048. vorbis_encode_ath_setup(vi,1);
  155049. if(!singleblock){
  155050. vorbis_encode_ath_setup(vi,2);
  155051. vorbis_encode_ath_setup(vi,3);
  155052. }
  155053. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155054. /* set bitrate readonlies and management */
  155055. if(hi->bitrate_av>0)
  155056. vi->bitrate_nominal=hi->bitrate_av;
  155057. else{
  155058. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155059. }
  155060. vi->bitrate_lower=hi->bitrate_min;
  155061. vi->bitrate_upper=hi->bitrate_max;
  155062. if(hi->bitrate_av)
  155063. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155064. else
  155065. vi->bitrate_window=0.;
  155066. if(hi->managed){
  155067. ci->bi.avg_rate=hi->bitrate_av;
  155068. ci->bi.min_rate=hi->bitrate_min;
  155069. ci->bi.max_rate=hi->bitrate_max;
  155070. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155071. ci->bi.reservoir_bias=
  155072. hi->bitrate_reservoir_bias;
  155073. ci->bi.slew_damp=hi->bitrate_av_damp;
  155074. }
  155075. return(0);
  155076. }
  155077. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155078. long channels,
  155079. long rate){
  155080. int ret=0,i,is;
  155081. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155082. highlevel_encode_setup *hi=&ci->hi;
  155083. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155084. double ds;
  155085. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155086. if(ret)return(ret);
  155087. is=hi->base_setting;
  155088. ds=hi->base_setting-is;
  155089. hi->short_setting=hi->base_setting;
  155090. hi->long_setting=hi->base_setting;
  155091. hi->managed=0;
  155092. hi->impulse_block_p=1;
  155093. hi->noise_normalize_p=1;
  155094. hi->stereo_point_setting=hi->base_setting;
  155095. hi->lowpass_kHz=
  155096. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155097. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155098. setup->psy_ath_float[is+1]*ds;
  155099. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155100. setup->psy_ath_abs[is+1]*ds;
  155101. hi->amplitude_track_dBpersec=-6.;
  155102. hi->trigger_setting=hi->base_setting;
  155103. for(i=0;i<4;i++){
  155104. hi->block[i].tone_mask_setting=hi->base_setting;
  155105. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155106. hi->block[i].noise_bias_setting=hi->base_setting;
  155107. hi->block[i].noise_compand_setting=hi->base_setting;
  155108. }
  155109. return(ret);
  155110. }
  155111. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155112. long channels,
  155113. long rate,
  155114. float quality){
  155115. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155116. highlevel_encode_setup *hi=&ci->hi;
  155117. quality+=.0000001;
  155118. if(quality>=1.)quality=.9999;
  155119. get_setup_template(vi,channels,rate,quality,0);
  155120. if(!hi->setup)return OV_EIMPL;
  155121. return vorbis_encode_setup_setting(vi,channels,rate);
  155122. }
  155123. int vorbis_encode_init_vbr(vorbis_info *vi,
  155124. long channels,
  155125. long rate,
  155126. float base_quality /* 0. to 1. */
  155127. ){
  155128. int ret=0;
  155129. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155130. if(ret){
  155131. vorbis_info_clear(vi);
  155132. return ret;
  155133. }
  155134. ret=vorbis_encode_setup_init(vi);
  155135. if(ret)
  155136. vorbis_info_clear(vi);
  155137. return(ret);
  155138. }
  155139. int vorbis_encode_setup_managed(vorbis_info *vi,
  155140. long channels,
  155141. long rate,
  155142. long max_bitrate,
  155143. long nominal_bitrate,
  155144. long min_bitrate){
  155145. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155146. highlevel_encode_setup *hi=&ci->hi;
  155147. double tnominal=nominal_bitrate;
  155148. int ret=0;
  155149. if(nominal_bitrate<=0.){
  155150. if(max_bitrate>0.){
  155151. if(min_bitrate>0.)
  155152. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155153. else
  155154. nominal_bitrate=max_bitrate*.875;
  155155. }else{
  155156. if(min_bitrate>0.){
  155157. nominal_bitrate=min_bitrate;
  155158. }else{
  155159. return(OV_EINVAL);
  155160. }
  155161. }
  155162. }
  155163. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155164. if(!hi->setup)return OV_EIMPL;
  155165. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155166. if(ret){
  155167. vorbis_info_clear(vi);
  155168. return ret;
  155169. }
  155170. /* initialize management with sane defaults */
  155171. hi->managed=1;
  155172. hi->bitrate_min=min_bitrate;
  155173. hi->bitrate_max=max_bitrate;
  155174. hi->bitrate_av=tnominal;
  155175. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155176. hi->bitrate_reservoir=nominal_bitrate*2;
  155177. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155178. return(ret);
  155179. }
  155180. int vorbis_encode_init(vorbis_info *vi,
  155181. long channels,
  155182. long rate,
  155183. long max_bitrate,
  155184. long nominal_bitrate,
  155185. long min_bitrate){
  155186. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155187. max_bitrate,
  155188. nominal_bitrate,
  155189. min_bitrate);
  155190. if(ret){
  155191. vorbis_info_clear(vi);
  155192. return(ret);
  155193. }
  155194. ret=vorbis_encode_setup_init(vi);
  155195. if(ret)
  155196. vorbis_info_clear(vi);
  155197. return(ret);
  155198. }
  155199. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155200. if(vi){
  155201. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155202. highlevel_encode_setup *hi=&ci->hi;
  155203. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155204. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155205. switch(number){
  155206. /* now deprecated *****************/
  155207. case OV_ECTL_RATEMANAGE_GET:
  155208. {
  155209. struct ovectl_ratemanage_arg *ai=
  155210. (struct ovectl_ratemanage_arg *)arg;
  155211. ai->management_active=hi->managed;
  155212. ai->bitrate_hard_window=ai->bitrate_av_window=
  155213. (double)hi->bitrate_reservoir/vi->rate;
  155214. ai->bitrate_av_window_center=1.;
  155215. ai->bitrate_hard_min=hi->bitrate_min;
  155216. ai->bitrate_hard_max=hi->bitrate_max;
  155217. ai->bitrate_av_lo=hi->bitrate_av;
  155218. ai->bitrate_av_hi=hi->bitrate_av;
  155219. }
  155220. return(0);
  155221. /* now deprecated *****************/
  155222. case OV_ECTL_RATEMANAGE_SET:
  155223. {
  155224. struct ovectl_ratemanage_arg *ai=
  155225. (struct ovectl_ratemanage_arg *)arg;
  155226. if(ai==NULL){
  155227. hi->managed=0;
  155228. }else{
  155229. hi->managed=ai->management_active;
  155230. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155231. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155232. }
  155233. }
  155234. return 0;
  155235. /* now deprecated *****************/
  155236. case OV_ECTL_RATEMANAGE_AVG:
  155237. {
  155238. struct ovectl_ratemanage_arg *ai=
  155239. (struct ovectl_ratemanage_arg *)arg;
  155240. if(ai==NULL){
  155241. hi->bitrate_av=0;
  155242. }else{
  155243. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155244. }
  155245. }
  155246. return(0);
  155247. /* now deprecated *****************/
  155248. case OV_ECTL_RATEMANAGE_HARD:
  155249. {
  155250. struct ovectl_ratemanage_arg *ai=
  155251. (struct ovectl_ratemanage_arg *)arg;
  155252. if(ai==NULL){
  155253. hi->bitrate_min=0;
  155254. hi->bitrate_max=0;
  155255. }else{
  155256. hi->bitrate_min=ai->bitrate_hard_min;
  155257. hi->bitrate_max=ai->bitrate_hard_max;
  155258. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155259. (hi->bitrate_max+hi->bitrate_min)*.5;
  155260. }
  155261. if(hi->bitrate_reservoir<128.)
  155262. hi->bitrate_reservoir=128.;
  155263. }
  155264. return(0);
  155265. /* replacement ratemanage interface */
  155266. case OV_ECTL_RATEMANAGE2_GET:
  155267. {
  155268. struct ovectl_ratemanage2_arg *ai=
  155269. (struct ovectl_ratemanage2_arg *)arg;
  155270. if(ai==NULL)return OV_EINVAL;
  155271. ai->management_active=hi->managed;
  155272. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155273. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155274. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155275. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155276. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155277. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155278. }
  155279. return (0);
  155280. case OV_ECTL_RATEMANAGE2_SET:
  155281. {
  155282. struct ovectl_ratemanage2_arg *ai=
  155283. (struct ovectl_ratemanage2_arg *)arg;
  155284. if(ai==NULL){
  155285. hi->managed=0;
  155286. }else{
  155287. /* sanity check; only catch invariant violations */
  155288. if(ai->bitrate_limit_min_kbps>0 &&
  155289. ai->bitrate_average_kbps>0 &&
  155290. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155291. return OV_EINVAL;
  155292. if(ai->bitrate_limit_max_kbps>0 &&
  155293. ai->bitrate_average_kbps>0 &&
  155294. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155295. return OV_EINVAL;
  155296. if(ai->bitrate_limit_min_kbps>0 &&
  155297. ai->bitrate_limit_max_kbps>0 &&
  155298. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155299. return OV_EINVAL;
  155300. if(ai->bitrate_average_damping <= 0.)
  155301. return OV_EINVAL;
  155302. if(ai->bitrate_limit_reservoir_bits < 0)
  155303. return OV_EINVAL;
  155304. if(ai->bitrate_limit_reservoir_bias < 0.)
  155305. return OV_EINVAL;
  155306. if(ai->bitrate_limit_reservoir_bias > 1.)
  155307. return OV_EINVAL;
  155308. hi->managed=ai->management_active;
  155309. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155310. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155311. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155312. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155313. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155314. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155315. }
  155316. }
  155317. return 0;
  155318. case OV_ECTL_LOWPASS_GET:
  155319. {
  155320. double *farg=(double *)arg;
  155321. *farg=hi->lowpass_kHz;
  155322. }
  155323. return(0);
  155324. case OV_ECTL_LOWPASS_SET:
  155325. {
  155326. double *farg=(double *)arg;
  155327. hi->lowpass_kHz=*farg;
  155328. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155329. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155330. }
  155331. return(0);
  155332. case OV_ECTL_IBLOCK_GET:
  155333. {
  155334. double *farg=(double *)arg;
  155335. *farg=hi->impulse_noisetune;
  155336. }
  155337. return(0);
  155338. case OV_ECTL_IBLOCK_SET:
  155339. {
  155340. double *farg=(double *)arg;
  155341. hi->impulse_noisetune=*farg;
  155342. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155343. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155344. }
  155345. return(0);
  155346. }
  155347. return(OV_EIMPL);
  155348. }
  155349. return(OV_EINVAL);
  155350. }
  155351. #endif
  155352. /*** End of inlined file: vorbisenc.c ***/
  155353. /*** Start of inlined file: vorbisfile.c ***/
  155354. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155355. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155356. // tasks..
  155357. #if JUCE_MSVC
  155358. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155359. #endif
  155360. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155361. #if JUCE_USE_OGGVORBIS
  155362. #include <stdlib.h>
  155363. #include <stdio.h>
  155364. #include <errno.h>
  155365. #include <string.h>
  155366. #include <math.h>
  155367. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155368. one logical bitstream arranged end to end (the only form of Ogg
  155369. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155370. multiplexing] is not allowed in Vorbis) */
  155371. /* A Vorbis file can be played beginning to end (streamed) without
  155372. worrying ahead of time about chaining (see decoder_example.c). If
  155373. we have the whole file, however, and want random access
  155374. (seeking/scrubbing) or desire to know the total length/time of a
  155375. file, we need to account for the possibility of chaining. */
  155376. /* We can handle things a number of ways; we can determine the entire
  155377. bitstream structure right off the bat, or find pieces on demand.
  155378. This example determines and caches structure for the entire
  155379. bitstream, but builds a virtual decoder on the fly when moving
  155380. between links in the chain. */
  155381. /* There are also different ways to implement seeking. Enough
  155382. information exists in an Ogg bitstream to seek to
  155383. sample-granularity positions in the output. Or, one can seek by
  155384. picking some portion of the stream roughly in the desired area if
  155385. we only want coarse navigation through the stream. */
  155386. /*************************************************************************
  155387. * Many, many internal helpers. The intention is not to be confusing;
  155388. * rampant duplication and monolithic function implementation would be
  155389. * harder to understand anyway. The high level functions are last. Begin
  155390. * grokking near the end of the file */
  155391. /* read a little more data from the file/pipe into the ogg_sync framer
  155392. */
  155393. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155394. over 8k gets what they deserve */
  155395. static long _get_data(OggVorbis_File *vf){
  155396. errno=0;
  155397. if(vf->datasource){
  155398. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155399. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155400. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155401. if(bytes==0 && errno)return(-1);
  155402. return(bytes);
  155403. }else
  155404. return(0);
  155405. }
  155406. /* save a tiny smidge of verbosity to make the code more readable */
  155407. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155408. if(vf->datasource){
  155409. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155410. vf->offset=offset;
  155411. ogg_sync_reset(&vf->oy);
  155412. }else{
  155413. /* shouldn't happen unless someone writes a broken callback */
  155414. return;
  155415. }
  155416. }
  155417. /* The read/seek functions track absolute position within the stream */
  155418. /* from the head of the stream, get the next page. boundary specifies
  155419. if the function is allowed to fetch more data from the stream (and
  155420. how much) or only use internally buffered data.
  155421. boundary: -1) unbounded search
  155422. 0) read no additional data; use cached only
  155423. n) search for a new page beginning for n bytes
  155424. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155425. n) found a page at absolute offset n */
  155426. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155427. ogg_int64_t boundary){
  155428. if(boundary>0)boundary+=vf->offset;
  155429. while(1){
  155430. long more;
  155431. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155432. more=ogg_sync_pageseek(&vf->oy,og);
  155433. if(more<0){
  155434. /* skipped n bytes */
  155435. vf->offset-=more;
  155436. }else{
  155437. if(more==0){
  155438. /* send more paramedics */
  155439. if(!boundary)return(OV_FALSE);
  155440. {
  155441. long ret=_get_data(vf);
  155442. if(ret==0)return(OV_EOF);
  155443. if(ret<0)return(OV_EREAD);
  155444. }
  155445. }else{
  155446. /* got a page. Return the offset at the page beginning,
  155447. advance the internal offset past the page end */
  155448. ogg_int64_t ret=vf->offset;
  155449. vf->offset+=more;
  155450. return(ret);
  155451. }
  155452. }
  155453. }
  155454. }
  155455. /* find the latest page beginning before the current stream cursor
  155456. position. Much dirtier than the above as Ogg doesn't have any
  155457. backward search linkage. no 'readp' as it will certainly have to
  155458. read. */
  155459. /* returns offset or OV_EREAD, OV_FAULT */
  155460. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155461. ogg_int64_t begin=vf->offset;
  155462. ogg_int64_t end=begin;
  155463. ogg_int64_t ret;
  155464. ogg_int64_t offset=-1;
  155465. while(offset==-1){
  155466. begin-=CHUNKSIZE;
  155467. if(begin<0)
  155468. begin=0;
  155469. _seek_helper(vf,begin);
  155470. while(vf->offset<end){
  155471. ret=_get_next_page(vf,og,end-vf->offset);
  155472. if(ret==OV_EREAD)return(OV_EREAD);
  155473. if(ret<0){
  155474. break;
  155475. }else{
  155476. offset=ret;
  155477. }
  155478. }
  155479. }
  155480. /* we have the offset. Actually snork and hold the page now */
  155481. _seek_helper(vf,offset);
  155482. ret=_get_next_page(vf,og,CHUNKSIZE);
  155483. if(ret<0)
  155484. /* this shouldn't be possible */
  155485. return(OV_EFAULT);
  155486. return(offset);
  155487. }
  155488. /* finds each bitstream link one at a time using a bisection search
  155489. (has to begin by knowing the offset of the lb's initial page).
  155490. Recurses for each link so it can alloc the link storage after
  155491. finding them all, then unroll and fill the cache at the same time */
  155492. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155493. ogg_int64_t begin,
  155494. ogg_int64_t searched,
  155495. ogg_int64_t end,
  155496. long currentno,
  155497. long m){
  155498. ogg_int64_t endsearched=end;
  155499. ogg_int64_t next=end;
  155500. ogg_page og;
  155501. ogg_int64_t ret;
  155502. /* the below guards against garbage seperating the last and
  155503. first pages of two links. */
  155504. while(searched<endsearched){
  155505. ogg_int64_t bisect;
  155506. if(endsearched-searched<CHUNKSIZE){
  155507. bisect=searched;
  155508. }else{
  155509. bisect=(searched+endsearched)/2;
  155510. }
  155511. _seek_helper(vf,bisect);
  155512. ret=_get_next_page(vf,&og,-1);
  155513. if(ret==OV_EREAD)return(OV_EREAD);
  155514. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155515. endsearched=bisect;
  155516. if(ret>=0)next=ret;
  155517. }else{
  155518. searched=ret+og.header_len+og.body_len;
  155519. }
  155520. }
  155521. _seek_helper(vf,next);
  155522. ret=_get_next_page(vf,&og,-1);
  155523. if(ret==OV_EREAD)return(OV_EREAD);
  155524. if(searched>=end || ret<0){
  155525. vf->links=m+1;
  155526. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155527. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155528. vf->offsets[m+1]=searched;
  155529. }else{
  155530. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155531. end,ogg_page_serialno(&og),m+1);
  155532. if(ret==OV_EREAD)return(OV_EREAD);
  155533. }
  155534. vf->offsets[m]=begin;
  155535. vf->serialnos[m]=currentno;
  155536. return(0);
  155537. }
  155538. /* uses the local ogg_stream storage in vf; this is important for
  155539. non-streaming input sources */
  155540. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155541. long *serialno,ogg_page *og_ptr){
  155542. ogg_page og;
  155543. ogg_packet op;
  155544. int i,ret;
  155545. if(!og_ptr){
  155546. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155547. if(llret==OV_EREAD)return(OV_EREAD);
  155548. if(llret<0)return OV_ENOTVORBIS;
  155549. og_ptr=&og;
  155550. }
  155551. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155552. if(serialno)*serialno=vf->os.serialno;
  155553. vf->ready_state=STREAMSET;
  155554. /* extract the initial header from the first page and verify that the
  155555. Ogg bitstream is in fact Vorbis data */
  155556. vorbis_info_init(vi);
  155557. vorbis_comment_init(vc);
  155558. i=0;
  155559. while(i<3){
  155560. ogg_stream_pagein(&vf->os,og_ptr);
  155561. while(i<3){
  155562. int result=ogg_stream_packetout(&vf->os,&op);
  155563. if(result==0)break;
  155564. if(result==-1){
  155565. ret=OV_EBADHEADER;
  155566. goto bail_header;
  155567. }
  155568. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155569. goto bail_header;
  155570. }
  155571. i++;
  155572. }
  155573. if(i<3)
  155574. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155575. ret=OV_EBADHEADER;
  155576. goto bail_header;
  155577. }
  155578. }
  155579. return 0;
  155580. bail_header:
  155581. vorbis_info_clear(vi);
  155582. vorbis_comment_clear(vc);
  155583. vf->ready_state=OPENED;
  155584. return ret;
  155585. }
  155586. /* last step of the OggVorbis_File initialization; get all the
  155587. vorbis_info structs and PCM positions. Only called by the seekable
  155588. initialization (local stream storage is hacked slightly; pay
  155589. attention to how that's done) */
  155590. /* this is void and does not propogate errors up because we want to be
  155591. able to open and use damaged bitstreams as well as we can. Just
  155592. watch out for missing information for links in the OggVorbis_File
  155593. struct */
  155594. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155595. ogg_page og;
  155596. int i;
  155597. ogg_int64_t ret;
  155598. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155599. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155600. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155601. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155602. for(i=0;i<vf->links;i++){
  155603. if(i==0){
  155604. /* we already grabbed the initial header earlier. Just set the offset */
  155605. vf->dataoffsets[i]=dataoffset;
  155606. _seek_helper(vf,dataoffset);
  155607. }else{
  155608. /* seek to the location of the initial header */
  155609. _seek_helper(vf,vf->offsets[i]);
  155610. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155611. vf->dataoffsets[i]=-1;
  155612. }else{
  155613. vf->dataoffsets[i]=vf->offset;
  155614. }
  155615. }
  155616. /* fetch beginning PCM offset */
  155617. if(vf->dataoffsets[i]!=-1){
  155618. ogg_int64_t accumulated=0;
  155619. long lastblock=-1;
  155620. int result;
  155621. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155622. while(1){
  155623. ogg_packet op;
  155624. ret=_get_next_page(vf,&og,-1);
  155625. if(ret<0)
  155626. /* this should not be possible unless the file is
  155627. truncated/mangled */
  155628. break;
  155629. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155630. break;
  155631. /* count blocksizes of all frames in the page */
  155632. ogg_stream_pagein(&vf->os,&og);
  155633. while((result=ogg_stream_packetout(&vf->os,&op))){
  155634. if(result>0){ /* ignore holes */
  155635. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155636. if(lastblock!=-1)
  155637. accumulated+=(lastblock+thisblock)>>2;
  155638. lastblock=thisblock;
  155639. }
  155640. }
  155641. if(ogg_page_granulepos(&og)!=-1){
  155642. /* pcm offset of last packet on the first audio page */
  155643. accumulated= ogg_page_granulepos(&og)-accumulated;
  155644. break;
  155645. }
  155646. }
  155647. /* less than zero? This is a stream with samples trimmed off
  155648. the beginning, a normal occurrence; set the offset to zero */
  155649. if(accumulated<0)accumulated=0;
  155650. vf->pcmlengths[i*2]=accumulated;
  155651. }
  155652. /* get the PCM length of this link. To do this,
  155653. get the last page of the stream */
  155654. {
  155655. ogg_int64_t end=vf->offsets[i+1];
  155656. _seek_helper(vf,end);
  155657. while(1){
  155658. ret=_get_prev_page(vf,&og);
  155659. if(ret<0){
  155660. /* this should not be possible */
  155661. vorbis_info_clear(vf->vi+i);
  155662. vorbis_comment_clear(vf->vc+i);
  155663. break;
  155664. }
  155665. if(ogg_page_granulepos(&og)!=-1){
  155666. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155667. break;
  155668. }
  155669. vf->offset=ret;
  155670. }
  155671. }
  155672. }
  155673. }
  155674. static int _make_decode_ready(OggVorbis_File *vf){
  155675. if(vf->ready_state>STREAMSET)return 0;
  155676. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155677. if(vf->seekable){
  155678. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155679. return OV_EBADLINK;
  155680. }else{
  155681. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155682. return OV_EBADLINK;
  155683. }
  155684. vorbis_block_init(&vf->vd,&vf->vb);
  155685. vf->ready_state=INITSET;
  155686. vf->bittrack=0.f;
  155687. vf->samptrack=0.f;
  155688. return 0;
  155689. }
  155690. static int _open_seekable2(OggVorbis_File *vf){
  155691. long serialno=vf->current_serialno;
  155692. ogg_int64_t dataoffset=vf->offset, end;
  155693. ogg_page og;
  155694. /* we're partially open and have a first link header state in
  155695. storage in vf */
  155696. /* we can seek, so set out learning all about this file */
  155697. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155698. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155699. /* We get the offset for the last page of the physical bitstream.
  155700. Most OggVorbis files will contain a single logical bitstream */
  155701. end=_get_prev_page(vf,&og);
  155702. if(end<0)return(end);
  155703. /* more than one logical bitstream? */
  155704. if(ogg_page_serialno(&og)!=serialno){
  155705. /* Chained bitstream. Bisect-search each logical bitstream
  155706. section. Do so based on serial number only */
  155707. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155708. }else{
  155709. /* Only one logical bitstream */
  155710. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155711. }
  155712. /* the initial header memory is referenced by vf after; don't free it */
  155713. _prefetch_all_headers(vf,dataoffset);
  155714. return(ov_raw_seek(vf,0));
  155715. }
  155716. /* clear out the current logical bitstream decoder */
  155717. static void _decode_clear(OggVorbis_File *vf){
  155718. vorbis_dsp_clear(&vf->vd);
  155719. vorbis_block_clear(&vf->vb);
  155720. vf->ready_state=OPENED;
  155721. }
  155722. /* fetch and process a packet. Handles the case where we're at a
  155723. bitstream boundary and dumps the decoding machine. If the decoding
  155724. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155725. date (seek and read both use this. seek uses a special hack with
  155726. readp).
  155727. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155728. 0) need more data (only if readp==0)
  155729. 1) got a packet
  155730. */
  155731. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155732. ogg_packet *op_in,
  155733. int readp,
  155734. int spanp){
  155735. ogg_page og;
  155736. /* handle one packet. Try to fetch it from current stream state */
  155737. /* extract packets from page */
  155738. while(1){
  155739. /* process a packet if we can. If the machine isn't loaded,
  155740. neither is a page */
  155741. if(vf->ready_state==INITSET){
  155742. while(1) {
  155743. ogg_packet op;
  155744. ogg_packet *op_ptr=(op_in?op_in:&op);
  155745. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155746. ogg_int64_t granulepos;
  155747. op_in=NULL;
  155748. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155749. if(result>0){
  155750. /* got a packet. process it */
  155751. granulepos=op_ptr->granulepos;
  155752. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155753. header handling. The
  155754. header packets aren't
  155755. audio, so if/when we
  155756. submit them,
  155757. vorbis_synthesis will
  155758. reject them */
  155759. /* suck in the synthesis data and track bitrate */
  155760. {
  155761. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155762. /* for proper use of libvorbis within libvorbisfile,
  155763. oldsamples will always be zero. */
  155764. if(oldsamples)return(OV_EFAULT);
  155765. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155766. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155767. vf->bittrack+=op_ptr->bytes*8;
  155768. }
  155769. /* update the pcm offset. */
  155770. if(granulepos!=-1 && !op_ptr->e_o_s){
  155771. int link=(vf->seekable?vf->current_link:0);
  155772. int i,samples;
  155773. /* this packet has a pcm_offset on it (the last packet
  155774. completed on a page carries the offset) After processing
  155775. (above), we know the pcm position of the *last* sample
  155776. ready to be returned. Find the offset of the *first*
  155777. As an aside, this trick is inaccurate if we begin
  155778. reading anew right at the last page; the end-of-stream
  155779. granulepos declares the last frame in the stream, and the
  155780. last packet of the last page may be a partial frame.
  155781. So, we need a previous granulepos from an in-sequence page
  155782. to have a reference point. Thus the !op_ptr->e_o_s clause
  155783. above */
  155784. if(vf->seekable && link>0)
  155785. granulepos-=vf->pcmlengths[link*2];
  155786. if(granulepos<0)granulepos=0; /* actually, this
  155787. shouldn't be possible
  155788. here unless the stream
  155789. is very broken */
  155790. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155791. granulepos-=samples;
  155792. for(i=0;i<link;i++)
  155793. granulepos+=vf->pcmlengths[i*2+1];
  155794. vf->pcm_offset=granulepos;
  155795. }
  155796. return(1);
  155797. }
  155798. }
  155799. else
  155800. break;
  155801. }
  155802. }
  155803. if(vf->ready_state>=OPENED){
  155804. ogg_int64_t ret;
  155805. if(!readp)return(0);
  155806. if((ret=_get_next_page(vf,&og,-1))<0){
  155807. return(OV_EOF); /* eof.
  155808. leave unitialized */
  155809. }
  155810. /* bitrate tracking; add the header's bytes here, the body bytes
  155811. are done by packet above */
  155812. vf->bittrack+=og.header_len*8;
  155813. /* has our decoding just traversed a bitstream boundary? */
  155814. if(vf->ready_state==INITSET){
  155815. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155816. if(!spanp)
  155817. return(OV_EOF);
  155818. _decode_clear(vf);
  155819. if(!vf->seekable){
  155820. vorbis_info_clear(vf->vi);
  155821. vorbis_comment_clear(vf->vc);
  155822. }
  155823. }
  155824. }
  155825. }
  155826. /* Do we need to load a new machine before submitting the page? */
  155827. /* This is different in the seekable and non-seekable cases.
  155828. In the seekable case, we already have all the header
  155829. information loaded and cached; we just initialize the machine
  155830. with it and continue on our merry way.
  155831. In the non-seekable (streaming) case, we'll only be at a
  155832. boundary if we just left the previous logical bitstream and
  155833. we're now nominally at the header of the next bitstream
  155834. */
  155835. if(vf->ready_state!=INITSET){
  155836. int link;
  155837. if(vf->ready_state<STREAMSET){
  155838. if(vf->seekable){
  155839. vf->current_serialno=ogg_page_serialno(&og);
  155840. /* match the serialno to bitstream section. We use this rather than
  155841. offset positions to avoid problems near logical bitstream
  155842. boundaries */
  155843. for(link=0;link<vf->links;link++)
  155844. if(vf->serialnos[link]==vf->current_serialno)break;
  155845. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155846. stream. error out,
  155847. leave machine
  155848. uninitialized */
  155849. vf->current_link=link;
  155850. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155851. vf->ready_state=STREAMSET;
  155852. }else{
  155853. /* we're streaming */
  155854. /* fetch the three header packets, build the info struct */
  155855. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155856. if(ret)return(ret);
  155857. vf->current_link++;
  155858. link=0;
  155859. }
  155860. }
  155861. {
  155862. int ret=_make_decode_ready(vf);
  155863. if(ret<0)return ret;
  155864. }
  155865. }
  155866. ogg_stream_pagein(&vf->os,&og);
  155867. }
  155868. }
  155869. /* if, eg, 64 bit stdio is configured by default, this will build with
  155870. fseek64 */
  155871. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155872. if(f==NULL)return(-1);
  155873. return fseek(f,off,whence);
  155874. }
  155875. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155876. long ibytes, ov_callbacks callbacks){
  155877. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155878. int ret;
  155879. memset(vf,0,sizeof(*vf));
  155880. vf->datasource=f;
  155881. vf->callbacks = callbacks;
  155882. /* init the framing state */
  155883. ogg_sync_init(&vf->oy);
  155884. /* perhaps some data was previously read into a buffer for testing
  155885. against other stream types. Allow initialization from this
  155886. previously read data (as we may be reading from a non-seekable
  155887. stream) */
  155888. if(initial){
  155889. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155890. memcpy(buffer,initial,ibytes);
  155891. ogg_sync_wrote(&vf->oy,ibytes);
  155892. }
  155893. /* can we seek? Stevens suggests the seek test was portable */
  155894. if(offsettest!=-1)vf->seekable=1;
  155895. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155896. entry for partial open */
  155897. vf->links=1;
  155898. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155899. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155900. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155901. /* Try to fetch the headers, maintaining all the storage */
  155902. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155903. vf->datasource=NULL;
  155904. ov_clear(vf);
  155905. }else
  155906. vf->ready_state=PARTOPEN;
  155907. return(ret);
  155908. }
  155909. static int _ov_open2(OggVorbis_File *vf){
  155910. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155911. vf->ready_state=OPENED;
  155912. if(vf->seekable){
  155913. int ret=_open_seekable2(vf);
  155914. if(ret){
  155915. vf->datasource=NULL;
  155916. ov_clear(vf);
  155917. }
  155918. return(ret);
  155919. }else
  155920. vf->ready_state=STREAMSET;
  155921. return 0;
  155922. }
  155923. /* clear out the OggVorbis_File struct */
  155924. int ov_clear(OggVorbis_File *vf){
  155925. if(vf){
  155926. vorbis_block_clear(&vf->vb);
  155927. vorbis_dsp_clear(&vf->vd);
  155928. ogg_stream_clear(&vf->os);
  155929. if(vf->vi && vf->links){
  155930. int i;
  155931. for(i=0;i<vf->links;i++){
  155932. vorbis_info_clear(vf->vi+i);
  155933. vorbis_comment_clear(vf->vc+i);
  155934. }
  155935. _ogg_free(vf->vi);
  155936. _ogg_free(vf->vc);
  155937. }
  155938. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155939. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155940. if(vf->serialnos)_ogg_free(vf->serialnos);
  155941. if(vf->offsets)_ogg_free(vf->offsets);
  155942. ogg_sync_clear(&vf->oy);
  155943. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155944. memset(vf,0,sizeof(*vf));
  155945. }
  155946. #ifdef DEBUG_LEAKS
  155947. _VDBG_dump();
  155948. #endif
  155949. return(0);
  155950. }
  155951. /* inspects the OggVorbis file and finds/documents all the logical
  155952. bitstreams contained in it. Tries to be tolerant of logical
  155953. bitstream sections that are truncated/woogie.
  155954. return: -1) error
  155955. 0) OK
  155956. */
  155957. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155958. ov_callbacks callbacks){
  155959. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155960. if(ret)return ret;
  155961. return _ov_open2(vf);
  155962. }
  155963. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155964. ov_callbacks callbacks = {
  155965. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155966. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155967. (int (*)(void *)) fclose,
  155968. (long (*)(void *)) ftell
  155969. };
  155970. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155971. }
  155972. /* cheap hack for game usage where downsampling is desirable; there's
  155973. no need for SRC as we can just do it cheaply in libvorbis. */
  155974. int ov_halfrate(OggVorbis_File *vf,int flag){
  155975. int i;
  155976. if(vf->vi==NULL)return OV_EINVAL;
  155977. if(!vf->seekable)return OV_EINVAL;
  155978. if(vf->ready_state>=STREAMSET)
  155979. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155980. will be able to swap this on the fly, but
  155981. for now dumping the decode machine is needed
  155982. to reinit the MDCT lookups. 1.1 libvorbis
  155983. is planned to be able to switch on the fly */
  155984. for(i=0;i<vf->links;i++){
  155985. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155986. ov_halfrate(vf,0);
  155987. return OV_EINVAL;
  155988. }
  155989. }
  155990. return 0;
  155991. }
  155992. int ov_halfrate_p(OggVorbis_File *vf){
  155993. if(vf->vi==NULL)return OV_EINVAL;
  155994. return vorbis_synthesis_halfrate_p(vf->vi);
  155995. }
  155996. /* Only partially open the vorbis file; test for Vorbisness, and load
  155997. the headers for the first chain. Do not seek (although test for
  155998. seekability). Use ov_test_open to finish opening the file, else
  155999. ov_clear to close/free it. Same return codes as open. */
  156000. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156001. ov_callbacks callbacks)
  156002. {
  156003. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156004. }
  156005. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156006. ov_callbacks callbacks = {
  156007. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156008. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156009. (int (*)(void *)) fclose,
  156010. (long (*)(void *)) ftell
  156011. };
  156012. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156013. }
  156014. int ov_test_open(OggVorbis_File *vf){
  156015. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156016. return _ov_open2(vf);
  156017. }
  156018. /* How many logical bitstreams in this physical bitstream? */
  156019. long ov_streams(OggVorbis_File *vf){
  156020. return vf->links;
  156021. }
  156022. /* Is the FILE * associated with vf seekable? */
  156023. long ov_seekable(OggVorbis_File *vf){
  156024. return vf->seekable;
  156025. }
  156026. /* returns the bitrate for a given logical bitstream or the entire
  156027. physical bitstream. If the file is open for random access, it will
  156028. find the *actual* average bitrate. If the file is streaming, it
  156029. returns the nominal bitrate (if set) else the average of the
  156030. upper/lower bounds (if set) else -1 (unset).
  156031. If you want the actual bitrate field settings, get them from the
  156032. vorbis_info structs */
  156033. long ov_bitrate(OggVorbis_File *vf,int i){
  156034. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156035. if(i>=vf->links)return(OV_EINVAL);
  156036. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156037. if(i<0){
  156038. ogg_int64_t bits=0;
  156039. int i;
  156040. float br;
  156041. for(i=0;i<vf->links;i++)
  156042. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156043. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156044. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156045. * so this is slightly transformed to make it work.
  156046. */
  156047. br = bits/ov_time_total(vf,-1);
  156048. return(rint(br));
  156049. }else{
  156050. if(vf->seekable){
  156051. /* return the actual bitrate */
  156052. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156053. }else{
  156054. /* return nominal if set */
  156055. if(vf->vi[i].bitrate_nominal>0){
  156056. return vf->vi[i].bitrate_nominal;
  156057. }else{
  156058. if(vf->vi[i].bitrate_upper>0){
  156059. if(vf->vi[i].bitrate_lower>0){
  156060. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156061. }else{
  156062. return vf->vi[i].bitrate_upper;
  156063. }
  156064. }
  156065. return(OV_FALSE);
  156066. }
  156067. }
  156068. }
  156069. }
  156070. /* returns the actual bitrate since last call. returns -1 if no
  156071. additional data to offer since last call (or at beginning of stream),
  156072. EINVAL if stream is only partially open
  156073. */
  156074. long ov_bitrate_instant(OggVorbis_File *vf){
  156075. int link=(vf->seekable?vf->current_link:0);
  156076. long ret;
  156077. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156078. if(vf->samptrack==0)return(OV_FALSE);
  156079. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156080. vf->bittrack=0.f;
  156081. vf->samptrack=0.f;
  156082. return(ret);
  156083. }
  156084. /* Guess */
  156085. long ov_serialnumber(OggVorbis_File *vf,int i){
  156086. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156087. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156088. if(i<0){
  156089. return(vf->current_serialno);
  156090. }else{
  156091. return(vf->serialnos[i]);
  156092. }
  156093. }
  156094. /* returns: total raw (compressed) length of content if i==-1
  156095. raw (compressed) length of that logical bitstream for i==0 to n
  156096. OV_EINVAL if the stream is not seekable (we can't know the length)
  156097. or if stream is only partially open
  156098. */
  156099. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156100. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156101. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156102. if(i<0){
  156103. ogg_int64_t acc=0;
  156104. int i;
  156105. for(i=0;i<vf->links;i++)
  156106. acc+=ov_raw_total(vf,i);
  156107. return(acc);
  156108. }else{
  156109. return(vf->offsets[i+1]-vf->offsets[i]);
  156110. }
  156111. }
  156112. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156113. (samples) of that logical bitstream for i==0 to n
  156114. OV_EINVAL if the stream is not seekable (we can't know the
  156115. length) or only partially open
  156116. */
  156117. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156118. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156119. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156120. if(i<0){
  156121. ogg_int64_t acc=0;
  156122. int i;
  156123. for(i=0;i<vf->links;i++)
  156124. acc+=ov_pcm_total(vf,i);
  156125. return(acc);
  156126. }else{
  156127. return(vf->pcmlengths[i*2+1]);
  156128. }
  156129. }
  156130. /* returns: total seconds of content if i==-1
  156131. seconds in that logical bitstream for i==0 to n
  156132. OV_EINVAL if the stream is not seekable (we can't know the
  156133. length) or only partially open
  156134. */
  156135. double ov_time_total(OggVorbis_File *vf,int i){
  156136. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156137. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156138. if(i<0){
  156139. double acc=0;
  156140. int i;
  156141. for(i=0;i<vf->links;i++)
  156142. acc+=ov_time_total(vf,i);
  156143. return(acc);
  156144. }else{
  156145. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156146. }
  156147. }
  156148. /* seek to an offset relative to the *compressed* data. This also
  156149. scans packets to update the PCM cursor. It will cross a logical
  156150. bitstream boundary, but only if it can't get any packets out of the
  156151. tail of the bitstream we seek to (so no surprises).
  156152. returns zero on success, nonzero on failure */
  156153. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156154. ogg_stream_state work_os;
  156155. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156156. if(!vf->seekable)
  156157. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156158. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156159. /* don't yet clear out decoding machine (if it's initialized), in
  156160. the case we're in the same link. Restart the decode lapping, and
  156161. let _fetch_and_process_packet deal with a potential bitstream
  156162. boundary */
  156163. vf->pcm_offset=-1;
  156164. ogg_stream_reset_serialno(&vf->os,
  156165. vf->current_serialno); /* must set serialno */
  156166. vorbis_synthesis_restart(&vf->vd);
  156167. _seek_helper(vf,pos);
  156168. /* we need to make sure the pcm_offset is set, but we don't want to
  156169. advance the raw cursor past good packets just to get to the first
  156170. with a granulepos. That's not equivalent behavior to beginning
  156171. decoding as immediately after the seek position as possible.
  156172. So, a hack. We use two stream states; a local scratch state and
  156173. the shared vf->os stream state. We use the local state to
  156174. scan, and the shared state as a buffer for later decode.
  156175. Unfortuantely, on the last page we still advance to last packet
  156176. because the granulepos on the last page is not necessarily on a
  156177. packet boundary, and we need to make sure the granpos is
  156178. correct.
  156179. */
  156180. {
  156181. ogg_page og;
  156182. ogg_packet op;
  156183. int lastblock=0;
  156184. int accblock=0;
  156185. int thisblock;
  156186. int eosflag;
  156187. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156188. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156189. return from not necessarily
  156190. starting from the beginning */
  156191. while(1){
  156192. if(vf->ready_state>=STREAMSET){
  156193. /* snarf/scan a packet if we can */
  156194. int result=ogg_stream_packetout(&work_os,&op);
  156195. if(result>0){
  156196. if(vf->vi[vf->current_link].codec_setup){
  156197. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156198. if(thisblock<0){
  156199. ogg_stream_packetout(&vf->os,NULL);
  156200. thisblock=0;
  156201. }else{
  156202. if(eosflag)
  156203. ogg_stream_packetout(&vf->os,NULL);
  156204. else
  156205. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156206. }
  156207. if(op.granulepos!=-1){
  156208. int i,link=vf->current_link;
  156209. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156210. if(granulepos<0)granulepos=0;
  156211. for(i=0;i<link;i++)
  156212. granulepos+=vf->pcmlengths[i*2+1];
  156213. vf->pcm_offset=granulepos-accblock;
  156214. break;
  156215. }
  156216. lastblock=thisblock;
  156217. continue;
  156218. }else
  156219. ogg_stream_packetout(&vf->os,NULL);
  156220. }
  156221. }
  156222. if(!lastblock){
  156223. if(_get_next_page(vf,&og,-1)<0){
  156224. vf->pcm_offset=ov_pcm_total(vf,-1);
  156225. break;
  156226. }
  156227. }else{
  156228. /* huh? Bogus stream with packets but no granulepos */
  156229. vf->pcm_offset=-1;
  156230. break;
  156231. }
  156232. /* has our decoding just traversed a bitstream boundary? */
  156233. if(vf->ready_state>=STREAMSET)
  156234. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156235. _decode_clear(vf); /* clear out stream state */
  156236. ogg_stream_clear(&work_os);
  156237. }
  156238. if(vf->ready_state<STREAMSET){
  156239. int link;
  156240. vf->current_serialno=ogg_page_serialno(&og);
  156241. for(link=0;link<vf->links;link++)
  156242. if(vf->serialnos[link]==vf->current_serialno)break;
  156243. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156244. error out, leave
  156245. machine uninitialized */
  156246. vf->current_link=link;
  156247. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156248. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156249. vf->ready_state=STREAMSET;
  156250. }
  156251. ogg_stream_pagein(&vf->os,&og);
  156252. ogg_stream_pagein(&work_os,&og);
  156253. eosflag=ogg_page_eos(&og);
  156254. }
  156255. }
  156256. ogg_stream_clear(&work_os);
  156257. vf->bittrack=0.f;
  156258. vf->samptrack=0.f;
  156259. return(0);
  156260. seek_error:
  156261. /* dump the machine so we're in a known state */
  156262. vf->pcm_offset=-1;
  156263. ogg_stream_clear(&work_os);
  156264. _decode_clear(vf);
  156265. return OV_EBADLINK;
  156266. }
  156267. /* Page granularity seek (faster than sample granularity because we
  156268. don't do the last bit of decode to find a specific sample).
  156269. Seek to the last [granule marked] page preceeding the specified pos
  156270. location, such that decoding past the returned point will quickly
  156271. arrive at the requested position. */
  156272. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156273. int link=-1;
  156274. ogg_int64_t result=0;
  156275. ogg_int64_t total=ov_pcm_total(vf,-1);
  156276. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156277. if(!vf->seekable)return(OV_ENOSEEK);
  156278. if(pos<0 || pos>total)return(OV_EINVAL);
  156279. /* which bitstream section does this pcm offset occur in? */
  156280. for(link=vf->links-1;link>=0;link--){
  156281. total-=vf->pcmlengths[link*2+1];
  156282. if(pos>=total)break;
  156283. }
  156284. /* search within the logical bitstream for the page with the highest
  156285. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156286. missing pages or incorrect frame number information in the
  156287. bitstream could make our task impossible. Account for that (it
  156288. would be an error condition) */
  156289. /* new search algorithm by HB (Nicholas Vinen) */
  156290. {
  156291. ogg_int64_t end=vf->offsets[link+1];
  156292. ogg_int64_t begin=vf->offsets[link];
  156293. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156294. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156295. ogg_int64_t target=pos-total+begintime;
  156296. ogg_int64_t best=begin;
  156297. ogg_page og;
  156298. while(begin<end){
  156299. ogg_int64_t bisect;
  156300. if(end-begin<CHUNKSIZE){
  156301. bisect=begin;
  156302. }else{
  156303. /* take a (pretty decent) guess. */
  156304. bisect=begin +
  156305. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156306. if(bisect<=begin)
  156307. bisect=begin+1;
  156308. }
  156309. _seek_helper(vf,bisect);
  156310. while(begin<end){
  156311. result=_get_next_page(vf,&og,end-vf->offset);
  156312. if(result==OV_EREAD) goto seek_error;
  156313. if(result<0){
  156314. if(bisect<=begin+1)
  156315. end=begin; /* found it */
  156316. else{
  156317. if(bisect==0) goto seek_error;
  156318. bisect-=CHUNKSIZE;
  156319. if(bisect<=begin)bisect=begin+1;
  156320. _seek_helper(vf,bisect);
  156321. }
  156322. }else{
  156323. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156324. if(granulepos==-1)continue;
  156325. if(granulepos<target){
  156326. best=result; /* raw offset of packet with granulepos */
  156327. begin=vf->offset; /* raw offset of next page */
  156328. begintime=granulepos;
  156329. if(target-begintime>44100)break;
  156330. bisect=begin; /* *not* begin + 1 */
  156331. }else{
  156332. if(bisect<=begin+1)
  156333. end=begin; /* found it */
  156334. else{
  156335. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156336. end=result;
  156337. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156338. if(bisect<=begin)bisect=begin+1;
  156339. _seek_helper(vf,bisect);
  156340. }else{
  156341. end=result;
  156342. endtime=granulepos;
  156343. break;
  156344. }
  156345. }
  156346. }
  156347. }
  156348. }
  156349. }
  156350. /* found our page. seek to it, update pcm offset. Easier case than
  156351. raw_seek, don't keep packets preceeding granulepos. */
  156352. {
  156353. ogg_page og;
  156354. ogg_packet op;
  156355. /* seek */
  156356. _seek_helper(vf,best);
  156357. vf->pcm_offset=-1;
  156358. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156359. if(link!=vf->current_link){
  156360. /* Different link; dump entire decode machine */
  156361. _decode_clear(vf);
  156362. vf->current_link=link;
  156363. vf->current_serialno=ogg_page_serialno(&og);
  156364. vf->ready_state=STREAMSET;
  156365. }else{
  156366. vorbis_synthesis_restart(&vf->vd);
  156367. }
  156368. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156369. ogg_stream_pagein(&vf->os,&og);
  156370. /* pull out all but last packet; the one with granulepos */
  156371. while(1){
  156372. result=ogg_stream_packetpeek(&vf->os,&op);
  156373. if(result==0){
  156374. /* !!! the packet finishing this page originated on a
  156375. preceeding page. Keep fetching previous pages until we
  156376. get one with a granulepos or without the 'continued' flag
  156377. set. Then just use raw_seek for simplicity. */
  156378. _seek_helper(vf,best);
  156379. while(1){
  156380. result=_get_prev_page(vf,&og);
  156381. if(result<0) goto seek_error;
  156382. if(ogg_page_granulepos(&og)>-1 ||
  156383. !ogg_page_continued(&og)){
  156384. return ov_raw_seek(vf,result);
  156385. }
  156386. vf->offset=result;
  156387. }
  156388. }
  156389. if(result<0){
  156390. result = OV_EBADPACKET;
  156391. goto seek_error;
  156392. }
  156393. if(op.granulepos!=-1){
  156394. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156395. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156396. vf->pcm_offset+=total;
  156397. break;
  156398. }else
  156399. result=ogg_stream_packetout(&vf->os,NULL);
  156400. }
  156401. }
  156402. }
  156403. /* verify result */
  156404. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156405. result=OV_EFAULT;
  156406. goto seek_error;
  156407. }
  156408. vf->bittrack=0.f;
  156409. vf->samptrack=0.f;
  156410. return(0);
  156411. seek_error:
  156412. /* dump machine so we're in a known state */
  156413. vf->pcm_offset=-1;
  156414. _decode_clear(vf);
  156415. return (int)result;
  156416. }
  156417. /* seek to a sample offset relative to the decompressed pcm stream
  156418. returns zero on success, nonzero on failure */
  156419. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156420. int thisblock,lastblock=0;
  156421. int ret=ov_pcm_seek_page(vf,pos);
  156422. if(ret<0)return(ret);
  156423. if((ret=_make_decode_ready(vf)))return ret;
  156424. /* discard leading packets we don't need for the lapping of the
  156425. position we want; don't decode them */
  156426. while(1){
  156427. ogg_packet op;
  156428. ogg_page og;
  156429. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156430. if(ret>0){
  156431. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156432. if(thisblock<0){
  156433. ogg_stream_packetout(&vf->os,NULL);
  156434. continue; /* non audio packet */
  156435. }
  156436. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156437. if(vf->pcm_offset+((thisblock+
  156438. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156439. /* remove the packet from packet queue and track its granulepos */
  156440. ogg_stream_packetout(&vf->os,NULL);
  156441. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156442. only tracking, no
  156443. pcm_decode */
  156444. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156445. /* end of logical stream case is hard, especially with exact
  156446. length positioning. */
  156447. if(op.granulepos>-1){
  156448. int i;
  156449. /* always believe the stream markers */
  156450. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156451. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156452. for(i=0;i<vf->current_link;i++)
  156453. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156454. }
  156455. lastblock=thisblock;
  156456. }else{
  156457. if(ret<0 && ret!=OV_HOLE)break;
  156458. /* suck in a new page */
  156459. if(_get_next_page(vf,&og,-1)<0)break;
  156460. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156461. if(vf->ready_state<STREAMSET){
  156462. int link;
  156463. vf->current_serialno=ogg_page_serialno(&og);
  156464. for(link=0;link<vf->links;link++)
  156465. if(vf->serialnos[link]==vf->current_serialno)break;
  156466. if(link==vf->links)return(OV_EBADLINK);
  156467. vf->current_link=link;
  156468. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156469. vf->ready_state=STREAMSET;
  156470. ret=_make_decode_ready(vf);
  156471. if(ret)return ret;
  156472. lastblock=0;
  156473. }
  156474. ogg_stream_pagein(&vf->os,&og);
  156475. }
  156476. }
  156477. vf->bittrack=0.f;
  156478. vf->samptrack=0.f;
  156479. /* discard samples until we reach the desired position. Crossing a
  156480. logical bitstream boundary with abandon is OK. */
  156481. while(vf->pcm_offset<pos){
  156482. ogg_int64_t target=pos-vf->pcm_offset;
  156483. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156484. if(samples>target)samples=target;
  156485. vorbis_synthesis_read(&vf->vd,samples);
  156486. vf->pcm_offset+=samples;
  156487. if(samples<target)
  156488. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156489. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156490. }
  156491. return 0;
  156492. }
  156493. /* seek to a playback time relative to the decompressed pcm stream
  156494. returns zero on success, nonzero on failure */
  156495. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156496. /* translate time to PCM position and call ov_pcm_seek */
  156497. int link=-1;
  156498. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156499. double time_total=ov_time_total(vf,-1);
  156500. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156501. if(!vf->seekable)return(OV_ENOSEEK);
  156502. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156503. /* which bitstream section does this time offset occur in? */
  156504. for(link=vf->links-1;link>=0;link--){
  156505. pcm_total-=vf->pcmlengths[link*2+1];
  156506. time_total-=ov_time_total(vf,link);
  156507. if(seconds>=time_total)break;
  156508. }
  156509. /* enough information to convert time offset to pcm offset */
  156510. {
  156511. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156512. return(ov_pcm_seek(vf,target));
  156513. }
  156514. }
  156515. /* page-granularity version of ov_time_seek
  156516. returns zero on success, nonzero on failure */
  156517. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156518. /* translate time to PCM position and call ov_pcm_seek */
  156519. int link=-1;
  156520. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156521. double time_total=ov_time_total(vf,-1);
  156522. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156523. if(!vf->seekable)return(OV_ENOSEEK);
  156524. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156525. /* which bitstream section does this time offset occur in? */
  156526. for(link=vf->links-1;link>=0;link--){
  156527. pcm_total-=vf->pcmlengths[link*2+1];
  156528. time_total-=ov_time_total(vf,link);
  156529. if(seconds>=time_total)break;
  156530. }
  156531. /* enough information to convert time offset to pcm offset */
  156532. {
  156533. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156534. return(ov_pcm_seek_page(vf,target));
  156535. }
  156536. }
  156537. /* tell the current stream offset cursor. Note that seek followed by
  156538. tell will likely not give the set offset due to caching */
  156539. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156540. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156541. return(vf->offset);
  156542. }
  156543. /* return PCM offset (sample) of next PCM sample to be read */
  156544. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156545. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156546. return(vf->pcm_offset);
  156547. }
  156548. /* return time offset (seconds) of next PCM sample to be read */
  156549. double ov_time_tell(OggVorbis_File *vf){
  156550. int link=0;
  156551. ogg_int64_t pcm_total=0;
  156552. double time_total=0.f;
  156553. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156554. if(vf->seekable){
  156555. pcm_total=ov_pcm_total(vf,-1);
  156556. time_total=ov_time_total(vf,-1);
  156557. /* which bitstream section does this time offset occur in? */
  156558. for(link=vf->links-1;link>=0;link--){
  156559. pcm_total-=vf->pcmlengths[link*2+1];
  156560. time_total-=ov_time_total(vf,link);
  156561. if(vf->pcm_offset>=pcm_total)break;
  156562. }
  156563. }
  156564. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156565. }
  156566. /* link: -1) return the vorbis_info struct for the bitstream section
  156567. currently being decoded
  156568. 0-n) to request information for a specific bitstream section
  156569. In the case of a non-seekable bitstream, any call returns the
  156570. current bitstream. NULL in the case that the machine is not
  156571. initialized */
  156572. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156573. if(vf->seekable){
  156574. if(link<0)
  156575. if(vf->ready_state>=STREAMSET)
  156576. return vf->vi+vf->current_link;
  156577. else
  156578. return vf->vi;
  156579. else
  156580. if(link>=vf->links)
  156581. return NULL;
  156582. else
  156583. return vf->vi+link;
  156584. }else{
  156585. return vf->vi;
  156586. }
  156587. }
  156588. /* grr, strong typing, grr, no templates/inheritence, grr */
  156589. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156590. if(vf->seekable){
  156591. if(link<0)
  156592. if(vf->ready_state>=STREAMSET)
  156593. return vf->vc+vf->current_link;
  156594. else
  156595. return vf->vc;
  156596. else
  156597. if(link>=vf->links)
  156598. return NULL;
  156599. else
  156600. return vf->vc+link;
  156601. }else{
  156602. return vf->vc;
  156603. }
  156604. }
  156605. static int host_is_big_endian() {
  156606. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156607. unsigned char *bytewise = (unsigned char *)&pattern;
  156608. if (bytewise[0] == 0xfe) return 1;
  156609. return 0;
  156610. }
  156611. /* up to this point, everything could more or less hide the multiple
  156612. logical bitstream nature of chaining from the toplevel application
  156613. if the toplevel application didn't particularly care. However, at
  156614. the point that we actually read audio back, the multiple-section
  156615. nature must surface: Multiple bitstream sections do not necessarily
  156616. have to have the same number of channels or sampling rate.
  156617. ov_read returns the sequential logical bitstream number currently
  156618. being decoded along with the PCM data in order that the toplevel
  156619. application can take action on channel/sample rate changes. This
  156620. number will be incremented even for streamed (non-seekable) streams
  156621. (for seekable streams, it represents the actual logical bitstream
  156622. index within the physical bitstream. Note that the accessor
  156623. functions above are aware of this dichotomy).
  156624. input values: buffer) a buffer to hold packed PCM data for return
  156625. length) the byte length requested to be placed into buffer
  156626. bigendianp) should the data be packed LSB first (0) or
  156627. MSB first (1)
  156628. word) word size for output. currently 1 (byte) or
  156629. 2 (16 bit short)
  156630. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156631. 0) EOF
  156632. n) number of bytes of PCM actually returned. The
  156633. below works on a packet-by-packet basis, so the
  156634. return length is not related to the 'length' passed
  156635. in, just guaranteed to fit.
  156636. *section) set to the logical bitstream number */
  156637. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156638. int bigendianp,int word,int sgned,int *bitstream){
  156639. int i,j;
  156640. int host_endian = host_is_big_endian();
  156641. float **pcm;
  156642. long samples;
  156643. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156644. while(1){
  156645. if(vf->ready_state==INITSET){
  156646. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156647. if(samples)break;
  156648. }
  156649. /* suck in another packet */
  156650. {
  156651. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156652. if(ret==OV_EOF)
  156653. return(0);
  156654. if(ret<=0)
  156655. return(ret);
  156656. }
  156657. }
  156658. if(samples>0){
  156659. /* yay! proceed to pack data into the byte buffer */
  156660. long channels=ov_info(vf,-1)->channels;
  156661. long bytespersample=word * channels;
  156662. vorbis_fpu_control fpu;
  156663. (void) fpu; // (to avoid a warning about it being unused)
  156664. if(samples>length/bytespersample)samples=length/bytespersample;
  156665. if(samples <= 0)
  156666. return OV_EINVAL;
  156667. /* a tight loop to pack each size */
  156668. {
  156669. int val;
  156670. if(word==1){
  156671. int off=(sgned?0:128);
  156672. vorbis_fpu_setround(&fpu);
  156673. for(j=0;j<samples;j++)
  156674. for(i=0;i<channels;i++){
  156675. val=vorbis_ftoi(pcm[i][j]*128.f);
  156676. if(val>127)val=127;
  156677. else if(val<-128)val=-128;
  156678. *buffer++=val+off;
  156679. }
  156680. vorbis_fpu_restore(fpu);
  156681. }else{
  156682. int off=(sgned?0:32768);
  156683. if(host_endian==bigendianp){
  156684. if(sgned){
  156685. vorbis_fpu_setround(&fpu);
  156686. for(i=0;i<channels;i++) { /* It's faster in this order */
  156687. float *src=pcm[i];
  156688. short *dest=((short *)buffer)+i;
  156689. for(j=0;j<samples;j++) {
  156690. val=vorbis_ftoi(src[j]*32768.f);
  156691. if(val>32767)val=32767;
  156692. else if(val<-32768)val=-32768;
  156693. *dest=val;
  156694. dest+=channels;
  156695. }
  156696. }
  156697. vorbis_fpu_restore(fpu);
  156698. }else{
  156699. vorbis_fpu_setround(&fpu);
  156700. for(i=0;i<channels;i++) {
  156701. float *src=pcm[i];
  156702. short *dest=((short *)buffer)+i;
  156703. for(j=0;j<samples;j++) {
  156704. val=vorbis_ftoi(src[j]*32768.f);
  156705. if(val>32767)val=32767;
  156706. else if(val<-32768)val=-32768;
  156707. *dest=val+off;
  156708. dest+=channels;
  156709. }
  156710. }
  156711. vorbis_fpu_restore(fpu);
  156712. }
  156713. }else if(bigendianp){
  156714. vorbis_fpu_setround(&fpu);
  156715. for(j=0;j<samples;j++)
  156716. for(i=0;i<channels;i++){
  156717. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156718. if(val>32767)val=32767;
  156719. else if(val<-32768)val=-32768;
  156720. val+=off;
  156721. *buffer++=(val>>8);
  156722. *buffer++=(val&0xff);
  156723. }
  156724. vorbis_fpu_restore(fpu);
  156725. }else{
  156726. int val;
  156727. vorbis_fpu_setround(&fpu);
  156728. for(j=0;j<samples;j++)
  156729. for(i=0;i<channels;i++){
  156730. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156731. if(val>32767)val=32767;
  156732. else if(val<-32768)val=-32768;
  156733. val+=off;
  156734. *buffer++=(val&0xff);
  156735. *buffer++=(val>>8);
  156736. }
  156737. vorbis_fpu_restore(fpu);
  156738. }
  156739. }
  156740. }
  156741. vorbis_synthesis_read(&vf->vd,samples);
  156742. vf->pcm_offset+=samples;
  156743. if(bitstream)*bitstream=vf->current_link;
  156744. return(samples*bytespersample);
  156745. }else{
  156746. return(samples);
  156747. }
  156748. }
  156749. /* input values: pcm_channels) a float vector per channel of output
  156750. length) the sample length being read by the app
  156751. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156752. 0) EOF
  156753. n) number of samples of PCM actually returned. The
  156754. below works on a packet-by-packet basis, so the
  156755. return length is not related to the 'length' passed
  156756. in, just guaranteed to fit.
  156757. *section) set to the logical bitstream number */
  156758. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156759. int *bitstream){
  156760. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156761. while(1){
  156762. if(vf->ready_state==INITSET){
  156763. float **pcm;
  156764. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156765. if(samples){
  156766. if(pcm_channels)*pcm_channels=pcm;
  156767. if(samples>length)samples=length;
  156768. vorbis_synthesis_read(&vf->vd,samples);
  156769. vf->pcm_offset+=samples;
  156770. if(bitstream)*bitstream=vf->current_link;
  156771. return samples;
  156772. }
  156773. }
  156774. /* suck in another packet */
  156775. {
  156776. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156777. if(ret==OV_EOF)return(0);
  156778. if(ret<=0)return(ret);
  156779. }
  156780. }
  156781. }
  156782. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156783. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156784. ogg_int64_t off);
  156785. static void _ov_splice(float **pcm,float **lappcm,
  156786. int n1, int n2,
  156787. int ch1, int ch2,
  156788. float *w1, float *w2){
  156789. int i,j;
  156790. float *w=w1;
  156791. int n=n1;
  156792. if(n1>n2){
  156793. n=n2;
  156794. w=w2;
  156795. }
  156796. /* splice */
  156797. for(j=0;j<ch1 && j<ch2;j++){
  156798. float *s=lappcm[j];
  156799. float *d=pcm[j];
  156800. for(i=0;i<n;i++){
  156801. float wd=w[i]*w[i];
  156802. float ws=1.-wd;
  156803. d[i]=d[i]*wd + s[i]*ws;
  156804. }
  156805. }
  156806. /* window from zero */
  156807. for(;j<ch2;j++){
  156808. float *d=pcm[j];
  156809. for(i=0;i<n;i++){
  156810. float wd=w[i]*w[i];
  156811. d[i]=d[i]*wd;
  156812. }
  156813. }
  156814. }
  156815. /* make sure vf is INITSET */
  156816. static int _ov_initset(OggVorbis_File *vf){
  156817. while(1){
  156818. if(vf->ready_state==INITSET)break;
  156819. /* suck in another packet */
  156820. {
  156821. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156822. if(ret<0 && ret!=OV_HOLE)return(ret);
  156823. }
  156824. }
  156825. return 0;
  156826. }
  156827. /* make sure vf is INITSET and that we have a primed buffer; if
  156828. we're crosslapping at a stream section boundary, this also makes
  156829. sure we're sanity checking against the right stream information */
  156830. static int _ov_initprime(OggVorbis_File *vf){
  156831. vorbis_dsp_state *vd=&vf->vd;
  156832. while(1){
  156833. if(vf->ready_state==INITSET)
  156834. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156835. /* suck in another packet */
  156836. {
  156837. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156838. if(ret<0 && ret!=OV_HOLE)return(ret);
  156839. }
  156840. }
  156841. return 0;
  156842. }
  156843. /* grab enough data for lapping from vf; this may be in the form of
  156844. unreturned, already-decoded pcm, remaining PCM we will need to
  156845. decode, or synthetic postextrapolation from last packets. */
  156846. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156847. float **lappcm,int lapsize){
  156848. int lapcount=0,i;
  156849. float **pcm;
  156850. /* try first to decode the lapping data */
  156851. while(lapcount<lapsize){
  156852. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156853. if(samples){
  156854. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156855. for(i=0;i<vi->channels;i++)
  156856. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156857. lapcount+=samples;
  156858. vorbis_synthesis_read(vd,samples);
  156859. }else{
  156860. /* suck in another packet */
  156861. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156862. if(ret==OV_EOF)break;
  156863. }
  156864. }
  156865. if(lapcount<lapsize){
  156866. /* failed to get lapping data from normal decode; pry it from the
  156867. postextrapolation buffering, or the second half of the MDCT
  156868. from the last packet */
  156869. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156870. if(samples==0){
  156871. for(i=0;i<vi->channels;i++)
  156872. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156873. lapcount=lapsize;
  156874. }else{
  156875. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156876. for(i=0;i<vi->channels;i++)
  156877. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156878. lapcount+=samples;
  156879. }
  156880. }
  156881. }
  156882. /* this sets up crosslapping of a sample by using trailing data from
  156883. sample 1 and lapping it into the windowing buffer of sample 2 */
  156884. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156885. vorbis_info *vi1,*vi2;
  156886. float **lappcm;
  156887. float **pcm;
  156888. float *w1,*w2;
  156889. int n1,n2,i,ret,hs1,hs2;
  156890. if(vf1==vf2)return(0); /* degenerate case */
  156891. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156892. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156893. /* the relevant overlap buffers must be pre-checked and pre-primed
  156894. before looking at settings in the event that priming would cross
  156895. a bitstream boundary. So, do it now */
  156896. ret=_ov_initset(vf1);
  156897. if(ret)return(ret);
  156898. ret=_ov_initprime(vf2);
  156899. if(ret)return(ret);
  156900. vi1=ov_info(vf1,-1);
  156901. vi2=ov_info(vf2,-1);
  156902. hs1=ov_halfrate_p(vf1);
  156903. hs2=ov_halfrate_p(vf2);
  156904. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156905. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156906. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156907. w1=vorbis_window(&vf1->vd,0);
  156908. w2=vorbis_window(&vf2->vd,0);
  156909. for(i=0;i<vi1->channels;i++)
  156910. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156911. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156912. /* have a lapping buffer from vf1; now to splice it into the lapping
  156913. buffer of vf2 */
  156914. /* consolidate and expose the buffer. */
  156915. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156916. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156917. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156918. /* splice */
  156919. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156920. /* done */
  156921. return(0);
  156922. }
  156923. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156924. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156925. vorbis_info *vi;
  156926. float **lappcm;
  156927. float **pcm;
  156928. float *w1,*w2;
  156929. int n1,n2,ch1,ch2,hs;
  156930. int i,ret;
  156931. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156932. ret=_ov_initset(vf);
  156933. if(ret)return(ret);
  156934. vi=ov_info(vf,-1);
  156935. hs=ov_halfrate_p(vf);
  156936. ch1=vi->channels;
  156937. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156938. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156939. persistent; even if the decode state
  156940. from this link gets dumped, this
  156941. window array continues to exist */
  156942. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156943. for(i=0;i<ch1;i++)
  156944. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156945. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156946. /* have lapping data; seek and prime the buffer */
  156947. ret=localseek(vf,pos);
  156948. if(ret)return ret;
  156949. ret=_ov_initprime(vf);
  156950. if(ret)return(ret);
  156951. /* Guard against cross-link changes; they're perfectly legal */
  156952. vi=ov_info(vf,-1);
  156953. ch2=vi->channels;
  156954. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156955. w2=vorbis_window(&vf->vd,0);
  156956. /* consolidate and expose the buffer. */
  156957. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156958. /* splice */
  156959. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156960. /* done */
  156961. return(0);
  156962. }
  156963. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156964. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156965. }
  156966. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156967. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156968. }
  156969. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156970. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156971. }
  156972. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156973. int (*localseek)(OggVorbis_File *,double)){
  156974. vorbis_info *vi;
  156975. float **lappcm;
  156976. float **pcm;
  156977. float *w1,*w2;
  156978. int n1,n2,ch1,ch2,hs;
  156979. int i,ret;
  156980. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156981. ret=_ov_initset(vf);
  156982. if(ret)return(ret);
  156983. vi=ov_info(vf,-1);
  156984. hs=ov_halfrate_p(vf);
  156985. ch1=vi->channels;
  156986. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156987. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156988. persistent; even if the decode state
  156989. from this link gets dumped, this
  156990. window array continues to exist */
  156991. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156992. for(i=0;i<ch1;i++)
  156993. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156994. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156995. /* have lapping data; seek and prime the buffer */
  156996. ret=localseek(vf,pos);
  156997. if(ret)return ret;
  156998. ret=_ov_initprime(vf);
  156999. if(ret)return(ret);
  157000. /* Guard against cross-link changes; they're perfectly legal */
  157001. vi=ov_info(vf,-1);
  157002. ch2=vi->channels;
  157003. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157004. w2=vorbis_window(&vf->vd,0);
  157005. /* consolidate and expose the buffer. */
  157006. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157007. /* splice */
  157008. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157009. /* done */
  157010. return(0);
  157011. }
  157012. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157013. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157014. }
  157015. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157016. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157017. }
  157018. #endif
  157019. /*** End of inlined file: vorbisfile.c ***/
  157020. /*** Start of inlined file: window.c ***/
  157021. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157022. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157023. // tasks..
  157024. #if JUCE_MSVC
  157025. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157026. #endif
  157027. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157028. #if JUCE_USE_OGGVORBIS
  157029. #include <stdlib.h>
  157030. #include <math.h>
  157031. static float vwin64[32] = {
  157032. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157033. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157034. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157035. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157036. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157037. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157038. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157039. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157040. };
  157041. static float vwin128[64] = {
  157042. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157043. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157044. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157045. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157046. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157047. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157048. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157049. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157050. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157051. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157052. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157053. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157054. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157055. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157056. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157057. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157058. };
  157059. static float vwin256[128] = {
  157060. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157061. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157062. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157063. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157064. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157065. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157066. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157067. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157068. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157069. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157070. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157071. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157072. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157073. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157074. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157075. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157076. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157077. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157078. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157079. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157080. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157081. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157082. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157083. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157084. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157085. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157086. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157087. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157088. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157089. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157090. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157091. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157092. };
  157093. static float vwin512[256] = {
  157094. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157095. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157096. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157097. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157098. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157099. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157100. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157101. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157102. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157103. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157104. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157105. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157106. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157107. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157108. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157109. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157110. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157111. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157112. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157113. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157114. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157115. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157116. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157117. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157118. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157119. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157120. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157121. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157122. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157123. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157124. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157125. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157126. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157127. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157128. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157129. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157130. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157131. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157132. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157133. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157134. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157135. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157136. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157137. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157138. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157139. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157140. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157141. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157142. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157143. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157144. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157145. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157146. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157147. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157148. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157149. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157150. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157151. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157152. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157153. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157154. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157155. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157156. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157157. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157158. };
  157159. static float vwin1024[512] = {
  157160. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157161. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157162. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157163. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157164. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157165. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157166. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157167. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157168. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157169. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157170. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157171. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157172. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157173. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157174. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157175. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157176. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157177. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157178. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157179. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157180. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157181. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157182. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157183. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157184. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157185. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157186. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157187. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157188. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157189. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157190. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157191. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157192. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157193. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157194. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157195. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157196. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157197. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157198. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157199. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157200. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157201. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157202. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157203. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157204. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157205. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157206. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157207. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157208. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157209. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157210. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157211. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157212. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157213. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157214. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157215. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157216. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157217. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157218. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157219. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157220. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157221. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157222. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157223. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157224. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157225. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157226. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157227. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157228. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157229. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157230. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157231. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157232. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157233. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157234. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157235. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157236. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157237. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157238. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157239. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157240. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157241. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157242. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157243. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157244. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157245. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157246. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157247. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157248. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157249. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157250. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157251. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157252. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157253. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157254. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157255. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157256. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157257. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157258. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157259. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157260. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157261. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157262. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157263. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157264. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157265. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157266. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157267. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157268. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157269. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157270. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157271. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157272. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157273. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157274. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157275. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157276. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157277. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157278. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157279. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157280. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157281. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157282. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157283. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157284. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157285. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157286. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157287. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157288. };
  157289. static float vwin2048[1024] = {
  157290. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157291. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157292. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157293. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157294. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157295. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157296. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157297. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157298. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157299. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157300. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157301. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157302. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157303. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157304. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157305. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157306. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157307. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157308. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157309. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157310. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157311. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157312. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157313. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157314. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157315. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157316. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157317. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157318. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157319. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157320. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157321. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157322. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157323. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157324. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157325. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157326. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157327. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157328. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157329. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157330. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157331. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157332. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157333. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157334. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157335. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157336. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157337. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157338. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157339. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157340. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157341. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157342. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157343. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157344. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157345. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157346. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157347. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157348. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157349. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157350. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157351. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157352. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157353. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157354. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157355. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157356. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157357. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157358. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157359. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157360. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157361. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157362. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157363. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157364. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157365. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157366. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157367. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157368. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157369. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157370. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157371. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157372. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157373. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157374. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157375. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157376. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157377. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157378. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157379. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157380. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157381. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157382. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157383. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157384. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157385. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157386. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157387. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157388. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157389. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157390. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157391. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157392. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157393. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157394. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157395. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157396. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157397. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157398. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157399. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157400. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157401. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157402. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157403. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157404. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157405. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157406. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157407. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157408. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157409. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157410. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157411. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157412. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157413. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157414. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157415. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157416. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157417. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157418. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157419. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157420. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157421. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157422. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157423. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157424. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157425. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157426. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157427. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157428. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157429. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157430. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157431. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157432. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157433. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157434. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157435. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157436. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157437. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157438. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157439. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157440. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157441. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157442. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157443. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157444. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157445. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157446. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157447. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157448. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157449. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157450. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157451. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157452. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157453. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157454. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157455. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157456. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157457. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157458. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157459. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157460. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157461. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157462. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157463. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157464. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157465. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157466. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157467. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157468. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157469. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157470. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157471. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157472. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157473. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157474. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157475. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157476. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157477. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157478. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157479. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157480. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157481. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157482. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157483. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157484. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157485. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157486. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157487. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157488. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157489. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157490. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157491. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157492. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157493. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157494. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157495. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157496. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157497. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157498. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157499. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157500. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157501. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157502. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157503. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157504. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157505. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157506. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157507. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157508. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157509. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157510. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157511. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157512. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157513. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157514. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157515. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157516. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157517. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157518. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157519. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157520. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157521. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157522. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157523. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157524. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157525. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157526. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157527. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157528. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157529. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157530. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157531. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157532. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157533. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157534. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157535. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157536. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157537. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157538. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157539. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157540. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157541. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157542. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157543. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157544. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157545. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157546. };
  157547. static float vwin4096[2048] = {
  157548. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157549. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157550. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157551. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157552. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157553. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157554. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157555. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157556. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157557. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157558. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157559. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157560. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157561. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157562. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157563. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157564. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157565. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157566. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157567. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157568. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157569. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157570. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157571. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157572. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157573. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157574. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157575. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157576. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157577. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157578. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157579. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157580. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157581. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157582. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157583. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157584. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157585. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157586. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157587. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157588. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157589. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157590. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157591. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157592. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157593. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157594. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157595. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157596. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157597. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157598. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157599. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157600. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157601. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157602. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157603. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157604. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157605. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157606. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157607. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157608. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157609. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157610. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157611. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157612. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157613. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157614. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157615. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157616. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157617. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157618. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157619. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157620. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157621. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157622. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157623. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157624. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157625. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157626. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157627. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157628. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157629. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157630. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157631. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157632. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157633. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157634. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157635. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157636. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157637. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157638. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157639. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157640. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157641. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157642. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157643. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157644. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157645. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157646. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157647. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157648. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157649. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157650. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157651. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157652. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157653. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157654. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157655. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157656. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157657. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157658. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157659. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157660. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157661. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157662. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157663. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157664. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157665. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157666. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157667. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157668. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157669. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157670. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157671. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157672. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157673. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157674. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157675. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157676. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157677. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157678. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157679. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157680. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157681. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157682. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157683. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157684. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157685. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157686. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157687. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157688. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157689. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157690. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157691. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157692. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157693. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157694. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157695. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157696. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157697. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157698. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157699. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157700. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157701. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157702. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157703. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157704. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157705. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157706. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157707. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157708. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157709. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157710. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157711. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157712. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157713. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157714. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157715. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157716. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157717. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157718. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157719. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157720. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157721. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157722. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157723. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157724. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157725. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157726. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157727. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157728. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157729. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157730. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157731. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157732. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157733. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157734. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157735. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157736. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157737. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157738. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157739. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157740. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157741. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157742. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157743. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157744. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157745. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157746. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157747. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157748. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157749. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157750. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157751. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157752. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157753. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157754. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157755. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157756. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157757. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157758. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157759. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157760. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157761. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157762. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157763. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157764. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157765. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157766. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157767. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157768. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157769. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157770. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157771. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157772. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157773. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157774. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157775. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157776. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157777. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157778. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157779. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157780. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157781. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157782. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157783. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157784. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157785. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157786. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157787. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157788. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157789. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157790. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157791. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157792. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157793. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157794. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157795. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157796. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157797. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157798. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157799. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157800. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157801. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157802. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157803. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157804. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157805. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157806. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157807. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157808. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157809. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157810. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157811. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157812. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157813. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157814. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157815. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157816. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157817. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157818. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157819. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157820. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157821. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157822. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157823. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157824. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157825. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157826. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157827. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157828. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157829. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157830. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157831. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157832. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157833. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157834. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157835. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157836. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157837. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157838. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157839. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157840. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157841. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157842. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157843. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157844. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157845. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157846. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157847. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157848. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157849. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157850. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157851. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157852. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157853. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157854. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157855. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157856. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157857. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157858. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157859. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157860. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157861. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157862. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157863. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157864. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157865. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157866. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157867. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157868. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157869. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157870. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157871. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157872. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157873. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157874. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157875. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157876. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157877. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157878. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157879. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157880. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157881. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157882. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157883. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157884. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157885. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157886. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157887. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157888. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157889. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157890. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157891. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157892. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157893. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157894. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157895. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157896. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157897. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157898. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157899. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157900. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157901. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157902. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157903. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157904. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157905. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157906. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157907. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157908. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157909. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157910. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157911. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157912. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157913. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157914. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157915. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157916. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157917. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157918. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157919. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157920. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157921. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157922. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157923. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157924. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157925. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157926. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157927. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157928. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157929. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157930. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157931. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157932. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157933. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157934. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157935. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157936. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157937. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157938. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157939. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157940. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157941. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157942. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157943. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157944. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157945. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157946. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157947. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157948. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157949. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157950. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157951. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157952. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157953. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157954. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157955. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157956. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157957. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157958. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157959. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157960. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157961. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157962. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157963. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157964. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157965. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157966. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157967. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157968. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157969. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157970. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157971. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157972. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157973. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157974. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157975. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157976. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157977. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157978. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157979. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157980. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157981. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157982. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157983. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157984. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157985. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157986. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157987. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157988. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157989. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157990. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157991. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157992. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157993. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157994. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157995. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157996. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157997. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157998. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157999. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158000. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158001. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158002. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158003. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158004. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158005. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158006. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158007. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158008. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158009. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158010. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158011. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158012. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158013. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158014. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158015. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158016. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158017. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158018. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158019. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158020. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158021. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158022. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158023. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158024. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158025. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158026. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158027. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158028. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158029. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158030. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158031. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158032. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158033. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158034. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158035. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158036. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158037. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158038. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158039. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158040. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158041. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158042. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158043. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158044. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158045. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158046. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158047. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158048. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158049. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158050. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158051. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158052. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158053. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158054. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158055. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158056. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158057. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158058. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158059. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158060. };
  158061. static float vwin8192[4096] = {
  158062. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158063. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158064. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158065. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158066. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158067. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158068. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158069. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158070. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158071. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158072. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158073. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158074. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158075. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158076. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158077. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158078. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158079. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158080. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158081. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158082. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158083. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158084. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158085. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158086. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158087. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158088. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158089. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158090. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158091. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158092. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158093. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158094. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158095. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158096. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158097. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158098. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158099. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158100. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158101. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158102. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158103. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158104. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158105. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158106. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158107. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158108. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158109. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158110. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158111. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158112. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158113. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158114. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158115. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158116. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158117. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158118. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158119. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158120. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158121. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158122. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158123. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158124. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158125. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158126. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158127. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158128. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158129. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158130. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158131. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158132. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158133. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158134. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158135. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158136. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158137. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158138. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158139. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158140. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158141. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158142. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158143. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158144. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158145. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158146. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158147. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158148. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158149. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158150. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158151. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158152. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158153. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158154. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158155. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158156. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158157. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158158. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158159. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158160. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158161. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158162. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158163. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158164. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158165. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158166. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158167. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158168. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158169. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158170. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158171. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158172. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158173. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158174. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158175. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158176. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158177. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158178. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158179. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158180. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158181. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158182. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158183. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158184. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158185. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158186. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158187. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158188. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158189. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158190. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158191. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158192. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158193. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158194. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158195. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158196. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158197. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158198. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158199. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158200. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158201. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158202. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158203. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158204. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158205. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158206. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158207. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158208. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158209. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158210. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158211. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158212. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158213. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158214. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158215. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158216. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158217. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158218. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158219. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158220. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158221. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158222. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158223. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158224. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158225. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158226. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158227. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158228. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158229. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158230. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158231. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158232. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158233. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158234. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158235. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158236. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158237. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158238. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158239. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158240. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158241. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158242. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158243. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158244. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158245. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158246. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158247. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158248. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158249. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158250. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158251. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158252. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158253. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158254. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158255. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158256. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158257. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158258. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158259. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158260. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158261. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158262. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158263. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158264. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158265. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158266. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158267. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158268. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158269. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158270. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158271. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158272. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158273. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158274. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158275. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158276. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158277. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158278. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158279. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158280. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158281. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158282. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158283. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158284. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158285. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158286. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158287. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158288. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158289. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158290. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158291. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158292. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158293. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158294. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158295. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158296. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158297. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158298. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158299. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158300. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158301. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158302. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158303. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158304. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158305. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158306. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158307. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158308. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158309. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158310. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158311. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158312. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158313. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158314. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158315. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158316. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158317. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158318. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158319. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158320. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158321. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158322. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158323. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158324. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158325. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158326. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158327. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158328. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158329. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158330. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158331. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158332. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158333. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158334. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158335. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158336. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158337. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158338. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158339. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158340. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158341. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158342. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158343. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158344. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158345. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158346. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158347. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158348. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158349. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158350. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158351. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158352. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158353. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158354. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158355. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158356. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158357. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158358. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158359. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158360. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158361. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158362. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158363. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158364. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158365. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158366. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158367. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158368. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158369. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158370. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158371. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158372. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158373. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158374. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158375. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158376. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158377. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158378. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158379. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158380. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158381. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158382. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158383. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158384. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158385. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158386. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158387. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158388. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158389. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158390. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158391. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158392. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158393. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158394. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158395. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158396. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158397. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158398. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158399. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158400. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158401. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158402. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158403. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158404. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158405. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158406. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158407. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158408. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158409. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158410. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158411. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158412. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158413. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158414. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158415. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158416. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158417. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158418. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158419. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158420. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158421. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158422. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158423. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158424. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158425. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158426. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158427. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158428. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158429. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158430. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158431. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158432. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158433. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158434. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158435. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158436. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158437. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158438. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158439. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158440. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158441. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158442. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158443. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158444. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158445. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158446. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158447. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158448. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158449. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158450. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158451. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158452. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158453. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158454. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158455. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158456. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158457. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158458. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158459. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158460. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158461. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158462. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158463. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158464. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158465. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158466. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158467. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158468. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158469. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158470. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158471. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158472. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158473. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158474. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158475. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158476. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158477. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158478. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158479. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158480. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158481. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158482. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158483. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158484. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158485. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158486. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158487. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158488. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158489. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158490. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158491. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158492. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158493. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158494. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158495. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158496. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158497. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158498. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158499. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158500. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158501. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158502. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158503. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158504. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158505. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158506. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158507. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158508. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158509. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158510. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158511. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158512. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158513. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158514. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158515. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158516. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158517. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158518. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158519. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158520. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158521. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158522. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158523. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158524. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158525. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158526. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158527. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158528. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158529. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158530. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158531. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158532. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158533. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158534. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158535. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158536. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158537. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158538. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158539. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158540. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158541. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158542. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158543. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158544. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158545. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158546. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158547. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158548. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158549. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158550. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158551. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158552. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158553. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158554. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158555. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158556. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158557. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158558. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158559. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158560. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158561. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158562. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158563. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158564. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158565. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158566. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158567. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158568. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158569. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158570. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158571. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158572. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158573. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158574. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158575. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158576. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158577. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158578. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158579. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158580. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158581. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158582. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158583. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158584. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158585. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158586. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158587. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158588. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158589. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158590. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158591. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158592. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158593. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158594. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158595. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158596. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158597. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158598. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158599. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158600. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158601. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158602. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158603. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158604. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158605. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158606. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158607. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158608. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158609. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158610. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158611. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158612. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158613. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158614. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158615. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158616. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158617. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158618. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158619. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158620. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158621. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158622. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158623. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158624. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158625. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158626. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158627. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158628. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158629. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158630. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158631. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158632. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158633. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158634. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158635. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158636. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158637. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158638. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158639. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158640. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158641. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158642. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158643. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158644. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158645. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158646. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158647. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158648. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158649. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158650. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158651. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158652. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158653. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158654. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158655. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158656. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158657. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158658. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158659. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158660. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158661. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158662. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158663. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158664. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158665. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158666. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158667. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158668. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158669. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158670. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158671. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158672. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158673. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158674. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158675. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158676. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158677. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158678. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158679. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158680. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158681. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158682. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158683. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158684. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158685. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158686. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158687. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158688. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158689. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158690. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158691. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158692. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158693. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158694. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158695. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158696. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158697. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158698. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158699. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158700. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158701. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158702. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158703. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158704. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158705. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158706. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158707. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158708. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158709. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158710. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158711. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158712. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158713. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158714. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158715. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158716. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158717. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158718. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158719. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158720. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158721. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158722. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158723. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158724. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158725. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158726. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158727. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158728. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158729. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158730. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158731. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158732. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158733. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158734. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158735. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158736. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158737. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158738. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158739. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158740. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158741. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158742. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158743. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158744. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158745. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158746. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158747. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158748. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158749. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158750. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158751. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158752. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158753. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158754. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158755. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158756. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158757. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158758. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158759. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158760. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158761. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158762. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158763. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158764. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158765. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158766. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158767. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158768. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158769. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158770. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158771. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158772. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158773. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158774. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158775. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158776. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158777. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158778. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158779. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158780. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158781. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158782. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158783. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158784. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158785. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158786. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158787. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158788. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158789. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158790. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158791. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158792. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158793. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158794. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158795. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158796. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158797. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158798. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158799. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158800. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158801. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158802. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158803. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158804. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158805. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158806. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158807. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158808. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158809. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158810. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158811. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158812. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158813. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158814. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158815. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158816. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158817. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158818. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158819. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158820. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158821. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158822. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158823. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158824. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158825. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158826. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158827. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158828. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158829. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158830. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158831. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158832. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158833. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158834. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158835. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158836. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158837. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158838. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158839. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158840. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158841. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158842. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158843. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158844. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158845. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158846. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158847. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158848. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158849. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158850. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158851. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158852. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158853. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158854. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158855. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158856. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158857. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158858. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158859. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158860. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158861. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158862. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158863. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158864. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158865. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158866. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158867. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158868. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158869. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158870. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158871. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158872. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158873. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158874. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158875. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158876. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158877. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158878. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158879. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158880. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158881. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158882. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158883. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158884. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158885. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158886. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158887. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158888. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158889. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158890. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158891. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158892. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158893. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158894. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158895. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158896. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158897. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158898. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158899. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158900. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158901. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158902. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158903. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158904. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158905. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158906. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158907. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158908. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158909. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158910. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158911. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158912. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158913. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158914. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158915. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158916. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158917. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158918. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158919. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158920. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158921. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158922. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158923. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158924. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158925. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158926. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158927. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158928. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158929. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158930. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158931. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158932. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158933. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158934. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158935. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158936. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158937. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158938. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158939. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158940. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158941. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158942. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158943. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158944. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158945. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158946. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158947. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158948. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158949. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158950. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158951. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158952. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158953. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158954. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158955. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158956. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158957. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158958. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158959. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158960. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158961. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158962. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158963. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158964. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158965. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158966. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158967. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158968. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158969. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158970. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158971. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158972. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158973. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158974. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158975. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158976. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158977. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158978. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158979. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158980. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158981. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158982. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158983. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158984. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158985. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158986. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158987. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158988. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158989. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158990. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158991. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158992. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158993. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158994. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158995. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158996. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158997. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158998. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158999. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159000. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159001. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159002. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159003. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159004. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159005. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159006. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159007. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159008. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159009. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159010. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159011. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159012. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159013. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159014. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159015. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159016. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159017. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159018. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159019. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159020. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159021. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159022. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159023. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159024. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159025. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159026. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159027. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159028. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159029. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159030. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159031. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159032. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159033. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159034. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159035. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159036. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159037. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159038. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159039. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159040. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159041. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159042. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159043. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159044. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159045. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159046. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159047. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159048. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159049. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159050. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159051. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159052. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159053. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159054. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159055. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159056. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159057. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159058. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159059. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159060. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159061. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159062. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159063. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159064. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159065. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159066. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159067. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159068. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159069. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159070. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159071. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159072. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159073. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159074. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159075. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159076. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159077. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159078. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159079. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159080. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159081. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159082. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159083. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159084. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159085. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159086. };
  159087. static float *vwin[8] = {
  159088. vwin64,
  159089. vwin128,
  159090. vwin256,
  159091. vwin512,
  159092. vwin1024,
  159093. vwin2048,
  159094. vwin4096,
  159095. vwin8192,
  159096. };
  159097. float *_vorbis_window_get(int n){
  159098. return vwin[n];
  159099. }
  159100. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159101. int lW,int W,int nW){
  159102. lW=(W?lW:0);
  159103. nW=(W?nW:0);
  159104. {
  159105. float *windowLW=vwin[winno[lW]];
  159106. float *windowNW=vwin[winno[nW]];
  159107. long n=blocksizes[W];
  159108. long ln=blocksizes[lW];
  159109. long rn=blocksizes[nW];
  159110. long leftbegin=n/4-ln/4;
  159111. long leftend=leftbegin+ln/2;
  159112. long rightbegin=n/2+n/4-rn/4;
  159113. long rightend=rightbegin+rn/2;
  159114. int i,p;
  159115. for(i=0;i<leftbegin;i++)
  159116. d[i]=0.f;
  159117. for(p=0;i<leftend;i++,p++)
  159118. d[i]*=windowLW[p];
  159119. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159120. d[i]*=windowNW[p];
  159121. for(;i<n;i++)
  159122. d[i]=0.f;
  159123. }
  159124. }
  159125. #endif
  159126. /*** End of inlined file: window.c ***/
  159127. #else
  159128. #include <vorbis/vorbisenc.h>
  159129. #include <vorbis/codec.h>
  159130. #include <vorbis/vorbisfile.h>
  159131. #endif
  159132. }
  159133. #undef max
  159134. #undef min
  159135. BEGIN_JUCE_NAMESPACE
  159136. static const char* const oggFormatName = "Ogg-Vorbis file";
  159137. static const char* const oggExtensions[] = { ".ogg", 0 };
  159138. class OggReader : public AudioFormatReader
  159139. {
  159140. OggVorbisNamespace::OggVorbis_File ovFile;
  159141. OggVorbisNamespace::ov_callbacks callbacks;
  159142. AudioSampleBuffer reservoir;
  159143. int reservoirStart, samplesInReservoir;
  159144. public:
  159145. OggReader (InputStream* const inp)
  159146. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159147. reservoir (2, 4096),
  159148. reservoirStart (0),
  159149. samplesInReservoir (0)
  159150. {
  159151. using namespace OggVorbisNamespace;
  159152. sampleRate = 0;
  159153. usesFloatingPointData = true;
  159154. callbacks.read_func = &oggReadCallback;
  159155. callbacks.seek_func = &oggSeekCallback;
  159156. callbacks.close_func = &oggCloseCallback;
  159157. callbacks.tell_func = &oggTellCallback;
  159158. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159159. if (err == 0)
  159160. {
  159161. vorbis_info* info = ov_info (&ovFile, -1);
  159162. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159163. numChannels = info->channels;
  159164. bitsPerSample = 16;
  159165. sampleRate = info->rate;
  159166. reservoir.setSize (numChannels,
  159167. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159168. }
  159169. }
  159170. ~OggReader()
  159171. {
  159172. OggVorbisNamespace::ov_clear (&ovFile);
  159173. }
  159174. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159175. int64 startSampleInFile, int numSamples)
  159176. {
  159177. while (numSamples > 0)
  159178. {
  159179. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159180. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159181. {
  159182. // got a few samples overlapping, so use them before seeking..
  159183. const int numToUse = jmin (numSamples, numAvailable);
  159184. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159185. if (destSamples[i] != 0)
  159186. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159187. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159188. sizeof (float) * numToUse);
  159189. startSampleInFile += numToUse;
  159190. numSamples -= numToUse;
  159191. startOffsetInDestBuffer += numToUse;
  159192. if (numSamples == 0)
  159193. break;
  159194. }
  159195. if (startSampleInFile < reservoirStart
  159196. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159197. {
  159198. // buffer miss, so refill the reservoir
  159199. int bitStream = 0;
  159200. reservoirStart = jmax (0, (int) startSampleInFile);
  159201. samplesInReservoir = reservoir.getNumSamples();
  159202. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159203. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159204. int offset = 0;
  159205. int numToRead = samplesInReservoir;
  159206. while (numToRead > 0)
  159207. {
  159208. float** dataIn = 0;
  159209. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159210. if (samps <= 0)
  159211. break;
  159212. jassert (samps <= numToRead);
  159213. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159214. {
  159215. memcpy (reservoir.getSampleData (i, offset),
  159216. dataIn[i],
  159217. sizeof (float) * samps);
  159218. }
  159219. numToRead -= samps;
  159220. offset += samps;
  159221. }
  159222. if (numToRead > 0)
  159223. reservoir.clear (offset, numToRead);
  159224. }
  159225. }
  159226. if (numSamples > 0)
  159227. {
  159228. for (int i = numDestChannels; --i >= 0;)
  159229. if (destSamples[i] != 0)
  159230. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159231. sizeof (int) * numSamples);
  159232. }
  159233. return true;
  159234. }
  159235. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159236. {
  159237. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159238. }
  159239. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159240. {
  159241. InputStream* const in = static_cast <InputStream*> (datasource);
  159242. if (whence == SEEK_CUR)
  159243. offset += in->getPosition();
  159244. else if (whence == SEEK_END)
  159245. offset += in->getTotalLength();
  159246. in->setPosition (offset);
  159247. return 0;
  159248. }
  159249. static int oggCloseCallback (void*)
  159250. {
  159251. return 0;
  159252. }
  159253. static long oggTellCallback (void* datasource)
  159254. {
  159255. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159256. }
  159257. juce_UseDebuggingNewOperator
  159258. };
  159259. class OggWriter : public AudioFormatWriter
  159260. {
  159261. OggVorbisNamespace::ogg_stream_state os;
  159262. OggVorbisNamespace::ogg_page og;
  159263. OggVorbisNamespace::ogg_packet op;
  159264. OggVorbisNamespace::vorbis_info vi;
  159265. OggVorbisNamespace::vorbis_comment vc;
  159266. OggVorbisNamespace::vorbis_dsp_state vd;
  159267. OggVorbisNamespace::vorbis_block vb;
  159268. public:
  159269. bool ok;
  159270. OggWriter (OutputStream* const out,
  159271. const double sampleRate,
  159272. const int numChannels,
  159273. const int bitsPerSample,
  159274. const int qualityIndex)
  159275. : AudioFormatWriter (out, TRANS (oggFormatName),
  159276. sampleRate,
  159277. numChannels,
  159278. bitsPerSample)
  159279. {
  159280. using namespace OggVorbisNamespace;
  159281. ok = false;
  159282. vorbis_info_init (&vi);
  159283. if (vorbis_encode_init_vbr (&vi,
  159284. numChannels,
  159285. (int) sampleRate,
  159286. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159287. {
  159288. vorbis_comment_init (&vc);
  159289. if (JUCEApplication::getInstance() != 0)
  159290. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159291. vorbis_analysis_init (&vd, &vi);
  159292. vorbis_block_init (&vd, &vb);
  159293. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159294. ogg_packet header;
  159295. ogg_packet header_comm;
  159296. ogg_packet header_code;
  159297. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159298. ogg_stream_packetin (&os, &header);
  159299. ogg_stream_packetin (&os, &header_comm);
  159300. ogg_stream_packetin (&os, &header_code);
  159301. for (;;)
  159302. {
  159303. if (ogg_stream_flush (&os, &og) == 0)
  159304. break;
  159305. output->write (og.header, og.header_len);
  159306. output->write (og.body, og.body_len);
  159307. }
  159308. ok = true;
  159309. }
  159310. }
  159311. ~OggWriter()
  159312. {
  159313. using namespace OggVorbisNamespace;
  159314. if (ok)
  159315. {
  159316. // write a zero-length packet to show ogg that we're finished..
  159317. write (0, 0);
  159318. ogg_stream_clear (&os);
  159319. vorbis_block_clear (&vb);
  159320. vorbis_dsp_clear (&vd);
  159321. vorbis_comment_clear (&vc);
  159322. vorbis_info_clear (&vi);
  159323. output->flush();
  159324. }
  159325. else
  159326. {
  159327. vorbis_info_clear (&vi);
  159328. output = 0; // to stop the base class deleting this, as it needs to be returned
  159329. // to the caller of createWriter()
  159330. }
  159331. }
  159332. bool write (const int** samplesToWrite, int numSamples)
  159333. {
  159334. using namespace OggVorbisNamespace;
  159335. if (! ok)
  159336. return false;
  159337. if (numSamples > 0)
  159338. {
  159339. const double gain = 1.0 / 0x80000000u;
  159340. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159341. for (int i = numChannels; --i >= 0;)
  159342. {
  159343. float* const dst = vorbisBuffer[i];
  159344. const int* const src = samplesToWrite [i];
  159345. if (src != 0 && dst != 0)
  159346. {
  159347. for (int j = 0; j < numSamples; ++j)
  159348. dst[j] = (float) (src[j] * gain);
  159349. }
  159350. }
  159351. }
  159352. vorbis_analysis_wrote (&vd, numSamples);
  159353. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159354. {
  159355. vorbis_analysis (&vb, 0);
  159356. vorbis_bitrate_addblock (&vb);
  159357. while (vorbis_bitrate_flushpacket (&vd, &op))
  159358. {
  159359. ogg_stream_packetin (&os, &op);
  159360. for (;;)
  159361. {
  159362. if (ogg_stream_pageout (&os, &og) == 0)
  159363. break;
  159364. output->write (og.header, og.header_len);
  159365. output->write (og.body, og.body_len);
  159366. if (ogg_page_eos (&og))
  159367. break;
  159368. }
  159369. }
  159370. }
  159371. return true;
  159372. }
  159373. juce_UseDebuggingNewOperator
  159374. };
  159375. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159376. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159377. {
  159378. }
  159379. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159380. {
  159381. }
  159382. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159383. {
  159384. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159385. return Array <int> (rates);
  159386. }
  159387. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159388. {
  159389. Array <int> depths;
  159390. depths.add (32);
  159391. return depths;
  159392. }
  159393. bool OggVorbisAudioFormat::canDoStereo()
  159394. {
  159395. return true;
  159396. }
  159397. bool OggVorbisAudioFormat::canDoMono()
  159398. {
  159399. return true;
  159400. }
  159401. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159402. const bool deleteStreamIfOpeningFails)
  159403. {
  159404. ScopedPointer <OggReader> r (new OggReader (in));
  159405. if (r->sampleRate != 0)
  159406. return r.release();
  159407. if (! deleteStreamIfOpeningFails)
  159408. r->input = 0;
  159409. return 0;
  159410. }
  159411. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159412. double sampleRate,
  159413. unsigned int numChannels,
  159414. int bitsPerSample,
  159415. const StringPairArray& /*metadataValues*/,
  159416. int qualityOptionIndex)
  159417. {
  159418. ScopedPointer <OggWriter> w (new OggWriter (out,
  159419. sampleRate,
  159420. numChannels,
  159421. bitsPerSample,
  159422. qualityOptionIndex));
  159423. return w->ok ? w.release() : 0;
  159424. }
  159425. bool OggVorbisAudioFormat::isCompressed()
  159426. {
  159427. return true;
  159428. }
  159429. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159430. {
  159431. StringArray s;
  159432. s.add ("Low Quality");
  159433. s.add ("Medium Quality");
  159434. s.add ("High Quality");
  159435. return s;
  159436. }
  159437. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159438. {
  159439. FileInputStream* const in = source.createInputStream();
  159440. if (in != 0)
  159441. {
  159442. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159443. if (r != 0)
  159444. {
  159445. const int64 numSamps = r->lengthInSamples;
  159446. r = 0;
  159447. const int64 fileNumSamps = source.getSize() / 4;
  159448. const double ratio = numSamps / (double) fileNumSamps;
  159449. if (ratio > 12.0)
  159450. return 0;
  159451. else if (ratio > 6.0)
  159452. return 1;
  159453. else
  159454. return 2;
  159455. }
  159456. }
  159457. return 1;
  159458. }
  159459. END_JUCE_NAMESPACE
  159460. #endif
  159461. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159462. #endif
  159463. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159464. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159465. #if JUCE_MSVC
  159466. #pragma warning (push)
  159467. #endif
  159468. namespace jpeglibNamespace
  159469. {
  159470. #if JUCE_INCLUDE_JPEGLIB_CODE
  159471. #if JUCE_MINGW
  159472. typedef unsigned char boolean;
  159473. #endif
  159474. #define JPEG_INTERNALS
  159475. #undef FAR
  159476. /*** Start of inlined file: jpeglib.h ***/
  159477. #ifndef JPEGLIB_H
  159478. #define JPEGLIB_H
  159479. /*
  159480. * First we include the configuration files that record how this
  159481. * installation of the JPEG library is set up. jconfig.h can be
  159482. * generated automatically for many systems. jmorecfg.h contains
  159483. * manual configuration options that most people need not worry about.
  159484. */
  159485. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159486. /*** Start of inlined file: jconfig.h ***/
  159487. /* see jconfig.doc for explanations */
  159488. // disable all the warnings under MSVC
  159489. #ifdef _MSC_VER
  159490. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159491. #endif
  159492. #ifdef __BORLANDC__
  159493. #pragma warn -8057
  159494. #pragma warn -8019
  159495. #pragma warn -8004
  159496. #pragma warn -8008
  159497. #endif
  159498. #define HAVE_PROTOTYPES
  159499. #define HAVE_UNSIGNED_CHAR
  159500. #define HAVE_UNSIGNED_SHORT
  159501. /* #define void char */
  159502. /* #define const */
  159503. #undef CHAR_IS_UNSIGNED
  159504. #define HAVE_STDDEF_H
  159505. #define HAVE_STDLIB_H
  159506. #undef NEED_BSD_STRINGS
  159507. #undef NEED_SYS_TYPES_H
  159508. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159509. #undef NEED_SHORT_EXTERNAL_NAMES
  159510. #undef INCOMPLETE_TYPES_BROKEN
  159511. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159512. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159513. typedef unsigned char boolean;
  159514. #endif
  159515. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159516. #ifdef JPEG_INTERNALS
  159517. #undef RIGHT_SHIFT_IS_UNSIGNED
  159518. #endif /* JPEG_INTERNALS */
  159519. #ifdef JPEG_CJPEG_DJPEG
  159520. #define BMP_SUPPORTED /* BMP image file format */
  159521. #define GIF_SUPPORTED /* GIF image file format */
  159522. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159523. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159524. #define TARGA_SUPPORTED /* Targa image file format */
  159525. #define TWO_FILE_COMMANDLINE /* optional */
  159526. #define USE_SETMODE /* Microsoft has setmode() */
  159527. #undef NEED_SIGNAL_CATCHER
  159528. #undef DONT_USE_B_MODE
  159529. #undef PROGRESS_REPORT /* optional */
  159530. #endif /* JPEG_CJPEG_DJPEG */
  159531. /*** End of inlined file: jconfig.h ***/
  159532. /* widely used configuration options */
  159533. #endif
  159534. /*** Start of inlined file: jmorecfg.h ***/
  159535. /*
  159536. * Define BITS_IN_JSAMPLE as either
  159537. * 8 for 8-bit sample values (the usual setting)
  159538. * 12 for 12-bit sample values
  159539. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159540. * JPEG standard, and the IJG code does not support anything else!
  159541. * We do not support run-time selection of data precision, sorry.
  159542. */
  159543. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159544. /*
  159545. * Maximum number of components (color channels) allowed in JPEG image.
  159546. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159547. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159548. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159549. * really short on memory. (Each allowed component costs a hundred or so
  159550. * bytes of storage, whether actually used in an image or not.)
  159551. */
  159552. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159553. /*
  159554. * Basic data types.
  159555. * You may need to change these if you have a machine with unusual data
  159556. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159557. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159558. * but it had better be at least 16.
  159559. */
  159560. /* Representation of a single sample (pixel element value).
  159561. * We frequently allocate large arrays of these, so it's important to keep
  159562. * them small. But if you have memory to burn and access to char or short
  159563. * arrays is very slow on your hardware, you might want to change these.
  159564. */
  159565. #if BITS_IN_JSAMPLE == 8
  159566. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159567. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159568. */
  159569. #ifdef HAVE_UNSIGNED_CHAR
  159570. typedef unsigned char JSAMPLE;
  159571. #define GETJSAMPLE(value) ((int) (value))
  159572. #else /* not HAVE_UNSIGNED_CHAR */
  159573. typedef char JSAMPLE;
  159574. #ifdef CHAR_IS_UNSIGNED
  159575. #define GETJSAMPLE(value) ((int) (value))
  159576. #else
  159577. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159578. #endif /* CHAR_IS_UNSIGNED */
  159579. #endif /* HAVE_UNSIGNED_CHAR */
  159580. #define MAXJSAMPLE 255
  159581. #define CENTERJSAMPLE 128
  159582. #endif /* BITS_IN_JSAMPLE == 8 */
  159583. #if BITS_IN_JSAMPLE == 12
  159584. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159585. * On nearly all machines "short" will do nicely.
  159586. */
  159587. typedef short JSAMPLE;
  159588. #define GETJSAMPLE(value) ((int) (value))
  159589. #define MAXJSAMPLE 4095
  159590. #define CENTERJSAMPLE 2048
  159591. #endif /* BITS_IN_JSAMPLE == 12 */
  159592. /* Representation of a DCT frequency coefficient.
  159593. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159594. * Again, we allocate large arrays of these, but you can change to int
  159595. * if you have memory to burn and "short" is really slow.
  159596. */
  159597. typedef short JCOEF;
  159598. /* Compressed datastreams are represented as arrays of JOCTET.
  159599. * These must be EXACTLY 8 bits wide, at least once they are written to
  159600. * external storage. Note that when using the stdio data source/destination
  159601. * managers, this is also the data type passed to fread/fwrite.
  159602. */
  159603. #ifdef HAVE_UNSIGNED_CHAR
  159604. typedef unsigned char JOCTET;
  159605. #define GETJOCTET(value) (value)
  159606. #else /* not HAVE_UNSIGNED_CHAR */
  159607. typedef char JOCTET;
  159608. #ifdef CHAR_IS_UNSIGNED
  159609. #define GETJOCTET(value) (value)
  159610. #else
  159611. #define GETJOCTET(value) ((value) & 0xFF)
  159612. #endif /* CHAR_IS_UNSIGNED */
  159613. #endif /* HAVE_UNSIGNED_CHAR */
  159614. /* These typedefs are used for various table entries and so forth.
  159615. * They must be at least as wide as specified; but making them too big
  159616. * won't cost a huge amount of memory, so we don't provide special
  159617. * extraction code like we did for JSAMPLE. (In other words, these
  159618. * typedefs live at a different point on the speed/space tradeoff curve.)
  159619. */
  159620. /* UINT8 must hold at least the values 0..255. */
  159621. #ifdef HAVE_UNSIGNED_CHAR
  159622. typedef unsigned char UINT8;
  159623. #else /* not HAVE_UNSIGNED_CHAR */
  159624. #ifdef CHAR_IS_UNSIGNED
  159625. typedef char UINT8;
  159626. #else /* not CHAR_IS_UNSIGNED */
  159627. typedef short UINT8;
  159628. #endif /* CHAR_IS_UNSIGNED */
  159629. #endif /* HAVE_UNSIGNED_CHAR */
  159630. /* UINT16 must hold at least the values 0..65535. */
  159631. #ifdef HAVE_UNSIGNED_SHORT
  159632. typedef unsigned short UINT16;
  159633. #else /* not HAVE_UNSIGNED_SHORT */
  159634. typedef unsigned int UINT16;
  159635. #endif /* HAVE_UNSIGNED_SHORT */
  159636. /* INT16 must hold at least the values -32768..32767. */
  159637. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159638. typedef short INT16;
  159639. #endif
  159640. /* INT32 must hold at least signed 32-bit values. */
  159641. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159642. typedef long INT32;
  159643. #endif
  159644. /* Datatype used for image dimensions. The JPEG standard only supports
  159645. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159646. * "unsigned int" is sufficient on all machines. However, if you need to
  159647. * handle larger images and you don't mind deviating from the spec, you
  159648. * can change this datatype.
  159649. */
  159650. typedef unsigned int JDIMENSION;
  159651. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159652. /* These macros are used in all function definitions and extern declarations.
  159653. * You could modify them if you need to change function linkage conventions;
  159654. * in particular, you'll need to do that to make the library a Windows DLL.
  159655. * Another application is to make all functions global for use with debuggers
  159656. * or code profilers that require it.
  159657. */
  159658. /* a function called through method pointers: */
  159659. #define METHODDEF(type) static type
  159660. /* a function used only in its module: */
  159661. #define LOCAL(type) static type
  159662. /* a function referenced thru EXTERNs: */
  159663. #define GLOBAL(type) type
  159664. /* a reference to a GLOBAL function: */
  159665. #define EXTERN(type) extern type
  159666. /* This macro is used to declare a "method", that is, a function pointer.
  159667. * We want to supply prototype parameters if the compiler can cope.
  159668. * Note that the arglist parameter must be parenthesized!
  159669. * Again, you can customize this if you need special linkage keywords.
  159670. */
  159671. #ifdef HAVE_PROTOTYPES
  159672. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159673. #else
  159674. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159675. #endif
  159676. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159677. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159678. * by just saying "FAR *" where such a pointer is needed. In a few places
  159679. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159680. */
  159681. #ifdef NEED_FAR_POINTERS
  159682. #define FAR far
  159683. #else
  159684. #define FAR
  159685. #endif
  159686. /*
  159687. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159688. * in standard header files. Or you may have conflicts with application-
  159689. * specific header files that you want to include together with these files.
  159690. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159691. */
  159692. #ifndef HAVE_BOOLEAN
  159693. typedef int boolean;
  159694. #endif
  159695. #ifndef FALSE /* in case these macros already exist */
  159696. #define FALSE 0 /* values of boolean */
  159697. #endif
  159698. #ifndef TRUE
  159699. #define TRUE 1
  159700. #endif
  159701. /*
  159702. * The remaining options affect code selection within the JPEG library,
  159703. * but they don't need to be visible to most applications using the library.
  159704. * To minimize application namespace pollution, the symbols won't be
  159705. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159706. */
  159707. #ifdef JPEG_INTERNALS
  159708. #define JPEG_INTERNAL_OPTIONS
  159709. #endif
  159710. #ifdef JPEG_INTERNAL_OPTIONS
  159711. /*
  159712. * These defines indicate whether to include various optional functions.
  159713. * Undefining some of these symbols will produce a smaller but less capable
  159714. * library. Note that you can leave certain source files out of the
  159715. * compilation/linking process if you've #undef'd the corresponding symbols.
  159716. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159717. */
  159718. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159719. /* Capability options common to encoder and decoder: */
  159720. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159721. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159722. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159723. /* Encoder capability options: */
  159724. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159725. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159726. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159727. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159728. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159729. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159730. * precision, so jchuff.c normally uses entropy optimization to compute
  159731. * usable tables for higher precision. If you don't want to do optimization,
  159732. * you'll have to supply different default Huffman tables.
  159733. * The exact same statements apply for progressive JPEG: the default tables
  159734. * don't work for progressive mode. (This may get fixed, however.)
  159735. */
  159736. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159737. /* Decoder capability options: */
  159738. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159739. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159740. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159741. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159742. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159743. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159744. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159745. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159746. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159747. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159748. /* more capability options later, no doubt */
  159749. /*
  159750. * Ordering of RGB data in scanlines passed to or from the application.
  159751. * If your application wants to deal with data in the order B,G,R, just
  159752. * change these macros. You can also deal with formats such as R,G,B,X
  159753. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159754. * the offsets will also change the order in which colormap data is organized.
  159755. * RESTRICTIONS:
  159756. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159757. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159758. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159759. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159760. * is not 3 (they don't understand about dummy color components!). So you
  159761. * can't use color quantization if you change that value.
  159762. */
  159763. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159764. #define RGB_GREEN 1 /* Offset of Green */
  159765. #define RGB_BLUE 2 /* Offset of Blue */
  159766. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159767. /* Definitions for speed-related optimizations. */
  159768. /* If your compiler supports inline functions, define INLINE
  159769. * as the inline keyword; otherwise define it as empty.
  159770. */
  159771. #ifndef INLINE
  159772. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159773. #define INLINE __inline__
  159774. #endif
  159775. #ifndef INLINE
  159776. #define INLINE /* default is to define it as empty */
  159777. #endif
  159778. #endif
  159779. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159780. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159781. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159782. */
  159783. #ifndef MULTIPLIER
  159784. #define MULTIPLIER int /* type for fastest integer multiply */
  159785. #endif
  159786. /* FAST_FLOAT should be either float or double, whichever is done faster
  159787. * by your compiler. (Note that this type is only used in the floating point
  159788. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159789. * Typically, float is faster in ANSI C compilers, while double is faster in
  159790. * pre-ANSI compilers (because they insist on converting to double anyway).
  159791. * The code below therefore chooses float if we have ANSI-style prototypes.
  159792. */
  159793. #ifndef FAST_FLOAT
  159794. #ifdef HAVE_PROTOTYPES
  159795. #define FAST_FLOAT float
  159796. #else
  159797. #define FAST_FLOAT double
  159798. #endif
  159799. #endif
  159800. #endif /* JPEG_INTERNAL_OPTIONS */
  159801. /*** End of inlined file: jmorecfg.h ***/
  159802. /* seldom changed options */
  159803. /* Version ID for the JPEG library.
  159804. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159805. */
  159806. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159807. /* Various constants determining the sizes of things.
  159808. * All of these are specified by the JPEG standard, so don't change them
  159809. * if you want to be compatible.
  159810. */
  159811. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159812. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159813. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159814. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159815. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159816. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159817. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159818. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159819. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159820. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159821. * to handle it. We even let you do this from the jconfig.h file. However,
  159822. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159823. * sometimes emits noncompliant files doesn't mean you should too.
  159824. */
  159825. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159826. #ifndef D_MAX_BLOCKS_IN_MCU
  159827. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159828. #endif
  159829. /* Data structures for images (arrays of samples and of DCT coefficients).
  159830. * On 80x86 machines, the image arrays are too big for near pointers,
  159831. * but the pointer arrays can fit in near memory.
  159832. */
  159833. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159834. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159835. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159836. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159837. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159838. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159839. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159840. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159841. /* Types for JPEG compression parameters and working tables. */
  159842. /* DCT coefficient quantization tables. */
  159843. typedef struct {
  159844. /* This array gives the coefficient quantizers in natural array order
  159845. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159846. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159847. */
  159848. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159849. /* This field is used only during compression. It's initialized FALSE when
  159850. * the table is created, and set TRUE when it's been output to the file.
  159851. * You could suppress output of a table by setting this to TRUE.
  159852. * (See jpeg_suppress_tables for an example.)
  159853. */
  159854. boolean sent_table; /* TRUE when table has been output */
  159855. } JQUANT_TBL;
  159856. /* Huffman coding tables. */
  159857. typedef struct {
  159858. /* These two fields directly represent the contents of a JPEG DHT marker */
  159859. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159860. /* length k bits; bits[0] is unused */
  159861. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159862. /* This field is used only during compression. It's initialized FALSE when
  159863. * the table is created, and set TRUE when it's been output to the file.
  159864. * You could suppress output of a table by setting this to TRUE.
  159865. * (See jpeg_suppress_tables for an example.)
  159866. */
  159867. boolean sent_table; /* TRUE when table has been output */
  159868. } JHUFF_TBL;
  159869. /* Basic info about one component (color channel). */
  159870. typedef struct {
  159871. /* These values are fixed over the whole image. */
  159872. /* For compression, they must be supplied by parameter setup; */
  159873. /* for decompression, they are read from the SOF marker. */
  159874. int component_id; /* identifier for this component (0..255) */
  159875. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159876. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159877. int v_samp_factor; /* vertical sampling factor (1..4) */
  159878. int quant_tbl_no; /* quantization table selector (0..3) */
  159879. /* These values may vary between scans. */
  159880. /* For compression, they must be supplied by parameter setup; */
  159881. /* for decompression, they are read from the SOS marker. */
  159882. /* The decompressor output side may not use these variables. */
  159883. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159884. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159885. /* Remaining fields should be treated as private by applications. */
  159886. /* These values are computed during compression or decompression startup: */
  159887. /* Component's size in DCT blocks.
  159888. * Any dummy blocks added to complete an MCU are not counted; therefore
  159889. * these values do not depend on whether a scan is interleaved or not.
  159890. */
  159891. JDIMENSION width_in_blocks;
  159892. JDIMENSION height_in_blocks;
  159893. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159894. * For decompression this is the size of the output from one DCT block,
  159895. * reflecting any scaling we choose to apply during the IDCT step.
  159896. * Values of 1,2,4,8 are likely to be supported. Note that different
  159897. * components may receive different IDCT scalings.
  159898. */
  159899. int DCT_scaled_size;
  159900. /* The downsampled dimensions are the component's actual, unpadded number
  159901. * of samples at the main buffer (preprocessing/compression interface), thus
  159902. * downsampled_width = ceil(image_width * Hi/Hmax)
  159903. * and similarly for height. For decompression, IDCT scaling is included, so
  159904. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159905. */
  159906. JDIMENSION downsampled_width; /* actual width in samples */
  159907. JDIMENSION downsampled_height; /* actual height in samples */
  159908. /* This flag is used only for decompression. In cases where some of the
  159909. * components will be ignored (eg grayscale output from YCbCr image),
  159910. * we can skip most computations for the unused components.
  159911. */
  159912. boolean component_needed; /* do we need the value of this component? */
  159913. /* These values are computed before starting a scan of the component. */
  159914. /* The decompressor output side may not use these variables. */
  159915. int MCU_width; /* number of blocks per MCU, horizontally */
  159916. int MCU_height; /* number of blocks per MCU, vertically */
  159917. int MCU_blocks; /* MCU_width * MCU_height */
  159918. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159919. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159920. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159921. /* Saved quantization table for component; NULL if none yet saved.
  159922. * See jdinput.c comments about the need for this information.
  159923. * This field is currently used only for decompression.
  159924. */
  159925. JQUANT_TBL * quant_table;
  159926. /* Private per-component storage for DCT or IDCT subsystem. */
  159927. void * dct_table;
  159928. } jpeg_component_info;
  159929. /* The script for encoding a multiple-scan file is an array of these: */
  159930. typedef struct {
  159931. int comps_in_scan; /* number of components encoded in this scan */
  159932. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159933. int Ss, Se; /* progressive JPEG spectral selection parms */
  159934. int Ah, Al; /* progressive JPEG successive approx. parms */
  159935. } jpeg_scan_info;
  159936. /* The decompressor can save APPn and COM markers in a list of these: */
  159937. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159938. struct jpeg_marker_struct {
  159939. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159940. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159941. unsigned int original_length; /* # bytes of data in the file */
  159942. unsigned int data_length; /* # bytes of data saved at data[] */
  159943. JOCTET FAR * data; /* the data contained in the marker */
  159944. /* the marker length word is not counted in data_length or original_length */
  159945. };
  159946. /* Known color spaces. */
  159947. typedef enum {
  159948. JCS_UNKNOWN, /* error/unspecified */
  159949. JCS_GRAYSCALE, /* monochrome */
  159950. JCS_RGB, /* red/green/blue */
  159951. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159952. JCS_CMYK, /* C/M/Y/K */
  159953. JCS_YCCK /* Y/Cb/Cr/K */
  159954. } J_COLOR_SPACE;
  159955. /* DCT/IDCT algorithm options. */
  159956. typedef enum {
  159957. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159958. JDCT_IFAST, /* faster, less accurate integer method */
  159959. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159960. } J_DCT_METHOD;
  159961. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159962. #define JDCT_DEFAULT JDCT_ISLOW
  159963. #endif
  159964. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159965. #define JDCT_FASTEST JDCT_IFAST
  159966. #endif
  159967. /* Dithering options for decompression. */
  159968. typedef enum {
  159969. JDITHER_NONE, /* no dithering */
  159970. JDITHER_ORDERED, /* simple ordered dither */
  159971. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159972. } J_DITHER_MODE;
  159973. /* Common fields between JPEG compression and decompression master structs. */
  159974. #define jpeg_common_fields \
  159975. struct jpeg_error_mgr * err; /* Error handler module */\
  159976. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159977. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159978. void * client_data; /* Available for use by application */\
  159979. boolean is_decompressor; /* So common code can tell which is which */\
  159980. int global_state /* For checking call sequence validity */
  159981. /* Routines that are to be used by both halves of the library are declared
  159982. * to receive a pointer to this structure. There are no actual instances of
  159983. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159984. */
  159985. struct jpeg_common_struct {
  159986. jpeg_common_fields; /* Fields common to both master struct types */
  159987. /* Additional fields follow in an actual jpeg_compress_struct or
  159988. * jpeg_decompress_struct. All three structs must agree on these
  159989. * initial fields! (This would be a lot cleaner in C++.)
  159990. */
  159991. };
  159992. typedef struct jpeg_common_struct * j_common_ptr;
  159993. typedef struct jpeg_compress_struct * j_compress_ptr;
  159994. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159995. /* Master record for a compression instance */
  159996. struct jpeg_compress_struct {
  159997. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159998. /* Destination for compressed data */
  159999. struct jpeg_destination_mgr * dest;
  160000. /* Description of source image --- these fields must be filled in by
  160001. * outer application before starting compression. in_color_space must
  160002. * be correct before you can even call jpeg_set_defaults().
  160003. */
  160004. JDIMENSION image_width; /* input image width */
  160005. JDIMENSION image_height; /* input image height */
  160006. int input_components; /* # of color components in input image */
  160007. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160008. double input_gamma; /* image gamma of input image */
  160009. /* Compression parameters --- these fields must be set before calling
  160010. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160011. * initialize everything to reasonable defaults, then changing anything
  160012. * the application specifically wants to change. That way you won't get
  160013. * burnt when new parameters are added. Also note that there are several
  160014. * helper routines to simplify changing parameters.
  160015. */
  160016. int data_precision; /* bits of precision in image data */
  160017. int num_components; /* # of color components in JPEG image */
  160018. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160019. jpeg_component_info * comp_info;
  160020. /* comp_info[i] describes component that appears i'th in SOF */
  160021. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160022. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160023. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160024. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160025. /* ptrs to Huffman coding tables, or NULL if not defined */
  160026. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160027. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160028. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160029. int num_scans; /* # of entries in scan_info array */
  160030. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160031. /* The default value of scan_info is NULL, which causes a single-scan
  160032. * sequential JPEG file to be emitted. To create a multi-scan file,
  160033. * set num_scans and scan_info to point to an array of scan definitions.
  160034. */
  160035. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160036. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160037. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160038. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160039. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160040. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160041. /* The restart interval can be specified in absolute MCUs by setting
  160042. * restart_interval, or in MCU rows by setting restart_in_rows
  160043. * (in which case the correct restart_interval will be figured
  160044. * for each scan).
  160045. */
  160046. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160047. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160048. /* Parameters controlling emission of special markers. */
  160049. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160050. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160051. UINT8 JFIF_minor_version;
  160052. /* These three values are not used by the JPEG code, merely copied */
  160053. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160054. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160055. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160056. UINT8 density_unit; /* JFIF code for pixel size units */
  160057. UINT16 X_density; /* Horizontal pixel density */
  160058. UINT16 Y_density; /* Vertical pixel density */
  160059. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160060. /* State variable: index of next scanline to be written to
  160061. * jpeg_write_scanlines(). Application may use this to control its
  160062. * processing loop, e.g., "while (next_scanline < image_height)".
  160063. */
  160064. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160065. /* Remaining fields are known throughout compressor, but generally
  160066. * should not be touched by a surrounding application.
  160067. */
  160068. /*
  160069. * These fields are computed during compression startup
  160070. */
  160071. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160072. int max_h_samp_factor; /* largest h_samp_factor */
  160073. int max_v_samp_factor; /* largest v_samp_factor */
  160074. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160075. /* The coefficient controller receives data in units of MCU rows as defined
  160076. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160077. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160078. * "iMCU" (interleaved MCU) row.
  160079. */
  160080. /*
  160081. * These fields are valid during any one scan.
  160082. * They describe the components and MCUs actually appearing in the scan.
  160083. */
  160084. int comps_in_scan; /* # of JPEG components in this scan */
  160085. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160086. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160087. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160088. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160089. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160090. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160091. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160092. /* i'th block in an MCU */
  160093. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160094. /*
  160095. * Links to compression subobjects (methods and private variables of modules)
  160096. */
  160097. struct jpeg_comp_master * master;
  160098. struct jpeg_c_main_controller * main;
  160099. struct jpeg_c_prep_controller * prep;
  160100. struct jpeg_c_coef_controller * coef;
  160101. struct jpeg_marker_writer * marker;
  160102. struct jpeg_color_converter * cconvert;
  160103. struct jpeg_downsampler * downsample;
  160104. struct jpeg_forward_dct * fdct;
  160105. struct jpeg_entropy_encoder * entropy;
  160106. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160107. int script_space_size;
  160108. };
  160109. /* Master record for a decompression instance */
  160110. struct jpeg_decompress_struct {
  160111. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160112. /* Source of compressed data */
  160113. struct jpeg_source_mgr * src;
  160114. /* Basic description of image --- filled in by jpeg_read_header(). */
  160115. /* Application may inspect these values to decide how to process image. */
  160116. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160117. JDIMENSION image_height; /* nominal image height */
  160118. int num_components; /* # of color components in JPEG image */
  160119. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160120. /* Decompression processing parameters --- these fields must be set before
  160121. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160122. * them to default values.
  160123. */
  160124. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160125. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160126. double output_gamma; /* image gamma wanted in output */
  160127. boolean buffered_image; /* TRUE=multiple output passes */
  160128. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160129. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160130. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160131. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160132. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160133. /* the following are ignored if not quantize_colors: */
  160134. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160135. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160136. int desired_number_of_colors; /* max # colors to use in created colormap */
  160137. /* these are significant only in buffered-image mode: */
  160138. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160139. boolean enable_external_quant;/* enable future use of external colormap */
  160140. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160141. /* Description of actual output image that will be returned to application.
  160142. * These fields are computed by jpeg_start_decompress().
  160143. * You can also use jpeg_calc_output_dimensions() to determine these values
  160144. * in advance of calling jpeg_start_decompress().
  160145. */
  160146. JDIMENSION output_width; /* scaled image width */
  160147. JDIMENSION output_height; /* scaled image height */
  160148. int out_color_components; /* # of color components in out_color_space */
  160149. int output_components; /* # of color components returned */
  160150. /* output_components is 1 (a colormap index) when quantizing colors;
  160151. * otherwise it equals out_color_components.
  160152. */
  160153. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160154. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160155. * high, space and time will be wasted due to unnecessary data copying.
  160156. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160157. */
  160158. /* When quantizing colors, the output colormap is described by these fields.
  160159. * The application can supply a colormap by setting colormap non-NULL before
  160160. * calling jpeg_start_decompress; otherwise a colormap is created during
  160161. * jpeg_start_decompress or jpeg_start_output.
  160162. * The map has out_color_components rows and actual_number_of_colors columns.
  160163. */
  160164. int actual_number_of_colors; /* number of entries in use */
  160165. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160166. /* State variables: these variables indicate the progress of decompression.
  160167. * The application may examine these but must not modify them.
  160168. */
  160169. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160170. * Application may use this to control its processing loop, e.g.,
  160171. * "while (output_scanline < output_height)".
  160172. */
  160173. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160174. /* Current input scan number and number of iMCU rows completed in scan.
  160175. * These indicate the progress of the decompressor input side.
  160176. */
  160177. int input_scan_number; /* Number of SOS markers seen so far */
  160178. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160179. /* The "output scan number" is the notional scan being displayed by the
  160180. * output side. The decompressor will not allow output scan/row number
  160181. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160182. */
  160183. int output_scan_number; /* Nominal scan number being displayed */
  160184. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160185. /* Current progression status. coef_bits[c][i] indicates the precision
  160186. * with which component c's DCT coefficient i (in zigzag order) is known.
  160187. * It is -1 when no data has yet been received, otherwise it is the point
  160188. * transform (shift) value for the most recent scan of the coefficient
  160189. * (thus, 0 at completion of the progression).
  160190. * This pointer is NULL when reading a non-progressive file.
  160191. */
  160192. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160193. /* Internal JPEG parameters --- the application usually need not look at
  160194. * these fields. Note that the decompressor output side may not use
  160195. * any parameters that can change between scans.
  160196. */
  160197. /* Quantization and Huffman tables are carried forward across input
  160198. * datastreams when processing abbreviated JPEG datastreams.
  160199. */
  160200. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160201. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160202. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160203. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160204. /* ptrs to Huffman coding tables, or NULL if not defined */
  160205. /* These parameters are never carried across datastreams, since they
  160206. * are given in SOF/SOS markers or defined to be reset by SOI.
  160207. */
  160208. int data_precision; /* bits of precision in image data */
  160209. jpeg_component_info * comp_info;
  160210. /* comp_info[i] describes component that appears i'th in SOF */
  160211. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160212. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160213. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160214. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160215. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160216. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160217. /* These fields record data obtained from optional markers recognized by
  160218. * the JPEG library.
  160219. */
  160220. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160221. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160222. UINT8 JFIF_major_version; /* JFIF version number */
  160223. UINT8 JFIF_minor_version;
  160224. UINT8 density_unit; /* JFIF code for pixel size units */
  160225. UINT16 X_density; /* Horizontal pixel density */
  160226. UINT16 Y_density; /* Vertical pixel density */
  160227. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160228. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160229. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160230. /* Aside from the specific data retained from APPn markers known to the
  160231. * library, the uninterpreted contents of any or all APPn and COM markers
  160232. * can be saved in a list for examination by the application.
  160233. */
  160234. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160235. /* Remaining fields are known throughout decompressor, but generally
  160236. * should not be touched by a surrounding application.
  160237. */
  160238. /*
  160239. * These fields are computed during decompression startup
  160240. */
  160241. int max_h_samp_factor; /* largest h_samp_factor */
  160242. int max_v_samp_factor; /* largest v_samp_factor */
  160243. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160244. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160245. /* The coefficient controller's input and output progress is measured in
  160246. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160247. * in fully interleaved JPEG scans, but are used whether the scan is
  160248. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160249. * rows of each component. Therefore, the IDCT output contains
  160250. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160251. */
  160252. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160253. /*
  160254. * These fields are valid during any one scan.
  160255. * They describe the components and MCUs actually appearing in the scan.
  160256. * Note that the decompressor output side must not use these fields.
  160257. */
  160258. int comps_in_scan; /* # of JPEG components in this scan */
  160259. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160260. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160261. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160262. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160263. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160264. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160265. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160266. /* i'th block in an MCU */
  160267. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160268. /* This field is shared between entropy decoder and marker parser.
  160269. * It is either zero or the code of a JPEG marker that has been
  160270. * read from the data source, but has not yet been processed.
  160271. */
  160272. int unread_marker;
  160273. /*
  160274. * Links to decompression subobjects (methods, private variables of modules)
  160275. */
  160276. struct jpeg_decomp_master * master;
  160277. struct jpeg_d_main_controller * main;
  160278. struct jpeg_d_coef_controller * coef;
  160279. struct jpeg_d_post_controller * post;
  160280. struct jpeg_input_controller * inputctl;
  160281. struct jpeg_marker_reader * marker;
  160282. struct jpeg_entropy_decoder * entropy;
  160283. struct jpeg_inverse_dct * idct;
  160284. struct jpeg_upsampler * upsample;
  160285. struct jpeg_color_deconverter * cconvert;
  160286. struct jpeg_color_quantizer * cquantize;
  160287. };
  160288. /* "Object" declarations for JPEG modules that may be supplied or called
  160289. * directly by the surrounding application.
  160290. * As with all objects in the JPEG library, these structs only define the
  160291. * publicly visible methods and state variables of a module. Additional
  160292. * private fields may exist after the public ones.
  160293. */
  160294. /* Error handler object */
  160295. struct jpeg_error_mgr {
  160296. /* Error exit handler: does not return to caller */
  160297. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160298. /* Conditionally emit a trace or warning message */
  160299. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160300. /* Routine that actually outputs a trace or error message */
  160301. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160302. /* Format a message string for the most recent JPEG error or message */
  160303. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160304. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160305. /* Reset error state variables at start of a new image */
  160306. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160307. /* The message ID code and any parameters are saved here.
  160308. * A message can have one string parameter or up to 8 int parameters.
  160309. */
  160310. int msg_code;
  160311. #define JMSG_STR_PARM_MAX 80
  160312. union {
  160313. int i[8];
  160314. char s[JMSG_STR_PARM_MAX];
  160315. } msg_parm;
  160316. /* Standard state variables for error facility */
  160317. int trace_level; /* max msg_level that will be displayed */
  160318. /* For recoverable corrupt-data errors, we emit a warning message,
  160319. * but keep going unless emit_message chooses to abort. emit_message
  160320. * should count warnings in num_warnings. The surrounding application
  160321. * can check for bad data by seeing if num_warnings is nonzero at the
  160322. * end of processing.
  160323. */
  160324. long num_warnings; /* number of corrupt-data warnings */
  160325. /* These fields point to the table(s) of error message strings.
  160326. * An application can change the table pointer to switch to a different
  160327. * message list (typically, to change the language in which errors are
  160328. * reported). Some applications may wish to add additional error codes
  160329. * that will be handled by the JPEG library error mechanism; the second
  160330. * table pointer is used for this purpose.
  160331. *
  160332. * First table includes all errors generated by JPEG library itself.
  160333. * Error code 0 is reserved for a "no such error string" message.
  160334. */
  160335. const char * const * jpeg_message_table; /* Library errors */
  160336. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160337. /* Second table can be added by application (see cjpeg/djpeg for example).
  160338. * It contains strings numbered first_addon_message..last_addon_message.
  160339. */
  160340. const char * const * addon_message_table; /* Non-library errors */
  160341. int first_addon_message; /* code for first string in addon table */
  160342. int last_addon_message; /* code for last string in addon table */
  160343. };
  160344. /* Progress monitor object */
  160345. struct jpeg_progress_mgr {
  160346. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160347. long pass_counter; /* work units completed in this pass */
  160348. long pass_limit; /* total number of work units in this pass */
  160349. int completed_passes; /* passes completed so far */
  160350. int total_passes; /* total number of passes expected */
  160351. };
  160352. /* Data destination object for compression */
  160353. struct jpeg_destination_mgr {
  160354. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160355. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160356. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160357. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160358. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160359. };
  160360. /* Data source object for decompression */
  160361. struct jpeg_source_mgr {
  160362. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160363. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160364. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160365. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160366. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160367. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160368. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160369. };
  160370. /* Memory manager object.
  160371. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160372. * and "really big" objects (virtual arrays with backing store if needed).
  160373. * The memory manager does not allow individual objects to be freed; rather,
  160374. * each created object is assigned to a pool, and whole pools can be freed
  160375. * at once. This is faster and more convenient than remembering exactly what
  160376. * to free, especially where malloc()/free() are not too speedy.
  160377. * NB: alloc routines never return NULL. They exit to error_exit if not
  160378. * successful.
  160379. */
  160380. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160381. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160382. #define JPOOL_NUMPOOLS 2
  160383. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160384. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160385. struct jpeg_memory_mgr {
  160386. /* Method pointers */
  160387. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160388. size_t sizeofobject));
  160389. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160390. size_t sizeofobject));
  160391. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160392. JDIMENSION samplesperrow,
  160393. JDIMENSION numrows));
  160394. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160395. JDIMENSION blocksperrow,
  160396. JDIMENSION numrows));
  160397. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160398. int pool_id,
  160399. boolean pre_zero,
  160400. JDIMENSION samplesperrow,
  160401. JDIMENSION numrows,
  160402. JDIMENSION maxaccess));
  160403. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160404. int pool_id,
  160405. boolean pre_zero,
  160406. JDIMENSION blocksperrow,
  160407. JDIMENSION numrows,
  160408. JDIMENSION maxaccess));
  160409. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160410. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160411. jvirt_sarray_ptr ptr,
  160412. JDIMENSION start_row,
  160413. JDIMENSION num_rows,
  160414. boolean writable));
  160415. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160416. jvirt_barray_ptr ptr,
  160417. JDIMENSION start_row,
  160418. JDIMENSION num_rows,
  160419. boolean writable));
  160420. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160421. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160422. /* Limit on memory allocation for this JPEG object. (Note that this is
  160423. * merely advisory, not a guaranteed maximum; it only affects the space
  160424. * used for virtual-array buffers.) May be changed by outer application
  160425. * after creating the JPEG object.
  160426. */
  160427. long max_memory_to_use;
  160428. /* Maximum allocation request accepted by alloc_large. */
  160429. long max_alloc_chunk;
  160430. };
  160431. /* Routine signature for application-supplied marker processing methods.
  160432. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160433. */
  160434. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160435. /* Declarations for routines called by application.
  160436. * The JPP macro hides prototype parameters from compilers that can't cope.
  160437. * Note JPP requires double parentheses.
  160438. */
  160439. #ifdef HAVE_PROTOTYPES
  160440. #define JPP(arglist) arglist
  160441. #else
  160442. #define JPP(arglist) ()
  160443. #endif
  160444. /* Short forms of external names for systems with brain-damaged linkers.
  160445. * We shorten external names to be unique in the first six letters, which
  160446. * is good enough for all known systems.
  160447. * (If your compiler itself needs names to be unique in less than 15
  160448. * characters, you are out of luck. Get a better compiler.)
  160449. */
  160450. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160451. #define jpeg_std_error jStdError
  160452. #define jpeg_CreateCompress jCreaCompress
  160453. #define jpeg_CreateDecompress jCreaDecompress
  160454. #define jpeg_destroy_compress jDestCompress
  160455. #define jpeg_destroy_decompress jDestDecompress
  160456. #define jpeg_stdio_dest jStdDest
  160457. #define jpeg_stdio_src jStdSrc
  160458. #define jpeg_set_defaults jSetDefaults
  160459. #define jpeg_set_colorspace jSetColorspace
  160460. #define jpeg_default_colorspace jDefColorspace
  160461. #define jpeg_set_quality jSetQuality
  160462. #define jpeg_set_linear_quality jSetLQuality
  160463. #define jpeg_add_quant_table jAddQuantTable
  160464. #define jpeg_quality_scaling jQualityScaling
  160465. #define jpeg_simple_progression jSimProgress
  160466. #define jpeg_suppress_tables jSuppressTables
  160467. #define jpeg_alloc_quant_table jAlcQTable
  160468. #define jpeg_alloc_huff_table jAlcHTable
  160469. #define jpeg_start_compress jStrtCompress
  160470. #define jpeg_write_scanlines jWrtScanlines
  160471. #define jpeg_finish_compress jFinCompress
  160472. #define jpeg_write_raw_data jWrtRawData
  160473. #define jpeg_write_marker jWrtMarker
  160474. #define jpeg_write_m_header jWrtMHeader
  160475. #define jpeg_write_m_byte jWrtMByte
  160476. #define jpeg_write_tables jWrtTables
  160477. #define jpeg_read_header jReadHeader
  160478. #define jpeg_start_decompress jStrtDecompress
  160479. #define jpeg_read_scanlines jReadScanlines
  160480. #define jpeg_finish_decompress jFinDecompress
  160481. #define jpeg_read_raw_data jReadRawData
  160482. #define jpeg_has_multiple_scans jHasMultScn
  160483. #define jpeg_start_output jStrtOutput
  160484. #define jpeg_finish_output jFinOutput
  160485. #define jpeg_input_complete jInComplete
  160486. #define jpeg_new_colormap jNewCMap
  160487. #define jpeg_consume_input jConsumeInput
  160488. #define jpeg_calc_output_dimensions jCalcDimensions
  160489. #define jpeg_save_markers jSaveMarkers
  160490. #define jpeg_set_marker_processor jSetMarker
  160491. #define jpeg_read_coefficients jReadCoefs
  160492. #define jpeg_write_coefficients jWrtCoefs
  160493. #define jpeg_copy_critical_parameters jCopyCrit
  160494. #define jpeg_abort_compress jAbrtCompress
  160495. #define jpeg_abort_decompress jAbrtDecompress
  160496. #define jpeg_abort jAbort
  160497. #define jpeg_destroy jDestroy
  160498. #define jpeg_resync_to_restart jResyncRestart
  160499. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160500. /* Default error-management setup */
  160501. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160502. JPP((struct jpeg_error_mgr * err));
  160503. /* Initialization of JPEG compression objects.
  160504. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160505. * names that applications should call. These expand to calls on
  160506. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160507. * passed for version mismatch checking.
  160508. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160509. */
  160510. #define jpeg_create_compress(cinfo) \
  160511. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160512. (size_t) sizeof(struct jpeg_compress_struct))
  160513. #define jpeg_create_decompress(cinfo) \
  160514. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160515. (size_t) sizeof(struct jpeg_decompress_struct))
  160516. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160517. int version, size_t structsize));
  160518. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160519. int version, size_t structsize));
  160520. /* Destruction of JPEG compression objects */
  160521. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160522. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160523. /* Standard data source and destination managers: stdio streams. */
  160524. /* Caller is responsible for opening the file before and closing after. */
  160525. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160526. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160527. /* Default parameter setup for compression */
  160528. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160529. /* Compression parameter setup aids */
  160530. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160531. J_COLOR_SPACE colorspace));
  160532. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160533. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160534. boolean force_baseline));
  160535. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160536. int scale_factor,
  160537. boolean force_baseline));
  160538. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160539. const unsigned int *basic_table,
  160540. int scale_factor,
  160541. boolean force_baseline));
  160542. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160543. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160544. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160545. boolean suppress));
  160546. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160547. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160548. /* Main entry points for compression */
  160549. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160550. boolean write_all_tables));
  160551. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160552. JSAMPARRAY scanlines,
  160553. JDIMENSION num_lines));
  160554. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160555. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160556. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160557. JSAMPIMAGE data,
  160558. JDIMENSION num_lines));
  160559. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160560. EXTERN(void) jpeg_write_marker
  160561. JPP((j_compress_ptr cinfo, int marker,
  160562. const JOCTET * dataptr, unsigned int datalen));
  160563. /* Same, but piecemeal. */
  160564. EXTERN(void) jpeg_write_m_header
  160565. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160566. EXTERN(void) jpeg_write_m_byte
  160567. JPP((j_compress_ptr cinfo, int val));
  160568. /* Alternate compression function: just write an abbreviated table file */
  160569. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160570. /* Decompression startup: read start of JPEG datastream to see what's there */
  160571. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160572. boolean require_image));
  160573. /* Return value is one of: */
  160574. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160575. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160576. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160577. /* If you pass require_image = TRUE (normal case), you need not check for
  160578. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160579. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160580. * give a suspension return (the stdio source module doesn't).
  160581. */
  160582. /* Main entry points for decompression */
  160583. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160584. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160585. JSAMPARRAY scanlines,
  160586. JDIMENSION max_lines));
  160587. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160588. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160589. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160590. JSAMPIMAGE data,
  160591. JDIMENSION max_lines));
  160592. /* Additional entry points for buffered-image mode. */
  160593. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160594. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160595. int scan_number));
  160596. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160597. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160598. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160599. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160600. /* Return value is one of: */
  160601. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160602. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160603. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160604. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160605. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160606. /* Precalculate output dimensions for current decompression parameters. */
  160607. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160608. /* Control saving of COM and APPn markers into marker_list. */
  160609. EXTERN(void) jpeg_save_markers
  160610. JPP((j_decompress_ptr cinfo, int marker_code,
  160611. unsigned int length_limit));
  160612. /* Install a special processing method for COM or APPn markers. */
  160613. EXTERN(void) jpeg_set_marker_processor
  160614. JPP((j_decompress_ptr cinfo, int marker_code,
  160615. jpeg_marker_parser_method routine));
  160616. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160617. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160618. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160619. jvirt_barray_ptr * coef_arrays));
  160620. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160621. j_compress_ptr dstinfo));
  160622. /* If you choose to abort compression or decompression before completing
  160623. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160624. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160625. * if you're done with the JPEG object, but if you want to clean it up and
  160626. * reuse it, call this:
  160627. */
  160628. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160629. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160630. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160631. * flavor of JPEG object. These may be more convenient in some places.
  160632. */
  160633. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160634. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160635. /* Default restart-marker-resync procedure for use by data source modules */
  160636. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160637. int desired));
  160638. /* These marker codes are exported since applications and data source modules
  160639. * are likely to want to use them.
  160640. */
  160641. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160642. #define JPEG_EOI 0xD9 /* EOI marker code */
  160643. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160644. #define JPEG_COM 0xFE /* COM marker code */
  160645. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160646. * for structure definitions that are never filled in, keep it quiet by
  160647. * supplying dummy definitions for the various substructures.
  160648. */
  160649. #ifdef INCOMPLETE_TYPES_BROKEN
  160650. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160651. struct jvirt_sarray_control { long dummy; };
  160652. struct jvirt_barray_control { long dummy; };
  160653. struct jpeg_comp_master { long dummy; };
  160654. struct jpeg_c_main_controller { long dummy; };
  160655. struct jpeg_c_prep_controller { long dummy; };
  160656. struct jpeg_c_coef_controller { long dummy; };
  160657. struct jpeg_marker_writer { long dummy; };
  160658. struct jpeg_color_converter { long dummy; };
  160659. struct jpeg_downsampler { long dummy; };
  160660. struct jpeg_forward_dct { long dummy; };
  160661. struct jpeg_entropy_encoder { long dummy; };
  160662. struct jpeg_decomp_master { long dummy; };
  160663. struct jpeg_d_main_controller { long dummy; };
  160664. struct jpeg_d_coef_controller { long dummy; };
  160665. struct jpeg_d_post_controller { long dummy; };
  160666. struct jpeg_input_controller { long dummy; };
  160667. struct jpeg_marker_reader { long dummy; };
  160668. struct jpeg_entropy_decoder { long dummy; };
  160669. struct jpeg_inverse_dct { long dummy; };
  160670. struct jpeg_upsampler { long dummy; };
  160671. struct jpeg_color_deconverter { long dummy; };
  160672. struct jpeg_color_quantizer { long dummy; };
  160673. #endif /* JPEG_INTERNALS */
  160674. #endif /* INCOMPLETE_TYPES_BROKEN */
  160675. /*
  160676. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160677. * The internal structure declarations are read only when that is true.
  160678. * Applications using the library should not include jpegint.h, but may wish
  160679. * to include jerror.h.
  160680. */
  160681. #ifdef JPEG_INTERNALS
  160682. /*** Start of inlined file: jpegint.h ***/
  160683. /* Declarations for both compression & decompression */
  160684. typedef enum { /* Operating modes for buffer controllers */
  160685. JBUF_PASS_THRU, /* Plain stripwise operation */
  160686. /* Remaining modes require a full-image buffer to have been created */
  160687. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160688. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160689. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160690. } J_BUF_MODE;
  160691. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160692. #define CSTATE_START 100 /* after create_compress */
  160693. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160694. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160695. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160696. #define DSTATE_START 200 /* after create_decompress */
  160697. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160698. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160699. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160700. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160701. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160702. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160703. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160704. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160705. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160706. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160707. /* Declarations for compression modules */
  160708. /* Master control module */
  160709. struct jpeg_comp_master {
  160710. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160711. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160712. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160713. /* State variables made visible to other modules */
  160714. boolean call_pass_startup; /* True if pass_startup must be called */
  160715. boolean is_last_pass; /* True during last pass */
  160716. };
  160717. /* Main buffer control (downsampled-data buffer) */
  160718. struct jpeg_c_main_controller {
  160719. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160720. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160721. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160722. JDIMENSION in_rows_avail));
  160723. };
  160724. /* Compression preprocessing (downsampling input buffer control) */
  160725. struct jpeg_c_prep_controller {
  160726. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160727. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160728. JSAMPARRAY input_buf,
  160729. JDIMENSION *in_row_ctr,
  160730. JDIMENSION in_rows_avail,
  160731. JSAMPIMAGE output_buf,
  160732. JDIMENSION *out_row_group_ctr,
  160733. JDIMENSION out_row_groups_avail));
  160734. };
  160735. /* Coefficient buffer control */
  160736. struct jpeg_c_coef_controller {
  160737. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160738. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160739. JSAMPIMAGE input_buf));
  160740. };
  160741. /* Colorspace conversion */
  160742. struct jpeg_color_converter {
  160743. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160744. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160745. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160746. JDIMENSION output_row, int num_rows));
  160747. };
  160748. /* Downsampling */
  160749. struct jpeg_downsampler {
  160750. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160751. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160752. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160753. JSAMPIMAGE output_buf,
  160754. JDIMENSION out_row_group_index));
  160755. boolean need_context_rows; /* TRUE if need rows above & below */
  160756. };
  160757. /* Forward DCT (also controls coefficient quantization) */
  160758. struct jpeg_forward_dct {
  160759. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160760. /* perhaps this should be an array??? */
  160761. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160762. jpeg_component_info * compptr,
  160763. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160764. JDIMENSION start_row, JDIMENSION start_col,
  160765. JDIMENSION num_blocks));
  160766. };
  160767. /* Entropy encoding */
  160768. struct jpeg_entropy_encoder {
  160769. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160770. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160771. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160772. };
  160773. /* Marker writing */
  160774. struct jpeg_marker_writer {
  160775. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160776. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160777. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160778. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160779. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160780. /* These routines are exported to allow insertion of extra markers */
  160781. /* Probably only COM and APPn markers should be written this way */
  160782. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160783. unsigned int datalen));
  160784. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160785. };
  160786. /* Declarations for decompression modules */
  160787. /* Master control module */
  160788. struct jpeg_decomp_master {
  160789. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160790. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160791. /* State variables made visible to other modules */
  160792. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160793. };
  160794. /* Input control module */
  160795. struct jpeg_input_controller {
  160796. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160797. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160798. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160799. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160800. /* State variables made visible to other modules */
  160801. boolean has_multiple_scans; /* True if file has multiple scans */
  160802. boolean eoi_reached; /* True when EOI has been consumed */
  160803. };
  160804. /* Main buffer control (downsampled-data buffer) */
  160805. struct jpeg_d_main_controller {
  160806. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160807. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160808. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160809. JDIMENSION out_rows_avail));
  160810. };
  160811. /* Coefficient buffer control */
  160812. struct jpeg_d_coef_controller {
  160813. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160814. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160815. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160816. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160817. JSAMPIMAGE output_buf));
  160818. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160819. jvirt_barray_ptr *coef_arrays;
  160820. };
  160821. /* Decompression postprocessing (color quantization buffer control) */
  160822. struct jpeg_d_post_controller {
  160823. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160824. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160825. JSAMPIMAGE input_buf,
  160826. JDIMENSION *in_row_group_ctr,
  160827. JDIMENSION in_row_groups_avail,
  160828. JSAMPARRAY output_buf,
  160829. JDIMENSION *out_row_ctr,
  160830. JDIMENSION out_rows_avail));
  160831. };
  160832. /* Marker reading & parsing */
  160833. struct jpeg_marker_reader {
  160834. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160835. /* Read markers until SOS or EOI.
  160836. * Returns same codes as are defined for jpeg_consume_input:
  160837. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160838. */
  160839. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160840. /* Read a restart marker --- exported for use by entropy decoder only */
  160841. jpeg_marker_parser_method read_restart_marker;
  160842. /* State of marker reader --- nominally internal, but applications
  160843. * supplying COM or APPn handlers might like to know the state.
  160844. */
  160845. boolean saw_SOI; /* found SOI? */
  160846. boolean saw_SOF; /* found SOF? */
  160847. int next_restart_num; /* next restart number expected (0-7) */
  160848. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160849. };
  160850. /* Entropy decoding */
  160851. struct jpeg_entropy_decoder {
  160852. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160853. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160854. JBLOCKROW *MCU_data));
  160855. /* This is here to share code between baseline and progressive decoders; */
  160856. /* other modules probably should not use it */
  160857. boolean insufficient_data; /* set TRUE after emitting warning */
  160858. };
  160859. /* Inverse DCT (also performs dequantization) */
  160860. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160861. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160862. JCOEFPTR coef_block,
  160863. JSAMPARRAY output_buf, JDIMENSION output_col));
  160864. struct jpeg_inverse_dct {
  160865. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160866. /* It is useful to allow each component to have a separate IDCT method. */
  160867. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160868. };
  160869. /* Upsampling (note that upsampler must also call color converter) */
  160870. struct jpeg_upsampler {
  160871. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160872. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160873. JSAMPIMAGE input_buf,
  160874. JDIMENSION *in_row_group_ctr,
  160875. JDIMENSION in_row_groups_avail,
  160876. JSAMPARRAY output_buf,
  160877. JDIMENSION *out_row_ctr,
  160878. JDIMENSION out_rows_avail));
  160879. boolean need_context_rows; /* TRUE if need rows above & below */
  160880. };
  160881. /* Colorspace conversion */
  160882. struct jpeg_color_deconverter {
  160883. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160884. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160885. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160886. JSAMPARRAY output_buf, int num_rows));
  160887. };
  160888. /* Color quantization or color precision reduction */
  160889. struct jpeg_color_quantizer {
  160890. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160891. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160892. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160893. int num_rows));
  160894. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160895. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160896. };
  160897. /* Miscellaneous useful macros */
  160898. #undef MAX
  160899. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160900. #undef MIN
  160901. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160902. /* We assume that right shift corresponds to signed division by 2 with
  160903. * rounding towards minus infinity. This is correct for typical "arithmetic
  160904. * shift" instructions that shift in copies of the sign bit. But some
  160905. * C compilers implement >> with an unsigned shift. For these machines you
  160906. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160907. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160908. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160909. * included in the variables of any routine using RIGHT_SHIFT.
  160910. */
  160911. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160912. #define SHIFT_TEMPS INT32 shift_temp;
  160913. #define RIGHT_SHIFT(x,shft) \
  160914. ((shift_temp = (x)) < 0 ? \
  160915. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160916. (shift_temp >> (shft)))
  160917. #else
  160918. #define SHIFT_TEMPS
  160919. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160920. #endif
  160921. /* Short forms of external names for systems with brain-damaged linkers. */
  160922. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160923. #define jinit_compress_master jICompress
  160924. #define jinit_c_master_control jICMaster
  160925. #define jinit_c_main_controller jICMainC
  160926. #define jinit_c_prep_controller jICPrepC
  160927. #define jinit_c_coef_controller jICCoefC
  160928. #define jinit_color_converter jICColor
  160929. #define jinit_downsampler jIDownsampler
  160930. #define jinit_forward_dct jIFDCT
  160931. #define jinit_huff_encoder jIHEncoder
  160932. #define jinit_phuff_encoder jIPHEncoder
  160933. #define jinit_marker_writer jIMWriter
  160934. #define jinit_master_decompress jIDMaster
  160935. #define jinit_d_main_controller jIDMainC
  160936. #define jinit_d_coef_controller jIDCoefC
  160937. #define jinit_d_post_controller jIDPostC
  160938. #define jinit_input_controller jIInCtlr
  160939. #define jinit_marker_reader jIMReader
  160940. #define jinit_huff_decoder jIHDecoder
  160941. #define jinit_phuff_decoder jIPHDecoder
  160942. #define jinit_inverse_dct jIIDCT
  160943. #define jinit_upsampler jIUpsampler
  160944. #define jinit_color_deconverter jIDColor
  160945. #define jinit_1pass_quantizer jI1Quant
  160946. #define jinit_2pass_quantizer jI2Quant
  160947. #define jinit_merged_upsampler jIMUpsampler
  160948. #define jinit_memory_mgr jIMemMgr
  160949. #define jdiv_round_up jDivRound
  160950. #define jround_up jRound
  160951. #define jcopy_sample_rows jCopySamples
  160952. #define jcopy_block_row jCopyBlocks
  160953. #define jzero_far jZeroFar
  160954. #define jpeg_zigzag_order jZIGTable
  160955. #define jpeg_natural_order jZAGTable
  160956. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160957. /* Compression module initialization routines */
  160958. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160959. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160960. boolean transcode_only));
  160961. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160962. boolean need_full_buffer));
  160963. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160964. boolean need_full_buffer));
  160965. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160966. boolean need_full_buffer));
  160967. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160968. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160969. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160970. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160971. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160972. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160973. /* Decompression module initialization routines */
  160974. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160975. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160976. boolean need_full_buffer));
  160977. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160978. boolean need_full_buffer));
  160979. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160980. boolean need_full_buffer));
  160981. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160982. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160983. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160984. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160985. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160986. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160987. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160988. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160989. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160990. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160991. /* Memory manager initialization */
  160992. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160993. /* Utility routines in jutils.c */
  160994. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160995. EXTERN(long) jround_up JPP((long a, long b));
  160996. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160997. JSAMPARRAY output_array, int dest_row,
  160998. int num_rows, JDIMENSION num_cols));
  160999. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161000. JDIMENSION num_blocks));
  161001. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161002. /* Constant tables in jutils.c */
  161003. #if 0 /* This table is not actually needed in v6a */
  161004. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161005. #endif
  161006. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161007. /* Suppress undefined-structure complaints if necessary. */
  161008. #ifdef INCOMPLETE_TYPES_BROKEN
  161009. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161010. struct jvirt_sarray_control { long dummy; };
  161011. struct jvirt_barray_control { long dummy; };
  161012. #endif
  161013. #endif /* INCOMPLETE_TYPES_BROKEN */
  161014. /*** End of inlined file: jpegint.h ***/
  161015. /* fetch private declarations */
  161016. /*** Start of inlined file: jerror.h ***/
  161017. /*
  161018. * To define the enum list of message codes, include this file without
  161019. * defining macro JMESSAGE. To create a message string table, include it
  161020. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161021. */
  161022. #ifndef JMESSAGE
  161023. #ifndef JERROR_H
  161024. /* First time through, define the enum list */
  161025. #define JMAKE_ENUM_LIST
  161026. #else
  161027. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161028. #define JMESSAGE(code,string)
  161029. #endif /* JERROR_H */
  161030. #endif /* JMESSAGE */
  161031. #ifdef JMAKE_ENUM_LIST
  161032. typedef enum {
  161033. #define JMESSAGE(code,string) code ,
  161034. #endif /* JMAKE_ENUM_LIST */
  161035. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161036. /* For maintenance convenience, list is alphabetical by message code name */
  161037. JMESSAGE(JERR_ARITH_NOTIMPL,
  161038. "Sorry, there are legal restrictions on arithmetic coding")
  161039. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161040. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161041. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161042. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161043. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161044. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161045. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161046. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161047. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161048. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161049. JMESSAGE(JERR_BAD_LIB_VERSION,
  161050. "Wrong JPEG library version: library is %d, caller expects %d")
  161051. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161052. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161053. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161054. JMESSAGE(JERR_BAD_PROGRESSION,
  161055. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161056. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161057. "Invalid progressive parameters at scan script entry %d")
  161058. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161059. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161060. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161061. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161062. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161063. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161064. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161065. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161066. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161067. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161068. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161069. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161070. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161071. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161072. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161073. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161074. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161075. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161076. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161077. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161078. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161079. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161080. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161081. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161082. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161083. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161084. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161085. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161086. "Cannot transcode due to multiple use of quantization table %d")
  161087. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161088. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161089. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161090. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161091. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161092. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161093. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161094. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161095. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161096. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161097. JMESSAGE(JERR_QUANT_COMPONENTS,
  161098. "Cannot quantize more than %d color components")
  161099. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161100. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161101. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161102. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161103. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161104. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161105. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161106. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161107. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161108. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161109. JMESSAGE(JERR_TFILE_WRITE,
  161110. "Write failed on temporary file --- out of disk space?")
  161111. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161112. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161113. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161114. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161115. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161116. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161117. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161118. JMESSAGE(JMSG_VERSION, JVERSION)
  161119. JMESSAGE(JTRC_16BIT_TABLES,
  161120. "Caution: quantization tables are too coarse for baseline JPEG")
  161121. JMESSAGE(JTRC_ADOBE,
  161122. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161123. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161124. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161125. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161126. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161127. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161128. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161129. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161130. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161131. JMESSAGE(JTRC_EOI, "End Of Image")
  161132. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161133. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161134. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161135. "Warning: thumbnail image size does not match data length %u")
  161136. JMESSAGE(JTRC_JFIF_EXTENSION,
  161137. "JFIF extension marker: type 0x%02x, length %u")
  161138. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161139. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161140. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161141. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161142. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161143. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161144. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161145. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161146. JMESSAGE(JTRC_RST, "RST%d")
  161147. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161148. "Smoothing not supported with nonstandard sampling ratios")
  161149. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161150. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161151. JMESSAGE(JTRC_SOI, "Start of Image")
  161152. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161153. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161154. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161155. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161156. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161157. JMESSAGE(JTRC_THUMB_JPEG,
  161158. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161159. JMESSAGE(JTRC_THUMB_PALETTE,
  161160. "JFIF extension marker: palette thumbnail image, length %u")
  161161. JMESSAGE(JTRC_THUMB_RGB,
  161162. "JFIF extension marker: RGB thumbnail image, length %u")
  161163. JMESSAGE(JTRC_UNKNOWN_IDS,
  161164. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161165. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161166. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161167. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161168. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161169. "Inconsistent progression sequence for component %d coefficient %d")
  161170. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161171. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161172. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161173. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161174. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161175. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161176. JMESSAGE(JWRN_MUST_RESYNC,
  161177. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161178. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161179. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161180. #ifdef JMAKE_ENUM_LIST
  161181. JMSG_LASTMSGCODE
  161182. } J_MESSAGE_CODE;
  161183. #undef JMAKE_ENUM_LIST
  161184. #endif /* JMAKE_ENUM_LIST */
  161185. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161186. #undef JMESSAGE
  161187. #ifndef JERROR_H
  161188. #define JERROR_H
  161189. /* Macros to simplify using the error and trace message stuff */
  161190. /* The first parameter is either type of cinfo pointer */
  161191. /* Fatal errors (print message and exit) */
  161192. #define ERREXIT(cinfo,code) \
  161193. ((cinfo)->err->msg_code = (code), \
  161194. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161195. #define ERREXIT1(cinfo,code,p1) \
  161196. ((cinfo)->err->msg_code = (code), \
  161197. (cinfo)->err->msg_parm.i[0] = (p1), \
  161198. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161199. #define ERREXIT2(cinfo,code,p1,p2) \
  161200. ((cinfo)->err->msg_code = (code), \
  161201. (cinfo)->err->msg_parm.i[0] = (p1), \
  161202. (cinfo)->err->msg_parm.i[1] = (p2), \
  161203. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161204. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161205. ((cinfo)->err->msg_code = (code), \
  161206. (cinfo)->err->msg_parm.i[0] = (p1), \
  161207. (cinfo)->err->msg_parm.i[1] = (p2), \
  161208. (cinfo)->err->msg_parm.i[2] = (p3), \
  161209. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161210. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161211. ((cinfo)->err->msg_code = (code), \
  161212. (cinfo)->err->msg_parm.i[0] = (p1), \
  161213. (cinfo)->err->msg_parm.i[1] = (p2), \
  161214. (cinfo)->err->msg_parm.i[2] = (p3), \
  161215. (cinfo)->err->msg_parm.i[3] = (p4), \
  161216. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161217. #define ERREXITS(cinfo,code,str) \
  161218. ((cinfo)->err->msg_code = (code), \
  161219. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161220. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161221. #define MAKESTMT(stuff) do { stuff } while (0)
  161222. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161223. #define WARNMS(cinfo,code) \
  161224. ((cinfo)->err->msg_code = (code), \
  161225. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161226. #define WARNMS1(cinfo,code,p1) \
  161227. ((cinfo)->err->msg_code = (code), \
  161228. (cinfo)->err->msg_parm.i[0] = (p1), \
  161229. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161230. #define WARNMS2(cinfo,code,p1,p2) \
  161231. ((cinfo)->err->msg_code = (code), \
  161232. (cinfo)->err->msg_parm.i[0] = (p1), \
  161233. (cinfo)->err->msg_parm.i[1] = (p2), \
  161234. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161235. /* Informational/debugging messages */
  161236. #define TRACEMS(cinfo,lvl,code) \
  161237. ((cinfo)->err->msg_code = (code), \
  161238. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161239. #define TRACEMS1(cinfo,lvl,code,p1) \
  161240. ((cinfo)->err->msg_code = (code), \
  161241. (cinfo)->err->msg_parm.i[0] = (p1), \
  161242. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161243. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161244. ((cinfo)->err->msg_code = (code), \
  161245. (cinfo)->err->msg_parm.i[0] = (p1), \
  161246. (cinfo)->err->msg_parm.i[1] = (p2), \
  161247. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161248. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161249. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161250. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161251. (cinfo)->err->msg_code = (code); \
  161252. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161253. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161254. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161255. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161256. (cinfo)->err->msg_code = (code); \
  161257. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161258. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161259. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161260. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161261. _mp[4] = (p5); \
  161262. (cinfo)->err->msg_code = (code); \
  161263. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161264. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161265. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161266. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161267. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161268. (cinfo)->err->msg_code = (code); \
  161269. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161270. #define TRACEMSS(cinfo,lvl,code,str) \
  161271. ((cinfo)->err->msg_code = (code), \
  161272. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161273. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161274. #endif /* JERROR_H */
  161275. /*** End of inlined file: jerror.h ***/
  161276. /* fetch error codes too */
  161277. #endif
  161278. #endif /* JPEGLIB_H */
  161279. /*** End of inlined file: jpeglib.h ***/
  161280. /*** Start of inlined file: jcapimin.c ***/
  161281. #define JPEG_INTERNALS
  161282. /*** Start of inlined file: jinclude.h ***/
  161283. /* Include auto-config file to find out which system include files we need. */
  161284. #ifndef __jinclude_h__
  161285. #define __jinclude_h__
  161286. /*** Start of inlined file: jconfig.h ***/
  161287. /* see jconfig.doc for explanations */
  161288. // disable all the warnings under MSVC
  161289. #ifdef _MSC_VER
  161290. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161291. #endif
  161292. #ifdef __BORLANDC__
  161293. #pragma warn -8057
  161294. #pragma warn -8019
  161295. #pragma warn -8004
  161296. #pragma warn -8008
  161297. #endif
  161298. #define HAVE_PROTOTYPES
  161299. #define HAVE_UNSIGNED_CHAR
  161300. #define HAVE_UNSIGNED_SHORT
  161301. /* #define void char */
  161302. /* #define const */
  161303. #undef CHAR_IS_UNSIGNED
  161304. #define HAVE_STDDEF_H
  161305. #define HAVE_STDLIB_H
  161306. #undef NEED_BSD_STRINGS
  161307. #undef NEED_SYS_TYPES_H
  161308. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161309. #undef NEED_SHORT_EXTERNAL_NAMES
  161310. #undef INCOMPLETE_TYPES_BROKEN
  161311. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161312. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161313. typedef unsigned char boolean;
  161314. #endif
  161315. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161316. #ifdef JPEG_INTERNALS
  161317. #undef RIGHT_SHIFT_IS_UNSIGNED
  161318. #endif /* JPEG_INTERNALS */
  161319. #ifdef JPEG_CJPEG_DJPEG
  161320. #define BMP_SUPPORTED /* BMP image file format */
  161321. #define GIF_SUPPORTED /* GIF image file format */
  161322. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161323. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161324. #define TARGA_SUPPORTED /* Targa image file format */
  161325. #define TWO_FILE_COMMANDLINE /* optional */
  161326. #define USE_SETMODE /* Microsoft has setmode() */
  161327. #undef NEED_SIGNAL_CATCHER
  161328. #undef DONT_USE_B_MODE
  161329. #undef PROGRESS_REPORT /* optional */
  161330. #endif /* JPEG_CJPEG_DJPEG */
  161331. /*** End of inlined file: jconfig.h ***/
  161332. /* auto configuration options */
  161333. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161334. /*
  161335. * We need the NULL macro and size_t typedef.
  161336. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161337. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161338. * pull in <sys/types.h> as well.
  161339. * Note that the core JPEG library does not require <stdio.h>;
  161340. * only the default error handler and data source/destination modules do.
  161341. * But we must pull it in because of the references to FILE in jpeglib.h.
  161342. * You can remove those references if you want to compile without <stdio.h>.
  161343. */
  161344. #ifdef HAVE_STDDEF_H
  161345. #include <stddef.h>
  161346. #endif
  161347. #ifdef HAVE_STDLIB_H
  161348. #include <stdlib.h>
  161349. #endif
  161350. #ifdef NEED_SYS_TYPES_H
  161351. #include <sys/types.h>
  161352. #endif
  161353. #include <stdio.h>
  161354. /*
  161355. * We need memory copying and zeroing functions, plus strncpy().
  161356. * ANSI and System V implementations declare these in <string.h>.
  161357. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161358. * Some systems may declare memset and memcpy in <memory.h>.
  161359. *
  161360. * NOTE: we assume the size parameters to these functions are of type size_t.
  161361. * Change the casts in these macros if not!
  161362. */
  161363. #ifdef NEED_BSD_STRINGS
  161364. #include <strings.h>
  161365. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161366. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161367. #else /* not BSD, assume ANSI/SysV string lib */
  161368. #include <string.h>
  161369. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161370. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161371. #endif
  161372. /*
  161373. * In ANSI C, and indeed any rational implementation, size_t is also the
  161374. * type returned by sizeof(). However, it seems there are some irrational
  161375. * implementations out there, in which sizeof() returns an int even though
  161376. * size_t is defined as long or unsigned long. To ensure consistent results
  161377. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161378. */
  161379. #define SIZEOF(object) ((size_t) sizeof(object))
  161380. /*
  161381. * The modules that use fread() and fwrite() always invoke them through
  161382. * these macros. On some systems you may need to twiddle the argument casts.
  161383. * CAUTION: argument order is different from underlying functions!
  161384. */
  161385. #define JFREAD(file,buf,sizeofbuf) \
  161386. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161387. #define JFWRITE(file,buf,sizeofbuf) \
  161388. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161389. typedef enum { /* JPEG marker codes */
  161390. M_SOF0 = 0xc0,
  161391. M_SOF1 = 0xc1,
  161392. M_SOF2 = 0xc2,
  161393. M_SOF3 = 0xc3,
  161394. M_SOF5 = 0xc5,
  161395. M_SOF6 = 0xc6,
  161396. M_SOF7 = 0xc7,
  161397. M_JPG = 0xc8,
  161398. M_SOF9 = 0xc9,
  161399. M_SOF10 = 0xca,
  161400. M_SOF11 = 0xcb,
  161401. M_SOF13 = 0xcd,
  161402. M_SOF14 = 0xce,
  161403. M_SOF15 = 0xcf,
  161404. M_DHT = 0xc4,
  161405. M_DAC = 0xcc,
  161406. M_RST0 = 0xd0,
  161407. M_RST1 = 0xd1,
  161408. M_RST2 = 0xd2,
  161409. M_RST3 = 0xd3,
  161410. M_RST4 = 0xd4,
  161411. M_RST5 = 0xd5,
  161412. M_RST6 = 0xd6,
  161413. M_RST7 = 0xd7,
  161414. M_SOI = 0xd8,
  161415. M_EOI = 0xd9,
  161416. M_SOS = 0xda,
  161417. M_DQT = 0xdb,
  161418. M_DNL = 0xdc,
  161419. M_DRI = 0xdd,
  161420. M_DHP = 0xde,
  161421. M_EXP = 0xdf,
  161422. M_APP0 = 0xe0,
  161423. M_APP1 = 0xe1,
  161424. M_APP2 = 0xe2,
  161425. M_APP3 = 0xe3,
  161426. M_APP4 = 0xe4,
  161427. M_APP5 = 0xe5,
  161428. M_APP6 = 0xe6,
  161429. M_APP7 = 0xe7,
  161430. M_APP8 = 0xe8,
  161431. M_APP9 = 0xe9,
  161432. M_APP10 = 0xea,
  161433. M_APP11 = 0xeb,
  161434. M_APP12 = 0xec,
  161435. M_APP13 = 0xed,
  161436. M_APP14 = 0xee,
  161437. M_APP15 = 0xef,
  161438. M_JPG0 = 0xf0,
  161439. M_JPG13 = 0xfd,
  161440. M_COM = 0xfe,
  161441. M_TEM = 0x01,
  161442. M_ERROR = 0x100
  161443. } JPEG_MARKER;
  161444. /*
  161445. * Figure F.12: extend sign bit.
  161446. * On some machines, a shift and add will be faster than a table lookup.
  161447. */
  161448. #ifdef AVOID_TABLES
  161449. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161450. #else
  161451. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161452. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161453. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161454. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161455. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161456. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161457. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161458. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161459. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161460. #endif /* AVOID_TABLES */
  161461. #endif
  161462. /*** End of inlined file: jinclude.h ***/
  161463. /*
  161464. * Initialization of a JPEG compression object.
  161465. * The error manager must already be set up (in case memory manager fails).
  161466. */
  161467. GLOBAL(void)
  161468. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161469. {
  161470. int i;
  161471. /* Guard against version mismatches between library and caller. */
  161472. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161473. if (version != JPEG_LIB_VERSION)
  161474. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161475. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161476. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161477. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161478. /* For debugging purposes, we zero the whole master structure.
  161479. * But the application has already set the err pointer, and may have set
  161480. * client_data, so we have to save and restore those fields.
  161481. * Note: if application hasn't set client_data, tools like Purify may
  161482. * complain here.
  161483. */
  161484. {
  161485. struct jpeg_error_mgr * err = cinfo->err;
  161486. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161487. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161488. cinfo->err = err;
  161489. cinfo->client_data = client_data;
  161490. }
  161491. cinfo->is_decompressor = FALSE;
  161492. /* Initialize a memory manager instance for this object */
  161493. jinit_memory_mgr((j_common_ptr) cinfo);
  161494. /* Zero out pointers to permanent structures. */
  161495. cinfo->progress = NULL;
  161496. cinfo->dest = NULL;
  161497. cinfo->comp_info = NULL;
  161498. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161499. cinfo->quant_tbl_ptrs[i] = NULL;
  161500. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161501. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161502. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161503. }
  161504. cinfo->script_space = NULL;
  161505. cinfo->input_gamma = 1.0; /* in case application forgets */
  161506. /* OK, I'm ready */
  161507. cinfo->global_state = CSTATE_START;
  161508. }
  161509. /*
  161510. * Destruction of a JPEG compression object
  161511. */
  161512. GLOBAL(void)
  161513. jpeg_destroy_compress (j_compress_ptr cinfo)
  161514. {
  161515. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161516. }
  161517. /*
  161518. * Abort processing of a JPEG compression operation,
  161519. * but don't destroy the object itself.
  161520. */
  161521. GLOBAL(void)
  161522. jpeg_abort_compress (j_compress_ptr cinfo)
  161523. {
  161524. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161525. }
  161526. /*
  161527. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161528. * Marks all currently defined tables as already written (if suppress)
  161529. * or not written (if !suppress). This will control whether they get emitted
  161530. * by a subsequent jpeg_start_compress call.
  161531. *
  161532. * This routine is exported for use by applications that want to produce
  161533. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161534. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161535. * jcparam.o would be linked whether the application used it or not.
  161536. */
  161537. GLOBAL(void)
  161538. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161539. {
  161540. int i;
  161541. JQUANT_TBL * qtbl;
  161542. JHUFF_TBL * htbl;
  161543. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161544. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161545. qtbl->sent_table = suppress;
  161546. }
  161547. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161548. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161549. htbl->sent_table = suppress;
  161550. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161551. htbl->sent_table = suppress;
  161552. }
  161553. }
  161554. /*
  161555. * Finish JPEG compression.
  161556. *
  161557. * If a multipass operating mode was selected, this may do a great deal of
  161558. * work including most of the actual output.
  161559. */
  161560. GLOBAL(void)
  161561. jpeg_finish_compress (j_compress_ptr cinfo)
  161562. {
  161563. JDIMENSION iMCU_row;
  161564. if (cinfo->global_state == CSTATE_SCANNING ||
  161565. cinfo->global_state == CSTATE_RAW_OK) {
  161566. /* Terminate first pass */
  161567. if (cinfo->next_scanline < cinfo->image_height)
  161568. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161569. (*cinfo->master->finish_pass) (cinfo);
  161570. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161571. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161572. /* Perform any remaining passes */
  161573. while (! cinfo->master->is_last_pass) {
  161574. (*cinfo->master->prepare_for_pass) (cinfo);
  161575. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161576. if (cinfo->progress != NULL) {
  161577. cinfo->progress->pass_counter = (long) iMCU_row;
  161578. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161579. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161580. }
  161581. /* We bypass the main controller and invoke coef controller directly;
  161582. * all work is being done from the coefficient buffer.
  161583. */
  161584. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161585. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161586. }
  161587. (*cinfo->master->finish_pass) (cinfo);
  161588. }
  161589. /* Write EOI, do final cleanup */
  161590. (*cinfo->marker->write_file_trailer) (cinfo);
  161591. (*cinfo->dest->term_destination) (cinfo);
  161592. /* We can use jpeg_abort to release memory and reset global_state */
  161593. jpeg_abort((j_common_ptr) cinfo);
  161594. }
  161595. /*
  161596. * Write a special marker.
  161597. * This is only recommended for writing COM or APPn markers.
  161598. * Must be called after jpeg_start_compress() and before
  161599. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161600. */
  161601. GLOBAL(void)
  161602. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161603. const JOCTET *dataptr, unsigned int datalen)
  161604. {
  161605. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161606. if (cinfo->next_scanline != 0 ||
  161607. (cinfo->global_state != CSTATE_SCANNING &&
  161608. cinfo->global_state != CSTATE_RAW_OK &&
  161609. cinfo->global_state != CSTATE_WRCOEFS))
  161610. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161611. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161612. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161613. while (datalen--) {
  161614. (*write_marker_byte) (cinfo, *dataptr);
  161615. dataptr++;
  161616. }
  161617. }
  161618. /* Same, but piecemeal. */
  161619. GLOBAL(void)
  161620. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161621. {
  161622. if (cinfo->next_scanline != 0 ||
  161623. (cinfo->global_state != CSTATE_SCANNING &&
  161624. cinfo->global_state != CSTATE_RAW_OK &&
  161625. cinfo->global_state != CSTATE_WRCOEFS))
  161626. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161627. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161628. }
  161629. GLOBAL(void)
  161630. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161631. {
  161632. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161633. }
  161634. /*
  161635. * Alternate compression function: just write an abbreviated table file.
  161636. * Before calling this, all parameters and a data destination must be set up.
  161637. *
  161638. * To produce a pair of files containing abbreviated tables and abbreviated
  161639. * image data, one would proceed as follows:
  161640. *
  161641. * initialize JPEG object
  161642. * set JPEG parameters
  161643. * set destination to table file
  161644. * jpeg_write_tables(cinfo);
  161645. * set destination to image file
  161646. * jpeg_start_compress(cinfo, FALSE);
  161647. * write data...
  161648. * jpeg_finish_compress(cinfo);
  161649. *
  161650. * jpeg_write_tables has the side effect of marking all tables written
  161651. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161652. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161653. */
  161654. GLOBAL(void)
  161655. jpeg_write_tables (j_compress_ptr cinfo)
  161656. {
  161657. if (cinfo->global_state != CSTATE_START)
  161658. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161659. /* (Re)initialize error mgr and destination modules */
  161660. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161661. (*cinfo->dest->init_destination) (cinfo);
  161662. /* Initialize the marker writer ... bit of a crock to do it here. */
  161663. jinit_marker_writer(cinfo);
  161664. /* Write them tables! */
  161665. (*cinfo->marker->write_tables_only) (cinfo);
  161666. /* And clean up. */
  161667. (*cinfo->dest->term_destination) (cinfo);
  161668. /*
  161669. * In library releases up through v6a, we called jpeg_abort() here to free
  161670. * any working memory allocated by the destination manager and marker
  161671. * writer. Some applications had a problem with that: they allocated space
  161672. * of their own from the library memory manager, and didn't want it to go
  161673. * away during write_tables. So now we do nothing. This will cause a
  161674. * memory leak if an app calls write_tables repeatedly without doing a full
  161675. * compression cycle or otherwise resetting the JPEG object. However, that
  161676. * seems less bad than unexpectedly freeing memory in the normal case.
  161677. * An app that prefers the old behavior can call jpeg_abort for itself after
  161678. * each call to jpeg_write_tables().
  161679. */
  161680. }
  161681. /*** End of inlined file: jcapimin.c ***/
  161682. /*** Start of inlined file: jcapistd.c ***/
  161683. #define JPEG_INTERNALS
  161684. /*
  161685. * Compression initialization.
  161686. * Before calling this, all parameters and a data destination must be set up.
  161687. *
  161688. * We require a write_all_tables parameter as a failsafe check when writing
  161689. * multiple datastreams from the same compression object. Since prior runs
  161690. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161691. * would emit an abbreviated stream (no tables) by default. This may be what
  161692. * is wanted, but for safety's sake it should not be the default behavior:
  161693. * programmers should have to make a deliberate choice to emit abbreviated
  161694. * images. Therefore the documentation and examples should encourage people
  161695. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161696. * wrong thing.
  161697. */
  161698. GLOBAL(void)
  161699. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161700. {
  161701. if (cinfo->global_state != CSTATE_START)
  161702. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161703. if (write_all_tables)
  161704. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161705. /* (Re)initialize error mgr and destination modules */
  161706. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161707. (*cinfo->dest->init_destination) (cinfo);
  161708. /* Perform master selection of active modules */
  161709. jinit_compress_master(cinfo);
  161710. /* Set up for the first pass */
  161711. (*cinfo->master->prepare_for_pass) (cinfo);
  161712. /* Ready for application to drive first pass through jpeg_write_scanlines
  161713. * or jpeg_write_raw_data.
  161714. */
  161715. cinfo->next_scanline = 0;
  161716. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161717. }
  161718. /*
  161719. * Write some scanlines of data to the JPEG compressor.
  161720. *
  161721. * The return value will be the number of lines actually written.
  161722. * This should be less than the supplied num_lines only in case that
  161723. * the data destination module has requested suspension of the compressor,
  161724. * or if more than image_height scanlines are passed in.
  161725. *
  161726. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161727. * this likely signals an application programmer error. However,
  161728. * excess scanlines passed in the last valid call are *silently* ignored,
  161729. * so that the application need not adjust num_lines for end-of-image
  161730. * when using a multiple-scanline buffer.
  161731. */
  161732. GLOBAL(JDIMENSION)
  161733. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161734. JDIMENSION num_lines)
  161735. {
  161736. JDIMENSION row_ctr, rows_left;
  161737. if (cinfo->global_state != CSTATE_SCANNING)
  161738. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161739. if (cinfo->next_scanline >= cinfo->image_height)
  161740. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161741. /* Call progress monitor hook if present */
  161742. if (cinfo->progress != NULL) {
  161743. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161744. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161745. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161746. }
  161747. /* Give master control module another chance if this is first call to
  161748. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161749. * delayed so that application can write COM, etc, markers between
  161750. * jpeg_start_compress and jpeg_write_scanlines.
  161751. */
  161752. if (cinfo->master->call_pass_startup)
  161753. (*cinfo->master->pass_startup) (cinfo);
  161754. /* Ignore any extra scanlines at bottom of image. */
  161755. rows_left = cinfo->image_height - cinfo->next_scanline;
  161756. if (num_lines > rows_left)
  161757. num_lines = rows_left;
  161758. row_ctr = 0;
  161759. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161760. cinfo->next_scanline += row_ctr;
  161761. return row_ctr;
  161762. }
  161763. /*
  161764. * Alternate entry point to write raw data.
  161765. * Processes exactly one iMCU row per call, unless suspended.
  161766. */
  161767. GLOBAL(JDIMENSION)
  161768. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161769. JDIMENSION num_lines)
  161770. {
  161771. JDIMENSION lines_per_iMCU_row;
  161772. if (cinfo->global_state != CSTATE_RAW_OK)
  161773. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161774. if (cinfo->next_scanline >= cinfo->image_height) {
  161775. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161776. return 0;
  161777. }
  161778. /* Call progress monitor hook if present */
  161779. if (cinfo->progress != NULL) {
  161780. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161781. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161782. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161783. }
  161784. /* Give master control module another chance if this is first call to
  161785. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161786. * delayed so that application can write COM, etc, markers between
  161787. * jpeg_start_compress and jpeg_write_raw_data.
  161788. */
  161789. if (cinfo->master->call_pass_startup)
  161790. (*cinfo->master->pass_startup) (cinfo);
  161791. /* Verify that at least one iMCU row has been passed. */
  161792. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161793. if (num_lines < lines_per_iMCU_row)
  161794. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161795. /* Directly compress the row. */
  161796. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161797. /* If compressor did not consume the whole row, suspend processing. */
  161798. return 0;
  161799. }
  161800. /* OK, we processed one iMCU row. */
  161801. cinfo->next_scanline += lines_per_iMCU_row;
  161802. return lines_per_iMCU_row;
  161803. }
  161804. /*** End of inlined file: jcapistd.c ***/
  161805. /*** Start of inlined file: jccoefct.c ***/
  161806. #define JPEG_INTERNALS
  161807. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161808. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161809. * step is run during the first pass, and subsequent passes need only read
  161810. * the buffered coefficients.
  161811. */
  161812. #ifdef ENTROPY_OPT_SUPPORTED
  161813. #define FULL_COEF_BUFFER_SUPPORTED
  161814. #else
  161815. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161816. #define FULL_COEF_BUFFER_SUPPORTED
  161817. #endif
  161818. #endif
  161819. /* Private buffer controller object */
  161820. typedef struct {
  161821. struct jpeg_c_coef_controller pub; /* public fields */
  161822. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161823. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161824. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161825. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161826. /* For single-pass compression, it's sufficient to buffer just one MCU
  161827. * (although this may prove a bit slow in practice). We allocate a
  161828. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161829. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161830. * it's not really very big; this is to keep the module interfaces unchanged
  161831. * when a large coefficient buffer is necessary.)
  161832. * In multi-pass modes, this array points to the current MCU's blocks
  161833. * within the virtual arrays.
  161834. */
  161835. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161836. /* In multi-pass modes, we need a virtual block array for each component. */
  161837. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161838. } my_coef_controller;
  161839. typedef my_coef_controller * my_coef_ptr;
  161840. /* Forward declarations */
  161841. METHODDEF(boolean) compress_data
  161842. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161843. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161844. METHODDEF(boolean) compress_first_pass
  161845. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161846. METHODDEF(boolean) compress_output
  161847. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161848. #endif
  161849. LOCAL(void)
  161850. start_iMCU_row (j_compress_ptr cinfo)
  161851. /* Reset within-iMCU-row counters for a new row */
  161852. {
  161853. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161854. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161855. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161856. * But at the bottom of the image, process only what's left.
  161857. */
  161858. if (cinfo->comps_in_scan > 1) {
  161859. coef->MCU_rows_per_iMCU_row = 1;
  161860. } else {
  161861. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161862. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161863. else
  161864. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161865. }
  161866. coef->mcu_ctr = 0;
  161867. coef->MCU_vert_offset = 0;
  161868. }
  161869. /*
  161870. * Initialize for a processing pass.
  161871. */
  161872. METHODDEF(void)
  161873. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161874. {
  161875. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161876. coef->iMCU_row_num = 0;
  161877. start_iMCU_row(cinfo);
  161878. switch (pass_mode) {
  161879. case JBUF_PASS_THRU:
  161880. if (coef->whole_image[0] != NULL)
  161881. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161882. coef->pub.compress_data = compress_data;
  161883. break;
  161884. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161885. case JBUF_SAVE_AND_PASS:
  161886. if (coef->whole_image[0] == NULL)
  161887. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161888. coef->pub.compress_data = compress_first_pass;
  161889. break;
  161890. case JBUF_CRANK_DEST:
  161891. if (coef->whole_image[0] == NULL)
  161892. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161893. coef->pub.compress_data = compress_output;
  161894. break;
  161895. #endif
  161896. default:
  161897. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161898. break;
  161899. }
  161900. }
  161901. /*
  161902. * Process some data in the single-pass case.
  161903. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161904. * per call, ie, v_samp_factor block rows for each component in the image.
  161905. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161906. *
  161907. * NB: input_buf contains a plane for each component in image,
  161908. * which we index according to the component's SOF position.
  161909. */
  161910. METHODDEF(boolean)
  161911. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161912. {
  161913. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161914. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161915. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161916. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161917. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161918. JDIMENSION ypos, xpos;
  161919. jpeg_component_info *compptr;
  161920. /* Loop to write as much as one whole iMCU row */
  161921. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161922. yoffset++) {
  161923. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161924. MCU_col_num++) {
  161925. /* Determine where data comes from in input_buf and do the DCT thing.
  161926. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161927. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161928. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161929. * specially. The data in them does not matter for image reconstruction,
  161930. * so we fill them with values that will encode to the smallest amount of
  161931. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161932. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161933. */
  161934. blkn = 0;
  161935. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161936. compptr = cinfo->cur_comp_info[ci];
  161937. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161938. : compptr->last_col_width;
  161939. xpos = MCU_col_num * compptr->MCU_sample_width;
  161940. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161941. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161942. if (coef->iMCU_row_num < last_iMCU_row ||
  161943. yoffset+yindex < compptr->last_row_height) {
  161944. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161945. input_buf[compptr->component_index],
  161946. coef->MCU_buffer[blkn],
  161947. ypos, xpos, (JDIMENSION) blockcnt);
  161948. if (blockcnt < compptr->MCU_width) {
  161949. /* Create some dummy blocks at the right edge of the image. */
  161950. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161951. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161952. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161953. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161954. }
  161955. }
  161956. } else {
  161957. /* Create a row of dummy blocks at the bottom of the image. */
  161958. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161959. compptr->MCU_width * SIZEOF(JBLOCK));
  161960. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161961. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161962. }
  161963. }
  161964. blkn += compptr->MCU_width;
  161965. ypos += DCTSIZE;
  161966. }
  161967. }
  161968. /* Try to write the MCU. In event of a suspension failure, we will
  161969. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161970. */
  161971. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161972. /* Suspension forced; update state counters and exit */
  161973. coef->MCU_vert_offset = yoffset;
  161974. coef->mcu_ctr = MCU_col_num;
  161975. return FALSE;
  161976. }
  161977. }
  161978. /* Completed an MCU row, but perhaps not an iMCU row */
  161979. coef->mcu_ctr = 0;
  161980. }
  161981. /* Completed the iMCU row, advance counters for next one */
  161982. coef->iMCU_row_num++;
  161983. start_iMCU_row(cinfo);
  161984. return TRUE;
  161985. }
  161986. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161987. /*
  161988. * Process some data in the first pass of a multi-pass case.
  161989. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161990. * per call, ie, v_samp_factor block rows for each component in the image.
  161991. * This amount of data is read from the source buffer, DCT'd and quantized,
  161992. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161993. * as needed at the right and lower edges. (The dummy blocks are constructed
  161994. * in the virtual arrays, which have been padded appropriately.) This makes
  161995. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161996. *
  161997. * We must also emit the data to the entropy encoder. This is conveniently
  161998. * done by calling compress_output() after we've loaded the current strip
  161999. * of the virtual arrays.
  162000. *
  162001. * NB: input_buf contains a plane for each component in image. All
  162002. * components are DCT'd and loaded into the virtual arrays in this pass.
  162003. * However, it may be that only a subset of the components are emitted to
  162004. * the entropy encoder during this first pass; be careful about looking
  162005. * at the scan-dependent variables (MCU dimensions, etc).
  162006. */
  162007. METHODDEF(boolean)
  162008. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162009. {
  162010. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162011. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162012. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162013. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162014. JCOEF lastDC;
  162015. jpeg_component_info *compptr;
  162016. JBLOCKARRAY buffer;
  162017. JBLOCKROW thisblockrow, lastblockrow;
  162018. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162019. ci++, compptr++) {
  162020. /* Align the virtual buffer for this component. */
  162021. buffer = (*cinfo->mem->access_virt_barray)
  162022. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162023. coef->iMCU_row_num * compptr->v_samp_factor,
  162024. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162025. /* Count non-dummy DCT block rows in this iMCU row. */
  162026. if (coef->iMCU_row_num < last_iMCU_row)
  162027. block_rows = compptr->v_samp_factor;
  162028. else {
  162029. /* NB: can't use last_row_height here, since may not be set! */
  162030. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162031. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162032. }
  162033. blocks_across = compptr->width_in_blocks;
  162034. h_samp_factor = compptr->h_samp_factor;
  162035. /* Count number of dummy blocks to be added at the right margin. */
  162036. ndummy = (int) (blocks_across % h_samp_factor);
  162037. if (ndummy > 0)
  162038. ndummy = h_samp_factor - ndummy;
  162039. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162040. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162041. */
  162042. for (block_row = 0; block_row < block_rows; block_row++) {
  162043. thisblockrow = buffer[block_row];
  162044. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162045. input_buf[ci], thisblockrow,
  162046. (JDIMENSION) (block_row * DCTSIZE),
  162047. (JDIMENSION) 0, blocks_across);
  162048. if (ndummy > 0) {
  162049. /* Create dummy blocks at the right edge of the image. */
  162050. thisblockrow += blocks_across; /* => first dummy block */
  162051. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162052. lastDC = thisblockrow[-1][0];
  162053. for (bi = 0; bi < ndummy; bi++) {
  162054. thisblockrow[bi][0] = lastDC;
  162055. }
  162056. }
  162057. }
  162058. /* If at end of image, create dummy block rows as needed.
  162059. * The tricky part here is that within each MCU, we want the DC values
  162060. * of the dummy blocks to match the last real block's DC value.
  162061. * This squeezes a few more bytes out of the resulting file...
  162062. */
  162063. if (coef->iMCU_row_num == last_iMCU_row) {
  162064. blocks_across += ndummy; /* include lower right corner */
  162065. MCUs_across = blocks_across / h_samp_factor;
  162066. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162067. block_row++) {
  162068. thisblockrow = buffer[block_row];
  162069. lastblockrow = buffer[block_row-1];
  162070. jzero_far((void FAR *) thisblockrow,
  162071. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162072. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162073. lastDC = lastblockrow[h_samp_factor-1][0];
  162074. for (bi = 0; bi < h_samp_factor; bi++) {
  162075. thisblockrow[bi][0] = lastDC;
  162076. }
  162077. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162078. lastblockrow += h_samp_factor;
  162079. }
  162080. }
  162081. }
  162082. }
  162083. /* NB: compress_output will increment iMCU_row_num if successful.
  162084. * A suspension return will result in redoing all the work above next time.
  162085. */
  162086. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162087. return compress_output(cinfo, input_buf);
  162088. }
  162089. /*
  162090. * Process some data in subsequent passes of a multi-pass case.
  162091. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162092. * per call, ie, v_samp_factor block rows for each component in the scan.
  162093. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162094. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162095. *
  162096. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162097. */
  162098. METHODDEF(boolean)
  162099. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162100. {
  162101. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162102. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162103. int blkn, ci, xindex, yindex, yoffset;
  162104. JDIMENSION start_col;
  162105. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162106. JBLOCKROW buffer_ptr;
  162107. jpeg_component_info *compptr;
  162108. /* Align the virtual buffers for the components used in this scan.
  162109. * NB: during first pass, this is safe only because the buffers will
  162110. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162111. */
  162112. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162113. compptr = cinfo->cur_comp_info[ci];
  162114. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162115. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162116. coef->iMCU_row_num * compptr->v_samp_factor,
  162117. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162118. }
  162119. /* Loop to process one whole iMCU row */
  162120. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162121. yoffset++) {
  162122. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162123. MCU_col_num++) {
  162124. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162125. blkn = 0; /* index of current DCT block within MCU */
  162126. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162127. compptr = cinfo->cur_comp_info[ci];
  162128. start_col = MCU_col_num * compptr->MCU_width;
  162129. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162130. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162131. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162132. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162133. }
  162134. }
  162135. }
  162136. /* Try to write the MCU. */
  162137. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162138. /* Suspension forced; update state counters and exit */
  162139. coef->MCU_vert_offset = yoffset;
  162140. coef->mcu_ctr = MCU_col_num;
  162141. return FALSE;
  162142. }
  162143. }
  162144. /* Completed an MCU row, but perhaps not an iMCU row */
  162145. coef->mcu_ctr = 0;
  162146. }
  162147. /* Completed the iMCU row, advance counters for next one */
  162148. coef->iMCU_row_num++;
  162149. start_iMCU_row(cinfo);
  162150. return TRUE;
  162151. }
  162152. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162153. /*
  162154. * Initialize coefficient buffer controller.
  162155. */
  162156. GLOBAL(void)
  162157. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162158. {
  162159. my_coef_ptr coef;
  162160. coef = (my_coef_ptr)
  162161. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162162. SIZEOF(my_coef_controller));
  162163. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162164. coef->pub.start_pass = start_pass_coef;
  162165. /* Create the coefficient buffer. */
  162166. if (need_full_buffer) {
  162167. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162168. /* Allocate a full-image virtual array for each component, */
  162169. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162170. int ci;
  162171. jpeg_component_info *compptr;
  162172. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162173. ci++, compptr++) {
  162174. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162175. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162176. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162177. (long) compptr->h_samp_factor),
  162178. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162179. (long) compptr->v_samp_factor),
  162180. (JDIMENSION) compptr->v_samp_factor);
  162181. }
  162182. #else
  162183. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162184. #endif
  162185. } else {
  162186. /* We only need a single-MCU buffer. */
  162187. JBLOCKROW buffer;
  162188. int i;
  162189. buffer = (JBLOCKROW)
  162190. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162191. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162192. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162193. coef->MCU_buffer[i] = buffer + i;
  162194. }
  162195. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162196. }
  162197. }
  162198. /*** End of inlined file: jccoefct.c ***/
  162199. /*** Start of inlined file: jccolor.c ***/
  162200. #define JPEG_INTERNALS
  162201. /* Private subobject */
  162202. typedef struct {
  162203. struct jpeg_color_converter pub; /* public fields */
  162204. /* Private state for RGB->YCC conversion */
  162205. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162206. } my_color_converter;
  162207. typedef my_color_converter * my_cconvert_ptr;
  162208. /**************** RGB -> YCbCr conversion: most common case **************/
  162209. /*
  162210. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162211. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162212. * The conversion equations to be implemented are therefore
  162213. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162214. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162215. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162216. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162217. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162218. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162219. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162220. * were not represented exactly. Now we sacrifice exact representation of
  162221. * maximum red and maximum blue in order to get exact grayscales.
  162222. *
  162223. * To avoid floating-point arithmetic, we represent the fractional constants
  162224. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162225. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162226. *
  162227. * For even more speed, we avoid doing any multiplications in the inner loop
  162228. * by precalculating the constants times R,G,B for all possible values.
  162229. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162230. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162231. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162232. * colorspace anyway.
  162233. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162234. * in the tables to save adding them separately in the inner loop.
  162235. */
  162236. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162237. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162238. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162239. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162240. /* We allocate one big table and divide it up into eight parts, instead of
  162241. * doing eight alloc_small requests. This lets us use a single table base
  162242. * address, which can be held in a register in the inner loops on many
  162243. * machines (more than can hold all eight addresses, anyway).
  162244. */
  162245. #define R_Y_OFF 0 /* offset to R => Y section */
  162246. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162247. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162248. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162249. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162250. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162251. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162252. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162253. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162254. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162255. /*
  162256. * Initialize for RGB->YCC colorspace conversion.
  162257. */
  162258. METHODDEF(void)
  162259. rgb_ycc_start (j_compress_ptr cinfo)
  162260. {
  162261. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162262. INT32 * rgb_ycc_tab;
  162263. INT32 i;
  162264. /* Allocate and fill in the conversion tables. */
  162265. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162266. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162267. (TABLE_SIZE * SIZEOF(INT32)));
  162268. for (i = 0; i <= MAXJSAMPLE; i++) {
  162269. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162270. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162271. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162272. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162273. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162274. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162275. * This ensures that the maximum output will round to MAXJSAMPLE
  162276. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162277. */
  162278. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162279. /* B=>Cb and R=>Cr tables are the same
  162280. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162281. */
  162282. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162283. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162284. }
  162285. }
  162286. /*
  162287. * Convert some rows of samples to the JPEG colorspace.
  162288. *
  162289. * Note that we change from the application's interleaved-pixel format
  162290. * to our internal noninterleaved, one-plane-per-component format.
  162291. * The input buffer is therefore three times as wide as the output buffer.
  162292. *
  162293. * A starting row offset is provided only for the output buffer. The caller
  162294. * can easily adjust the passed input_buf value to accommodate any row
  162295. * offset required on that side.
  162296. */
  162297. METHODDEF(void)
  162298. rgb_ycc_convert (j_compress_ptr cinfo,
  162299. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162300. JDIMENSION output_row, int num_rows)
  162301. {
  162302. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162303. register int r, g, b;
  162304. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162305. register JSAMPROW inptr;
  162306. register JSAMPROW outptr0, outptr1, outptr2;
  162307. register JDIMENSION col;
  162308. JDIMENSION num_cols = cinfo->image_width;
  162309. while (--num_rows >= 0) {
  162310. inptr = *input_buf++;
  162311. outptr0 = output_buf[0][output_row];
  162312. outptr1 = output_buf[1][output_row];
  162313. outptr2 = output_buf[2][output_row];
  162314. output_row++;
  162315. for (col = 0; col < num_cols; col++) {
  162316. r = GETJSAMPLE(inptr[RGB_RED]);
  162317. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162318. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162319. inptr += RGB_PIXELSIZE;
  162320. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162321. * must be too; we do not need an explicit range-limiting operation.
  162322. * Hence the value being shifted is never negative, and we don't
  162323. * need the general RIGHT_SHIFT macro.
  162324. */
  162325. /* Y */
  162326. outptr0[col] = (JSAMPLE)
  162327. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162328. >> SCALEBITS);
  162329. /* Cb */
  162330. outptr1[col] = (JSAMPLE)
  162331. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162332. >> SCALEBITS);
  162333. /* Cr */
  162334. outptr2[col] = (JSAMPLE)
  162335. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162336. >> SCALEBITS);
  162337. }
  162338. }
  162339. }
  162340. /**************** Cases other than RGB -> YCbCr **************/
  162341. /*
  162342. * Convert some rows of samples to the JPEG colorspace.
  162343. * This version handles RGB->grayscale conversion, which is the same
  162344. * as the RGB->Y portion of RGB->YCbCr.
  162345. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162346. */
  162347. METHODDEF(void)
  162348. rgb_gray_convert (j_compress_ptr cinfo,
  162349. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162350. JDIMENSION output_row, int num_rows)
  162351. {
  162352. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162353. register int r, g, b;
  162354. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162355. register JSAMPROW inptr;
  162356. register JSAMPROW outptr;
  162357. register JDIMENSION col;
  162358. JDIMENSION num_cols = cinfo->image_width;
  162359. while (--num_rows >= 0) {
  162360. inptr = *input_buf++;
  162361. outptr = output_buf[0][output_row];
  162362. output_row++;
  162363. for (col = 0; col < num_cols; col++) {
  162364. r = GETJSAMPLE(inptr[RGB_RED]);
  162365. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162366. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162367. inptr += RGB_PIXELSIZE;
  162368. /* Y */
  162369. outptr[col] = (JSAMPLE)
  162370. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162371. >> SCALEBITS);
  162372. }
  162373. }
  162374. }
  162375. /*
  162376. * Convert some rows of samples to the JPEG colorspace.
  162377. * This version handles Adobe-style CMYK->YCCK conversion,
  162378. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162379. * conversion as above, while passing K (black) unchanged.
  162380. * We assume rgb_ycc_start has been called.
  162381. */
  162382. METHODDEF(void)
  162383. cmyk_ycck_convert (j_compress_ptr cinfo,
  162384. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162385. JDIMENSION output_row, int num_rows)
  162386. {
  162387. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162388. register int r, g, b;
  162389. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162390. register JSAMPROW inptr;
  162391. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162392. register JDIMENSION col;
  162393. JDIMENSION num_cols = cinfo->image_width;
  162394. while (--num_rows >= 0) {
  162395. inptr = *input_buf++;
  162396. outptr0 = output_buf[0][output_row];
  162397. outptr1 = output_buf[1][output_row];
  162398. outptr2 = output_buf[2][output_row];
  162399. outptr3 = output_buf[3][output_row];
  162400. output_row++;
  162401. for (col = 0; col < num_cols; col++) {
  162402. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162403. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162404. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162405. /* K passes through as-is */
  162406. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162407. inptr += 4;
  162408. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162409. * must be too; we do not need an explicit range-limiting operation.
  162410. * Hence the value being shifted is never negative, and we don't
  162411. * need the general RIGHT_SHIFT macro.
  162412. */
  162413. /* Y */
  162414. outptr0[col] = (JSAMPLE)
  162415. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162416. >> SCALEBITS);
  162417. /* Cb */
  162418. outptr1[col] = (JSAMPLE)
  162419. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162420. >> SCALEBITS);
  162421. /* Cr */
  162422. outptr2[col] = (JSAMPLE)
  162423. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162424. >> SCALEBITS);
  162425. }
  162426. }
  162427. }
  162428. /*
  162429. * Convert some rows of samples to the JPEG colorspace.
  162430. * This version handles grayscale output with no conversion.
  162431. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162432. */
  162433. METHODDEF(void)
  162434. grayscale_convert (j_compress_ptr cinfo,
  162435. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162436. JDIMENSION output_row, int num_rows)
  162437. {
  162438. register JSAMPROW inptr;
  162439. register JSAMPROW outptr;
  162440. register JDIMENSION col;
  162441. JDIMENSION num_cols = cinfo->image_width;
  162442. int instride = cinfo->input_components;
  162443. while (--num_rows >= 0) {
  162444. inptr = *input_buf++;
  162445. outptr = output_buf[0][output_row];
  162446. output_row++;
  162447. for (col = 0; col < num_cols; col++) {
  162448. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162449. inptr += instride;
  162450. }
  162451. }
  162452. }
  162453. /*
  162454. * Convert some rows of samples to the JPEG colorspace.
  162455. * This version handles multi-component colorspaces without conversion.
  162456. * We assume input_components == num_components.
  162457. */
  162458. METHODDEF(void)
  162459. null_convert (j_compress_ptr cinfo,
  162460. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162461. JDIMENSION output_row, int num_rows)
  162462. {
  162463. register JSAMPROW inptr;
  162464. register JSAMPROW outptr;
  162465. register JDIMENSION col;
  162466. register int ci;
  162467. int nc = cinfo->num_components;
  162468. JDIMENSION num_cols = cinfo->image_width;
  162469. while (--num_rows >= 0) {
  162470. /* It seems fastest to make a separate pass for each component. */
  162471. for (ci = 0; ci < nc; ci++) {
  162472. inptr = *input_buf;
  162473. outptr = output_buf[ci][output_row];
  162474. for (col = 0; col < num_cols; col++) {
  162475. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162476. inptr += nc;
  162477. }
  162478. }
  162479. input_buf++;
  162480. output_row++;
  162481. }
  162482. }
  162483. /*
  162484. * Empty method for start_pass.
  162485. */
  162486. METHODDEF(void)
  162487. null_method (j_compress_ptr)
  162488. {
  162489. /* no work needed */
  162490. }
  162491. /*
  162492. * Module initialization routine for input colorspace conversion.
  162493. */
  162494. GLOBAL(void)
  162495. jinit_color_converter (j_compress_ptr cinfo)
  162496. {
  162497. my_cconvert_ptr cconvert;
  162498. cconvert = (my_cconvert_ptr)
  162499. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162500. SIZEOF(my_color_converter));
  162501. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162502. /* set start_pass to null method until we find out differently */
  162503. cconvert->pub.start_pass = null_method;
  162504. /* Make sure input_components agrees with in_color_space */
  162505. switch (cinfo->in_color_space) {
  162506. case JCS_GRAYSCALE:
  162507. if (cinfo->input_components != 1)
  162508. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162509. break;
  162510. case JCS_RGB:
  162511. #if RGB_PIXELSIZE != 3
  162512. if (cinfo->input_components != RGB_PIXELSIZE)
  162513. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162514. break;
  162515. #endif /* else share code with YCbCr */
  162516. case JCS_YCbCr:
  162517. if (cinfo->input_components != 3)
  162518. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162519. break;
  162520. case JCS_CMYK:
  162521. case JCS_YCCK:
  162522. if (cinfo->input_components != 4)
  162523. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162524. break;
  162525. default: /* JCS_UNKNOWN can be anything */
  162526. if (cinfo->input_components < 1)
  162527. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162528. break;
  162529. }
  162530. /* Check num_components, set conversion method based on requested space */
  162531. switch (cinfo->jpeg_color_space) {
  162532. case JCS_GRAYSCALE:
  162533. if (cinfo->num_components != 1)
  162534. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162535. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162536. cconvert->pub.color_convert = grayscale_convert;
  162537. else if (cinfo->in_color_space == JCS_RGB) {
  162538. cconvert->pub.start_pass = rgb_ycc_start;
  162539. cconvert->pub.color_convert = rgb_gray_convert;
  162540. } else if (cinfo->in_color_space == JCS_YCbCr)
  162541. cconvert->pub.color_convert = grayscale_convert;
  162542. else
  162543. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162544. break;
  162545. case JCS_RGB:
  162546. if (cinfo->num_components != 3)
  162547. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162548. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162549. cconvert->pub.color_convert = null_convert;
  162550. else
  162551. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162552. break;
  162553. case JCS_YCbCr:
  162554. if (cinfo->num_components != 3)
  162555. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162556. if (cinfo->in_color_space == JCS_RGB) {
  162557. cconvert->pub.start_pass = rgb_ycc_start;
  162558. cconvert->pub.color_convert = rgb_ycc_convert;
  162559. } else if (cinfo->in_color_space == JCS_YCbCr)
  162560. cconvert->pub.color_convert = null_convert;
  162561. else
  162562. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162563. break;
  162564. case JCS_CMYK:
  162565. if (cinfo->num_components != 4)
  162566. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162567. if (cinfo->in_color_space == JCS_CMYK)
  162568. cconvert->pub.color_convert = null_convert;
  162569. else
  162570. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162571. break;
  162572. case JCS_YCCK:
  162573. if (cinfo->num_components != 4)
  162574. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162575. if (cinfo->in_color_space == JCS_CMYK) {
  162576. cconvert->pub.start_pass = rgb_ycc_start;
  162577. cconvert->pub.color_convert = cmyk_ycck_convert;
  162578. } else if (cinfo->in_color_space == JCS_YCCK)
  162579. cconvert->pub.color_convert = null_convert;
  162580. else
  162581. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162582. break;
  162583. default: /* allow null conversion of JCS_UNKNOWN */
  162584. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162585. cinfo->num_components != cinfo->input_components)
  162586. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162587. cconvert->pub.color_convert = null_convert;
  162588. break;
  162589. }
  162590. }
  162591. /*** End of inlined file: jccolor.c ***/
  162592. #undef FIX
  162593. /*** Start of inlined file: jcdctmgr.c ***/
  162594. #define JPEG_INTERNALS
  162595. /*** Start of inlined file: jdct.h ***/
  162596. /*
  162597. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162598. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162599. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162600. * implementations use an array of type FAST_FLOAT, instead.)
  162601. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162602. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162603. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162604. * convention improves accuracy in integer implementations and saves some
  162605. * work in floating-point ones.
  162606. * Quantization of the output coefficients is done by jcdctmgr.c.
  162607. */
  162608. #ifndef __jdct_h__
  162609. #define __jdct_h__
  162610. #if BITS_IN_JSAMPLE == 8
  162611. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162612. #else
  162613. typedef INT32 DCTELEM; /* must have 32 bits */
  162614. #endif
  162615. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162616. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162617. /*
  162618. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162619. * to an output sample array. The routine must dequantize the input data as
  162620. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162621. * pointed to by compptr->dct_table. The output data is to be placed into the
  162622. * sample array starting at a specified column. (Any row offset needed will
  162623. * be applied to the array pointer before it is passed to the IDCT code.)
  162624. * Note that the number of samples emitted by the IDCT routine is
  162625. * DCT_scaled_size * DCT_scaled_size.
  162626. */
  162627. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162628. /*
  162629. * Each IDCT routine has its own ideas about the best dct_table element type.
  162630. */
  162631. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162632. #if BITS_IN_JSAMPLE == 8
  162633. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162634. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162635. #else
  162636. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162637. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162638. #endif
  162639. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162640. /*
  162641. * Each IDCT routine is responsible for range-limiting its results and
  162642. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162643. * be quite far out of range if the input data is corrupt, so a bulletproof
  162644. * range-limiting step is required. We use a mask-and-table-lookup method
  162645. * to do the combined operations quickly. See the comments with
  162646. * prepare_range_limit_table (in jdmaster.c) for more info.
  162647. */
  162648. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162649. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162650. /* Short forms of external names for systems with brain-damaged linkers. */
  162651. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162652. #define jpeg_fdct_islow jFDislow
  162653. #define jpeg_fdct_ifast jFDifast
  162654. #define jpeg_fdct_float jFDfloat
  162655. #define jpeg_idct_islow jRDislow
  162656. #define jpeg_idct_ifast jRDifast
  162657. #define jpeg_idct_float jRDfloat
  162658. #define jpeg_idct_4x4 jRD4x4
  162659. #define jpeg_idct_2x2 jRD2x2
  162660. #define jpeg_idct_1x1 jRD1x1
  162661. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162662. /* Extern declarations for the forward and inverse DCT routines. */
  162663. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162664. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162665. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162666. EXTERN(void) jpeg_idct_islow
  162667. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162668. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162669. EXTERN(void) jpeg_idct_ifast
  162670. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162671. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162672. EXTERN(void) jpeg_idct_float
  162673. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162674. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162675. EXTERN(void) jpeg_idct_4x4
  162676. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162677. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162678. EXTERN(void) jpeg_idct_2x2
  162679. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162680. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162681. EXTERN(void) jpeg_idct_1x1
  162682. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162683. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162684. /*
  162685. * Macros for handling fixed-point arithmetic; these are used by many
  162686. * but not all of the DCT/IDCT modules.
  162687. *
  162688. * All values are expected to be of type INT32.
  162689. * Fractional constants are scaled left by CONST_BITS bits.
  162690. * CONST_BITS is defined within each module using these macros,
  162691. * and may differ from one module to the next.
  162692. */
  162693. #define ONE ((INT32) 1)
  162694. #define CONST_SCALE (ONE << CONST_BITS)
  162695. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162696. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162697. * thus causing a lot of useless floating-point operations at run time.
  162698. */
  162699. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162700. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162701. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162702. * the fudge factor is correct for either sign of X.
  162703. */
  162704. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162705. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162706. * This macro is used only when the two inputs will actually be no more than
  162707. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162708. * full 32x32 multiply. This provides a useful speedup on many machines.
  162709. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162710. * in C, but some C compilers will do the right thing if you provide the
  162711. * correct combination of casts.
  162712. */
  162713. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162714. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162715. #endif
  162716. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162717. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162718. #endif
  162719. #ifndef MULTIPLY16C16 /* default definition */
  162720. #define MULTIPLY16C16(var,const) ((var) * (const))
  162721. #endif
  162722. /* Same except both inputs are variables. */
  162723. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162724. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162725. #endif
  162726. #ifndef MULTIPLY16V16 /* default definition */
  162727. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162728. #endif
  162729. #endif
  162730. /*** End of inlined file: jdct.h ***/
  162731. /* Private declarations for DCT subsystem */
  162732. /* Private subobject for this module */
  162733. typedef struct {
  162734. struct jpeg_forward_dct pub; /* public fields */
  162735. /* Pointer to the DCT routine actually in use */
  162736. forward_DCT_method_ptr do_dct;
  162737. /* The actual post-DCT divisors --- not identical to the quant table
  162738. * entries, because of scaling (especially for an unnormalized DCT).
  162739. * Each table is given in normal array order.
  162740. */
  162741. DCTELEM * divisors[NUM_QUANT_TBLS];
  162742. #ifdef DCT_FLOAT_SUPPORTED
  162743. /* Same as above for the floating-point case. */
  162744. float_DCT_method_ptr do_float_dct;
  162745. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162746. #endif
  162747. } my_fdct_controller;
  162748. typedef my_fdct_controller * my_fdct_ptr;
  162749. /*
  162750. * Initialize for a processing pass.
  162751. * Verify that all referenced Q-tables are present, and set up
  162752. * the divisor table for each one.
  162753. * In the current implementation, DCT of all components is done during
  162754. * the first pass, even if only some components will be output in the
  162755. * first scan. Hence all components should be examined here.
  162756. */
  162757. METHODDEF(void)
  162758. start_pass_fdctmgr (j_compress_ptr cinfo)
  162759. {
  162760. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162761. int ci, qtblno, i;
  162762. jpeg_component_info *compptr;
  162763. JQUANT_TBL * qtbl;
  162764. DCTELEM * dtbl;
  162765. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162766. ci++, compptr++) {
  162767. qtblno = compptr->quant_tbl_no;
  162768. /* Make sure specified quantization table is present */
  162769. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162770. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162771. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162772. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162773. /* Compute divisors for this quant table */
  162774. /* We may do this more than once for same table, but it's not a big deal */
  162775. switch (cinfo->dct_method) {
  162776. #ifdef DCT_ISLOW_SUPPORTED
  162777. case JDCT_ISLOW:
  162778. /* For LL&M IDCT method, divisors are equal to raw quantization
  162779. * coefficients multiplied by 8 (to counteract scaling).
  162780. */
  162781. if (fdct->divisors[qtblno] == NULL) {
  162782. fdct->divisors[qtblno] = (DCTELEM *)
  162783. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162784. DCTSIZE2 * SIZEOF(DCTELEM));
  162785. }
  162786. dtbl = fdct->divisors[qtblno];
  162787. for (i = 0; i < DCTSIZE2; i++) {
  162788. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162789. }
  162790. break;
  162791. #endif
  162792. #ifdef DCT_IFAST_SUPPORTED
  162793. case JDCT_IFAST:
  162794. {
  162795. /* For AA&N IDCT method, divisors are equal to quantization
  162796. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162797. * scalefactor[0] = 1
  162798. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162799. * We apply a further scale factor of 8.
  162800. */
  162801. #define CONST_BITS 14
  162802. static const INT16 aanscales[DCTSIZE2] = {
  162803. /* precomputed values scaled up by 14 bits */
  162804. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162805. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162806. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162807. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162808. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162809. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162810. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162811. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162812. };
  162813. SHIFT_TEMPS
  162814. if (fdct->divisors[qtblno] == NULL) {
  162815. fdct->divisors[qtblno] = (DCTELEM *)
  162816. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162817. DCTSIZE2 * SIZEOF(DCTELEM));
  162818. }
  162819. dtbl = fdct->divisors[qtblno];
  162820. for (i = 0; i < DCTSIZE2; i++) {
  162821. dtbl[i] = (DCTELEM)
  162822. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162823. (INT32) aanscales[i]),
  162824. CONST_BITS-3);
  162825. }
  162826. }
  162827. break;
  162828. #endif
  162829. #ifdef DCT_FLOAT_SUPPORTED
  162830. case JDCT_FLOAT:
  162831. {
  162832. /* For float AA&N IDCT method, divisors are equal to quantization
  162833. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162834. * scalefactor[0] = 1
  162835. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162836. * We apply a further scale factor of 8.
  162837. * What's actually stored is 1/divisor so that the inner loop can
  162838. * use a multiplication rather than a division.
  162839. */
  162840. FAST_FLOAT * fdtbl;
  162841. int row, col;
  162842. static const double aanscalefactor[DCTSIZE] = {
  162843. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162844. 1.0, 0.785694958, 0.541196100, 0.275899379
  162845. };
  162846. if (fdct->float_divisors[qtblno] == NULL) {
  162847. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162848. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162849. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162850. }
  162851. fdtbl = fdct->float_divisors[qtblno];
  162852. i = 0;
  162853. for (row = 0; row < DCTSIZE; row++) {
  162854. for (col = 0; col < DCTSIZE; col++) {
  162855. fdtbl[i] = (FAST_FLOAT)
  162856. (1.0 / (((double) qtbl->quantval[i] *
  162857. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162858. i++;
  162859. }
  162860. }
  162861. }
  162862. break;
  162863. #endif
  162864. default:
  162865. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162866. break;
  162867. }
  162868. }
  162869. }
  162870. /*
  162871. * Perform forward DCT on one or more blocks of a component.
  162872. *
  162873. * The input samples are taken from the sample_data[] array starting at
  162874. * position start_row/start_col, and moving to the right for any additional
  162875. * blocks. The quantized coefficients are returned in coef_blocks[].
  162876. */
  162877. METHODDEF(void)
  162878. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162879. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162880. JDIMENSION start_row, JDIMENSION start_col,
  162881. JDIMENSION num_blocks)
  162882. /* This version is used for integer DCT implementations. */
  162883. {
  162884. /* This routine is heavily used, so it's worth coding it tightly. */
  162885. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162886. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162887. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162888. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162889. JDIMENSION bi;
  162890. sample_data += start_row; /* fold in the vertical offset once */
  162891. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162892. /* Load data into workspace, applying unsigned->signed conversion */
  162893. { register DCTELEM *workspaceptr;
  162894. register JSAMPROW elemptr;
  162895. register int elemr;
  162896. workspaceptr = workspace;
  162897. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162898. elemptr = sample_data[elemr] + start_col;
  162899. #if DCTSIZE == 8 /* unroll the inner loop */
  162900. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162901. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162902. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162903. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162904. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162905. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162906. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162907. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162908. #else
  162909. { register int elemc;
  162910. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162911. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162912. }
  162913. }
  162914. #endif
  162915. }
  162916. }
  162917. /* Perform the DCT */
  162918. (*do_dct) (workspace);
  162919. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162920. { register DCTELEM temp, qval;
  162921. register int i;
  162922. register JCOEFPTR output_ptr = coef_blocks[bi];
  162923. for (i = 0; i < DCTSIZE2; i++) {
  162924. qval = divisors[i];
  162925. temp = workspace[i];
  162926. /* Divide the coefficient value by qval, ensuring proper rounding.
  162927. * Since C does not specify the direction of rounding for negative
  162928. * quotients, we have to force the dividend positive for portability.
  162929. *
  162930. * In most files, at least half of the output values will be zero
  162931. * (at default quantization settings, more like three-quarters...)
  162932. * so we should ensure that this case is fast. On many machines,
  162933. * a comparison is enough cheaper than a divide to make a special test
  162934. * a win. Since both inputs will be nonnegative, we need only test
  162935. * for a < b to discover whether a/b is 0.
  162936. * If your machine's division is fast enough, define FAST_DIVIDE.
  162937. */
  162938. #ifdef FAST_DIVIDE
  162939. #define DIVIDE_BY(a,b) a /= b
  162940. #else
  162941. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162942. #endif
  162943. if (temp < 0) {
  162944. temp = -temp;
  162945. temp += qval>>1; /* for rounding */
  162946. DIVIDE_BY(temp, qval);
  162947. temp = -temp;
  162948. } else {
  162949. temp += qval>>1; /* for rounding */
  162950. DIVIDE_BY(temp, qval);
  162951. }
  162952. output_ptr[i] = (JCOEF) temp;
  162953. }
  162954. }
  162955. }
  162956. }
  162957. #ifdef DCT_FLOAT_SUPPORTED
  162958. METHODDEF(void)
  162959. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162960. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162961. JDIMENSION start_row, JDIMENSION start_col,
  162962. JDIMENSION num_blocks)
  162963. /* This version is used for floating-point DCT implementations. */
  162964. {
  162965. /* This routine is heavily used, so it's worth coding it tightly. */
  162966. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162967. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162968. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162969. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162970. JDIMENSION bi;
  162971. sample_data += start_row; /* fold in the vertical offset once */
  162972. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162973. /* Load data into workspace, applying unsigned->signed conversion */
  162974. { register FAST_FLOAT *workspaceptr;
  162975. register JSAMPROW elemptr;
  162976. register int elemr;
  162977. workspaceptr = workspace;
  162978. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162979. elemptr = sample_data[elemr] + start_col;
  162980. #if DCTSIZE == 8 /* unroll the inner loop */
  162981. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162982. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162983. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162984. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162985. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162986. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162987. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162988. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162989. #else
  162990. { register int elemc;
  162991. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162992. *workspaceptr++ = (FAST_FLOAT)
  162993. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162994. }
  162995. }
  162996. #endif
  162997. }
  162998. }
  162999. /* Perform the DCT */
  163000. (*do_dct) (workspace);
  163001. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163002. { register FAST_FLOAT temp;
  163003. register int i;
  163004. register JCOEFPTR output_ptr = coef_blocks[bi];
  163005. for (i = 0; i < DCTSIZE2; i++) {
  163006. /* Apply the quantization and scaling factor */
  163007. temp = workspace[i] * divisors[i];
  163008. /* Round to nearest integer.
  163009. * Since C does not specify the direction of rounding for negative
  163010. * quotients, we have to force the dividend positive for portability.
  163011. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163012. * code should work for either 16-bit or 32-bit ints.
  163013. */
  163014. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163015. }
  163016. }
  163017. }
  163018. }
  163019. #endif /* DCT_FLOAT_SUPPORTED */
  163020. /*
  163021. * Initialize FDCT manager.
  163022. */
  163023. GLOBAL(void)
  163024. jinit_forward_dct (j_compress_ptr cinfo)
  163025. {
  163026. my_fdct_ptr fdct;
  163027. int i;
  163028. fdct = (my_fdct_ptr)
  163029. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163030. SIZEOF(my_fdct_controller));
  163031. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163032. fdct->pub.start_pass = start_pass_fdctmgr;
  163033. switch (cinfo->dct_method) {
  163034. #ifdef DCT_ISLOW_SUPPORTED
  163035. case JDCT_ISLOW:
  163036. fdct->pub.forward_DCT = forward_DCT;
  163037. fdct->do_dct = jpeg_fdct_islow;
  163038. break;
  163039. #endif
  163040. #ifdef DCT_IFAST_SUPPORTED
  163041. case JDCT_IFAST:
  163042. fdct->pub.forward_DCT = forward_DCT;
  163043. fdct->do_dct = jpeg_fdct_ifast;
  163044. break;
  163045. #endif
  163046. #ifdef DCT_FLOAT_SUPPORTED
  163047. case JDCT_FLOAT:
  163048. fdct->pub.forward_DCT = forward_DCT_float;
  163049. fdct->do_float_dct = jpeg_fdct_float;
  163050. break;
  163051. #endif
  163052. default:
  163053. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163054. break;
  163055. }
  163056. /* Mark divisor tables unallocated */
  163057. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163058. fdct->divisors[i] = NULL;
  163059. #ifdef DCT_FLOAT_SUPPORTED
  163060. fdct->float_divisors[i] = NULL;
  163061. #endif
  163062. }
  163063. }
  163064. /*** End of inlined file: jcdctmgr.c ***/
  163065. #undef CONST_BITS
  163066. /*** Start of inlined file: jchuff.c ***/
  163067. #define JPEG_INTERNALS
  163068. /*** Start of inlined file: jchuff.h ***/
  163069. /* The legal range of a DCT coefficient is
  163070. * -1024 .. +1023 for 8-bit data;
  163071. * -16384 .. +16383 for 12-bit data.
  163072. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163073. */
  163074. #ifndef _jchuff_h_
  163075. #define _jchuff_h_
  163076. #if BITS_IN_JSAMPLE == 8
  163077. #define MAX_COEF_BITS 10
  163078. #else
  163079. #define MAX_COEF_BITS 14
  163080. #endif
  163081. /* Derived data constructed for each Huffman table */
  163082. typedef struct {
  163083. unsigned int ehufco[256]; /* code for each symbol */
  163084. char ehufsi[256]; /* length of code for each symbol */
  163085. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163086. } c_derived_tbl;
  163087. /* Short forms of external names for systems with brain-damaged linkers. */
  163088. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163089. #define jpeg_make_c_derived_tbl jMkCDerived
  163090. #define jpeg_gen_optimal_table jGenOptTbl
  163091. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163092. /* Expand a Huffman table definition into the derived format */
  163093. EXTERN(void) jpeg_make_c_derived_tbl
  163094. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163095. c_derived_tbl ** pdtbl));
  163096. /* Generate an optimal table definition given the specified counts */
  163097. EXTERN(void) jpeg_gen_optimal_table
  163098. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163099. #endif
  163100. /*** End of inlined file: jchuff.h ***/
  163101. /* Declarations shared with jcphuff.c */
  163102. /* Expanded entropy encoder object for Huffman encoding.
  163103. *
  163104. * The savable_state subrecord contains fields that change within an MCU,
  163105. * but must not be updated permanently until we complete the MCU.
  163106. */
  163107. typedef struct {
  163108. INT32 put_buffer; /* current bit-accumulation buffer */
  163109. int put_bits; /* # of bits now in it */
  163110. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163111. } savable_state;
  163112. /* This macro is to work around compilers with missing or broken
  163113. * structure assignment. You'll need to fix this code if you have
  163114. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163115. */
  163116. #ifndef NO_STRUCT_ASSIGN
  163117. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163118. #else
  163119. #if MAX_COMPS_IN_SCAN == 4
  163120. #define ASSIGN_STATE(dest,src) \
  163121. ((dest).put_buffer = (src).put_buffer, \
  163122. (dest).put_bits = (src).put_bits, \
  163123. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163124. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163125. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163126. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163127. #endif
  163128. #endif
  163129. typedef struct {
  163130. struct jpeg_entropy_encoder pub; /* public fields */
  163131. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163132. /* These fields are NOT loaded into local working state. */
  163133. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163134. int next_restart_num; /* next restart number to write (0-7) */
  163135. /* Pointers to derived tables (these workspaces have image lifespan) */
  163136. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163137. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163138. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163139. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163140. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163141. #endif
  163142. } huff_entropy_encoder;
  163143. typedef huff_entropy_encoder * huff_entropy_ptr;
  163144. /* Working state while writing an MCU.
  163145. * This struct contains all the fields that are needed by subroutines.
  163146. */
  163147. typedef struct {
  163148. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163149. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163150. savable_state cur; /* Current bit buffer & DC state */
  163151. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163152. } working_state;
  163153. /* Forward declarations */
  163154. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163155. JBLOCKROW *MCU_data));
  163156. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163157. #ifdef ENTROPY_OPT_SUPPORTED
  163158. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163159. JBLOCKROW *MCU_data));
  163160. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163161. #endif
  163162. /*
  163163. * Initialize for a Huffman-compressed scan.
  163164. * If gather_statistics is TRUE, we do not output anything during the scan,
  163165. * just count the Huffman symbols used and generate Huffman code tables.
  163166. */
  163167. METHODDEF(void)
  163168. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163169. {
  163170. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163171. int ci, dctbl, actbl;
  163172. jpeg_component_info * compptr;
  163173. if (gather_statistics) {
  163174. #ifdef ENTROPY_OPT_SUPPORTED
  163175. entropy->pub.encode_mcu = encode_mcu_gather;
  163176. entropy->pub.finish_pass = finish_pass_gather;
  163177. #else
  163178. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163179. #endif
  163180. } else {
  163181. entropy->pub.encode_mcu = encode_mcu_huff;
  163182. entropy->pub.finish_pass = finish_pass_huff;
  163183. }
  163184. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163185. compptr = cinfo->cur_comp_info[ci];
  163186. dctbl = compptr->dc_tbl_no;
  163187. actbl = compptr->ac_tbl_no;
  163188. if (gather_statistics) {
  163189. #ifdef ENTROPY_OPT_SUPPORTED
  163190. /* Check for invalid table indexes */
  163191. /* (make_c_derived_tbl does this in the other path) */
  163192. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163193. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163194. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163195. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163196. /* Allocate and zero the statistics tables */
  163197. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163198. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163199. entropy->dc_count_ptrs[dctbl] = (long *)
  163200. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163201. 257 * SIZEOF(long));
  163202. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163203. if (entropy->ac_count_ptrs[actbl] == NULL)
  163204. entropy->ac_count_ptrs[actbl] = (long *)
  163205. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163206. 257 * SIZEOF(long));
  163207. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163208. #endif
  163209. } else {
  163210. /* Compute derived values for Huffman tables */
  163211. /* We may do this more than once for a table, but it's not expensive */
  163212. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163213. & entropy->dc_derived_tbls[dctbl]);
  163214. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163215. & entropy->ac_derived_tbls[actbl]);
  163216. }
  163217. /* Initialize DC predictions to 0 */
  163218. entropy->saved.last_dc_val[ci] = 0;
  163219. }
  163220. /* Initialize bit buffer to empty */
  163221. entropy->saved.put_buffer = 0;
  163222. entropy->saved.put_bits = 0;
  163223. /* Initialize restart stuff */
  163224. entropy->restarts_to_go = cinfo->restart_interval;
  163225. entropy->next_restart_num = 0;
  163226. }
  163227. /*
  163228. * Compute the derived values for a Huffman table.
  163229. * This routine also performs some validation checks on the table.
  163230. *
  163231. * Note this is also used by jcphuff.c.
  163232. */
  163233. GLOBAL(void)
  163234. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163235. c_derived_tbl ** pdtbl)
  163236. {
  163237. JHUFF_TBL *htbl;
  163238. c_derived_tbl *dtbl;
  163239. int p, i, l, lastp, si, maxsymbol;
  163240. char huffsize[257];
  163241. unsigned int huffcode[257];
  163242. unsigned int code;
  163243. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163244. * paralleling the order of the symbols themselves in htbl->huffval[].
  163245. */
  163246. /* Find the input Huffman table */
  163247. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163248. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163249. htbl =
  163250. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163251. if (htbl == NULL)
  163252. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163253. /* Allocate a workspace if we haven't already done so. */
  163254. if (*pdtbl == NULL)
  163255. *pdtbl = (c_derived_tbl *)
  163256. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163257. SIZEOF(c_derived_tbl));
  163258. dtbl = *pdtbl;
  163259. /* Figure C.1: make table of Huffman code length for each symbol */
  163260. p = 0;
  163261. for (l = 1; l <= 16; l++) {
  163262. i = (int) htbl->bits[l];
  163263. if (i < 0 || p + i > 256) /* protect against table overrun */
  163264. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163265. while (i--)
  163266. huffsize[p++] = (char) l;
  163267. }
  163268. huffsize[p] = 0;
  163269. lastp = p;
  163270. /* Figure C.2: generate the codes themselves */
  163271. /* We also validate that the counts represent a legal Huffman code tree. */
  163272. code = 0;
  163273. si = huffsize[0];
  163274. p = 0;
  163275. while (huffsize[p]) {
  163276. while (((int) huffsize[p]) == si) {
  163277. huffcode[p++] = code;
  163278. code++;
  163279. }
  163280. /* code is now 1 more than the last code used for codelength si; but
  163281. * it must still fit in si bits, since no code is allowed to be all ones.
  163282. */
  163283. if (((INT32) code) >= (((INT32) 1) << si))
  163284. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163285. code <<= 1;
  163286. si++;
  163287. }
  163288. /* Figure C.3: generate encoding tables */
  163289. /* These are code and size indexed by symbol value */
  163290. /* Set all codeless symbols to have code length 0;
  163291. * this lets us detect duplicate VAL entries here, and later
  163292. * allows emit_bits to detect any attempt to emit such symbols.
  163293. */
  163294. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163295. /* This is also a convenient place to check for out-of-range
  163296. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163297. * but only 0..15 for DC. (We could constrain them further
  163298. * based on data depth and mode, but this seems enough.)
  163299. */
  163300. maxsymbol = isDC ? 15 : 255;
  163301. for (p = 0; p < lastp; p++) {
  163302. i = htbl->huffval[p];
  163303. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163304. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163305. dtbl->ehufco[i] = huffcode[p];
  163306. dtbl->ehufsi[i] = huffsize[p];
  163307. }
  163308. }
  163309. /* Outputting bytes to the file */
  163310. /* Emit a byte, taking 'action' if must suspend. */
  163311. #define emit_byte(state,val,action) \
  163312. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163313. if (--(state)->free_in_buffer == 0) \
  163314. if (! dump_buffer(state)) \
  163315. { action; } }
  163316. LOCAL(boolean)
  163317. dump_buffer (working_state * state)
  163318. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163319. {
  163320. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163321. if (! (*dest->empty_output_buffer) (state->cinfo))
  163322. return FALSE;
  163323. /* After a successful buffer dump, must reset buffer pointers */
  163324. state->next_output_byte = dest->next_output_byte;
  163325. state->free_in_buffer = dest->free_in_buffer;
  163326. return TRUE;
  163327. }
  163328. /* Outputting bits to the file */
  163329. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163330. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163331. * in one call, and we never retain more than 7 bits in put_buffer
  163332. * between calls, so 24 bits are sufficient.
  163333. */
  163334. INLINE
  163335. LOCAL(boolean)
  163336. emit_bits (working_state * state, unsigned int code, int size)
  163337. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163338. {
  163339. /* This routine is heavily used, so it's worth coding tightly. */
  163340. register INT32 put_buffer = (INT32) code;
  163341. register int put_bits = state->cur.put_bits;
  163342. /* if size is 0, caller used an invalid Huffman table entry */
  163343. if (size == 0)
  163344. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163345. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163346. put_bits += size; /* new number of bits in buffer */
  163347. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163348. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163349. while (put_bits >= 8) {
  163350. int c = (int) ((put_buffer >> 16) & 0xFF);
  163351. emit_byte(state, c, return FALSE);
  163352. if (c == 0xFF) { /* need to stuff a zero byte? */
  163353. emit_byte(state, 0, return FALSE);
  163354. }
  163355. put_buffer <<= 8;
  163356. put_bits -= 8;
  163357. }
  163358. state->cur.put_buffer = put_buffer; /* update state variables */
  163359. state->cur.put_bits = put_bits;
  163360. return TRUE;
  163361. }
  163362. LOCAL(boolean)
  163363. flush_bits (working_state * state)
  163364. {
  163365. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163366. return FALSE;
  163367. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163368. state->cur.put_bits = 0;
  163369. return TRUE;
  163370. }
  163371. /* Encode a single block's worth of coefficients */
  163372. LOCAL(boolean)
  163373. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163374. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163375. {
  163376. register int temp, temp2;
  163377. register int nbits;
  163378. register int k, r, i;
  163379. /* Encode the DC coefficient difference per section F.1.2.1 */
  163380. temp = temp2 = block[0] - last_dc_val;
  163381. if (temp < 0) {
  163382. temp = -temp; /* temp is abs value of input */
  163383. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163384. /* This code assumes we are on a two's complement machine */
  163385. temp2--;
  163386. }
  163387. /* Find the number of bits needed for the magnitude of the coefficient */
  163388. nbits = 0;
  163389. while (temp) {
  163390. nbits++;
  163391. temp >>= 1;
  163392. }
  163393. /* Check for out-of-range coefficient values.
  163394. * Since we're encoding a difference, the range limit is twice as much.
  163395. */
  163396. if (nbits > MAX_COEF_BITS+1)
  163397. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163398. /* Emit the Huffman-coded symbol for the number of bits */
  163399. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163400. return FALSE;
  163401. /* Emit that number of bits of the value, if positive, */
  163402. /* or the complement of its magnitude, if negative. */
  163403. if (nbits) /* emit_bits rejects calls with size 0 */
  163404. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163405. return FALSE;
  163406. /* Encode the AC coefficients per section F.1.2.2 */
  163407. r = 0; /* r = run length of zeros */
  163408. for (k = 1; k < DCTSIZE2; k++) {
  163409. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163410. r++;
  163411. } else {
  163412. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163413. while (r > 15) {
  163414. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163415. return FALSE;
  163416. r -= 16;
  163417. }
  163418. temp2 = temp;
  163419. if (temp < 0) {
  163420. temp = -temp; /* temp is abs value of input */
  163421. /* This code assumes we are on a two's complement machine */
  163422. temp2--;
  163423. }
  163424. /* Find the number of bits needed for the magnitude of the coefficient */
  163425. nbits = 1; /* there must be at least one 1 bit */
  163426. while ((temp >>= 1))
  163427. nbits++;
  163428. /* Check for out-of-range coefficient values */
  163429. if (nbits > MAX_COEF_BITS)
  163430. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163431. /* Emit Huffman symbol for run length / number of bits */
  163432. i = (r << 4) + nbits;
  163433. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163434. return FALSE;
  163435. /* Emit that number of bits of the value, if positive, */
  163436. /* or the complement of its magnitude, if negative. */
  163437. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163438. return FALSE;
  163439. r = 0;
  163440. }
  163441. }
  163442. /* If the last coef(s) were zero, emit an end-of-block code */
  163443. if (r > 0)
  163444. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163445. return FALSE;
  163446. return TRUE;
  163447. }
  163448. /*
  163449. * Emit a restart marker & resynchronize predictions.
  163450. */
  163451. LOCAL(boolean)
  163452. emit_restart (working_state * state, int restart_num)
  163453. {
  163454. int ci;
  163455. if (! flush_bits(state))
  163456. return FALSE;
  163457. emit_byte(state, 0xFF, return FALSE);
  163458. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163459. /* Re-initialize DC predictions to 0 */
  163460. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163461. state->cur.last_dc_val[ci] = 0;
  163462. /* The restart counter is not updated until we successfully write the MCU. */
  163463. return TRUE;
  163464. }
  163465. /*
  163466. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163467. */
  163468. METHODDEF(boolean)
  163469. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163470. {
  163471. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163472. working_state state;
  163473. int blkn, ci;
  163474. jpeg_component_info * compptr;
  163475. /* Load up working state */
  163476. state.next_output_byte = cinfo->dest->next_output_byte;
  163477. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163478. ASSIGN_STATE(state.cur, entropy->saved);
  163479. state.cinfo = cinfo;
  163480. /* Emit restart marker if needed */
  163481. if (cinfo->restart_interval) {
  163482. if (entropy->restarts_to_go == 0)
  163483. if (! emit_restart(&state, entropy->next_restart_num))
  163484. return FALSE;
  163485. }
  163486. /* Encode the MCU data blocks */
  163487. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163488. ci = cinfo->MCU_membership[blkn];
  163489. compptr = cinfo->cur_comp_info[ci];
  163490. if (! encode_one_block(&state,
  163491. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163492. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163493. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163494. return FALSE;
  163495. /* Update last_dc_val */
  163496. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163497. }
  163498. /* Completed MCU, so update state */
  163499. cinfo->dest->next_output_byte = state.next_output_byte;
  163500. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163501. ASSIGN_STATE(entropy->saved, state.cur);
  163502. /* Update restart-interval state too */
  163503. if (cinfo->restart_interval) {
  163504. if (entropy->restarts_to_go == 0) {
  163505. entropy->restarts_to_go = cinfo->restart_interval;
  163506. entropy->next_restart_num++;
  163507. entropy->next_restart_num &= 7;
  163508. }
  163509. entropy->restarts_to_go--;
  163510. }
  163511. return TRUE;
  163512. }
  163513. /*
  163514. * Finish up at the end of a Huffman-compressed scan.
  163515. */
  163516. METHODDEF(void)
  163517. finish_pass_huff (j_compress_ptr cinfo)
  163518. {
  163519. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163520. working_state state;
  163521. /* Load up working state ... flush_bits needs it */
  163522. state.next_output_byte = cinfo->dest->next_output_byte;
  163523. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163524. ASSIGN_STATE(state.cur, entropy->saved);
  163525. state.cinfo = cinfo;
  163526. /* Flush out the last data */
  163527. if (! flush_bits(&state))
  163528. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163529. /* Update state */
  163530. cinfo->dest->next_output_byte = state.next_output_byte;
  163531. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163532. ASSIGN_STATE(entropy->saved, state.cur);
  163533. }
  163534. /*
  163535. * Huffman coding optimization.
  163536. *
  163537. * We first scan the supplied data and count the number of uses of each symbol
  163538. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163539. * Then we build a Huffman coding tree for the observed counts.
  163540. * Symbols which are not needed at all for the particular image are not
  163541. * assigned any code, which saves space in the DHT marker as well as in
  163542. * the compressed data.
  163543. */
  163544. #ifdef ENTROPY_OPT_SUPPORTED
  163545. /* Process a single block's worth of coefficients */
  163546. LOCAL(void)
  163547. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163548. long dc_counts[], long ac_counts[])
  163549. {
  163550. register int temp;
  163551. register int nbits;
  163552. register int k, r;
  163553. /* Encode the DC coefficient difference per section F.1.2.1 */
  163554. temp = block[0] - last_dc_val;
  163555. if (temp < 0)
  163556. temp = -temp;
  163557. /* Find the number of bits needed for the magnitude of the coefficient */
  163558. nbits = 0;
  163559. while (temp) {
  163560. nbits++;
  163561. temp >>= 1;
  163562. }
  163563. /* Check for out-of-range coefficient values.
  163564. * Since we're encoding a difference, the range limit is twice as much.
  163565. */
  163566. if (nbits > MAX_COEF_BITS+1)
  163567. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163568. /* Count the Huffman symbol for the number of bits */
  163569. dc_counts[nbits]++;
  163570. /* Encode the AC coefficients per section F.1.2.2 */
  163571. r = 0; /* r = run length of zeros */
  163572. for (k = 1; k < DCTSIZE2; k++) {
  163573. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163574. r++;
  163575. } else {
  163576. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163577. while (r > 15) {
  163578. ac_counts[0xF0]++;
  163579. r -= 16;
  163580. }
  163581. /* Find the number of bits needed for the magnitude of the coefficient */
  163582. if (temp < 0)
  163583. temp = -temp;
  163584. /* Find the number of bits needed for the magnitude of the coefficient */
  163585. nbits = 1; /* there must be at least one 1 bit */
  163586. while ((temp >>= 1))
  163587. nbits++;
  163588. /* Check for out-of-range coefficient values */
  163589. if (nbits > MAX_COEF_BITS)
  163590. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163591. /* Count Huffman symbol for run length / number of bits */
  163592. ac_counts[(r << 4) + nbits]++;
  163593. r = 0;
  163594. }
  163595. }
  163596. /* If the last coef(s) were zero, emit an end-of-block code */
  163597. if (r > 0)
  163598. ac_counts[0]++;
  163599. }
  163600. /*
  163601. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163602. * No data is actually output, so no suspension return is possible.
  163603. */
  163604. METHODDEF(boolean)
  163605. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163606. {
  163607. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163608. int blkn, ci;
  163609. jpeg_component_info * compptr;
  163610. /* Take care of restart intervals if needed */
  163611. if (cinfo->restart_interval) {
  163612. if (entropy->restarts_to_go == 0) {
  163613. /* Re-initialize DC predictions to 0 */
  163614. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163615. entropy->saved.last_dc_val[ci] = 0;
  163616. /* Update restart state */
  163617. entropy->restarts_to_go = cinfo->restart_interval;
  163618. }
  163619. entropy->restarts_to_go--;
  163620. }
  163621. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163622. ci = cinfo->MCU_membership[blkn];
  163623. compptr = cinfo->cur_comp_info[ci];
  163624. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163625. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163626. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163627. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163628. }
  163629. return TRUE;
  163630. }
  163631. /*
  163632. * Generate the best Huffman code table for the given counts, fill htbl.
  163633. * Note this is also used by jcphuff.c.
  163634. *
  163635. * The JPEG standard requires that no symbol be assigned a codeword of all
  163636. * one bits (so that padding bits added at the end of a compressed segment
  163637. * can't look like a valid code). Because of the canonical ordering of
  163638. * codewords, this just means that there must be an unused slot in the
  163639. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163640. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163641. * with count 1. In theory that's not optimal; giving it count zero but
  163642. * including it in the symbol set anyway should give a better Huffman code.
  163643. * But the theoretically better code actually seems to come out worse in
  163644. * practice, because it produces more all-ones bytes (which incur stuffed
  163645. * zero bytes in the final file). In any case the difference is tiny.
  163646. *
  163647. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163648. * If some symbols have a very small but nonzero probability, the Huffman tree
  163649. * must be adjusted to meet the code length restriction. We currently use
  163650. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163651. * optimal; it may not choose the best possible limited-length code. But
  163652. * typically only very-low-frequency symbols will be given less-than-optimal
  163653. * lengths, so the code is almost optimal. Experimental comparisons against
  163654. * an optimal limited-length-code algorithm indicate that the difference is
  163655. * microscopic --- usually less than a hundredth of a percent of total size.
  163656. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163657. */
  163658. GLOBAL(void)
  163659. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163660. {
  163661. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163662. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163663. int codesize[257]; /* codesize[k] = code length of symbol k */
  163664. int others[257]; /* next symbol in current branch of tree */
  163665. int c1, c2;
  163666. int p, i, j;
  163667. long v;
  163668. /* This algorithm is explained in section K.2 of the JPEG standard */
  163669. MEMZERO(bits, SIZEOF(bits));
  163670. MEMZERO(codesize, SIZEOF(codesize));
  163671. for (i = 0; i < 257; i++)
  163672. others[i] = -1; /* init links to empty */
  163673. freq[256] = 1; /* make sure 256 has a nonzero count */
  163674. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163675. * that no real symbol is given code-value of all ones, because 256
  163676. * will be placed last in the largest codeword category.
  163677. */
  163678. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163679. for (;;) {
  163680. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163681. /* In case of ties, take the larger symbol number */
  163682. c1 = -1;
  163683. v = 1000000000L;
  163684. for (i = 0; i <= 256; i++) {
  163685. if (freq[i] && freq[i] <= v) {
  163686. v = freq[i];
  163687. c1 = i;
  163688. }
  163689. }
  163690. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163691. /* In case of ties, take the larger symbol number */
  163692. c2 = -1;
  163693. v = 1000000000L;
  163694. for (i = 0; i <= 256; i++) {
  163695. if (freq[i] && freq[i] <= v && i != c1) {
  163696. v = freq[i];
  163697. c2 = i;
  163698. }
  163699. }
  163700. /* Done if we've merged everything into one frequency */
  163701. if (c2 < 0)
  163702. break;
  163703. /* Else merge the two counts/trees */
  163704. freq[c1] += freq[c2];
  163705. freq[c2] = 0;
  163706. /* Increment the codesize of everything in c1's tree branch */
  163707. codesize[c1]++;
  163708. while (others[c1] >= 0) {
  163709. c1 = others[c1];
  163710. codesize[c1]++;
  163711. }
  163712. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163713. /* Increment the codesize of everything in c2's tree branch */
  163714. codesize[c2]++;
  163715. while (others[c2] >= 0) {
  163716. c2 = others[c2];
  163717. codesize[c2]++;
  163718. }
  163719. }
  163720. /* Now count the number of symbols of each code length */
  163721. for (i = 0; i <= 256; i++) {
  163722. if (codesize[i]) {
  163723. /* The JPEG standard seems to think that this can't happen, */
  163724. /* but I'm paranoid... */
  163725. if (codesize[i] > MAX_CLEN)
  163726. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163727. bits[codesize[i]]++;
  163728. }
  163729. }
  163730. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163731. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163732. * Here is what the JPEG spec says about how this next bit works:
  163733. * Since symbols are paired for the longest Huffman code, the symbols are
  163734. * removed from this length category two at a time. The prefix for the pair
  163735. * (which is one bit shorter) is allocated to one of the pair; then,
  163736. * skipping the BITS entry for that prefix length, a code word from the next
  163737. * shortest nonzero BITS entry is converted into a prefix for two code words
  163738. * one bit longer.
  163739. */
  163740. for (i = MAX_CLEN; i > 16; i--) {
  163741. while (bits[i] > 0) {
  163742. j = i - 2; /* find length of new prefix to be used */
  163743. while (bits[j] == 0)
  163744. j--;
  163745. bits[i] -= 2; /* remove two symbols */
  163746. bits[i-1]++; /* one goes in this length */
  163747. bits[j+1] += 2; /* two new symbols in this length */
  163748. bits[j]--; /* symbol of this length is now a prefix */
  163749. }
  163750. }
  163751. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163752. while (bits[i] == 0) /* find largest codelength still in use */
  163753. i--;
  163754. bits[i]--;
  163755. /* Return final symbol counts (only for lengths 0..16) */
  163756. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163757. /* Return a list of the symbols sorted by code length */
  163758. /* It's not real clear to me why we don't need to consider the codelength
  163759. * changes made above, but the JPEG spec seems to think this works.
  163760. */
  163761. p = 0;
  163762. for (i = 1; i <= MAX_CLEN; i++) {
  163763. for (j = 0; j <= 255; j++) {
  163764. if (codesize[j] == i) {
  163765. htbl->huffval[p] = (UINT8) j;
  163766. p++;
  163767. }
  163768. }
  163769. }
  163770. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163771. htbl->sent_table = FALSE;
  163772. }
  163773. /*
  163774. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163775. */
  163776. METHODDEF(void)
  163777. finish_pass_gather (j_compress_ptr cinfo)
  163778. {
  163779. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163780. int ci, dctbl, actbl;
  163781. jpeg_component_info * compptr;
  163782. JHUFF_TBL **htblptr;
  163783. boolean did_dc[NUM_HUFF_TBLS];
  163784. boolean did_ac[NUM_HUFF_TBLS];
  163785. /* It's important not to apply jpeg_gen_optimal_table more than once
  163786. * per table, because it clobbers the input frequency counts!
  163787. */
  163788. MEMZERO(did_dc, SIZEOF(did_dc));
  163789. MEMZERO(did_ac, SIZEOF(did_ac));
  163790. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163791. compptr = cinfo->cur_comp_info[ci];
  163792. dctbl = compptr->dc_tbl_no;
  163793. actbl = compptr->ac_tbl_no;
  163794. if (! did_dc[dctbl]) {
  163795. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163796. if (*htblptr == NULL)
  163797. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163798. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163799. did_dc[dctbl] = TRUE;
  163800. }
  163801. if (! did_ac[actbl]) {
  163802. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163803. if (*htblptr == NULL)
  163804. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163805. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163806. did_ac[actbl] = TRUE;
  163807. }
  163808. }
  163809. }
  163810. #endif /* ENTROPY_OPT_SUPPORTED */
  163811. /*
  163812. * Module initialization routine for Huffman entropy encoding.
  163813. */
  163814. GLOBAL(void)
  163815. jinit_huff_encoder (j_compress_ptr cinfo)
  163816. {
  163817. huff_entropy_ptr entropy;
  163818. int i;
  163819. entropy = (huff_entropy_ptr)
  163820. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163821. SIZEOF(huff_entropy_encoder));
  163822. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163823. entropy->pub.start_pass = start_pass_huff;
  163824. /* Mark tables unallocated */
  163825. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163826. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163827. #ifdef ENTROPY_OPT_SUPPORTED
  163828. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163829. #endif
  163830. }
  163831. }
  163832. /*** End of inlined file: jchuff.c ***/
  163833. #undef emit_byte
  163834. /*** Start of inlined file: jcinit.c ***/
  163835. #define JPEG_INTERNALS
  163836. /*
  163837. * Master selection of compression modules.
  163838. * This is done once at the start of processing an image. We determine
  163839. * which modules will be used and give them appropriate initialization calls.
  163840. */
  163841. GLOBAL(void)
  163842. jinit_compress_master (j_compress_ptr cinfo)
  163843. {
  163844. /* Initialize master control (includes parameter checking/processing) */
  163845. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163846. /* Preprocessing */
  163847. if (! cinfo->raw_data_in) {
  163848. jinit_color_converter(cinfo);
  163849. jinit_downsampler(cinfo);
  163850. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163851. }
  163852. /* Forward DCT */
  163853. jinit_forward_dct(cinfo);
  163854. /* Entropy encoding: either Huffman or arithmetic coding. */
  163855. if (cinfo->arith_code) {
  163856. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163857. } else {
  163858. if (cinfo->progressive_mode) {
  163859. #ifdef C_PROGRESSIVE_SUPPORTED
  163860. jinit_phuff_encoder(cinfo);
  163861. #else
  163862. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163863. #endif
  163864. } else
  163865. jinit_huff_encoder(cinfo);
  163866. }
  163867. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163868. jinit_c_coef_controller(cinfo,
  163869. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163870. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163871. jinit_marker_writer(cinfo);
  163872. /* We can now tell the memory manager to allocate virtual arrays. */
  163873. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163874. /* Write the datastream header (SOI) immediately.
  163875. * Frame and scan headers are postponed till later.
  163876. * This lets application insert special markers after the SOI.
  163877. */
  163878. (*cinfo->marker->write_file_header) (cinfo);
  163879. }
  163880. /*** End of inlined file: jcinit.c ***/
  163881. /*** Start of inlined file: jcmainct.c ***/
  163882. #define JPEG_INTERNALS
  163883. /* Note: currently, there is no operating mode in which a full-image buffer
  163884. * is needed at this step. If there were, that mode could not be used with
  163885. * "raw data" input, since this module is bypassed in that case. However,
  163886. * we've left the code here for possible use in special applications.
  163887. */
  163888. #undef FULL_MAIN_BUFFER_SUPPORTED
  163889. /* Private buffer controller object */
  163890. typedef struct {
  163891. struct jpeg_c_main_controller pub; /* public fields */
  163892. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163893. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163894. boolean suspended; /* remember if we suspended output */
  163895. J_BUF_MODE pass_mode; /* current operating mode */
  163896. /* If using just a strip buffer, this points to the entire set of buffers
  163897. * (we allocate one for each component). In the full-image case, this
  163898. * points to the currently accessible strips of the virtual arrays.
  163899. */
  163900. JSAMPARRAY buffer[MAX_COMPONENTS];
  163901. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163902. /* If using full-image storage, this array holds pointers to virtual-array
  163903. * control blocks for each component. Unused if not full-image storage.
  163904. */
  163905. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163906. #endif
  163907. } my_main_controller;
  163908. typedef my_main_controller * my_main_ptr;
  163909. /* Forward declarations */
  163910. METHODDEF(void) process_data_simple_main
  163911. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163912. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163913. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163914. METHODDEF(void) process_data_buffer_main
  163915. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163916. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163917. #endif
  163918. /*
  163919. * Initialize for a processing pass.
  163920. */
  163921. METHODDEF(void)
  163922. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163923. {
  163924. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163925. /* Do nothing in raw-data mode. */
  163926. if (cinfo->raw_data_in)
  163927. return;
  163928. main_->cur_iMCU_row = 0; /* initialize counters */
  163929. main_->rowgroup_ctr = 0;
  163930. main_->suspended = FALSE;
  163931. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163932. switch (pass_mode) {
  163933. case JBUF_PASS_THRU:
  163934. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163935. if (main_->whole_image[0] != NULL)
  163936. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163937. #endif
  163938. main_->pub.process_data = process_data_simple_main;
  163939. break;
  163940. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163941. case JBUF_SAVE_SOURCE:
  163942. case JBUF_CRANK_DEST:
  163943. case JBUF_SAVE_AND_PASS:
  163944. if (main_->whole_image[0] == NULL)
  163945. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163946. main_->pub.process_data = process_data_buffer_main;
  163947. break;
  163948. #endif
  163949. default:
  163950. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163951. break;
  163952. }
  163953. }
  163954. /*
  163955. * Process some data.
  163956. * This routine handles the simple pass-through mode,
  163957. * where we have only a strip buffer.
  163958. */
  163959. METHODDEF(void)
  163960. process_data_simple_main (j_compress_ptr cinfo,
  163961. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163962. JDIMENSION in_rows_avail)
  163963. {
  163964. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163965. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163966. /* Read input data if we haven't filled the main buffer yet */
  163967. if (main_->rowgroup_ctr < DCTSIZE)
  163968. (*cinfo->prep->pre_process_data) (cinfo,
  163969. input_buf, in_row_ctr, in_rows_avail,
  163970. main_->buffer, &main_->rowgroup_ctr,
  163971. (JDIMENSION) DCTSIZE);
  163972. /* If we don't have a full iMCU row buffered, return to application for
  163973. * more data. Note that preprocessor will always pad to fill the iMCU row
  163974. * at the bottom of the image.
  163975. */
  163976. if (main_->rowgroup_ctr != DCTSIZE)
  163977. return;
  163978. /* Send the completed row to the compressor */
  163979. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163980. /* If compressor did not consume the whole row, then we must need to
  163981. * suspend processing and return to the application. In this situation
  163982. * we pretend we didn't yet consume the last input row; otherwise, if
  163983. * it happened to be the last row of the image, the application would
  163984. * think we were done.
  163985. */
  163986. if (! main_->suspended) {
  163987. (*in_row_ctr)--;
  163988. main_->suspended = TRUE;
  163989. }
  163990. return;
  163991. }
  163992. /* We did finish the row. Undo our little suspension hack if a previous
  163993. * call suspended; then mark the main buffer empty.
  163994. */
  163995. if (main_->suspended) {
  163996. (*in_row_ctr)++;
  163997. main_->suspended = FALSE;
  163998. }
  163999. main_->rowgroup_ctr = 0;
  164000. main_->cur_iMCU_row++;
  164001. }
  164002. }
  164003. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164004. /*
  164005. * Process some data.
  164006. * This routine handles all of the modes that use a full-size buffer.
  164007. */
  164008. METHODDEF(void)
  164009. process_data_buffer_main (j_compress_ptr cinfo,
  164010. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164011. JDIMENSION in_rows_avail)
  164012. {
  164013. my_main_ptr main = (my_main_ptr) cinfo->main;
  164014. int ci;
  164015. jpeg_component_info *compptr;
  164016. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164017. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164018. /* Realign the virtual buffers if at the start of an iMCU row. */
  164019. if (main->rowgroup_ctr == 0) {
  164020. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164021. ci++, compptr++) {
  164022. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164023. ((j_common_ptr) cinfo, main->whole_image[ci],
  164024. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164025. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164026. }
  164027. /* In a read pass, pretend we just read some source data. */
  164028. if (! writing) {
  164029. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164030. main->rowgroup_ctr = DCTSIZE;
  164031. }
  164032. }
  164033. /* If a write pass, read input data until the current iMCU row is full. */
  164034. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164035. if (writing) {
  164036. (*cinfo->prep->pre_process_data) (cinfo,
  164037. input_buf, in_row_ctr, in_rows_avail,
  164038. main->buffer, &main->rowgroup_ctr,
  164039. (JDIMENSION) DCTSIZE);
  164040. /* Return to application if we need more data to fill the iMCU row. */
  164041. if (main->rowgroup_ctr < DCTSIZE)
  164042. return;
  164043. }
  164044. /* Emit data, unless this is a sink-only pass. */
  164045. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164046. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164047. /* If compressor did not consume the whole row, then we must need to
  164048. * suspend processing and return to the application. In this situation
  164049. * we pretend we didn't yet consume the last input row; otherwise, if
  164050. * it happened to be the last row of the image, the application would
  164051. * think we were done.
  164052. */
  164053. if (! main->suspended) {
  164054. (*in_row_ctr)--;
  164055. main->suspended = TRUE;
  164056. }
  164057. return;
  164058. }
  164059. /* We did finish the row. Undo our little suspension hack if a previous
  164060. * call suspended; then mark the main buffer empty.
  164061. */
  164062. if (main->suspended) {
  164063. (*in_row_ctr)++;
  164064. main->suspended = FALSE;
  164065. }
  164066. }
  164067. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164068. main->rowgroup_ctr = 0;
  164069. main->cur_iMCU_row++;
  164070. }
  164071. }
  164072. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164073. /*
  164074. * Initialize main buffer controller.
  164075. */
  164076. GLOBAL(void)
  164077. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164078. {
  164079. my_main_ptr main_;
  164080. int ci;
  164081. jpeg_component_info *compptr;
  164082. main_ = (my_main_ptr)
  164083. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164084. SIZEOF(my_main_controller));
  164085. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164086. main_->pub.start_pass = start_pass_main;
  164087. /* We don't need to create a buffer in raw-data mode. */
  164088. if (cinfo->raw_data_in)
  164089. return;
  164090. /* Create the buffer. It holds downsampled data, so each component
  164091. * may be of a different size.
  164092. */
  164093. if (need_full_buffer) {
  164094. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164095. /* Allocate a full-image virtual array for each component */
  164096. /* Note we pad the bottom to a multiple of the iMCU height */
  164097. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164098. ci++, compptr++) {
  164099. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164100. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164101. compptr->width_in_blocks * DCTSIZE,
  164102. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164103. (long) compptr->v_samp_factor) * DCTSIZE,
  164104. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164105. }
  164106. #else
  164107. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164108. #endif
  164109. } else {
  164110. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164111. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164112. #endif
  164113. /* Allocate a strip buffer for each component */
  164114. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164115. ci++, compptr++) {
  164116. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164117. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164118. compptr->width_in_blocks * DCTSIZE,
  164119. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164120. }
  164121. }
  164122. }
  164123. /*** End of inlined file: jcmainct.c ***/
  164124. /*** Start of inlined file: jcmarker.c ***/
  164125. #define JPEG_INTERNALS
  164126. /* Private state */
  164127. typedef struct {
  164128. struct jpeg_marker_writer pub; /* public fields */
  164129. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164130. } my_marker_writer;
  164131. typedef my_marker_writer * my_marker_ptr;
  164132. /*
  164133. * Basic output routines.
  164134. *
  164135. * Note that we do not support suspension while writing a marker.
  164136. * Therefore, an application using suspension must ensure that there is
  164137. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164138. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164139. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164140. * modes are not supported at all with suspension, so those two are the only
  164141. * points where markers will be written.
  164142. */
  164143. LOCAL(void)
  164144. emit_byte (j_compress_ptr cinfo, int val)
  164145. /* Emit a byte */
  164146. {
  164147. struct jpeg_destination_mgr * dest = cinfo->dest;
  164148. *(dest->next_output_byte)++ = (JOCTET) val;
  164149. if (--dest->free_in_buffer == 0) {
  164150. if (! (*dest->empty_output_buffer) (cinfo))
  164151. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164152. }
  164153. }
  164154. LOCAL(void)
  164155. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164156. /* Emit a marker code */
  164157. {
  164158. emit_byte(cinfo, 0xFF);
  164159. emit_byte(cinfo, (int) mark);
  164160. }
  164161. LOCAL(void)
  164162. emit_2bytes (j_compress_ptr cinfo, int value)
  164163. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164164. {
  164165. emit_byte(cinfo, (value >> 8) & 0xFF);
  164166. emit_byte(cinfo, value & 0xFF);
  164167. }
  164168. /*
  164169. * Routines to write specific marker types.
  164170. */
  164171. LOCAL(int)
  164172. emit_dqt (j_compress_ptr cinfo, int index)
  164173. /* Emit a DQT marker */
  164174. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164175. {
  164176. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164177. int prec;
  164178. int i;
  164179. if (qtbl == NULL)
  164180. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164181. prec = 0;
  164182. for (i = 0; i < DCTSIZE2; i++) {
  164183. if (qtbl->quantval[i] > 255)
  164184. prec = 1;
  164185. }
  164186. if (! qtbl->sent_table) {
  164187. emit_marker(cinfo, M_DQT);
  164188. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164189. emit_byte(cinfo, index + (prec<<4));
  164190. for (i = 0; i < DCTSIZE2; i++) {
  164191. /* The table entries must be emitted in zigzag order. */
  164192. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164193. if (prec)
  164194. emit_byte(cinfo, (int) (qval >> 8));
  164195. emit_byte(cinfo, (int) (qval & 0xFF));
  164196. }
  164197. qtbl->sent_table = TRUE;
  164198. }
  164199. return prec;
  164200. }
  164201. LOCAL(void)
  164202. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164203. /* Emit a DHT marker */
  164204. {
  164205. JHUFF_TBL * htbl;
  164206. int length, i;
  164207. if (is_ac) {
  164208. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164209. index += 0x10; /* output index has AC bit set */
  164210. } else {
  164211. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164212. }
  164213. if (htbl == NULL)
  164214. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164215. if (! htbl->sent_table) {
  164216. emit_marker(cinfo, M_DHT);
  164217. length = 0;
  164218. for (i = 1; i <= 16; i++)
  164219. length += htbl->bits[i];
  164220. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164221. emit_byte(cinfo, index);
  164222. for (i = 1; i <= 16; i++)
  164223. emit_byte(cinfo, htbl->bits[i]);
  164224. for (i = 0; i < length; i++)
  164225. emit_byte(cinfo, htbl->huffval[i]);
  164226. htbl->sent_table = TRUE;
  164227. }
  164228. }
  164229. LOCAL(void)
  164230. emit_dac (j_compress_ptr)
  164231. /* Emit a DAC marker */
  164232. /* Since the useful info is so small, we want to emit all the tables in */
  164233. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164234. {
  164235. #ifdef C_ARITH_CODING_SUPPORTED
  164236. char dc_in_use[NUM_ARITH_TBLS];
  164237. char ac_in_use[NUM_ARITH_TBLS];
  164238. int length, i;
  164239. jpeg_component_info *compptr;
  164240. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164241. dc_in_use[i] = ac_in_use[i] = 0;
  164242. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164243. compptr = cinfo->cur_comp_info[i];
  164244. dc_in_use[compptr->dc_tbl_no] = 1;
  164245. ac_in_use[compptr->ac_tbl_no] = 1;
  164246. }
  164247. length = 0;
  164248. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164249. length += dc_in_use[i] + ac_in_use[i];
  164250. emit_marker(cinfo, M_DAC);
  164251. emit_2bytes(cinfo, length*2 + 2);
  164252. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164253. if (dc_in_use[i]) {
  164254. emit_byte(cinfo, i);
  164255. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164256. }
  164257. if (ac_in_use[i]) {
  164258. emit_byte(cinfo, i + 0x10);
  164259. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164260. }
  164261. }
  164262. #endif /* C_ARITH_CODING_SUPPORTED */
  164263. }
  164264. LOCAL(void)
  164265. emit_dri (j_compress_ptr cinfo)
  164266. /* Emit a DRI marker */
  164267. {
  164268. emit_marker(cinfo, M_DRI);
  164269. emit_2bytes(cinfo, 4); /* fixed length */
  164270. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164271. }
  164272. LOCAL(void)
  164273. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164274. /* Emit a SOF marker */
  164275. {
  164276. int ci;
  164277. jpeg_component_info *compptr;
  164278. emit_marker(cinfo, code);
  164279. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164280. /* Make sure image isn't bigger than SOF field can handle */
  164281. if ((long) cinfo->image_height > 65535L ||
  164282. (long) cinfo->image_width > 65535L)
  164283. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164284. emit_byte(cinfo, cinfo->data_precision);
  164285. emit_2bytes(cinfo, (int) cinfo->image_height);
  164286. emit_2bytes(cinfo, (int) cinfo->image_width);
  164287. emit_byte(cinfo, cinfo->num_components);
  164288. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164289. ci++, compptr++) {
  164290. emit_byte(cinfo, compptr->component_id);
  164291. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164292. emit_byte(cinfo, compptr->quant_tbl_no);
  164293. }
  164294. }
  164295. LOCAL(void)
  164296. emit_sos (j_compress_ptr cinfo)
  164297. /* Emit a SOS marker */
  164298. {
  164299. int i, td, ta;
  164300. jpeg_component_info *compptr;
  164301. emit_marker(cinfo, M_SOS);
  164302. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164303. emit_byte(cinfo, cinfo->comps_in_scan);
  164304. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164305. compptr = cinfo->cur_comp_info[i];
  164306. emit_byte(cinfo, compptr->component_id);
  164307. td = compptr->dc_tbl_no;
  164308. ta = compptr->ac_tbl_no;
  164309. if (cinfo->progressive_mode) {
  164310. /* Progressive mode: only DC or only AC tables are used in one scan;
  164311. * furthermore, Huffman coding of DC refinement uses no table at all.
  164312. * We emit 0 for unused field(s); this is recommended by the P&M text
  164313. * but does not seem to be specified in the standard.
  164314. */
  164315. if (cinfo->Ss == 0) {
  164316. ta = 0; /* DC scan */
  164317. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164318. td = 0; /* no DC table either */
  164319. } else {
  164320. td = 0; /* AC scan */
  164321. }
  164322. }
  164323. emit_byte(cinfo, (td << 4) + ta);
  164324. }
  164325. emit_byte(cinfo, cinfo->Ss);
  164326. emit_byte(cinfo, cinfo->Se);
  164327. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164328. }
  164329. LOCAL(void)
  164330. emit_jfif_app0 (j_compress_ptr cinfo)
  164331. /* Emit a JFIF-compliant APP0 marker */
  164332. {
  164333. /*
  164334. * Length of APP0 block (2 bytes)
  164335. * Block ID (4 bytes - ASCII "JFIF")
  164336. * Zero byte (1 byte to terminate the ID string)
  164337. * Version Major, Minor (2 bytes - major first)
  164338. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164339. * Xdpu (2 bytes - dots per unit horizontal)
  164340. * Ydpu (2 bytes - dots per unit vertical)
  164341. * Thumbnail X size (1 byte)
  164342. * Thumbnail Y size (1 byte)
  164343. */
  164344. emit_marker(cinfo, M_APP0);
  164345. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164346. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164347. emit_byte(cinfo, 0x46);
  164348. emit_byte(cinfo, 0x49);
  164349. emit_byte(cinfo, 0x46);
  164350. emit_byte(cinfo, 0);
  164351. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164352. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164353. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164354. emit_2bytes(cinfo, (int) cinfo->X_density);
  164355. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164356. emit_byte(cinfo, 0); /* No thumbnail image */
  164357. emit_byte(cinfo, 0);
  164358. }
  164359. LOCAL(void)
  164360. emit_adobe_app14 (j_compress_ptr cinfo)
  164361. /* Emit an Adobe APP14 marker */
  164362. {
  164363. /*
  164364. * Length of APP14 block (2 bytes)
  164365. * Block ID (5 bytes - ASCII "Adobe")
  164366. * Version Number (2 bytes - currently 100)
  164367. * Flags0 (2 bytes - currently 0)
  164368. * Flags1 (2 bytes - currently 0)
  164369. * Color transform (1 byte)
  164370. *
  164371. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164372. * now in circulation seem to use Version = 100, so that's what we write.
  164373. *
  164374. * We write the color transform byte as 1 if the JPEG color space is
  164375. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164376. * whether the encoder performed a transformation, which is pretty useless.
  164377. */
  164378. emit_marker(cinfo, M_APP14);
  164379. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164380. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164381. emit_byte(cinfo, 0x64);
  164382. emit_byte(cinfo, 0x6F);
  164383. emit_byte(cinfo, 0x62);
  164384. emit_byte(cinfo, 0x65);
  164385. emit_2bytes(cinfo, 100); /* Version */
  164386. emit_2bytes(cinfo, 0); /* Flags0 */
  164387. emit_2bytes(cinfo, 0); /* Flags1 */
  164388. switch (cinfo->jpeg_color_space) {
  164389. case JCS_YCbCr:
  164390. emit_byte(cinfo, 1); /* Color transform = 1 */
  164391. break;
  164392. case JCS_YCCK:
  164393. emit_byte(cinfo, 2); /* Color transform = 2 */
  164394. break;
  164395. default:
  164396. emit_byte(cinfo, 0); /* Color transform = 0 */
  164397. break;
  164398. }
  164399. }
  164400. /*
  164401. * These routines allow writing an arbitrary marker with parameters.
  164402. * The only intended use is to emit COM or APPn markers after calling
  164403. * write_file_header and before calling write_frame_header.
  164404. * Other uses are not guaranteed to produce desirable results.
  164405. * Counting the parameter bytes properly is the caller's responsibility.
  164406. */
  164407. METHODDEF(void)
  164408. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164409. /* Emit an arbitrary marker header */
  164410. {
  164411. if (datalen > (unsigned int) 65533) /* safety check */
  164412. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164413. emit_marker(cinfo, (JPEG_MARKER) marker);
  164414. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164415. }
  164416. METHODDEF(void)
  164417. write_marker_byte (j_compress_ptr cinfo, int val)
  164418. /* Emit one byte of marker parameters following write_marker_header */
  164419. {
  164420. emit_byte(cinfo, val);
  164421. }
  164422. /*
  164423. * Write datastream header.
  164424. * This consists of an SOI and optional APPn markers.
  164425. * We recommend use of the JFIF marker, but not the Adobe marker,
  164426. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164427. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164428. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164429. * Note that an application can write additional header markers after
  164430. * jpeg_start_compress returns.
  164431. */
  164432. METHODDEF(void)
  164433. write_file_header (j_compress_ptr cinfo)
  164434. {
  164435. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164436. emit_marker(cinfo, M_SOI); /* first the SOI */
  164437. /* SOI is defined to reset restart interval to 0 */
  164438. marker->last_restart_interval = 0;
  164439. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164440. emit_jfif_app0(cinfo);
  164441. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164442. emit_adobe_app14(cinfo);
  164443. }
  164444. /*
  164445. * Write frame header.
  164446. * This consists of DQT and SOFn markers.
  164447. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164448. * This avoids compatibility problems with incorrect implementations that
  164449. * try to error-check the quant table numbers as soon as they see the SOF.
  164450. */
  164451. METHODDEF(void)
  164452. write_frame_header (j_compress_ptr cinfo)
  164453. {
  164454. int ci, prec;
  164455. boolean is_baseline;
  164456. jpeg_component_info *compptr;
  164457. /* Emit DQT for each quantization table.
  164458. * Note that emit_dqt() suppresses any duplicate tables.
  164459. */
  164460. prec = 0;
  164461. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164462. ci++, compptr++) {
  164463. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164464. }
  164465. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164466. /* Check for a non-baseline specification.
  164467. * Note we assume that Huffman table numbers won't be changed later.
  164468. */
  164469. if (cinfo->arith_code || cinfo->progressive_mode ||
  164470. cinfo->data_precision != 8) {
  164471. is_baseline = FALSE;
  164472. } else {
  164473. is_baseline = TRUE;
  164474. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164475. ci++, compptr++) {
  164476. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164477. is_baseline = FALSE;
  164478. }
  164479. if (prec && is_baseline) {
  164480. is_baseline = FALSE;
  164481. /* If it's baseline except for quantizer size, warn the user */
  164482. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164483. }
  164484. }
  164485. /* Emit the proper SOF marker */
  164486. if (cinfo->arith_code) {
  164487. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164488. } else {
  164489. if (cinfo->progressive_mode)
  164490. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164491. else if (is_baseline)
  164492. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164493. else
  164494. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164495. }
  164496. }
  164497. /*
  164498. * Write scan header.
  164499. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164500. * Compressed data will be written following the SOS.
  164501. */
  164502. METHODDEF(void)
  164503. write_scan_header (j_compress_ptr cinfo)
  164504. {
  164505. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164506. int i;
  164507. jpeg_component_info *compptr;
  164508. if (cinfo->arith_code) {
  164509. /* Emit arith conditioning info. We may have some duplication
  164510. * if the file has multiple scans, but it's so small it's hardly
  164511. * worth worrying about.
  164512. */
  164513. emit_dac(cinfo);
  164514. } else {
  164515. /* Emit Huffman tables.
  164516. * Note that emit_dht() suppresses any duplicate tables.
  164517. */
  164518. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164519. compptr = cinfo->cur_comp_info[i];
  164520. if (cinfo->progressive_mode) {
  164521. /* Progressive mode: only DC or only AC tables are used in one scan */
  164522. if (cinfo->Ss == 0) {
  164523. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164524. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164525. } else {
  164526. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164527. }
  164528. } else {
  164529. /* Sequential mode: need both DC and AC tables */
  164530. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164531. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164532. }
  164533. }
  164534. }
  164535. /* Emit DRI if required --- note that DRI value could change for each scan.
  164536. * We avoid wasting space with unnecessary DRIs, however.
  164537. */
  164538. if (cinfo->restart_interval != marker->last_restart_interval) {
  164539. emit_dri(cinfo);
  164540. marker->last_restart_interval = cinfo->restart_interval;
  164541. }
  164542. emit_sos(cinfo);
  164543. }
  164544. /*
  164545. * Write datastream trailer.
  164546. */
  164547. METHODDEF(void)
  164548. write_file_trailer (j_compress_ptr cinfo)
  164549. {
  164550. emit_marker(cinfo, M_EOI);
  164551. }
  164552. /*
  164553. * Write an abbreviated table-specification datastream.
  164554. * This consists of SOI, DQT and DHT tables, and EOI.
  164555. * Any table that is defined and not marked sent_table = TRUE will be
  164556. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164557. */
  164558. METHODDEF(void)
  164559. write_tables_only (j_compress_ptr cinfo)
  164560. {
  164561. int i;
  164562. emit_marker(cinfo, M_SOI);
  164563. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164564. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164565. (void) emit_dqt(cinfo, i);
  164566. }
  164567. if (! cinfo->arith_code) {
  164568. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164569. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164570. emit_dht(cinfo, i, FALSE);
  164571. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164572. emit_dht(cinfo, i, TRUE);
  164573. }
  164574. }
  164575. emit_marker(cinfo, M_EOI);
  164576. }
  164577. /*
  164578. * Initialize the marker writer module.
  164579. */
  164580. GLOBAL(void)
  164581. jinit_marker_writer (j_compress_ptr cinfo)
  164582. {
  164583. my_marker_ptr marker;
  164584. /* Create the subobject */
  164585. marker = (my_marker_ptr)
  164586. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164587. SIZEOF(my_marker_writer));
  164588. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164589. /* Initialize method pointers */
  164590. marker->pub.write_file_header = write_file_header;
  164591. marker->pub.write_frame_header = write_frame_header;
  164592. marker->pub.write_scan_header = write_scan_header;
  164593. marker->pub.write_file_trailer = write_file_trailer;
  164594. marker->pub.write_tables_only = write_tables_only;
  164595. marker->pub.write_marker_header = write_marker_header;
  164596. marker->pub.write_marker_byte = write_marker_byte;
  164597. /* Initialize private state */
  164598. marker->last_restart_interval = 0;
  164599. }
  164600. /*** End of inlined file: jcmarker.c ***/
  164601. /*** Start of inlined file: jcmaster.c ***/
  164602. #define JPEG_INTERNALS
  164603. /* Private state */
  164604. typedef enum {
  164605. main_pass, /* input data, also do first output step */
  164606. huff_opt_pass, /* Huffman code optimization pass */
  164607. output_pass /* data output pass */
  164608. } c_pass_type;
  164609. typedef struct {
  164610. struct jpeg_comp_master pub; /* public fields */
  164611. c_pass_type pass_type; /* the type of the current pass */
  164612. int pass_number; /* # of passes completed */
  164613. int total_passes; /* total # of passes needed */
  164614. int scan_number; /* current index in scan_info[] */
  164615. } my_comp_master;
  164616. typedef my_comp_master * my_master_ptr;
  164617. /*
  164618. * Support routines that do various essential calculations.
  164619. */
  164620. LOCAL(void)
  164621. initial_setup (j_compress_ptr cinfo)
  164622. /* Do computations that are needed before master selection phase */
  164623. {
  164624. int ci;
  164625. jpeg_component_info *compptr;
  164626. long samplesperrow;
  164627. JDIMENSION jd_samplesperrow;
  164628. /* Sanity check on image dimensions */
  164629. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164630. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164631. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164632. /* Make sure image isn't bigger than I can handle */
  164633. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164634. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164635. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164636. /* Width of an input scanline must be representable as JDIMENSION. */
  164637. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164638. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164639. if ((long) jd_samplesperrow != samplesperrow)
  164640. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164641. /* For now, precision must match compiled-in value... */
  164642. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164643. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164644. /* Check that number of components won't exceed internal array sizes */
  164645. if (cinfo->num_components > MAX_COMPONENTS)
  164646. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164647. MAX_COMPONENTS);
  164648. /* Compute maximum sampling factors; check factor validity */
  164649. cinfo->max_h_samp_factor = 1;
  164650. cinfo->max_v_samp_factor = 1;
  164651. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164652. ci++, compptr++) {
  164653. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164654. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164655. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164656. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164657. compptr->h_samp_factor);
  164658. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164659. compptr->v_samp_factor);
  164660. }
  164661. /* Compute dimensions of components */
  164662. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164663. ci++, compptr++) {
  164664. /* Fill in the correct component_index value; don't rely on application */
  164665. compptr->component_index = ci;
  164666. /* For compression, we never do DCT scaling. */
  164667. compptr->DCT_scaled_size = DCTSIZE;
  164668. /* Size in DCT blocks */
  164669. compptr->width_in_blocks = (JDIMENSION)
  164670. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164671. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164672. compptr->height_in_blocks = (JDIMENSION)
  164673. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164674. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164675. /* Size in samples */
  164676. compptr->downsampled_width = (JDIMENSION)
  164677. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164678. (long) cinfo->max_h_samp_factor);
  164679. compptr->downsampled_height = (JDIMENSION)
  164680. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164681. (long) cinfo->max_v_samp_factor);
  164682. /* Mark component needed (this flag isn't actually used for compression) */
  164683. compptr->component_needed = TRUE;
  164684. }
  164685. /* Compute number of fully interleaved MCU rows (number of times that
  164686. * main controller will call coefficient controller).
  164687. */
  164688. cinfo->total_iMCU_rows = (JDIMENSION)
  164689. jdiv_round_up((long) cinfo->image_height,
  164690. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164691. }
  164692. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164693. LOCAL(void)
  164694. validate_script (j_compress_ptr cinfo)
  164695. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164696. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164697. */
  164698. {
  164699. const jpeg_scan_info * scanptr;
  164700. int scanno, ncomps, ci, coefi, thisi;
  164701. int Ss, Se, Ah, Al;
  164702. boolean component_sent[MAX_COMPONENTS];
  164703. #ifdef C_PROGRESSIVE_SUPPORTED
  164704. int * last_bitpos_ptr;
  164705. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164706. /* -1 until that coefficient has been seen; then last Al for it */
  164707. #endif
  164708. if (cinfo->num_scans <= 0)
  164709. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164710. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164711. * for progressive JPEG, no scan can have this.
  164712. */
  164713. scanptr = cinfo->scan_info;
  164714. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164715. #ifdef C_PROGRESSIVE_SUPPORTED
  164716. cinfo->progressive_mode = TRUE;
  164717. last_bitpos_ptr = & last_bitpos[0][0];
  164718. for (ci = 0; ci < cinfo->num_components; ci++)
  164719. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164720. *last_bitpos_ptr++ = -1;
  164721. #else
  164722. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164723. #endif
  164724. } else {
  164725. cinfo->progressive_mode = FALSE;
  164726. for (ci = 0; ci < cinfo->num_components; ci++)
  164727. component_sent[ci] = FALSE;
  164728. }
  164729. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164730. /* Validate component indexes */
  164731. ncomps = scanptr->comps_in_scan;
  164732. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164733. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164734. for (ci = 0; ci < ncomps; ci++) {
  164735. thisi = scanptr->component_index[ci];
  164736. if (thisi < 0 || thisi >= cinfo->num_components)
  164737. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164738. /* Components must appear in SOF order within each scan */
  164739. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164740. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164741. }
  164742. /* Validate progression parameters */
  164743. Ss = scanptr->Ss;
  164744. Se = scanptr->Se;
  164745. Ah = scanptr->Ah;
  164746. Al = scanptr->Al;
  164747. if (cinfo->progressive_mode) {
  164748. #ifdef C_PROGRESSIVE_SUPPORTED
  164749. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164750. * seems wrong: the upper bound ought to depend on data precision.
  164751. * Perhaps they really meant 0..N+1 for N-bit precision.
  164752. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164753. * out-of-range reconstructed DC values during the first DC scan,
  164754. * which might cause problems for some decoders.
  164755. */
  164756. #if BITS_IN_JSAMPLE == 8
  164757. #define MAX_AH_AL 10
  164758. #else
  164759. #define MAX_AH_AL 13
  164760. #endif
  164761. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164762. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164763. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164764. if (Ss == 0) {
  164765. if (Se != 0) /* DC and AC together not OK */
  164766. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164767. } else {
  164768. if (ncomps != 1) /* AC scans must be for only one component */
  164769. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164770. }
  164771. for (ci = 0; ci < ncomps; ci++) {
  164772. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164773. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164774. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164775. for (coefi = Ss; coefi <= Se; coefi++) {
  164776. if (last_bitpos_ptr[coefi] < 0) {
  164777. /* first scan of this coefficient */
  164778. if (Ah != 0)
  164779. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164780. } else {
  164781. /* not first scan */
  164782. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164783. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164784. }
  164785. last_bitpos_ptr[coefi] = Al;
  164786. }
  164787. }
  164788. #endif
  164789. } else {
  164790. /* For sequential JPEG, all progression parameters must be these: */
  164791. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164792. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164793. /* Make sure components are not sent twice */
  164794. for (ci = 0; ci < ncomps; ci++) {
  164795. thisi = scanptr->component_index[ci];
  164796. if (component_sent[thisi])
  164797. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164798. component_sent[thisi] = TRUE;
  164799. }
  164800. }
  164801. }
  164802. /* Now verify that everything got sent. */
  164803. if (cinfo->progressive_mode) {
  164804. #ifdef C_PROGRESSIVE_SUPPORTED
  164805. /* For progressive mode, we only check that at least some DC data
  164806. * got sent for each component; the spec does not require that all bits
  164807. * of all coefficients be transmitted. Would it be wiser to enforce
  164808. * transmission of all coefficient bits??
  164809. */
  164810. for (ci = 0; ci < cinfo->num_components; ci++) {
  164811. if (last_bitpos[ci][0] < 0)
  164812. ERREXIT(cinfo, JERR_MISSING_DATA);
  164813. }
  164814. #endif
  164815. } else {
  164816. for (ci = 0; ci < cinfo->num_components; ci++) {
  164817. if (! component_sent[ci])
  164818. ERREXIT(cinfo, JERR_MISSING_DATA);
  164819. }
  164820. }
  164821. }
  164822. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164823. LOCAL(void)
  164824. select_scan_parameters (j_compress_ptr cinfo)
  164825. /* Set up the scan parameters for the current scan */
  164826. {
  164827. int ci;
  164828. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164829. if (cinfo->scan_info != NULL) {
  164830. /* Prepare for current scan --- the script is already validated */
  164831. my_master_ptr master = (my_master_ptr) cinfo->master;
  164832. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164833. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164834. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164835. cinfo->cur_comp_info[ci] =
  164836. &cinfo->comp_info[scanptr->component_index[ci]];
  164837. }
  164838. cinfo->Ss = scanptr->Ss;
  164839. cinfo->Se = scanptr->Se;
  164840. cinfo->Ah = scanptr->Ah;
  164841. cinfo->Al = scanptr->Al;
  164842. }
  164843. else
  164844. #endif
  164845. {
  164846. /* Prepare for single sequential-JPEG scan containing all components */
  164847. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164848. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164849. MAX_COMPS_IN_SCAN);
  164850. cinfo->comps_in_scan = cinfo->num_components;
  164851. for (ci = 0; ci < cinfo->num_components; ci++) {
  164852. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164853. }
  164854. cinfo->Ss = 0;
  164855. cinfo->Se = DCTSIZE2-1;
  164856. cinfo->Ah = 0;
  164857. cinfo->Al = 0;
  164858. }
  164859. }
  164860. LOCAL(void)
  164861. per_scan_setup (j_compress_ptr cinfo)
  164862. /* Do computations that are needed before processing a JPEG scan */
  164863. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164864. {
  164865. int ci, mcublks, tmp;
  164866. jpeg_component_info *compptr;
  164867. if (cinfo->comps_in_scan == 1) {
  164868. /* Noninterleaved (single-component) scan */
  164869. compptr = cinfo->cur_comp_info[0];
  164870. /* Overall image size in MCUs */
  164871. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164872. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164873. /* For noninterleaved scan, always one block per MCU */
  164874. compptr->MCU_width = 1;
  164875. compptr->MCU_height = 1;
  164876. compptr->MCU_blocks = 1;
  164877. compptr->MCU_sample_width = DCTSIZE;
  164878. compptr->last_col_width = 1;
  164879. /* For noninterleaved scans, it is convenient to define last_row_height
  164880. * as the number of block rows present in the last iMCU row.
  164881. */
  164882. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164883. if (tmp == 0) tmp = compptr->v_samp_factor;
  164884. compptr->last_row_height = tmp;
  164885. /* Prepare array describing MCU composition */
  164886. cinfo->blocks_in_MCU = 1;
  164887. cinfo->MCU_membership[0] = 0;
  164888. } else {
  164889. /* Interleaved (multi-component) scan */
  164890. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164891. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164892. MAX_COMPS_IN_SCAN);
  164893. /* Overall image size in MCUs */
  164894. cinfo->MCUs_per_row = (JDIMENSION)
  164895. jdiv_round_up((long) cinfo->image_width,
  164896. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164897. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164898. jdiv_round_up((long) cinfo->image_height,
  164899. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164900. cinfo->blocks_in_MCU = 0;
  164901. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164902. compptr = cinfo->cur_comp_info[ci];
  164903. /* Sampling factors give # of blocks of component in each MCU */
  164904. compptr->MCU_width = compptr->h_samp_factor;
  164905. compptr->MCU_height = compptr->v_samp_factor;
  164906. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164907. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164908. /* Figure number of non-dummy blocks in last MCU column & row */
  164909. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164910. if (tmp == 0) tmp = compptr->MCU_width;
  164911. compptr->last_col_width = tmp;
  164912. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164913. if (tmp == 0) tmp = compptr->MCU_height;
  164914. compptr->last_row_height = tmp;
  164915. /* Prepare array describing MCU composition */
  164916. mcublks = compptr->MCU_blocks;
  164917. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164918. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164919. while (mcublks-- > 0) {
  164920. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164921. }
  164922. }
  164923. }
  164924. /* Convert restart specified in rows to actual MCU count. */
  164925. /* Note that count must fit in 16 bits, so we provide limiting. */
  164926. if (cinfo->restart_in_rows > 0) {
  164927. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164928. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164929. }
  164930. }
  164931. /*
  164932. * Per-pass setup.
  164933. * This is called at the beginning of each pass. We determine which modules
  164934. * will be active during this pass and give them appropriate start_pass calls.
  164935. * We also set is_last_pass to indicate whether any more passes will be
  164936. * required.
  164937. */
  164938. METHODDEF(void)
  164939. prepare_for_pass (j_compress_ptr cinfo)
  164940. {
  164941. my_master_ptr master = (my_master_ptr) cinfo->master;
  164942. switch (master->pass_type) {
  164943. case main_pass:
  164944. /* Initial pass: will collect input data, and do either Huffman
  164945. * optimization or data output for the first scan.
  164946. */
  164947. select_scan_parameters(cinfo);
  164948. per_scan_setup(cinfo);
  164949. if (! cinfo->raw_data_in) {
  164950. (*cinfo->cconvert->start_pass) (cinfo);
  164951. (*cinfo->downsample->start_pass) (cinfo);
  164952. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164953. }
  164954. (*cinfo->fdct->start_pass) (cinfo);
  164955. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164956. (*cinfo->coef->start_pass) (cinfo,
  164957. (master->total_passes > 1 ?
  164958. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164959. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164960. if (cinfo->optimize_coding) {
  164961. /* No immediate data output; postpone writing frame/scan headers */
  164962. master->pub.call_pass_startup = FALSE;
  164963. } else {
  164964. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164965. master->pub.call_pass_startup = TRUE;
  164966. }
  164967. break;
  164968. #ifdef ENTROPY_OPT_SUPPORTED
  164969. case huff_opt_pass:
  164970. /* Do Huffman optimization for a scan after the first one. */
  164971. select_scan_parameters(cinfo);
  164972. per_scan_setup(cinfo);
  164973. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164974. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164975. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164976. master->pub.call_pass_startup = FALSE;
  164977. break;
  164978. }
  164979. /* Special case: Huffman DC refinement scans need no Huffman table
  164980. * and therefore we can skip the optimization pass for them.
  164981. */
  164982. master->pass_type = output_pass;
  164983. master->pass_number++;
  164984. /*FALLTHROUGH*/
  164985. #endif
  164986. case output_pass:
  164987. /* Do a data-output pass. */
  164988. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164989. if (! cinfo->optimize_coding) {
  164990. select_scan_parameters(cinfo);
  164991. per_scan_setup(cinfo);
  164992. }
  164993. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164994. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164995. /* We emit frame/scan headers now */
  164996. if (master->scan_number == 0)
  164997. (*cinfo->marker->write_frame_header) (cinfo);
  164998. (*cinfo->marker->write_scan_header) (cinfo);
  164999. master->pub.call_pass_startup = FALSE;
  165000. break;
  165001. default:
  165002. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165003. }
  165004. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165005. /* Set up progress monitor's pass info if present */
  165006. if (cinfo->progress != NULL) {
  165007. cinfo->progress->completed_passes = master->pass_number;
  165008. cinfo->progress->total_passes = master->total_passes;
  165009. }
  165010. }
  165011. /*
  165012. * Special start-of-pass hook.
  165013. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165014. * In single-pass processing, we need this hook because we don't want to
  165015. * write frame/scan headers during jpeg_start_compress; we want to let the
  165016. * application write COM markers etc. between jpeg_start_compress and the
  165017. * jpeg_write_scanlines loop.
  165018. * In multi-pass processing, this routine is not used.
  165019. */
  165020. METHODDEF(void)
  165021. pass_startup (j_compress_ptr cinfo)
  165022. {
  165023. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165024. (*cinfo->marker->write_frame_header) (cinfo);
  165025. (*cinfo->marker->write_scan_header) (cinfo);
  165026. }
  165027. /*
  165028. * Finish up at end of pass.
  165029. */
  165030. METHODDEF(void)
  165031. finish_pass_master (j_compress_ptr cinfo)
  165032. {
  165033. my_master_ptr master = (my_master_ptr) cinfo->master;
  165034. /* The entropy coder always needs an end-of-pass call,
  165035. * either to analyze statistics or to flush its output buffer.
  165036. */
  165037. (*cinfo->entropy->finish_pass) (cinfo);
  165038. /* Update state for next pass */
  165039. switch (master->pass_type) {
  165040. case main_pass:
  165041. /* next pass is either output of scan 0 (after optimization)
  165042. * or output of scan 1 (if no optimization).
  165043. */
  165044. master->pass_type = output_pass;
  165045. if (! cinfo->optimize_coding)
  165046. master->scan_number++;
  165047. break;
  165048. case huff_opt_pass:
  165049. /* next pass is always output of current scan */
  165050. master->pass_type = output_pass;
  165051. break;
  165052. case output_pass:
  165053. /* next pass is either optimization or output of next scan */
  165054. if (cinfo->optimize_coding)
  165055. master->pass_type = huff_opt_pass;
  165056. master->scan_number++;
  165057. break;
  165058. }
  165059. master->pass_number++;
  165060. }
  165061. /*
  165062. * Initialize master compression control.
  165063. */
  165064. GLOBAL(void)
  165065. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165066. {
  165067. my_master_ptr master;
  165068. master = (my_master_ptr)
  165069. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165070. SIZEOF(my_comp_master));
  165071. cinfo->master = (struct jpeg_comp_master *) master;
  165072. master->pub.prepare_for_pass = prepare_for_pass;
  165073. master->pub.pass_startup = pass_startup;
  165074. master->pub.finish_pass = finish_pass_master;
  165075. master->pub.is_last_pass = FALSE;
  165076. /* Validate parameters, determine derived values */
  165077. initial_setup(cinfo);
  165078. if (cinfo->scan_info != NULL) {
  165079. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165080. validate_script(cinfo);
  165081. #else
  165082. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165083. #endif
  165084. } else {
  165085. cinfo->progressive_mode = FALSE;
  165086. cinfo->num_scans = 1;
  165087. }
  165088. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165089. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165090. /* Initialize my private state */
  165091. if (transcode_only) {
  165092. /* no main pass in transcoding */
  165093. if (cinfo->optimize_coding)
  165094. master->pass_type = huff_opt_pass;
  165095. else
  165096. master->pass_type = output_pass;
  165097. } else {
  165098. /* for normal compression, first pass is always this type: */
  165099. master->pass_type = main_pass;
  165100. }
  165101. master->scan_number = 0;
  165102. master->pass_number = 0;
  165103. if (cinfo->optimize_coding)
  165104. master->total_passes = cinfo->num_scans * 2;
  165105. else
  165106. master->total_passes = cinfo->num_scans;
  165107. }
  165108. /*** End of inlined file: jcmaster.c ***/
  165109. /*** Start of inlined file: jcomapi.c ***/
  165110. #define JPEG_INTERNALS
  165111. /*
  165112. * Abort processing of a JPEG compression or decompression operation,
  165113. * but don't destroy the object itself.
  165114. *
  165115. * For this, we merely clean up all the nonpermanent memory pools.
  165116. * Note that temp files (virtual arrays) are not allowed to belong to
  165117. * the permanent pool, so we will be able to close all temp files here.
  165118. * Closing a data source or destination, if necessary, is the application's
  165119. * responsibility.
  165120. */
  165121. GLOBAL(void)
  165122. jpeg_abort (j_common_ptr cinfo)
  165123. {
  165124. int pool;
  165125. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165126. if (cinfo->mem == NULL)
  165127. return;
  165128. /* Releasing pools in reverse order might help avoid fragmentation
  165129. * with some (brain-damaged) malloc libraries.
  165130. */
  165131. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165132. (*cinfo->mem->free_pool) (cinfo, pool);
  165133. }
  165134. /* Reset overall state for possible reuse of object */
  165135. if (cinfo->is_decompressor) {
  165136. cinfo->global_state = DSTATE_START;
  165137. /* Try to keep application from accessing now-deleted marker list.
  165138. * A bit kludgy to do it here, but this is the most central place.
  165139. */
  165140. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165141. } else {
  165142. cinfo->global_state = CSTATE_START;
  165143. }
  165144. }
  165145. /*
  165146. * Destruction of a JPEG object.
  165147. *
  165148. * Everything gets deallocated except the master jpeg_compress_struct itself
  165149. * and the error manager struct. Both of these are supplied by the application
  165150. * and must be freed, if necessary, by the application. (Often they are on
  165151. * the stack and so don't need to be freed anyway.)
  165152. * Closing a data source or destination, if necessary, is the application's
  165153. * responsibility.
  165154. */
  165155. GLOBAL(void)
  165156. jpeg_destroy (j_common_ptr cinfo)
  165157. {
  165158. /* We need only tell the memory manager to release everything. */
  165159. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165160. if (cinfo->mem != NULL)
  165161. (*cinfo->mem->self_destruct) (cinfo);
  165162. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165163. cinfo->global_state = 0; /* mark it destroyed */
  165164. }
  165165. /*
  165166. * Convenience routines for allocating quantization and Huffman tables.
  165167. * (Would jutils.c be a more reasonable place to put these?)
  165168. */
  165169. GLOBAL(JQUANT_TBL *)
  165170. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165171. {
  165172. JQUANT_TBL *tbl;
  165173. tbl = (JQUANT_TBL *)
  165174. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165175. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165176. return tbl;
  165177. }
  165178. GLOBAL(JHUFF_TBL *)
  165179. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165180. {
  165181. JHUFF_TBL *tbl;
  165182. tbl = (JHUFF_TBL *)
  165183. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165184. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165185. return tbl;
  165186. }
  165187. /*** End of inlined file: jcomapi.c ***/
  165188. /*** Start of inlined file: jcparam.c ***/
  165189. #define JPEG_INTERNALS
  165190. /*
  165191. * Quantization table setup routines
  165192. */
  165193. GLOBAL(void)
  165194. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165195. const unsigned int *basic_table,
  165196. int scale_factor, boolean force_baseline)
  165197. /* Define a quantization table equal to the basic_table times
  165198. * a scale factor (given as a percentage).
  165199. * If force_baseline is TRUE, the computed quantization table entries
  165200. * are limited to 1..255 for JPEG baseline compatibility.
  165201. */
  165202. {
  165203. JQUANT_TBL ** qtblptr;
  165204. int i;
  165205. long temp;
  165206. /* Safety check to ensure start_compress not called yet. */
  165207. if (cinfo->global_state != CSTATE_START)
  165208. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165209. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165210. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165211. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165212. if (*qtblptr == NULL)
  165213. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165214. for (i = 0; i < DCTSIZE2; i++) {
  165215. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165216. /* limit the values to the valid range */
  165217. if (temp <= 0L) temp = 1L;
  165218. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165219. if (force_baseline && temp > 255L)
  165220. temp = 255L; /* limit to baseline range if requested */
  165221. (*qtblptr)->quantval[i] = (UINT16) temp;
  165222. }
  165223. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165224. (*qtblptr)->sent_table = FALSE;
  165225. }
  165226. GLOBAL(void)
  165227. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165228. boolean force_baseline)
  165229. /* Set or change the 'quality' (quantization) setting, using default tables
  165230. * and a straight percentage-scaling quality scale. In most cases it's better
  165231. * to use jpeg_set_quality (below); this entry point is provided for
  165232. * applications that insist on a linear percentage scaling.
  165233. */
  165234. {
  165235. /* These are the sample quantization tables given in JPEG spec section K.1.
  165236. * The spec says that the values given produce "good" quality, and
  165237. * when divided by 2, "very good" quality.
  165238. */
  165239. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165240. 16, 11, 10, 16, 24, 40, 51, 61,
  165241. 12, 12, 14, 19, 26, 58, 60, 55,
  165242. 14, 13, 16, 24, 40, 57, 69, 56,
  165243. 14, 17, 22, 29, 51, 87, 80, 62,
  165244. 18, 22, 37, 56, 68, 109, 103, 77,
  165245. 24, 35, 55, 64, 81, 104, 113, 92,
  165246. 49, 64, 78, 87, 103, 121, 120, 101,
  165247. 72, 92, 95, 98, 112, 100, 103, 99
  165248. };
  165249. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165250. 17, 18, 24, 47, 99, 99, 99, 99,
  165251. 18, 21, 26, 66, 99, 99, 99, 99,
  165252. 24, 26, 56, 99, 99, 99, 99, 99,
  165253. 47, 66, 99, 99, 99, 99, 99, 99,
  165254. 99, 99, 99, 99, 99, 99, 99, 99,
  165255. 99, 99, 99, 99, 99, 99, 99, 99,
  165256. 99, 99, 99, 99, 99, 99, 99, 99,
  165257. 99, 99, 99, 99, 99, 99, 99, 99
  165258. };
  165259. /* Set up two quantization tables using the specified scaling */
  165260. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165261. scale_factor, force_baseline);
  165262. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165263. scale_factor, force_baseline);
  165264. }
  165265. GLOBAL(int)
  165266. jpeg_quality_scaling (int quality)
  165267. /* Convert a user-specified quality rating to a percentage scaling factor
  165268. * for an underlying quantization table, using our recommended scaling curve.
  165269. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165270. */
  165271. {
  165272. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165273. if (quality <= 0) quality = 1;
  165274. if (quality > 100) quality = 100;
  165275. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165276. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165277. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165278. * to make all the table entries 1 (hence, minimum quantization loss).
  165279. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165280. */
  165281. if (quality < 50)
  165282. quality = 5000 / quality;
  165283. else
  165284. quality = 200 - quality*2;
  165285. return quality;
  165286. }
  165287. GLOBAL(void)
  165288. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165289. /* Set or change the 'quality' (quantization) setting, using default tables.
  165290. * This is the standard quality-adjusting entry point for typical user
  165291. * interfaces; only those who want detailed control over quantization tables
  165292. * would use the preceding three routines directly.
  165293. */
  165294. {
  165295. /* Convert user 0-100 rating to percentage scaling */
  165296. quality = jpeg_quality_scaling(quality);
  165297. /* Set up standard quality tables */
  165298. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165299. }
  165300. /*
  165301. * Huffman table setup routines
  165302. */
  165303. LOCAL(void)
  165304. add_huff_table (j_compress_ptr cinfo,
  165305. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165306. /* Define a Huffman table */
  165307. {
  165308. int nsymbols, len;
  165309. if (*htblptr == NULL)
  165310. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165311. /* Copy the number-of-symbols-of-each-code-length counts */
  165312. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165313. /* Validate the counts. We do this here mainly so we can copy the right
  165314. * number of symbols from the val[] array, without risking marching off
  165315. * the end of memory. jchuff.c will do a more thorough test later.
  165316. */
  165317. nsymbols = 0;
  165318. for (len = 1; len <= 16; len++)
  165319. nsymbols += bits[len];
  165320. if (nsymbols < 1 || nsymbols > 256)
  165321. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165322. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165323. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165324. (*htblptr)->sent_table = FALSE;
  165325. }
  165326. LOCAL(void)
  165327. std_huff_tables (j_compress_ptr cinfo)
  165328. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165329. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165330. {
  165331. static const UINT8 bits_dc_luminance[17] =
  165332. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165333. static const UINT8 val_dc_luminance[] =
  165334. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165335. static const UINT8 bits_dc_chrominance[17] =
  165336. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165337. static const UINT8 val_dc_chrominance[] =
  165338. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165339. static const UINT8 bits_ac_luminance[17] =
  165340. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165341. static const UINT8 val_ac_luminance[] =
  165342. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165343. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165344. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165345. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165346. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165347. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165348. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165349. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165350. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165351. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165352. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165353. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165354. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165355. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165356. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165357. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165358. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165359. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165360. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165361. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165362. 0xf9, 0xfa };
  165363. static const UINT8 bits_ac_chrominance[17] =
  165364. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165365. static const UINT8 val_ac_chrominance[] =
  165366. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165367. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165368. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165369. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165370. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165371. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165372. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165373. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165374. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165375. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165376. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165377. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165378. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165379. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165380. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165381. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165382. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165383. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165384. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165385. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165386. 0xf9, 0xfa };
  165387. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165388. bits_dc_luminance, val_dc_luminance);
  165389. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165390. bits_ac_luminance, val_ac_luminance);
  165391. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165392. bits_dc_chrominance, val_dc_chrominance);
  165393. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165394. bits_ac_chrominance, val_ac_chrominance);
  165395. }
  165396. /*
  165397. * Default parameter setup for compression.
  165398. *
  165399. * Applications that don't choose to use this routine must do their
  165400. * own setup of all these parameters. Alternately, you can call this
  165401. * to establish defaults and then alter parameters selectively. This
  165402. * is the recommended approach since, if we add any new parameters,
  165403. * your code will still work (they'll be set to reasonable defaults).
  165404. */
  165405. GLOBAL(void)
  165406. jpeg_set_defaults (j_compress_ptr cinfo)
  165407. {
  165408. int i;
  165409. /* Safety check to ensure start_compress not called yet. */
  165410. if (cinfo->global_state != CSTATE_START)
  165411. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165412. /* Allocate comp_info array large enough for maximum component count.
  165413. * Array is made permanent in case application wants to compress
  165414. * multiple images at same param settings.
  165415. */
  165416. if (cinfo->comp_info == NULL)
  165417. cinfo->comp_info = (jpeg_component_info *)
  165418. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165419. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165420. /* Initialize everything not dependent on the color space */
  165421. cinfo->data_precision = BITS_IN_JSAMPLE;
  165422. /* Set up two quantization tables using default quality of 75 */
  165423. jpeg_set_quality(cinfo, 75, TRUE);
  165424. /* Set up two Huffman tables */
  165425. std_huff_tables(cinfo);
  165426. /* Initialize default arithmetic coding conditioning */
  165427. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165428. cinfo->arith_dc_L[i] = 0;
  165429. cinfo->arith_dc_U[i] = 1;
  165430. cinfo->arith_ac_K[i] = 5;
  165431. }
  165432. /* Default is no multiple-scan output */
  165433. cinfo->scan_info = NULL;
  165434. cinfo->num_scans = 0;
  165435. /* Expect normal source image, not raw downsampled data */
  165436. cinfo->raw_data_in = FALSE;
  165437. /* Use Huffman coding, not arithmetic coding, by default */
  165438. cinfo->arith_code = FALSE;
  165439. /* By default, don't do extra passes to optimize entropy coding */
  165440. cinfo->optimize_coding = FALSE;
  165441. /* The standard Huffman tables are only valid for 8-bit data precision.
  165442. * If the precision is higher, force optimization on so that usable
  165443. * tables will be computed. This test can be removed if default tables
  165444. * are supplied that are valid for the desired precision.
  165445. */
  165446. if (cinfo->data_precision > 8)
  165447. cinfo->optimize_coding = TRUE;
  165448. /* By default, use the simpler non-cosited sampling alignment */
  165449. cinfo->CCIR601_sampling = FALSE;
  165450. /* No input smoothing */
  165451. cinfo->smoothing_factor = 0;
  165452. /* DCT algorithm preference */
  165453. cinfo->dct_method = JDCT_DEFAULT;
  165454. /* No restart markers */
  165455. cinfo->restart_interval = 0;
  165456. cinfo->restart_in_rows = 0;
  165457. /* Fill in default JFIF marker parameters. Note that whether the marker
  165458. * will actually be written is determined by jpeg_set_colorspace.
  165459. *
  165460. * By default, the library emits JFIF version code 1.01.
  165461. * An application that wants to emit JFIF 1.02 extension markers should set
  165462. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165463. * to 1.02, but there may still be some decoders in use that will complain
  165464. * about that; saying 1.01 should minimize compatibility problems.
  165465. */
  165466. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165467. cinfo->JFIF_minor_version = 1;
  165468. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165469. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165470. cinfo->Y_density = 1;
  165471. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165472. jpeg_default_colorspace(cinfo);
  165473. }
  165474. /*
  165475. * Select an appropriate JPEG colorspace for in_color_space.
  165476. */
  165477. GLOBAL(void)
  165478. jpeg_default_colorspace (j_compress_ptr cinfo)
  165479. {
  165480. switch (cinfo->in_color_space) {
  165481. case JCS_GRAYSCALE:
  165482. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165483. break;
  165484. case JCS_RGB:
  165485. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165486. break;
  165487. case JCS_YCbCr:
  165488. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165489. break;
  165490. case JCS_CMYK:
  165491. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165492. break;
  165493. case JCS_YCCK:
  165494. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165495. break;
  165496. case JCS_UNKNOWN:
  165497. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165498. break;
  165499. default:
  165500. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165501. }
  165502. }
  165503. /*
  165504. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165505. */
  165506. GLOBAL(void)
  165507. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165508. {
  165509. jpeg_component_info * compptr;
  165510. int ci;
  165511. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165512. (compptr = &cinfo->comp_info[index], \
  165513. compptr->component_id = (id), \
  165514. compptr->h_samp_factor = (hsamp), \
  165515. compptr->v_samp_factor = (vsamp), \
  165516. compptr->quant_tbl_no = (quant), \
  165517. compptr->dc_tbl_no = (dctbl), \
  165518. compptr->ac_tbl_no = (actbl) )
  165519. /* Safety check to ensure start_compress not called yet. */
  165520. if (cinfo->global_state != CSTATE_START)
  165521. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165522. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165523. * tables 1 for chrominance components.
  165524. */
  165525. cinfo->jpeg_color_space = colorspace;
  165526. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165527. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165528. switch (colorspace) {
  165529. case JCS_GRAYSCALE:
  165530. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165531. cinfo->num_components = 1;
  165532. /* JFIF specifies component ID 1 */
  165533. SET_COMP(0, 1, 1,1, 0, 0,0);
  165534. break;
  165535. case JCS_RGB:
  165536. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165537. cinfo->num_components = 3;
  165538. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165539. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165540. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165541. break;
  165542. case JCS_YCbCr:
  165543. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165544. cinfo->num_components = 3;
  165545. /* JFIF specifies component IDs 1,2,3 */
  165546. /* We default to 2x2 subsamples of chrominance */
  165547. SET_COMP(0, 1, 2,2, 0, 0,0);
  165548. SET_COMP(1, 2, 1,1, 1, 1,1);
  165549. SET_COMP(2, 3, 1,1, 1, 1,1);
  165550. break;
  165551. case JCS_CMYK:
  165552. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165553. cinfo->num_components = 4;
  165554. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165555. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165556. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165557. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165558. break;
  165559. case JCS_YCCK:
  165560. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165561. cinfo->num_components = 4;
  165562. SET_COMP(0, 1, 2,2, 0, 0,0);
  165563. SET_COMP(1, 2, 1,1, 1, 1,1);
  165564. SET_COMP(2, 3, 1,1, 1, 1,1);
  165565. SET_COMP(3, 4, 2,2, 0, 0,0);
  165566. break;
  165567. case JCS_UNKNOWN:
  165568. cinfo->num_components = cinfo->input_components;
  165569. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165570. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165571. MAX_COMPONENTS);
  165572. for (ci = 0; ci < cinfo->num_components; ci++) {
  165573. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165574. }
  165575. break;
  165576. default:
  165577. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165578. }
  165579. }
  165580. #ifdef C_PROGRESSIVE_SUPPORTED
  165581. LOCAL(jpeg_scan_info *)
  165582. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165583. int Ss, int Se, int Ah, int Al)
  165584. /* Support routine: generate one scan for specified component */
  165585. {
  165586. scanptr->comps_in_scan = 1;
  165587. scanptr->component_index[0] = ci;
  165588. scanptr->Ss = Ss;
  165589. scanptr->Se = Se;
  165590. scanptr->Ah = Ah;
  165591. scanptr->Al = Al;
  165592. scanptr++;
  165593. return scanptr;
  165594. }
  165595. LOCAL(jpeg_scan_info *)
  165596. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165597. int Ss, int Se, int Ah, int Al)
  165598. /* Support routine: generate one scan for each component */
  165599. {
  165600. int ci;
  165601. for (ci = 0; ci < ncomps; ci++) {
  165602. scanptr->comps_in_scan = 1;
  165603. scanptr->component_index[0] = ci;
  165604. scanptr->Ss = Ss;
  165605. scanptr->Se = Se;
  165606. scanptr->Ah = Ah;
  165607. scanptr->Al = Al;
  165608. scanptr++;
  165609. }
  165610. return scanptr;
  165611. }
  165612. LOCAL(jpeg_scan_info *)
  165613. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165614. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165615. {
  165616. int ci;
  165617. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165618. /* Single interleaved DC scan */
  165619. scanptr->comps_in_scan = ncomps;
  165620. for (ci = 0; ci < ncomps; ci++)
  165621. scanptr->component_index[ci] = ci;
  165622. scanptr->Ss = scanptr->Se = 0;
  165623. scanptr->Ah = Ah;
  165624. scanptr->Al = Al;
  165625. scanptr++;
  165626. } else {
  165627. /* Noninterleaved DC scan for each component */
  165628. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165629. }
  165630. return scanptr;
  165631. }
  165632. /*
  165633. * Create a recommended progressive-JPEG script.
  165634. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165635. */
  165636. GLOBAL(void)
  165637. jpeg_simple_progression (j_compress_ptr cinfo)
  165638. {
  165639. int ncomps = cinfo->num_components;
  165640. int nscans;
  165641. jpeg_scan_info * scanptr;
  165642. /* Safety check to ensure start_compress not called yet. */
  165643. if (cinfo->global_state != CSTATE_START)
  165644. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165645. /* Figure space needed for script. Calculation must match code below! */
  165646. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165647. /* Custom script for YCbCr color images. */
  165648. nscans = 10;
  165649. } else {
  165650. /* All-purpose script for other color spaces. */
  165651. if (ncomps > MAX_COMPS_IN_SCAN)
  165652. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165653. else
  165654. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165655. }
  165656. /* Allocate space for script.
  165657. * We need to put it in the permanent pool in case the application performs
  165658. * multiple compressions without changing the settings. To avoid a memory
  165659. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165660. * object, we try to re-use previously allocated space, and we allocate
  165661. * enough space to handle YCbCr even if initially asked for grayscale.
  165662. */
  165663. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165664. cinfo->script_space_size = MAX(nscans, 10);
  165665. cinfo->script_space = (jpeg_scan_info *)
  165666. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165667. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165668. }
  165669. scanptr = cinfo->script_space;
  165670. cinfo->scan_info = scanptr;
  165671. cinfo->num_scans = nscans;
  165672. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165673. /* Custom script for YCbCr color images. */
  165674. /* Initial DC scan */
  165675. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165676. /* Initial AC scan: get some luma data out in a hurry */
  165677. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165678. /* Chroma data is too small to be worth expending many scans on */
  165679. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165680. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165681. /* Complete spectral selection for luma AC */
  165682. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165683. /* Refine next bit of luma AC */
  165684. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165685. /* Finish DC successive approximation */
  165686. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165687. /* Finish AC successive approximation */
  165688. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165689. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165690. /* Luma bottom bit comes last since it's usually largest scan */
  165691. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165692. } else {
  165693. /* All-purpose script for other color spaces. */
  165694. /* Successive approximation first pass */
  165695. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165696. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165697. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165698. /* Successive approximation second pass */
  165699. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165700. /* Successive approximation final pass */
  165701. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165702. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165703. }
  165704. }
  165705. #endif /* C_PROGRESSIVE_SUPPORTED */
  165706. /*** End of inlined file: jcparam.c ***/
  165707. /*** Start of inlined file: jcphuff.c ***/
  165708. #define JPEG_INTERNALS
  165709. #ifdef C_PROGRESSIVE_SUPPORTED
  165710. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165711. typedef struct {
  165712. struct jpeg_entropy_encoder pub; /* public fields */
  165713. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165714. boolean gather_statistics;
  165715. /* Bit-level coding status.
  165716. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165717. */
  165718. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165719. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165720. INT32 put_buffer; /* current bit-accumulation buffer */
  165721. int put_bits; /* # of bits now in it */
  165722. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165723. /* Coding status for DC components */
  165724. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165725. /* Coding status for AC components */
  165726. int ac_tbl_no; /* the table number of the single component */
  165727. unsigned int EOBRUN; /* run length of EOBs */
  165728. unsigned int BE; /* # of buffered correction bits before MCU */
  165729. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165730. /* packing correction bits tightly would save some space but cost time... */
  165731. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165732. int next_restart_num; /* next restart number to write (0-7) */
  165733. /* Pointers to derived tables (these workspaces have image lifespan).
  165734. * Since any one scan codes only DC or only AC, we only need one set
  165735. * of tables, not one for DC and one for AC.
  165736. */
  165737. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165738. /* Statistics tables for optimization; again, one set is enough */
  165739. long * count_ptrs[NUM_HUFF_TBLS];
  165740. } phuff_entropy_encoder;
  165741. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165742. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165743. * buffer can hold. Larger sizes may slightly improve compression, but
  165744. * 1000 is already well into the realm of overkill.
  165745. * The minimum safe size is 64 bits.
  165746. */
  165747. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165748. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165749. * We assume that int right shift is unsigned if INT32 right shift is,
  165750. * which should be safe.
  165751. */
  165752. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165753. #define ISHIFT_TEMPS int ishift_temp;
  165754. #define IRIGHT_SHIFT(x,shft) \
  165755. ((ishift_temp = (x)) < 0 ? \
  165756. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165757. (ishift_temp >> (shft)))
  165758. #else
  165759. #define ISHIFT_TEMPS
  165760. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165761. #endif
  165762. /* Forward declarations */
  165763. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165764. JBLOCKROW *MCU_data));
  165765. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165766. JBLOCKROW *MCU_data));
  165767. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165768. JBLOCKROW *MCU_data));
  165769. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165770. JBLOCKROW *MCU_data));
  165771. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165772. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165773. /*
  165774. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165775. */
  165776. METHODDEF(void)
  165777. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165778. {
  165779. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165780. boolean is_DC_band;
  165781. int ci, tbl;
  165782. jpeg_component_info * compptr;
  165783. entropy->cinfo = cinfo;
  165784. entropy->gather_statistics = gather_statistics;
  165785. is_DC_band = (cinfo->Ss == 0);
  165786. /* We assume jcmaster.c already validated the scan parameters. */
  165787. /* Select execution routines */
  165788. if (cinfo->Ah == 0) {
  165789. if (is_DC_band)
  165790. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165791. else
  165792. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165793. } else {
  165794. if (is_DC_band)
  165795. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165796. else {
  165797. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165798. /* AC refinement needs a correction bit buffer */
  165799. if (entropy->bit_buffer == NULL)
  165800. entropy->bit_buffer = (char *)
  165801. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165802. MAX_CORR_BITS * SIZEOF(char));
  165803. }
  165804. }
  165805. if (gather_statistics)
  165806. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165807. else
  165808. entropy->pub.finish_pass = finish_pass_phuff;
  165809. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165810. * for AC coefficients.
  165811. */
  165812. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165813. compptr = cinfo->cur_comp_info[ci];
  165814. /* Initialize DC predictions to 0 */
  165815. entropy->last_dc_val[ci] = 0;
  165816. /* Get table index */
  165817. if (is_DC_band) {
  165818. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165819. continue;
  165820. tbl = compptr->dc_tbl_no;
  165821. } else {
  165822. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165823. }
  165824. if (gather_statistics) {
  165825. /* Check for invalid table index */
  165826. /* (make_c_derived_tbl does this in the other path) */
  165827. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165828. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165829. /* Allocate and zero the statistics tables */
  165830. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165831. if (entropy->count_ptrs[tbl] == NULL)
  165832. entropy->count_ptrs[tbl] = (long *)
  165833. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165834. 257 * SIZEOF(long));
  165835. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165836. } else {
  165837. /* Compute derived values for Huffman table */
  165838. /* We may do this more than once for a table, but it's not expensive */
  165839. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165840. & entropy->derived_tbls[tbl]);
  165841. }
  165842. }
  165843. /* Initialize AC stuff */
  165844. entropy->EOBRUN = 0;
  165845. entropy->BE = 0;
  165846. /* Initialize bit buffer to empty */
  165847. entropy->put_buffer = 0;
  165848. entropy->put_bits = 0;
  165849. /* Initialize restart stuff */
  165850. entropy->restarts_to_go = cinfo->restart_interval;
  165851. entropy->next_restart_num = 0;
  165852. }
  165853. /* Outputting bytes to the file.
  165854. * NB: these must be called only when actually outputting,
  165855. * that is, entropy->gather_statistics == FALSE.
  165856. */
  165857. /* Emit a byte */
  165858. #define emit_byte(entropy,val) \
  165859. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165860. if (--(entropy)->free_in_buffer == 0) \
  165861. dump_buffer_p(entropy); }
  165862. LOCAL(void)
  165863. dump_buffer_p (phuff_entropy_ptr entropy)
  165864. /* Empty the output buffer; we do not support suspension in this module. */
  165865. {
  165866. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165867. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165868. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165869. /* After a successful buffer dump, must reset buffer pointers */
  165870. entropy->next_output_byte = dest->next_output_byte;
  165871. entropy->free_in_buffer = dest->free_in_buffer;
  165872. }
  165873. /* Outputting bits to the file */
  165874. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165875. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165876. * in one call, and we never retain more than 7 bits in put_buffer
  165877. * between calls, so 24 bits are sufficient.
  165878. */
  165879. INLINE
  165880. LOCAL(void)
  165881. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165882. /* Emit some bits, unless we are in gather mode */
  165883. {
  165884. /* This routine is heavily used, so it's worth coding tightly. */
  165885. register INT32 put_buffer = (INT32) code;
  165886. register int put_bits = entropy->put_bits;
  165887. /* if size is 0, caller used an invalid Huffman table entry */
  165888. if (size == 0)
  165889. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165890. if (entropy->gather_statistics)
  165891. return; /* do nothing if we're only getting stats */
  165892. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165893. put_bits += size; /* new number of bits in buffer */
  165894. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165895. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165896. while (put_bits >= 8) {
  165897. int c = (int) ((put_buffer >> 16) & 0xFF);
  165898. emit_byte(entropy, c);
  165899. if (c == 0xFF) { /* need to stuff a zero byte? */
  165900. emit_byte(entropy, 0);
  165901. }
  165902. put_buffer <<= 8;
  165903. put_bits -= 8;
  165904. }
  165905. entropy->put_buffer = put_buffer; /* update variables */
  165906. entropy->put_bits = put_bits;
  165907. }
  165908. LOCAL(void)
  165909. flush_bits_p (phuff_entropy_ptr entropy)
  165910. {
  165911. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165912. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165913. entropy->put_bits = 0;
  165914. }
  165915. /*
  165916. * Emit (or just count) a Huffman symbol.
  165917. */
  165918. INLINE
  165919. LOCAL(void)
  165920. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165921. {
  165922. if (entropy->gather_statistics)
  165923. entropy->count_ptrs[tbl_no][symbol]++;
  165924. else {
  165925. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165926. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165927. }
  165928. }
  165929. /*
  165930. * Emit bits from a correction bit buffer.
  165931. */
  165932. LOCAL(void)
  165933. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165934. unsigned int nbits)
  165935. {
  165936. if (entropy->gather_statistics)
  165937. return; /* no real work */
  165938. while (nbits > 0) {
  165939. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165940. bufstart++;
  165941. nbits--;
  165942. }
  165943. }
  165944. /*
  165945. * Emit any pending EOBRUN symbol.
  165946. */
  165947. LOCAL(void)
  165948. emit_eobrun (phuff_entropy_ptr entropy)
  165949. {
  165950. register int temp, nbits;
  165951. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165952. temp = entropy->EOBRUN;
  165953. nbits = 0;
  165954. while ((temp >>= 1))
  165955. nbits++;
  165956. /* safety check: shouldn't happen given limited correction-bit buffer */
  165957. if (nbits > 14)
  165958. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165959. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165960. if (nbits)
  165961. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165962. entropy->EOBRUN = 0;
  165963. /* Emit any buffered correction bits */
  165964. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165965. entropy->BE = 0;
  165966. }
  165967. }
  165968. /*
  165969. * Emit a restart marker & resynchronize predictions.
  165970. */
  165971. LOCAL(void)
  165972. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165973. {
  165974. int ci;
  165975. emit_eobrun(entropy);
  165976. if (! entropy->gather_statistics) {
  165977. flush_bits_p(entropy);
  165978. emit_byte(entropy, 0xFF);
  165979. emit_byte(entropy, JPEG_RST0 + restart_num);
  165980. }
  165981. if (entropy->cinfo->Ss == 0) {
  165982. /* Re-initialize DC predictions to 0 */
  165983. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165984. entropy->last_dc_val[ci] = 0;
  165985. } else {
  165986. /* Re-initialize all AC-related fields to 0 */
  165987. entropy->EOBRUN = 0;
  165988. entropy->BE = 0;
  165989. }
  165990. }
  165991. /*
  165992. * MCU encoding for DC initial scan (either spectral selection,
  165993. * or first pass of successive approximation).
  165994. */
  165995. METHODDEF(boolean)
  165996. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165997. {
  165998. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165999. register int temp, temp2;
  166000. register int nbits;
  166001. int blkn, ci;
  166002. int Al = cinfo->Al;
  166003. JBLOCKROW block;
  166004. jpeg_component_info * compptr;
  166005. ISHIFT_TEMPS
  166006. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166007. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166008. /* Emit restart marker if needed */
  166009. if (cinfo->restart_interval)
  166010. if (entropy->restarts_to_go == 0)
  166011. emit_restart_p(entropy, entropy->next_restart_num);
  166012. /* Encode the MCU data blocks */
  166013. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166014. block = MCU_data[blkn];
  166015. ci = cinfo->MCU_membership[blkn];
  166016. compptr = cinfo->cur_comp_info[ci];
  166017. /* Compute the DC value after the required point transform by Al.
  166018. * This is simply an arithmetic right shift.
  166019. */
  166020. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166021. /* DC differences are figured on the point-transformed values. */
  166022. temp = temp2 - entropy->last_dc_val[ci];
  166023. entropy->last_dc_val[ci] = temp2;
  166024. /* Encode the DC coefficient difference per section G.1.2.1 */
  166025. temp2 = temp;
  166026. if (temp < 0) {
  166027. temp = -temp; /* temp is abs value of input */
  166028. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166029. /* This code assumes we are on a two's complement machine */
  166030. temp2--;
  166031. }
  166032. /* Find the number of bits needed for the magnitude of the coefficient */
  166033. nbits = 0;
  166034. while (temp) {
  166035. nbits++;
  166036. temp >>= 1;
  166037. }
  166038. /* Check for out-of-range coefficient values.
  166039. * Since we're encoding a difference, the range limit is twice as much.
  166040. */
  166041. if (nbits > MAX_COEF_BITS+1)
  166042. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166043. /* Count/emit the Huffman-coded symbol for the number of bits */
  166044. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166045. /* Emit that number of bits of the value, if positive, */
  166046. /* or the complement of its magnitude, if negative. */
  166047. if (nbits) /* emit_bits rejects calls with size 0 */
  166048. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166049. }
  166050. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166051. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166052. /* Update restart-interval state too */
  166053. if (cinfo->restart_interval) {
  166054. if (entropy->restarts_to_go == 0) {
  166055. entropy->restarts_to_go = cinfo->restart_interval;
  166056. entropy->next_restart_num++;
  166057. entropy->next_restart_num &= 7;
  166058. }
  166059. entropy->restarts_to_go--;
  166060. }
  166061. return TRUE;
  166062. }
  166063. /*
  166064. * MCU encoding for AC initial scan (either spectral selection,
  166065. * or first pass of successive approximation).
  166066. */
  166067. METHODDEF(boolean)
  166068. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166069. {
  166070. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166071. register int temp, temp2;
  166072. register int nbits;
  166073. register int r, k;
  166074. int Se = cinfo->Se;
  166075. int Al = cinfo->Al;
  166076. JBLOCKROW block;
  166077. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166078. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166079. /* Emit restart marker if needed */
  166080. if (cinfo->restart_interval)
  166081. if (entropy->restarts_to_go == 0)
  166082. emit_restart_p(entropy, entropy->next_restart_num);
  166083. /* Encode the MCU data block */
  166084. block = MCU_data[0];
  166085. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166086. r = 0; /* r = run length of zeros */
  166087. for (k = cinfo->Ss; k <= Se; k++) {
  166088. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166089. r++;
  166090. continue;
  166091. }
  166092. /* We must apply the point transform by Al. For AC coefficients this
  166093. * is an integer division with rounding towards 0. To do this portably
  166094. * in C, we shift after obtaining the absolute value; so the code is
  166095. * interwoven with finding the abs value (temp) and output bits (temp2).
  166096. */
  166097. if (temp < 0) {
  166098. temp = -temp; /* temp is abs value of input */
  166099. temp >>= Al; /* apply the point transform */
  166100. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166101. temp2 = ~temp;
  166102. } else {
  166103. temp >>= Al; /* apply the point transform */
  166104. temp2 = temp;
  166105. }
  166106. /* Watch out for case that nonzero coef is zero after point transform */
  166107. if (temp == 0) {
  166108. r++;
  166109. continue;
  166110. }
  166111. /* Emit any pending EOBRUN */
  166112. if (entropy->EOBRUN > 0)
  166113. emit_eobrun(entropy);
  166114. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166115. while (r > 15) {
  166116. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166117. r -= 16;
  166118. }
  166119. /* Find the number of bits needed for the magnitude of the coefficient */
  166120. nbits = 1; /* there must be at least one 1 bit */
  166121. while ((temp >>= 1))
  166122. nbits++;
  166123. /* Check for out-of-range coefficient values */
  166124. if (nbits > MAX_COEF_BITS)
  166125. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166126. /* Count/emit Huffman symbol for run length / number of bits */
  166127. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166128. /* Emit that number of bits of the value, if positive, */
  166129. /* or the complement of its magnitude, if negative. */
  166130. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166131. r = 0; /* reset zero run length */
  166132. }
  166133. if (r > 0) { /* If there are trailing zeroes, */
  166134. entropy->EOBRUN++; /* count an EOB */
  166135. if (entropy->EOBRUN == 0x7FFF)
  166136. emit_eobrun(entropy); /* force it out to avoid overflow */
  166137. }
  166138. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166139. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166140. /* Update restart-interval state too */
  166141. if (cinfo->restart_interval) {
  166142. if (entropy->restarts_to_go == 0) {
  166143. entropy->restarts_to_go = cinfo->restart_interval;
  166144. entropy->next_restart_num++;
  166145. entropy->next_restart_num &= 7;
  166146. }
  166147. entropy->restarts_to_go--;
  166148. }
  166149. return TRUE;
  166150. }
  166151. /*
  166152. * MCU encoding for DC successive approximation refinement scan.
  166153. * Note: we assume such scans can be multi-component, although the spec
  166154. * is not very clear on the point.
  166155. */
  166156. METHODDEF(boolean)
  166157. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166158. {
  166159. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166160. register int temp;
  166161. int blkn;
  166162. int Al = cinfo->Al;
  166163. JBLOCKROW block;
  166164. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166165. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166166. /* Emit restart marker if needed */
  166167. if (cinfo->restart_interval)
  166168. if (entropy->restarts_to_go == 0)
  166169. emit_restart_p(entropy, entropy->next_restart_num);
  166170. /* Encode the MCU data blocks */
  166171. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166172. block = MCU_data[blkn];
  166173. /* We simply emit the Al'th bit of the DC coefficient value. */
  166174. temp = (*block)[0];
  166175. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166176. }
  166177. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166178. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166179. /* Update restart-interval state too */
  166180. if (cinfo->restart_interval) {
  166181. if (entropy->restarts_to_go == 0) {
  166182. entropy->restarts_to_go = cinfo->restart_interval;
  166183. entropy->next_restart_num++;
  166184. entropy->next_restart_num &= 7;
  166185. }
  166186. entropy->restarts_to_go--;
  166187. }
  166188. return TRUE;
  166189. }
  166190. /*
  166191. * MCU encoding for AC successive approximation refinement scan.
  166192. */
  166193. METHODDEF(boolean)
  166194. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166195. {
  166196. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166197. register int temp;
  166198. register int r, k;
  166199. int EOB;
  166200. char *BR_buffer;
  166201. unsigned int BR;
  166202. int Se = cinfo->Se;
  166203. int Al = cinfo->Al;
  166204. JBLOCKROW block;
  166205. int absvalues[DCTSIZE2];
  166206. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166207. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166208. /* Emit restart marker if needed */
  166209. if (cinfo->restart_interval)
  166210. if (entropy->restarts_to_go == 0)
  166211. emit_restart_p(entropy, entropy->next_restart_num);
  166212. /* Encode the MCU data block */
  166213. block = MCU_data[0];
  166214. /* It is convenient to make a pre-pass to determine the transformed
  166215. * coefficients' absolute values and the EOB position.
  166216. */
  166217. EOB = 0;
  166218. for (k = cinfo->Ss; k <= Se; k++) {
  166219. temp = (*block)[jpeg_natural_order[k]];
  166220. /* We must apply the point transform by Al. For AC coefficients this
  166221. * is an integer division with rounding towards 0. To do this portably
  166222. * in C, we shift after obtaining the absolute value.
  166223. */
  166224. if (temp < 0)
  166225. temp = -temp; /* temp is abs value of input */
  166226. temp >>= Al; /* apply the point transform */
  166227. absvalues[k] = temp; /* save abs value for main pass */
  166228. if (temp == 1)
  166229. EOB = k; /* EOB = index of last newly-nonzero coef */
  166230. }
  166231. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166232. r = 0; /* r = run length of zeros */
  166233. BR = 0; /* BR = count of buffered bits added now */
  166234. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166235. for (k = cinfo->Ss; k <= Se; k++) {
  166236. if ((temp = absvalues[k]) == 0) {
  166237. r++;
  166238. continue;
  166239. }
  166240. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166241. while (r > 15 && k <= EOB) {
  166242. /* emit any pending EOBRUN and the BE correction bits */
  166243. emit_eobrun(entropy);
  166244. /* Emit ZRL */
  166245. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166246. r -= 16;
  166247. /* Emit buffered correction bits that must be associated with ZRL */
  166248. emit_buffered_bits(entropy, BR_buffer, BR);
  166249. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166250. BR = 0;
  166251. }
  166252. /* If the coef was previously nonzero, it only needs a correction bit.
  166253. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166254. * that we also need to test r > 15. But if r > 15, we can only get here
  166255. * if k > EOB, which implies that this coefficient is not 1.
  166256. */
  166257. if (temp > 1) {
  166258. /* The correction bit is the next bit of the absolute value. */
  166259. BR_buffer[BR++] = (char) (temp & 1);
  166260. continue;
  166261. }
  166262. /* Emit any pending EOBRUN and the BE correction bits */
  166263. emit_eobrun(entropy);
  166264. /* Count/emit Huffman symbol for run length / number of bits */
  166265. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166266. /* Emit output bit for newly-nonzero coef */
  166267. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166268. emit_bits_p(entropy, (unsigned int) temp, 1);
  166269. /* Emit buffered correction bits that must be associated with this code */
  166270. emit_buffered_bits(entropy, BR_buffer, BR);
  166271. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166272. BR = 0;
  166273. r = 0; /* reset zero run length */
  166274. }
  166275. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166276. entropy->EOBRUN++; /* count an EOB */
  166277. entropy->BE += BR; /* concat my correction bits to older ones */
  166278. /* We force out the EOB if we risk either:
  166279. * 1. overflow of the EOB counter;
  166280. * 2. overflow of the correction bit buffer during the next MCU.
  166281. */
  166282. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166283. emit_eobrun(entropy);
  166284. }
  166285. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166286. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166287. /* Update restart-interval state too */
  166288. if (cinfo->restart_interval) {
  166289. if (entropy->restarts_to_go == 0) {
  166290. entropy->restarts_to_go = cinfo->restart_interval;
  166291. entropy->next_restart_num++;
  166292. entropy->next_restart_num &= 7;
  166293. }
  166294. entropy->restarts_to_go--;
  166295. }
  166296. return TRUE;
  166297. }
  166298. /*
  166299. * Finish up at the end of a Huffman-compressed progressive scan.
  166300. */
  166301. METHODDEF(void)
  166302. finish_pass_phuff (j_compress_ptr cinfo)
  166303. {
  166304. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166305. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166306. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166307. /* Flush out any buffered data */
  166308. emit_eobrun(entropy);
  166309. flush_bits_p(entropy);
  166310. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166311. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166312. }
  166313. /*
  166314. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166315. */
  166316. METHODDEF(void)
  166317. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166318. {
  166319. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166320. boolean is_DC_band;
  166321. int ci, tbl;
  166322. jpeg_component_info * compptr;
  166323. JHUFF_TBL **htblptr;
  166324. boolean did[NUM_HUFF_TBLS];
  166325. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166326. emit_eobrun(entropy);
  166327. is_DC_band = (cinfo->Ss == 0);
  166328. /* It's important not to apply jpeg_gen_optimal_table more than once
  166329. * per table, because it clobbers the input frequency counts!
  166330. */
  166331. MEMZERO(did, SIZEOF(did));
  166332. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166333. compptr = cinfo->cur_comp_info[ci];
  166334. if (is_DC_band) {
  166335. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166336. continue;
  166337. tbl = compptr->dc_tbl_no;
  166338. } else {
  166339. tbl = compptr->ac_tbl_no;
  166340. }
  166341. if (! did[tbl]) {
  166342. if (is_DC_band)
  166343. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166344. else
  166345. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166346. if (*htblptr == NULL)
  166347. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166348. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166349. did[tbl] = TRUE;
  166350. }
  166351. }
  166352. }
  166353. /*
  166354. * Module initialization routine for progressive Huffman entropy encoding.
  166355. */
  166356. GLOBAL(void)
  166357. jinit_phuff_encoder (j_compress_ptr cinfo)
  166358. {
  166359. phuff_entropy_ptr entropy;
  166360. int i;
  166361. entropy = (phuff_entropy_ptr)
  166362. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166363. SIZEOF(phuff_entropy_encoder));
  166364. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166365. entropy->pub.start_pass = start_pass_phuff;
  166366. /* Mark tables unallocated */
  166367. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166368. entropy->derived_tbls[i] = NULL;
  166369. entropy->count_ptrs[i] = NULL;
  166370. }
  166371. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166372. }
  166373. #endif /* C_PROGRESSIVE_SUPPORTED */
  166374. /*** End of inlined file: jcphuff.c ***/
  166375. /*** Start of inlined file: jcprepct.c ***/
  166376. #define JPEG_INTERNALS
  166377. /* At present, jcsample.c can request context rows only for smoothing.
  166378. * In the future, we might also need context rows for CCIR601 sampling
  166379. * or other more-complex downsampling procedures. The code to support
  166380. * context rows should be compiled only if needed.
  166381. */
  166382. #ifdef INPUT_SMOOTHING_SUPPORTED
  166383. #define CONTEXT_ROWS_SUPPORTED
  166384. #endif
  166385. /*
  166386. * For the simple (no-context-row) case, we just need to buffer one
  166387. * row group's worth of pixels for the downsampling step. At the bottom of
  166388. * the image, we pad to a full row group by replicating the last pixel row.
  166389. * The downsampler's last output row is then replicated if needed to pad
  166390. * out to a full iMCU row.
  166391. *
  166392. * When providing context rows, we must buffer three row groups' worth of
  166393. * pixels. Three row groups are physically allocated, but the row pointer
  166394. * arrays are made five row groups high, with the extra pointers above and
  166395. * below "wrapping around" to point to the last and first real row groups.
  166396. * This allows the downsampler to access the proper context rows.
  166397. * At the top and bottom of the image, we create dummy context rows by
  166398. * copying the first or last real pixel row. This copying could be avoided
  166399. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166400. * trouble on the compression side.
  166401. */
  166402. /* Private buffer controller object */
  166403. typedef struct {
  166404. struct jpeg_c_prep_controller pub; /* public fields */
  166405. /* Downsampling input buffer. This buffer holds color-converted data
  166406. * until we have enough to do a downsample step.
  166407. */
  166408. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166409. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166410. int next_buf_row; /* index of next row to store in color_buf */
  166411. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166412. int this_row_group; /* starting row index of group to process */
  166413. int next_buf_stop; /* downsample when we reach this index */
  166414. #endif
  166415. } my_prep_controller;
  166416. typedef my_prep_controller * my_prep_ptr;
  166417. /*
  166418. * Initialize for a processing pass.
  166419. */
  166420. METHODDEF(void)
  166421. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166422. {
  166423. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166424. if (pass_mode != JBUF_PASS_THRU)
  166425. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166426. /* Initialize total-height counter for detecting bottom of image */
  166427. prep->rows_to_go = cinfo->image_height;
  166428. /* Mark the conversion buffer empty */
  166429. prep->next_buf_row = 0;
  166430. #ifdef CONTEXT_ROWS_SUPPORTED
  166431. /* Preset additional state variables for context mode.
  166432. * These aren't used in non-context mode, so we needn't test which mode.
  166433. */
  166434. prep->this_row_group = 0;
  166435. /* Set next_buf_stop to stop after two row groups have been read in. */
  166436. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166437. #endif
  166438. }
  166439. /*
  166440. * Expand an image vertically from height input_rows to height output_rows,
  166441. * by duplicating the bottom row.
  166442. */
  166443. LOCAL(void)
  166444. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166445. int input_rows, int output_rows)
  166446. {
  166447. register int row;
  166448. for (row = input_rows; row < output_rows; row++) {
  166449. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166450. 1, num_cols);
  166451. }
  166452. }
  166453. /*
  166454. * Process some data in the simple no-context case.
  166455. *
  166456. * Preprocessor output data is counted in "row groups". A row group
  166457. * is defined to be v_samp_factor sample rows of each component.
  166458. * Downsampling will produce this much data from each max_v_samp_factor
  166459. * input rows.
  166460. */
  166461. METHODDEF(void)
  166462. pre_process_data (j_compress_ptr cinfo,
  166463. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166464. JDIMENSION in_rows_avail,
  166465. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166466. JDIMENSION out_row_groups_avail)
  166467. {
  166468. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166469. int numrows, ci;
  166470. JDIMENSION inrows;
  166471. jpeg_component_info * compptr;
  166472. while (*in_row_ctr < in_rows_avail &&
  166473. *out_row_group_ctr < out_row_groups_avail) {
  166474. /* Do color conversion to fill the conversion buffer. */
  166475. inrows = in_rows_avail - *in_row_ctr;
  166476. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166477. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166478. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166479. prep->color_buf,
  166480. (JDIMENSION) prep->next_buf_row,
  166481. numrows);
  166482. *in_row_ctr += numrows;
  166483. prep->next_buf_row += numrows;
  166484. prep->rows_to_go -= numrows;
  166485. /* If at bottom of image, pad to fill the conversion buffer. */
  166486. if (prep->rows_to_go == 0 &&
  166487. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166488. for (ci = 0; ci < cinfo->num_components; ci++) {
  166489. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166490. prep->next_buf_row, cinfo->max_v_samp_factor);
  166491. }
  166492. prep->next_buf_row = cinfo->max_v_samp_factor;
  166493. }
  166494. /* If we've filled the conversion buffer, empty it. */
  166495. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166496. (*cinfo->downsample->downsample) (cinfo,
  166497. prep->color_buf, (JDIMENSION) 0,
  166498. output_buf, *out_row_group_ctr);
  166499. prep->next_buf_row = 0;
  166500. (*out_row_group_ctr)++;
  166501. }
  166502. /* If at bottom of image, pad the output to a full iMCU height.
  166503. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166504. */
  166505. if (prep->rows_to_go == 0 &&
  166506. *out_row_group_ctr < out_row_groups_avail) {
  166507. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166508. ci++, compptr++) {
  166509. expand_bottom_edge(output_buf[ci],
  166510. compptr->width_in_blocks * DCTSIZE,
  166511. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166512. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166513. }
  166514. *out_row_group_ctr = out_row_groups_avail;
  166515. break; /* can exit outer loop without test */
  166516. }
  166517. }
  166518. }
  166519. #ifdef CONTEXT_ROWS_SUPPORTED
  166520. /*
  166521. * Process some data in the context case.
  166522. */
  166523. METHODDEF(void)
  166524. pre_process_context (j_compress_ptr cinfo,
  166525. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166526. JDIMENSION in_rows_avail,
  166527. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166528. JDIMENSION out_row_groups_avail)
  166529. {
  166530. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166531. int numrows, ci;
  166532. int buf_height = cinfo->max_v_samp_factor * 3;
  166533. JDIMENSION inrows;
  166534. while (*out_row_group_ctr < out_row_groups_avail) {
  166535. if (*in_row_ctr < in_rows_avail) {
  166536. /* Do color conversion to fill the conversion buffer. */
  166537. inrows = in_rows_avail - *in_row_ctr;
  166538. numrows = prep->next_buf_stop - prep->next_buf_row;
  166539. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166540. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166541. prep->color_buf,
  166542. (JDIMENSION) prep->next_buf_row,
  166543. numrows);
  166544. /* Pad at top of image, if first time through */
  166545. if (prep->rows_to_go == cinfo->image_height) {
  166546. for (ci = 0; ci < cinfo->num_components; ci++) {
  166547. int row;
  166548. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166549. jcopy_sample_rows(prep->color_buf[ci], 0,
  166550. prep->color_buf[ci], -row,
  166551. 1, cinfo->image_width);
  166552. }
  166553. }
  166554. }
  166555. *in_row_ctr += numrows;
  166556. prep->next_buf_row += numrows;
  166557. prep->rows_to_go -= numrows;
  166558. } else {
  166559. /* Return for more data, unless we are at the bottom of the image. */
  166560. if (prep->rows_to_go != 0)
  166561. break;
  166562. /* When at bottom of image, pad to fill the conversion buffer. */
  166563. if (prep->next_buf_row < prep->next_buf_stop) {
  166564. for (ci = 0; ci < cinfo->num_components; ci++) {
  166565. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166566. prep->next_buf_row, prep->next_buf_stop);
  166567. }
  166568. prep->next_buf_row = prep->next_buf_stop;
  166569. }
  166570. }
  166571. /* If we've gotten enough data, downsample a row group. */
  166572. if (prep->next_buf_row == prep->next_buf_stop) {
  166573. (*cinfo->downsample->downsample) (cinfo,
  166574. prep->color_buf,
  166575. (JDIMENSION) prep->this_row_group,
  166576. output_buf, *out_row_group_ctr);
  166577. (*out_row_group_ctr)++;
  166578. /* Advance pointers with wraparound as necessary. */
  166579. prep->this_row_group += cinfo->max_v_samp_factor;
  166580. if (prep->this_row_group >= buf_height)
  166581. prep->this_row_group = 0;
  166582. if (prep->next_buf_row >= buf_height)
  166583. prep->next_buf_row = 0;
  166584. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166585. }
  166586. }
  166587. }
  166588. /*
  166589. * Create the wrapped-around downsampling input buffer needed for context mode.
  166590. */
  166591. LOCAL(void)
  166592. create_context_buffer (j_compress_ptr cinfo)
  166593. {
  166594. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166595. int rgroup_height = cinfo->max_v_samp_factor;
  166596. int ci, i;
  166597. jpeg_component_info * compptr;
  166598. JSAMPARRAY true_buffer, fake_buffer;
  166599. /* Grab enough space for fake row pointers for all the components;
  166600. * we need five row groups' worth of pointers for each component.
  166601. */
  166602. fake_buffer = (JSAMPARRAY)
  166603. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166604. (cinfo->num_components * 5 * rgroup_height) *
  166605. SIZEOF(JSAMPROW));
  166606. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166607. ci++, compptr++) {
  166608. /* Allocate the actual buffer space (3 row groups) for this component.
  166609. * We make the buffer wide enough to allow the downsampler to edge-expand
  166610. * horizontally within the buffer, if it so chooses.
  166611. */
  166612. true_buffer = (*cinfo->mem->alloc_sarray)
  166613. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166614. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166615. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166616. (JDIMENSION) (3 * rgroup_height));
  166617. /* Copy true buffer row pointers into the middle of the fake row array */
  166618. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166619. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166620. /* Fill in the above and below wraparound pointers */
  166621. for (i = 0; i < rgroup_height; i++) {
  166622. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166623. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166624. }
  166625. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166626. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166627. }
  166628. }
  166629. #endif /* CONTEXT_ROWS_SUPPORTED */
  166630. /*
  166631. * Initialize preprocessing controller.
  166632. */
  166633. GLOBAL(void)
  166634. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166635. {
  166636. my_prep_ptr prep;
  166637. int ci;
  166638. jpeg_component_info * compptr;
  166639. if (need_full_buffer) /* safety check */
  166640. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166641. prep = (my_prep_ptr)
  166642. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166643. SIZEOF(my_prep_controller));
  166644. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166645. prep->pub.start_pass = start_pass_prep;
  166646. /* Allocate the color conversion buffer.
  166647. * We make the buffer wide enough to allow the downsampler to edge-expand
  166648. * horizontally within the buffer, if it so chooses.
  166649. */
  166650. if (cinfo->downsample->need_context_rows) {
  166651. /* Set up to provide context rows */
  166652. #ifdef CONTEXT_ROWS_SUPPORTED
  166653. prep->pub.pre_process_data = pre_process_context;
  166654. create_context_buffer(cinfo);
  166655. #else
  166656. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166657. #endif
  166658. } else {
  166659. /* No context, just make it tall enough for one row group */
  166660. prep->pub.pre_process_data = pre_process_data;
  166661. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166662. ci++, compptr++) {
  166663. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166664. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166665. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166666. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166667. (JDIMENSION) cinfo->max_v_samp_factor);
  166668. }
  166669. }
  166670. }
  166671. /*** End of inlined file: jcprepct.c ***/
  166672. /*** Start of inlined file: jcsample.c ***/
  166673. #define JPEG_INTERNALS
  166674. /* Pointer to routine to downsample a single component */
  166675. typedef JMETHOD(void, downsample1_ptr,
  166676. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166677. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166678. /* Private subobject */
  166679. typedef struct {
  166680. struct jpeg_downsampler pub; /* public fields */
  166681. /* Downsampling method pointers, one per component */
  166682. downsample1_ptr methods[MAX_COMPONENTS];
  166683. } my_downsampler;
  166684. typedef my_downsampler * my_downsample_ptr;
  166685. /*
  166686. * Initialize for a downsampling pass.
  166687. */
  166688. METHODDEF(void)
  166689. start_pass_downsample (j_compress_ptr)
  166690. {
  166691. /* no work for now */
  166692. }
  166693. /*
  166694. * Expand a component horizontally from width input_cols to width output_cols,
  166695. * by duplicating the rightmost samples.
  166696. */
  166697. LOCAL(void)
  166698. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166699. JDIMENSION input_cols, JDIMENSION output_cols)
  166700. {
  166701. register JSAMPROW ptr;
  166702. register JSAMPLE pixval;
  166703. register int count;
  166704. int row;
  166705. int numcols = (int) (output_cols - input_cols);
  166706. if (numcols > 0) {
  166707. for (row = 0; row < num_rows; row++) {
  166708. ptr = image_data[row] + input_cols;
  166709. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166710. for (count = numcols; count > 0; count--)
  166711. *ptr++ = pixval;
  166712. }
  166713. }
  166714. }
  166715. /*
  166716. * Do downsampling for a whole row group (all components).
  166717. *
  166718. * In this version we simply downsample each component independently.
  166719. */
  166720. METHODDEF(void)
  166721. sep_downsample (j_compress_ptr cinfo,
  166722. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166723. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166724. {
  166725. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166726. int ci;
  166727. jpeg_component_info * compptr;
  166728. JSAMPARRAY in_ptr, out_ptr;
  166729. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166730. ci++, compptr++) {
  166731. in_ptr = input_buf[ci] + in_row_index;
  166732. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166733. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166734. }
  166735. }
  166736. /*
  166737. * Downsample pixel values of a single component.
  166738. * One row group is processed per call.
  166739. * This version handles arbitrary integral sampling ratios, without smoothing.
  166740. * Note that this version is not actually used for customary sampling ratios.
  166741. */
  166742. METHODDEF(void)
  166743. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166744. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166745. {
  166746. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166747. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166748. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166749. JSAMPROW inptr, outptr;
  166750. INT32 outvalue;
  166751. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166752. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166753. numpix = h_expand * v_expand;
  166754. numpix2 = numpix/2;
  166755. /* Expand input data enough to let all the output samples be generated
  166756. * by the standard loop. Special-casing padded output would be more
  166757. * efficient.
  166758. */
  166759. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166760. cinfo->image_width, output_cols * h_expand);
  166761. inrow = 0;
  166762. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166763. outptr = output_data[outrow];
  166764. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166765. outcol++, outcol_h += h_expand) {
  166766. outvalue = 0;
  166767. for (v = 0; v < v_expand; v++) {
  166768. inptr = input_data[inrow+v] + outcol_h;
  166769. for (h = 0; h < h_expand; h++) {
  166770. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166771. }
  166772. }
  166773. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166774. }
  166775. inrow += v_expand;
  166776. }
  166777. }
  166778. /*
  166779. * Downsample pixel values of a single component.
  166780. * This version handles the special case of a full-size component,
  166781. * without smoothing.
  166782. */
  166783. METHODDEF(void)
  166784. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166785. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166786. {
  166787. /* Copy the data */
  166788. jcopy_sample_rows(input_data, 0, output_data, 0,
  166789. cinfo->max_v_samp_factor, cinfo->image_width);
  166790. /* Edge-expand */
  166791. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166792. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166793. }
  166794. /*
  166795. * Downsample pixel values of a single component.
  166796. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166797. * without smoothing.
  166798. *
  166799. * A note about the "bias" calculations: when rounding fractional values to
  166800. * integer, we do not want to always round 0.5 up to the next integer.
  166801. * If we did that, we'd introduce a noticeable bias towards larger values.
  166802. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166803. * alternate pixel locations (a simple ordered dither pattern).
  166804. */
  166805. METHODDEF(void)
  166806. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166807. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166808. {
  166809. int outrow;
  166810. JDIMENSION outcol;
  166811. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166812. register JSAMPROW inptr, outptr;
  166813. register int bias;
  166814. /* Expand input data enough to let all the output samples be generated
  166815. * by the standard loop. Special-casing padded output would be more
  166816. * efficient.
  166817. */
  166818. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166819. cinfo->image_width, output_cols * 2);
  166820. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166821. outptr = output_data[outrow];
  166822. inptr = input_data[outrow];
  166823. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166824. for (outcol = 0; outcol < output_cols; outcol++) {
  166825. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166826. + bias) >> 1);
  166827. bias ^= 1; /* 0=>1, 1=>0 */
  166828. inptr += 2;
  166829. }
  166830. }
  166831. }
  166832. /*
  166833. * Downsample pixel values of a single component.
  166834. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166835. * without smoothing.
  166836. */
  166837. METHODDEF(void)
  166838. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166839. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166840. {
  166841. int inrow, outrow;
  166842. JDIMENSION outcol;
  166843. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166844. register JSAMPROW inptr0, inptr1, outptr;
  166845. register int bias;
  166846. /* Expand input data enough to let all the output samples be generated
  166847. * by the standard loop. Special-casing padded output would be more
  166848. * efficient.
  166849. */
  166850. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166851. cinfo->image_width, output_cols * 2);
  166852. inrow = 0;
  166853. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166854. outptr = output_data[outrow];
  166855. inptr0 = input_data[inrow];
  166856. inptr1 = input_data[inrow+1];
  166857. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166858. for (outcol = 0; outcol < output_cols; outcol++) {
  166859. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166860. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166861. + bias) >> 2);
  166862. bias ^= 3; /* 1=>2, 2=>1 */
  166863. inptr0 += 2; inptr1 += 2;
  166864. }
  166865. inrow += 2;
  166866. }
  166867. }
  166868. #ifdef INPUT_SMOOTHING_SUPPORTED
  166869. /*
  166870. * Downsample pixel values of a single component.
  166871. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166872. * with smoothing. One row of context is required.
  166873. */
  166874. METHODDEF(void)
  166875. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166876. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166877. {
  166878. int inrow, outrow;
  166879. JDIMENSION colctr;
  166880. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166881. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166882. INT32 membersum, neighsum, memberscale, neighscale;
  166883. /* Expand input data enough to let all the output samples be generated
  166884. * by the standard loop. Special-casing padded output would be more
  166885. * efficient.
  166886. */
  166887. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166888. cinfo->image_width, output_cols * 2);
  166889. /* We don't bother to form the individual "smoothed" input pixel values;
  166890. * we can directly compute the output which is the average of the four
  166891. * smoothed values. Each of the four member pixels contributes a fraction
  166892. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166893. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166894. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166895. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166896. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166897. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166898. * factors are scaled by 2^16 = 65536.
  166899. * Also recall that SF = smoothing_factor / 1024.
  166900. */
  166901. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166902. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166903. inrow = 0;
  166904. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166905. outptr = output_data[outrow];
  166906. inptr0 = input_data[inrow];
  166907. inptr1 = input_data[inrow+1];
  166908. above_ptr = input_data[inrow-1];
  166909. below_ptr = input_data[inrow+2];
  166910. /* Special case for first column: pretend column -1 is same as column 0 */
  166911. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166912. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166913. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166914. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166915. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166916. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166917. neighsum += neighsum;
  166918. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166919. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166920. membersum = membersum * memberscale + neighsum * neighscale;
  166921. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166922. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166923. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166924. /* sum of pixels directly mapped to this output element */
  166925. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166926. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166927. /* sum of edge-neighbor pixels */
  166928. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166929. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166930. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166931. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166932. /* The edge-neighbors count twice as much as corner-neighbors */
  166933. neighsum += neighsum;
  166934. /* Add in the corner-neighbors */
  166935. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166936. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166937. /* form final output scaled up by 2^16 */
  166938. membersum = membersum * memberscale + neighsum * neighscale;
  166939. /* round, descale and output it */
  166940. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166941. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166942. }
  166943. /* Special case for last column */
  166944. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166945. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166946. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166947. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166948. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166949. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166950. neighsum += neighsum;
  166951. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166952. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166953. membersum = membersum * memberscale + neighsum * neighscale;
  166954. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166955. inrow += 2;
  166956. }
  166957. }
  166958. /*
  166959. * Downsample pixel values of a single component.
  166960. * This version handles the special case of a full-size component,
  166961. * with smoothing. One row of context is required.
  166962. */
  166963. METHODDEF(void)
  166964. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166965. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166966. {
  166967. int outrow;
  166968. JDIMENSION colctr;
  166969. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166970. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166971. INT32 membersum, neighsum, memberscale, neighscale;
  166972. int colsum, lastcolsum, nextcolsum;
  166973. /* Expand input data enough to let all the output samples be generated
  166974. * by the standard loop. Special-casing padded output would be more
  166975. * efficient.
  166976. */
  166977. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166978. cinfo->image_width, output_cols);
  166979. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166980. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166981. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166982. * Also recall that SF = smoothing_factor / 1024.
  166983. */
  166984. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166985. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166986. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166987. outptr = output_data[outrow];
  166988. inptr = input_data[outrow];
  166989. above_ptr = input_data[outrow-1];
  166990. below_ptr = input_data[outrow+1];
  166991. /* Special case for first column */
  166992. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166993. GETJSAMPLE(*inptr);
  166994. membersum = GETJSAMPLE(*inptr++);
  166995. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166996. GETJSAMPLE(*inptr);
  166997. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166998. membersum = membersum * memberscale + neighsum * neighscale;
  166999. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167000. lastcolsum = colsum; colsum = nextcolsum;
  167001. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167002. membersum = GETJSAMPLE(*inptr++);
  167003. above_ptr++; below_ptr++;
  167004. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167005. GETJSAMPLE(*inptr);
  167006. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167007. membersum = membersum * memberscale + neighsum * neighscale;
  167008. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167009. lastcolsum = colsum; colsum = nextcolsum;
  167010. }
  167011. /* Special case for last column */
  167012. membersum = GETJSAMPLE(*inptr);
  167013. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167014. membersum = membersum * memberscale + neighsum * neighscale;
  167015. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167016. }
  167017. }
  167018. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167019. /*
  167020. * Module initialization routine for downsampling.
  167021. * Note that we must select a routine for each component.
  167022. */
  167023. GLOBAL(void)
  167024. jinit_downsampler (j_compress_ptr cinfo)
  167025. {
  167026. my_downsample_ptr downsample;
  167027. int ci;
  167028. jpeg_component_info * compptr;
  167029. boolean smoothok = TRUE;
  167030. downsample = (my_downsample_ptr)
  167031. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167032. SIZEOF(my_downsampler));
  167033. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167034. downsample->pub.start_pass = start_pass_downsample;
  167035. downsample->pub.downsample = sep_downsample;
  167036. downsample->pub.need_context_rows = FALSE;
  167037. if (cinfo->CCIR601_sampling)
  167038. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167039. /* Verify we can handle the sampling factors, and set up method pointers */
  167040. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167041. ci++, compptr++) {
  167042. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167043. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167044. #ifdef INPUT_SMOOTHING_SUPPORTED
  167045. if (cinfo->smoothing_factor) {
  167046. downsample->methods[ci] = fullsize_smooth_downsample;
  167047. downsample->pub.need_context_rows = TRUE;
  167048. } else
  167049. #endif
  167050. downsample->methods[ci] = fullsize_downsample;
  167051. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167052. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167053. smoothok = FALSE;
  167054. downsample->methods[ci] = h2v1_downsample;
  167055. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167056. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167057. #ifdef INPUT_SMOOTHING_SUPPORTED
  167058. if (cinfo->smoothing_factor) {
  167059. downsample->methods[ci] = h2v2_smooth_downsample;
  167060. downsample->pub.need_context_rows = TRUE;
  167061. } else
  167062. #endif
  167063. downsample->methods[ci] = h2v2_downsample;
  167064. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167065. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167066. smoothok = FALSE;
  167067. downsample->methods[ci] = int_downsample;
  167068. } else
  167069. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167070. }
  167071. #ifdef INPUT_SMOOTHING_SUPPORTED
  167072. if (cinfo->smoothing_factor && !smoothok)
  167073. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167074. #endif
  167075. }
  167076. /*** End of inlined file: jcsample.c ***/
  167077. /*** Start of inlined file: jctrans.c ***/
  167078. #define JPEG_INTERNALS
  167079. /* Forward declarations */
  167080. LOCAL(void) transencode_master_selection
  167081. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167082. LOCAL(void) transencode_coef_controller
  167083. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167084. /*
  167085. * Compression initialization for writing raw-coefficient data.
  167086. * Before calling this, all parameters and a data destination must be set up.
  167087. * Call jpeg_finish_compress() to actually write the data.
  167088. *
  167089. * The number of passed virtual arrays must match cinfo->num_components.
  167090. * Note that the virtual arrays need not be filled or even realized at
  167091. * the time write_coefficients is called; indeed, if the virtual arrays
  167092. * were requested from this compression object's memory manager, they
  167093. * typically will be realized during this routine and filled afterwards.
  167094. */
  167095. GLOBAL(void)
  167096. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167097. {
  167098. if (cinfo->global_state != CSTATE_START)
  167099. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167100. /* Mark all tables to be written */
  167101. jpeg_suppress_tables(cinfo, FALSE);
  167102. /* (Re)initialize error mgr and destination modules */
  167103. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167104. (*cinfo->dest->init_destination) (cinfo);
  167105. /* Perform master selection of active modules */
  167106. transencode_master_selection(cinfo, coef_arrays);
  167107. /* Wait for jpeg_finish_compress() call */
  167108. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167109. cinfo->global_state = CSTATE_WRCOEFS;
  167110. }
  167111. /*
  167112. * Initialize the compression object with default parameters,
  167113. * then copy from the source object all parameters needed for lossless
  167114. * transcoding. Parameters that can be varied without loss (such as
  167115. * scan script and Huffman optimization) are left in their default states.
  167116. */
  167117. GLOBAL(void)
  167118. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167119. j_compress_ptr dstinfo)
  167120. {
  167121. JQUANT_TBL ** qtblptr;
  167122. jpeg_component_info *incomp, *outcomp;
  167123. JQUANT_TBL *c_quant, *slot_quant;
  167124. int tblno, ci, coefi;
  167125. /* Safety check to ensure start_compress not called yet. */
  167126. if (dstinfo->global_state != CSTATE_START)
  167127. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167128. /* Copy fundamental image dimensions */
  167129. dstinfo->image_width = srcinfo->image_width;
  167130. dstinfo->image_height = srcinfo->image_height;
  167131. dstinfo->input_components = srcinfo->num_components;
  167132. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167133. /* Initialize all parameters to default values */
  167134. jpeg_set_defaults(dstinfo);
  167135. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167136. * Fix it to get the right header markers for the image colorspace.
  167137. */
  167138. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167139. dstinfo->data_precision = srcinfo->data_precision;
  167140. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167141. /* Copy the source's quantization tables. */
  167142. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167143. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167144. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167145. if (*qtblptr == NULL)
  167146. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167147. MEMCOPY((*qtblptr)->quantval,
  167148. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167149. SIZEOF((*qtblptr)->quantval));
  167150. (*qtblptr)->sent_table = FALSE;
  167151. }
  167152. }
  167153. /* Copy the source's per-component info.
  167154. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167155. */
  167156. dstinfo->num_components = srcinfo->num_components;
  167157. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167158. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167159. MAX_COMPONENTS);
  167160. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167161. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167162. outcomp->component_id = incomp->component_id;
  167163. outcomp->h_samp_factor = incomp->h_samp_factor;
  167164. outcomp->v_samp_factor = incomp->v_samp_factor;
  167165. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167166. /* Make sure saved quantization table for component matches the qtable
  167167. * slot. If not, the input file re-used this qtable slot.
  167168. * IJG encoder currently cannot duplicate this.
  167169. */
  167170. tblno = outcomp->quant_tbl_no;
  167171. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167172. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167173. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167174. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167175. c_quant = incomp->quant_table;
  167176. if (c_quant != NULL) {
  167177. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167178. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167179. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167180. }
  167181. }
  167182. /* Note: we do not copy the source's Huffman table assignments;
  167183. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167184. */
  167185. }
  167186. /* Also copy JFIF version and resolution information, if available.
  167187. * Strictly speaking this isn't "critical" info, but it's nearly
  167188. * always appropriate to copy it if available. In particular,
  167189. * if the application chooses to copy JFIF 1.02 extension markers from
  167190. * the source file, we need to copy the version to make sure we don't
  167191. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167192. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167193. */
  167194. if (srcinfo->saw_JFIF_marker) {
  167195. if (srcinfo->JFIF_major_version == 1) {
  167196. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167197. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167198. }
  167199. dstinfo->density_unit = srcinfo->density_unit;
  167200. dstinfo->X_density = srcinfo->X_density;
  167201. dstinfo->Y_density = srcinfo->Y_density;
  167202. }
  167203. }
  167204. /*
  167205. * Master selection of compression modules for transcoding.
  167206. * This substitutes for jcinit.c's initialization of the full compressor.
  167207. */
  167208. LOCAL(void)
  167209. transencode_master_selection (j_compress_ptr cinfo,
  167210. jvirt_barray_ptr * coef_arrays)
  167211. {
  167212. /* Although we don't actually use input_components for transcoding,
  167213. * jcmaster.c's initial_setup will complain if input_components is 0.
  167214. */
  167215. cinfo->input_components = 1;
  167216. /* Initialize master control (includes parameter checking/processing) */
  167217. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167218. /* Entropy encoding: either Huffman or arithmetic coding. */
  167219. if (cinfo->arith_code) {
  167220. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167221. } else {
  167222. if (cinfo->progressive_mode) {
  167223. #ifdef C_PROGRESSIVE_SUPPORTED
  167224. jinit_phuff_encoder(cinfo);
  167225. #else
  167226. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167227. #endif
  167228. } else
  167229. jinit_huff_encoder(cinfo);
  167230. }
  167231. /* We need a special coefficient buffer controller. */
  167232. transencode_coef_controller(cinfo, coef_arrays);
  167233. jinit_marker_writer(cinfo);
  167234. /* We can now tell the memory manager to allocate virtual arrays. */
  167235. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167236. /* Write the datastream header (SOI, JFIF) immediately.
  167237. * Frame and scan headers are postponed till later.
  167238. * This lets application insert special markers after the SOI.
  167239. */
  167240. (*cinfo->marker->write_file_header) (cinfo);
  167241. }
  167242. /*
  167243. * The rest of this file is a special implementation of the coefficient
  167244. * buffer controller. This is similar to jccoefct.c, but it handles only
  167245. * output from presupplied virtual arrays. Furthermore, we generate any
  167246. * dummy padding blocks on-the-fly rather than expecting them to be present
  167247. * in the arrays.
  167248. */
  167249. /* Private buffer controller object */
  167250. typedef struct {
  167251. struct jpeg_c_coef_controller pub; /* public fields */
  167252. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167253. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167254. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167255. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167256. /* Virtual block array for each component. */
  167257. jvirt_barray_ptr * whole_image;
  167258. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167259. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167260. } my_coef_controller2;
  167261. typedef my_coef_controller2 * my_coef_ptr2;
  167262. LOCAL(void)
  167263. start_iMCU_row2 (j_compress_ptr cinfo)
  167264. /* Reset within-iMCU-row counters for a new row */
  167265. {
  167266. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167267. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167268. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167269. * But at the bottom of the image, process only what's left.
  167270. */
  167271. if (cinfo->comps_in_scan > 1) {
  167272. coef->MCU_rows_per_iMCU_row = 1;
  167273. } else {
  167274. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167275. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167276. else
  167277. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167278. }
  167279. coef->mcu_ctr = 0;
  167280. coef->MCU_vert_offset = 0;
  167281. }
  167282. /*
  167283. * Initialize for a processing pass.
  167284. */
  167285. METHODDEF(void)
  167286. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167287. {
  167288. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167289. if (pass_mode != JBUF_CRANK_DEST)
  167290. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167291. coef->iMCU_row_num = 0;
  167292. start_iMCU_row2(cinfo);
  167293. }
  167294. /*
  167295. * Process some data.
  167296. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167297. * per call, ie, v_samp_factor block rows for each component in the scan.
  167298. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167299. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167300. *
  167301. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167302. */
  167303. METHODDEF(boolean)
  167304. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167305. {
  167306. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167307. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167308. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167309. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167310. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167311. JDIMENSION start_col;
  167312. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167313. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167314. JBLOCKROW buffer_ptr;
  167315. jpeg_component_info *compptr;
  167316. /* Align the virtual buffers for the components used in this scan. */
  167317. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167318. compptr = cinfo->cur_comp_info[ci];
  167319. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167320. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167321. coef->iMCU_row_num * compptr->v_samp_factor,
  167322. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167323. }
  167324. /* Loop to process one whole iMCU row */
  167325. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167326. yoffset++) {
  167327. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167328. MCU_col_num++) {
  167329. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167330. blkn = 0; /* index of current DCT block within MCU */
  167331. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167332. compptr = cinfo->cur_comp_info[ci];
  167333. start_col = MCU_col_num * compptr->MCU_width;
  167334. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167335. : compptr->last_col_width;
  167336. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167337. if (coef->iMCU_row_num < last_iMCU_row ||
  167338. yindex+yoffset < compptr->last_row_height) {
  167339. /* Fill in pointers to real blocks in this row */
  167340. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167341. for (xindex = 0; xindex < blockcnt; xindex++)
  167342. MCU_buffer[blkn++] = buffer_ptr++;
  167343. } else {
  167344. /* At bottom of image, need a whole row of dummy blocks */
  167345. xindex = 0;
  167346. }
  167347. /* Fill in any dummy blocks needed in this row.
  167348. * Dummy blocks are filled in the same way as in jccoefct.c:
  167349. * all zeroes in the AC entries, DC entries equal to previous
  167350. * block's DC value. The init routine has already zeroed the
  167351. * AC entries, so we need only set the DC entries correctly.
  167352. */
  167353. for (; xindex < compptr->MCU_width; xindex++) {
  167354. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167355. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167356. blkn++;
  167357. }
  167358. }
  167359. }
  167360. /* Try to write the MCU. */
  167361. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167362. /* Suspension forced; update state counters and exit */
  167363. coef->MCU_vert_offset = yoffset;
  167364. coef->mcu_ctr = MCU_col_num;
  167365. return FALSE;
  167366. }
  167367. }
  167368. /* Completed an MCU row, but perhaps not an iMCU row */
  167369. coef->mcu_ctr = 0;
  167370. }
  167371. /* Completed the iMCU row, advance counters for next one */
  167372. coef->iMCU_row_num++;
  167373. start_iMCU_row2(cinfo);
  167374. return TRUE;
  167375. }
  167376. /*
  167377. * Initialize coefficient buffer controller.
  167378. *
  167379. * Each passed coefficient array must be the right size for that
  167380. * coefficient: width_in_blocks wide and height_in_blocks high,
  167381. * with unitheight at least v_samp_factor.
  167382. */
  167383. LOCAL(void)
  167384. transencode_coef_controller (j_compress_ptr cinfo,
  167385. jvirt_barray_ptr * coef_arrays)
  167386. {
  167387. my_coef_ptr2 coef;
  167388. JBLOCKROW buffer;
  167389. int i;
  167390. coef = (my_coef_ptr2)
  167391. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167392. SIZEOF(my_coef_controller2));
  167393. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167394. coef->pub.start_pass = start_pass_coef2;
  167395. coef->pub.compress_data = compress_output2;
  167396. /* Save pointer to virtual arrays */
  167397. coef->whole_image = coef_arrays;
  167398. /* Allocate and pre-zero space for dummy DCT blocks. */
  167399. buffer = (JBLOCKROW)
  167400. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167401. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167402. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167403. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167404. coef->dummy_buffer[i] = buffer + i;
  167405. }
  167406. }
  167407. /*** End of inlined file: jctrans.c ***/
  167408. /*** Start of inlined file: jdapistd.c ***/
  167409. #define JPEG_INTERNALS
  167410. /* Forward declarations */
  167411. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167412. /*
  167413. * Decompression initialization.
  167414. * jpeg_read_header must be completed before calling this.
  167415. *
  167416. * If a multipass operating mode was selected, this will do all but the
  167417. * last pass, and thus may take a great deal of time.
  167418. *
  167419. * Returns FALSE if suspended. The return value need be inspected only if
  167420. * a suspending data source is used.
  167421. */
  167422. GLOBAL(boolean)
  167423. jpeg_start_decompress (j_decompress_ptr cinfo)
  167424. {
  167425. if (cinfo->global_state == DSTATE_READY) {
  167426. /* First call: initialize master control, select active modules */
  167427. jinit_master_decompress(cinfo);
  167428. if (cinfo->buffered_image) {
  167429. /* No more work here; expecting jpeg_start_output next */
  167430. cinfo->global_state = DSTATE_BUFIMAGE;
  167431. return TRUE;
  167432. }
  167433. cinfo->global_state = DSTATE_PRELOAD;
  167434. }
  167435. if (cinfo->global_state == DSTATE_PRELOAD) {
  167436. /* If file has multiple scans, absorb them all into the coef buffer */
  167437. if (cinfo->inputctl->has_multiple_scans) {
  167438. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167439. for (;;) {
  167440. int retcode;
  167441. /* Call progress monitor hook if present */
  167442. if (cinfo->progress != NULL)
  167443. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167444. /* Absorb some more input */
  167445. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167446. if (retcode == JPEG_SUSPENDED)
  167447. return FALSE;
  167448. if (retcode == JPEG_REACHED_EOI)
  167449. break;
  167450. /* Advance progress counter if appropriate */
  167451. if (cinfo->progress != NULL &&
  167452. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167453. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167454. /* jdmaster underestimated number of scans; ratchet up one scan */
  167455. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167456. }
  167457. }
  167458. }
  167459. #else
  167460. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167461. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167462. }
  167463. cinfo->output_scan_number = cinfo->input_scan_number;
  167464. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167465. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167466. /* Perform any dummy output passes, and set up for the final pass */
  167467. return output_pass_setup(cinfo);
  167468. }
  167469. /*
  167470. * Set up for an output pass, and perform any dummy pass(es) needed.
  167471. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167472. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167473. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167474. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167475. */
  167476. LOCAL(boolean)
  167477. output_pass_setup (j_decompress_ptr cinfo)
  167478. {
  167479. if (cinfo->global_state != DSTATE_PRESCAN) {
  167480. /* First call: do pass setup */
  167481. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167482. cinfo->output_scanline = 0;
  167483. cinfo->global_state = DSTATE_PRESCAN;
  167484. }
  167485. /* Loop over any required dummy passes */
  167486. while (cinfo->master->is_dummy_pass) {
  167487. #ifdef QUANT_2PASS_SUPPORTED
  167488. /* Crank through the dummy pass */
  167489. while (cinfo->output_scanline < cinfo->output_height) {
  167490. JDIMENSION last_scanline;
  167491. /* Call progress monitor hook if present */
  167492. if (cinfo->progress != NULL) {
  167493. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167494. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167495. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167496. }
  167497. /* Process some data */
  167498. last_scanline = cinfo->output_scanline;
  167499. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167500. &cinfo->output_scanline, (JDIMENSION) 0);
  167501. if (cinfo->output_scanline == last_scanline)
  167502. return FALSE; /* No progress made, must suspend */
  167503. }
  167504. /* Finish up dummy pass, and set up for another one */
  167505. (*cinfo->master->finish_output_pass) (cinfo);
  167506. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167507. cinfo->output_scanline = 0;
  167508. #else
  167509. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167510. #endif /* QUANT_2PASS_SUPPORTED */
  167511. }
  167512. /* Ready for application to drive output pass through
  167513. * jpeg_read_scanlines or jpeg_read_raw_data.
  167514. */
  167515. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167516. return TRUE;
  167517. }
  167518. /*
  167519. * Read some scanlines of data from the JPEG decompressor.
  167520. *
  167521. * The return value will be the number of lines actually read.
  167522. * This may be less than the number requested in several cases,
  167523. * including bottom of image, data source suspension, and operating
  167524. * modes that emit multiple scanlines at a time.
  167525. *
  167526. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167527. * this likely signals an application programmer error. However,
  167528. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167529. */
  167530. GLOBAL(JDIMENSION)
  167531. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167532. JDIMENSION max_lines)
  167533. {
  167534. JDIMENSION row_ctr;
  167535. if (cinfo->global_state != DSTATE_SCANNING)
  167536. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167537. if (cinfo->output_scanline >= cinfo->output_height) {
  167538. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167539. return 0;
  167540. }
  167541. /* Call progress monitor hook if present */
  167542. if (cinfo->progress != NULL) {
  167543. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167544. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167545. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167546. }
  167547. /* Process some data */
  167548. row_ctr = 0;
  167549. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167550. cinfo->output_scanline += row_ctr;
  167551. return row_ctr;
  167552. }
  167553. /*
  167554. * Alternate entry point to read raw data.
  167555. * Processes exactly one iMCU row per call, unless suspended.
  167556. */
  167557. GLOBAL(JDIMENSION)
  167558. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167559. JDIMENSION max_lines)
  167560. {
  167561. JDIMENSION lines_per_iMCU_row;
  167562. if (cinfo->global_state != DSTATE_RAW_OK)
  167563. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167564. if (cinfo->output_scanline >= cinfo->output_height) {
  167565. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167566. return 0;
  167567. }
  167568. /* Call progress monitor hook if present */
  167569. if (cinfo->progress != NULL) {
  167570. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167571. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167572. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167573. }
  167574. /* Verify that at least one iMCU row can be returned. */
  167575. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167576. if (max_lines < lines_per_iMCU_row)
  167577. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167578. /* Decompress directly into user's buffer. */
  167579. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167580. return 0; /* suspension forced, can do nothing more */
  167581. /* OK, we processed one iMCU row. */
  167582. cinfo->output_scanline += lines_per_iMCU_row;
  167583. return lines_per_iMCU_row;
  167584. }
  167585. /* Additional entry points for buffered-image mode. */
  167586. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167587. /*
  167588. * Initialize for an output pass in buffered-image mode.
  167589. */
  167590. GLOBAL(boolean)
  167591. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167592. {
  167593. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167594. cinfo->global_state != DSTATE_PRESCAN)
  167595. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167596. /* Limit scan number to valid range */
  167597. if (scan_number <= 0)
  167598. scan_number = 1;
  167599. if (cinfo->inputctl->eoi_reached &&
  167600. scan_number > cinfo->input_scan_number)
  167601. scan_number = cinfo->input_scan_number;
  167602. cinfo->output_scan_number = scan_number;
  167603. /* Perform any dummy output passes, and set up for the real pass */
  167604. return output_pass_setup(cinfo);
  167605. }
  167606. /*
  167607. * Finish up after an output pass in buffered-image mode.
  167608. *
  167609. * Returns FALSE if suspended. The return value need be inspected only if
  167610. * a suspending data source is used.
  167611. */
  167612. GLOBAL(boolean)
  167613. jpeg_finish_output (j_decompress_ptr cinfo)
  167614. {
  167615. if ((cinfo->global_state == DSTATE_SCANNING ||
  167616. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167617. /* Terminate this pass. */
  167618. /* We do not require the whole pass to have been completed. */
  167619. (*cinfo->master->finish_output_pass) (cinfo);
  167620. cinfo->global_state = DSTATE_BUFPOST;
  167621. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167622. /* BUFPOST = repeat call after a suspension, anything else is error */
  167623. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167624. }
  167625. /* Read markers looking for SOS or EOI */
  167626. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167627. ! cinfo->inputctl->eoi_reached) {
  167628. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167629. return FALSE; /* Suspend, come back later */
  167630. }
  167631. cinfo->global_state = DSTATE_BUFIMAGE;
  167632. return TRUE;
  167633. }
  167634. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167635. /*** End of inlined file: jdapistd.c ***/
  167636. /*** Start of inlined file: jdapimin.c ***/
  167637. #define JPEG_INTERNALS
  167638. /*
  167639. * Initialization of a JPEG decompression object.
  167640. * The error manager must already be set up (in case memory manager fails).
  167641. */
  167642. GLOBAL(void)
  167643. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167644. {
  167645. int i;
  167646. /* Guard against version mismatches between library and caller. */
  167647. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167648. if (version != JPEG_LIB_VERSION)
  167649. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167650. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167651. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167652. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167653. /* For debugging purposes, we zero the whole master structure.
  167654. * But the application has already set the err pointer, and may have set
  167655. * client_data, so we have to save and restore those fields.
  167656. * Note: if application hasn't set client_data, tools like Purify may
  167657. * complain here.
  167658. */
  167659. {
  167660. struct jpeg_error_mgr * err = cinfo->err;
  167661. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167662. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167663. cinfo->err = err;
  167664. cinfo->client_data = client_data;
  167665. }
  167666. cinfo->is_decompressor = TRUE;
  167667. /* Initialize a memory manager instance for this object */
  167668. jinit_memory_mgr((j_common_ptr) cinfo);
  167669. /* Zero out pointers to permanent structures. */
  167670. cinfo->progress = NULL;
  167671. cinfo->src = NULL;
  167672. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167673. cinfo->quant_tbl_ptrs[i] = NULL;
  167674. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167675. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167676. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167677. }
  167678. /* Initialize marker processor so application can override methods
  167679. * for COM, APPn markers before calling jpeg_read_header.
  167680. */
  167681. cinfo->marker_list = NULL;
  167682. jinit_marker_reader(cinfo);
  167683. /* And initialize the overall input controller. */
  167684. jinit_input_controller(cinfo);
  167685. /* OK, I'm ready */
  167686. cinfo->global_state = DSTATE_START;
  167687. }
  167688. /*
  167689. * Destruction of a JPEG decompression object
  167690. */
  167691. GLOBAL(void)
  167692. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167693. {
  167694. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167695. }
  167696. /*
  167697. * Abort processing of a JPEG decompression operation,
  167698. * but don't destroy the object itself.
  167699. */
  167700. GLOBAL(void)
  167701. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167702. {
  167703. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167704. }
  167705. /*
  167706. * Set default decompression parameters.
  167707. */
  167708. LOCAL(void)
  167709. default_decompress_parms (j_decompress_ptr cinfo)
  167710. {
  167711. /* Guess the input colorspace, and set output colorspace accordingly. */
  167712. /* (Wish JPEG committee had provided a real way to specify this...) */
  167713. /* Note application may override our guesses. */
  167714. switch (cinfo->num_components) {
  167715. case 1:
  167716. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167717. cinfo->out_color_space = JCS_GRAYSCALE;
  167718. break;
  167719. case 3:
  167720. if (cinfo->saw_JFIF_marker) {
  167721. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167722. } else if (cinfo->saw_Adobe_marker) {
  167723. switch (cinfo->Adobe_transform) {
  167724. case 0:
  167725. cinfo->jpeg_color_space = JCS_RGB;
  167726. break;
  167727. case 1:
  167728. cinfo->jpeg_color_space = JCS_YCbCr;
  167729. break;
  167730. default:
  167731. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167732. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167733. break;
  167734. }
  167735. } else {
  167736. /* Saw no special markers, try to guess from the component IDs */
  167737. int cid0 = cinfo->comp_info[0].component_id;
  167738. int cid1 = cinfo->comp_info[1].component_id;
  167739. int cid2 = cinfo->comp_info[2].component_id;
  167740. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167741. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167742. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167743. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167744. else {
  167745. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167746. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167747. }
  167748. }
  167749. /* Always guess RGB is proper output colorspace. */
  167750. cinfo->out_color_space = JCS_RGB;
  167751. break;
  167752. case 4:
  167753. if (cinfo->saw_Adobe_marker) {
  167754. switch (cinfo->Adobe_transform) {
  167755. case 0:
  167756. cinfo->jpeg_color_space = JCS_CMYK;
  167757. break;
  167758. case 2:
  167759. cinfo->jpeg_color_space = JCS_YCCK;
  167760. break;
  167761. default:
  167762. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167763. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167764. break;
  167765. }
  167766. } else {
  167767. /* No special markers, assume straight CMYK. */
  167768. cinfo->jpeg_color_space = JCS_CMYK;
  167769. }
  167770. cinfo->out_color_space = JCS_CMYK;
  167771. break;
  167772. default:
  167773. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167774. cinfo->out_color_space = JCS_UNKNOWN;
  167775. break;
  167776. }
  167777. /* Set defaults for other decompression parameters. */
  167778. cinfo->scale_num = 1; /* 1:1 scaling */
  167779. cinfo->scale_denom = 1;
  167780. cinfo->output_gamma = 1.0;
  167781. cinfo->buffered_image = FALSE;
  167782. cinfo->raw_data_out = FALSE;
  167783. cinfo->dct_method = JDCT_DEFAULT;
  167784. cinfo->do_fancy_upsampling = TRUE;
  167785. cinfo->do_block_smoothing = TRUE;
  167786. cinfo->quantize_colors = FALSE;
  167787. /* We set these in case application only sets quantize_colors. */
  167788. cinfo->dither_mode = JDITHER_FS;
  167789. #ifdef QUANT_2PASS_SUPPORTED
  167790. cinfo->two_pass_quantize = TRUE;
  167791. #else
  167792. cinfo->two_pass_quantize = FALSE;
  167793. #endif
  167794. cinfo->desired_number_of_colors = 256;
  167795. cinfo->colormap = NULL;
  167796. /* Initialize for no mode change in buffered-image mode. */
  167797. cinfo->enable_1pass_quant = FALSE;
  167798. cinfo->enable_external_quant = FALSE;
  167799. cinfo->enable_2pass_quant = FALSE;
  167800. }
  167801. /*
  167802. * Decompression startup: read start of JPEG datastream to see what's there.
  167803. * Need only initialize JPEG object and supply a data source before calling.
  167804. *
  167805. * This routine will read as far as the first SOS marker (ie, actual start of
  167806. * compressed data), and will save all tables and parameters in the JPEG
  167807. * object. It will also initialize the decompression parameters to default
  167808. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167809. * adjust the decompression parameters and then call jpeg_start_decompress.
  167810. * (Or, if the application only wanted to determine the image parameters,
  167811. * the data need not be decompressed. In that case, call jpeg_abort or
  167812. * jpeg_destroy to release any temporary space.)
  167813. * If an abbreviated (tables only) datastream is presented, the routine will
  167814. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167815. * re-use the JPEG object to read the abbreviated image datastream(s).
  167816. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167817. * The JPEG_SUSPENDED return code only occurs if the data source module
  167818. * requests suspension of the decompressor. In this case the application
  167819. * should load more source data and then re-call jpeg_read_header to resume
  167820. * processing.
  167821. * If a non-suspending data source is used and require_image is TRUE, then the
  167822. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167823. *
  167824. * This routine is now just a front end to jpeg_consume_input, with some
  167825. * extra error checking.
  167826. */
  167827. GLOBAL(int)
  167828. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167829. {
  167830. int retcode;
  167831. if (cinfo->global_state != DSTATE_START &&
  167832. cinfo->global_state != DSTATE_INHEADER)
  167833. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167834. retcode = jpeg_consume_input(cinfo);
  167835. switch (retcode) {
  167836. case JPEG_REACHED_SOS:
  167837. retcode = JPEG_HEADER_OK;
  167838. break;
  167839. case JPEG_REACHED_EOI:
  167840. if (require_image) /* Complain if application wanted an image */
  167841. ERREXIT(cinfo, JERR_NO_IMAGE);
  167842. /* Reset to start state; it would be safer to require the application to
  167843. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167844. * A side effect is to free any temporary memory (there shouldn't be any).
  167845. */
  167846. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167847. retcode = JPEG_HEADER_TABLES_ONLY;
  167848. break;
  167849. case JPEG_SUSPENDED:
  167850. /* no work */
  167851. break;
  167852. }
  167853. return retcode;
  167854. }
  167855. /*
  167856. * Consume data in advance of what the decompressor requires.
  167857. * This can be called at any time once the decompressor object has
  167858. * been created and a data source has been set up.
  167859. *
  167860. * This routine is essentially a state machine that handles a couple
  167861. * of critical state-transition actions, namely initial setup and
  167862. * transition from header scanning to ready-for-start_decompress.
  167863. * All the actual input is done via the input controller's consume_input
  167864. * method.
  167865. */
  167866. GLOBAL(int)
  167867. jpeg_consume_input (j_decompress_ptr cinfo)
  167868. {
  167869. int retcode = JPEG_SUSPENDED;
  167870. /* NB: every possible DSTATE value should be listed in this switch */
  167871. switch (cinfo->global_state) {
  167872. case DSTATE_START:
  167873. /* Start-of-datastream actions: reset appropriate modules */
  167874. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167875. /* Initialize application's data source module */
  167876. (*cinfo->src->init_source) (cinfo);
  167877. cinfo->global_state = DSTATE_INHEADER;
  167878. /*FALLTHROUGH*/
  167879. case DSTATE_INHEADER:
  167880. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167881. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167882. /* Set up default parameters based on header data */
  167883. default_decompress_parms(cinfo);
  167884. /* Set global state: ready for start_decompress */
  167885. cinfo->global_state = DSTATE_READY;
  167886. }
  167887. break;
  167888. case DSTATE_READY:
  167889. /* Can't advance past first SOS until start_decompress is called */
  167890. retcode = JPEG_REACHED_SOS;
  167891. break;
  167892. case DSTATE_PRELOAD:
  167893. case DSTATE_PRESCAN:
  167894. case DSTATE_SCANNING:
  167895. case DSTATE_RAW_OK:
  167896. case DSTATE_BUFIMAGE:
  167897. case DSTATE_BUFPOST:
  167898. case DSTATE_STOPPING:
  167899. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167900. break;
  167901. default:
  167902. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167903. }
  167904. return retcode;
  167905. }
  167906. /*
  167907. * Have we finished reading the input file?
  167908. */
  167909. GLOBAL(boolean)
  167910. jpeg_input_complete (j_decompress_ptr cinfo)
  167911. {
  167912. /* Check for valid jpeg object */
  167913. if (cinfo->global_state < DSTATE_START ||
  167914. cinfo->global_state > DSTATE_STOPPING)
  167915. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167916. return cinfo->inputctl->eoi_reached;
  167917. }
  167918. /*
  167919. * Is there more than one scan?
  167920. */
  167921. GLOBAL(boolean)
  167922. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167923. {
  167924. /* Only valid after jpeg_read_header completes */
  167925. if (cinfo->global_state < DSTATE_READY ||
  167926. cinfo->global_state > DSTATE_STOPPING)
  167927. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167928. return cinfo->inputctl->has_multiple_scans;
  167929. }
  167930. /*
  167931. * Finish JPEG decompression.
  167932. *
  167933. * This will normally just verify the file trailer and release temp storage.
  167934. *
  167935. * Returns FALSE if suspended. The return value need be inspected only if
  167936. * a suspending data source is used.
  167937. */
  167938. GLOBAL(boolean)
  167939. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167940. {
  167941. if ((cinfo->global_state == DSTATE_SCANNING ||
  167942. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167943. /* Terminate final pass of non-buffered mode */
  167944. if (cinfo->output_scanline < cinfo->output_height)
  167945. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167946. (*cinfo->master->finish_output_pass) (cinfo);
  167947. cinfo->global_state = DSTATE_STOPPING;
  167948. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167949. /* Finishing after a buffered-image operation */
  167950. cinfo->global_state = DSTATE_STOPPING;
  167951. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167952. /* STOPPING = repeat call after a suspension, anything else is error */
  167953. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167954. }
  167955. /* Read until EOI */
  167956. while (! cinfo->inputctl->eoi_reached) {
  167957. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167958. return FALSE; /* Suspend, come back later */
  167959. }
  167960. /* Do final cleanup */
  167961. (*cinfo->src->term_source) (cinfo);
  167962. /* We can use jpeg_abort to release memory and reset global_state */
  167963. jpeg_abort((j_common_ptr) cinfo);
  167964. return TRUE;
  167965. }
  167966. /*** End of inlined file: jdapimin.c ***/
  167967. /*** Start of inlined file: jdatasrc.c ***/
  167968. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167969. /*** Start of inlined file: jerror.h ***/
  167970. /*
  167971. * To define the enum list of message codes, include this file without
  167972. * defining macro JMESSAGE. To create a message string table, include it
  167973. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167974. */
  167975. #ifndef JMESSAGE
  167976. #ifndef JERROR_H
  167977. /* First time through, define the enum list */
  167978. #define JMAKE_ENUM_LIST
  167979. #else
  167980. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167981. #define JMESSAGE(code,string)
  167982. #endif /* JERROR_H */
  167983. #endif /* JMESSAGE */
  167984. #ifdef JMAKE_ENUM_LIST
  167985. typedef enum {
  167986. #define JMESSAGE(code,string) code ,
  167987. #endif /* JMAKE_ENUM_LIST */
  167988. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167989. /* For maintenance convenience, list is alphabetical by message code name */
  167990. JMESSAGE(JERR_ARITH_NOTIMPL,
  167991. "Sorry, there are legal restrictions on arithmetic coding")
  167992. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167993. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167994. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167995. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167996. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167997. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167998. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167999. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168000. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168001. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168002. JMESSAGE(JERR_BAD_LIB_VERSION,
  168003. "Wrong JPEG library version: library is %d, caller expects %d")
  168004. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168005. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168006. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168007. JMESSAGE(JERR_BAD_PROGRESSION,
  168008. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168009. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168010. "Invalid progressive parameters at scan script entry %d")
  168011. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168012. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168013. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168014. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168015. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168016. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168017. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168018. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168019. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168020. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168021. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168022. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168023. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168024. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168025. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168026. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168027. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168028. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168029. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168030. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168031. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168032. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168033. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168034. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168035. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168036. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168037. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168038. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168039. "Cannot transcode due to multiple use of quantization table %d")
  168040. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168041. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168042. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168043. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168044. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168045. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168046. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168047. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168048. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168049. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168050. JMESSAGE(JERR_QUANT_COMPONENTS,
  168051. "Cannot quantize more than %d color components")
  168052. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168053. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168054. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168055. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168056. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168057. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168058. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168059. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168060. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168061. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168062. JMESSAGE(JERR_TFILE_WRITE,
  168063. "Write failed on temporary file --- out of disk space?")
  168064. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168065. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168066. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168067. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168068. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168069. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168070. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168071. JMESSAGE(JMSG_VERSION, JVERSION)
  168072. JMESSAGE(JTRC_16BIT_TABLES,
  168073. "Caution: quantization tables are too coarse for baseline JPEG")
  168074. JMESSAGE(JTRC_ADOBE,
  168075. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168076. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168077. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168078. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168079. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168080. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168081. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168082. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168083. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168084. JMESSAGE(JTRC_EOI, "End Of Image")
  168085. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168086. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168087. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168088. "Warning: thumbnail image size does not match data length %u")
  168089. JMESSAGE(JTRC_JFIF_EXTENSION,
  168090. "JFIF extension marker: type 0x%02x, length %u")
  168091. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168092. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168093. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168094. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168095. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168096. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168097. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168098. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168099. JMESSAGE(JTRC_RST, "RST%d")
  168100. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168101. "Smoothing not supported with nonstandard sampling ratios")
  168102. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168103. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168104. JMESSAGE(JTRC_SOI, "Start of Image")
  168105. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168106. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168107. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168108. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168109. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168110. JMESSAGE(JTRC_THUMB_JPEG,
  168111. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168112. JMESSAGE(JTRC_THUMB_PALETTE,
  168113. "JFIF extension marker: palette thumbnail image, length %u")
  168114. JMESSAGE(JTRC_THUMB_RGB,
  168115. "JFIF extension marker: RGB thumbnail image, length %u")
  168116. JMESSAGE(JTRC_UNKNOWN_IDS,
  168117. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168118. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168119. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168120. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168121. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168122. "Inconsistent progression sequence for component %d coefficient %d")
  168123. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168124. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168125. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168126. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168127. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168128. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168129. JMESSAGE(JWRN_MUST_RESYNC,
  168130. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168131. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168132. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168133. #ifdef JMAKE_ENUM_LIST
  168134. JMSG_LASTMSGCODE
  168135. } J_MESSAGE_CODE;
  168136. #undef JMAKE_ENUM_LIST
  168137. #endif /* JMAKE_ENUM_LIST */
  168138. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168139. #undef JMESSAGE
  168140. #ifndef JERROR_H
  168141. #define JERROR_H
  168142. /* Macros to simplify using the error and trace message stuff */
  168143. /* The first parameter is either type of cinfo pointer */
  168144. /* Fatal errors (print message and exit) */
  168145. #define ERREXIT(cinfo,code) \
  168146. ((cinfo)->err->msg_code = (code), \
  168147. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168148. #define ERREXIT1(cinfo,code,p1) \
  168149. ((cinfo)->err->msg_code = (code), \
  168150. (cinfo)->err->msg_parm.i[0] = (p1), \
  168151. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168152. #define ERREXIT2(cinfo,code,p1,p2) \
  168153. ((cinfo)->err->msg_code = (code), \
  168154. (cinfo)->err->msg_parm.i[0] = (p1), \
  168155. (cinfo)->err->msg_parm.i[1] = (p2), \
  168156. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168157. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168158. ((cinfo)->err->msg_code = (code), \
  168159. (cinfo)->err->msg_parm.i[0] = (p1), \
  168160. (cinfo)->err->msg_parm.i[1] = (p2), \
  168161. (cinfo)->err->msg_parm.i[2] = (p3), \
  168162. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168163. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168164. ((cinfo)->err->msg_code = (code), \
  168165. (cinfo)->err->msg_parm.i[0] = (p1), \
  168166. (cinfo)->err->msg_parm.i[1] = (p2), \
  168167. (cinfo)->err->msg_parm.i[2] = (p3), \
  168168. (cinfo)->err->msg_parm.i[3] = (p4), \
  168169. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168170. #define ERREXITS(cinfo,code,str) \
  168171. ((cinfo)->err->msg_code = (code), \
  168172. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168173. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168174. #define MAKESTMT(stuff) do { stuff } while (0)
  168175. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168176. #define WARNMS(cinfo,code) \
  168177. ((cinfo)->err->msg_code = (code), \
  168178. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168179. #define WARNMS1(cinfo,code,p1) \
  168180. ((cinfo)->err->msg_code = (code), \
  168181. (cinfo)->err->msg_parm.i[0] = (p1), \
  168182. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168183. #define WARNMS2(cinfo,code,p1,p2) \
  168184. ((cinfo)->err->msg_code = (code), \
  168185. (cinfo)->err->msg_parm.i[0] = (p1), \
  168186. (cinfo)->err->msg_parm.i[1] = (p2), \
  168187. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168188. /* Informational/debugging messages */
  168189. #define TRACEMS(cinfo,lvl,code) \
  168190. ((cinfo)->err->msg_code = (code), \
  168191. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168192. #define TRACEMS1(cinfo,lvl,code,p1) \
  168193. ((cinfo)->err->msg_code = (code), \
  168194. (cinfo)->err->msg_parm.i[0] = (p1), \
  168195. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168196. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168197. ((cinfo)->err->msg_code = (code), \
  168198. (cinfo)->err->msg_parm.i[0] = (p1), \
  168199. (cinfo)->err->msg_parm.i[1] = (p2), \
  168200. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168201. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168202. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168203. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168204. (cinfo)->err->msg_code = (code); \
  168205. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168206. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168207. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168208. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168209. (cinfo)->err->msg_code = (code); \
  168210. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168211. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168212. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168213. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168214. _mp[4] = (p5); \
  168215. (cinfo)->err->msg_code = (code); \
  168216. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168217. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168218. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168219. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168220. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168221. (cinfo)->err->msg_code = (code); \
  168222. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168223. #define TRACEMSS(cinfo,lvl,code,str) \
  168224. ((cinfo)->err->msg_code = (code), \
  168225. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168226. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168227. #endif /* JERROR_H */
  168228. /*** End of inlined file: jerror.h ***/
  168229. /* Expanded data source object for stdio input */
  168230. typedef struct {
  168231. struct jpeg_source_mgr pub; /* public fields */
  168232. FILE * infile; /* source stream */
  168233. JOCTET * buffer; /* start of buffer */
  168234. boolean start_of_file; /* have we gotten any data yet? */
  168235. } my_source_mgr;
  168236. typedef my_source_mgr * my_src_ptr;
  168237. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168238. /*
  168239. * Initialize source --- called by jpeg_read_header
  168240. * before any data is actually read.
  168241. */
  168242. METHODDEF(void)
  168243. init_source (j_decompress_ptr cinfo)
  168244. {
  168245. my_src_ptr src = (my_src_ptr) cinfo->src;
  168246. /* We reset the empty-input-file flag for each image,
  168247. * but we don't clear the input buffer.
  168248. * This is correct behavior for reading a series of images from one source.
  168249. */
  168250. src->start_of_file = TRUE;
  168251. }
  168252. /*
  168253. * Fill the input buffer --- called whenever buffer is emptied.
  168254. *
  168255. * In typical applications, this should read fresh data into the buffer
  168256. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168257. * reset the pointer & count to the start of the buffer, and return TRUE
  168258. * indicating that the buffer has been reloaded. It is not necessary to
  168259. * fill the buffer entirely, only to obtain at least one more byte.
  168260. *
  168261. * There is no such thing as an EOF return. If the end of the file has been
  168262. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168263. * the buffer. In most cases, generating a warning message and inserting a
  168264. * fake EOI marker is the best course of action --- this will allow the
  168265. * decompressor to output however much of the image is there. However,
  168266. * the resulting error message is misleading if the real problem is an empty
  168267. * input file, so we handle that case specially.
  168268. *
  168269. * In applications that need to be able to suspend compression due to input
  168270. * not being available yet, a FALSE return indicates that no more data can be
  168271. * obtained right now, but more may be forthcoming later. In this situation,
  168272. * the decompressor will return to its caller (with an indication of the
  168273. * number of scanlines it has read, if any). The application should resume
  168274. * decompression after it has loaded more data into the input buffer. Note
  168275. * that there are substantial restrictions on the use of suspension --- see
  168276. * the documentation.
  168277. *
  168278. * When suspending, the decompressor will back up to a convenient restart point
  168279. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168280. * indicate where the restart point will be if the current call returns FALSE.
  168281. * Data beyond this point must be rescanned after resumption, so move it to
  168282. * the front of the buffer rather than discarding it.
  168283. */
  168284. METHODDEF(boolean)
  168285. fill_input_buffer (j_decompress_ptr cinfo)
  168286. {
  168287. my_src_ptr src = (my_src_ptr) cinfo->src;
  168288. size_t nbytes;
  168289. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168290. if (nbytes <= 0) {
  168291. if (src->start_of_file) /* Treat empty input file as fatal error */
  168292. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168293. WARNMS(cinfo, JWRN_JPEG_EOF);
  168294. /* Insert a fake EOI marker */
  168295. src->buffer[0] = (JOCTET) 0xFF;
  168296. src->buffer[1] = (JOCTET) JPEG_EOI;
  168297. nbytes = 2;
  168298. }
  168299. src->pub.next_input_byte = src->buffer;
  168300. src->pub.bytes_in_buffer = nbytes;
  168301. src->start_of_file = FALSE;
  168302. return TRUE;
  168303. }
  168304. /*
  168305. * Skip data --- used to skip over a potentially large amount of
  168306. * uninteresting data (such as an APPn marker).
  168307. *
  168308. * Writers of suspendable-input applications must note that skip_input_data
  168309. * is not granted the right to give a suspension return. If the skip extends
  168310. * beyond the data currently in the buffer, the buffer can be marked empty so
  168311. * that the next read will cause a fill_input_buffer call that can suspend.
  168312. * Arranging for additional bytes to be discarded before reloading the input
  168313. * buffer is the application writer's problem.
  168314. */
  168315. METHODDEF(void)
  168316. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168317. {
  168318. my_src_ptr src = (my_src_ptr) cinfo->src;
  168319. /* Just a dumb implementation for now. Could use fseek() except
  168320. * it doesn't work on pipes. Not clear that being smart is worth
  168321. * any trouble anyway --- large skips are infrequent.
  168322. */
  168323. if (num_bytes > 0) {
  168324. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168325. num_bytes -= (long) src->pub.bytes_in_buffer;
  168326. (void) fill_input_buffer(cinfo);
  168327. /* note we assume that fill_input_buffer will never return FALSE,
  168328. * so suspension need not be handled.
  168329. */
  168330. }
  168331. src->pub.next_input_byte += (size_t) num_bytes;
  168332. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168333. }
  168334. }
  168335. /*
  168336. * An additional method that can be provided by data source modules is the
  168337. * resync_to_restart method for error recovery in the presence of RST markers.
  168338. * For the moment, this source module just uses the default resync method
  168339. * provided by the JPEG library. That method assumes that no backtracking
  168340. * is possible.
  168341. */
  168342. /*
  168343. * Terminate source --- called by jpeg_finish_decompress
  168344. * after all data has been read. Often a no-op.
  168345. *
  168346. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168347. * application must deal with any cleanup that should happen even
  168348. * for error exit.
  168349. */
  168350. METHODDEF(void)
  168351. term_source (j_decompress_ptr)
  168352. {
  168353. /* no work necessary here */
  168354. }
  168355. /*
  168356. * Prepare for input from a stdio stream.
  168357. * The caller must have already opened the stream, and is responsible
  168358. * for closing it after finishing decompression.
  168359. */
  168360. GLOBAL(void)
  168361. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168362. {
  168363. my_src_ptr src;
  168364. /* The source object and input buffer are made permanent so that a series
  168365. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168366. * only before the first one. (If we discarded the buffer at the end of
  168367. * one image, we'd likely lose the start of the next one.)
  168368. * This makes it unsafe to use this manager and a different source
  168369. * manager serially with the same JPEG object. Caveat programmer.
  168370. */
  168371. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168372. cinfo->src = (struct jpeg_source_mgr *)
  168373. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168374. SIZEOF(my_source_mgr));
  168375. src = (my_src_ptr) cinfo->src;
  168376. src->buffer = (JOCTET *)
  168377. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168378. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168379. }
  168380. src = (my_src_ptr) cinfo->src;
  168381. src->pub.init_source = init_source;
  168382. src->pub.fill_input_buffer = fill_input_buffer;
  168383. src->pub.skip_input_data = skip_input_data;
  168384. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168385. src->pub.term_source = term_source;
  168386. src->infile = infile;
  168387. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168388. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168389. }
  168390. /*** End of inlined file: jdatasrc.c ***/
  168391. /*** Start of inlined file: jdcoefct.c ***/
  168392. #define JPEG_INTERNALS
  168393. /* Block smoothing is only applicable for progressive JPEG, so: */
  168394. #ifndef D_PROGRESSIVE_SUPPORTED
  168395. #undef BLOCK_SMOOTHING_SUPPORTED
  168396. #endif
  168397. /* Private buffer controller object */
  168398. typedef struct {
  168399. struct jpeg_d_coef_controller pub; /* public fields */
  168400. /* These variables keep track of the current location of the input side. */
  168401. /* cinfo->input_iMCU_row is also used for this. */
  168402. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168403. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168404. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168405. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168406. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168407. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168408. * and let the entropy decoder write into that workspace each time.
  168409. * (On 80x86, the workspace is FAR even though it's not really very big;
  168410. * this is to keep the module interfaces unchanged when a large coefficient
  168411. * buffer is necessary.)
  168412. * In multi-pass modes, this array points to the current MCU's blocks
  168413. * within the virtual arrays; it is used only by the input side.
  168414. */
  168415. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168416. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168417. /* In multi-pass modes, we need a virtual block array for each component. */
  168418. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168419. #endif
  168420. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168421. /* When doing block smoothing, we latch coefficient Al values here */
  168422. int * coef_bits_latch;
  168423. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168424. #endif
  168425. } my_coef_controller3;
  168426. typedef my_coef_controller3 * my_coef_ptr3;
  168427. /* Forward declarations */
  168428. METHODDEF(int) decompress_onepass
  168429. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168430. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168431. METHODDEF(int) decompress_data
  168432. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168433. #endif
  168434. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168435. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168436. METHODDEF(int) decompress_smooth_data
  168437. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168438. #endif
  168439. LOCAL(void)
  168440. start_iMCU_row3 (j_decompress_ptr cinfo)
  168441. /* Reset within-iMCU-row counters for a new row (input side) */
  168442. {
  168443. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168444. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168445. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168446. * But at the bottom of the image, process only what's left.
  168447. */
  168448. if (cinfo->comps_in_scan > 1) {
  168449. coef->MCU_rows_per_iMCU_row = 1;
  168450. } else {
  168451. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168452. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168453. else
  168454. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168455. }
  168456. coef->MCU_ctr = 0;
  168457. coef->MCU_vert_offset = 0;
  168458. }
  168459. /*
  168460. * Initialize for an input processing pass.
  168461. */
  168462. METHODDEF(void)
  168463. start_input_pass (j_decompress_ptr cinfo)
  168464. {
  168465. cinfo->input_iMCU_row = 0;
  168466. start_iMCU_row3(cinfo);
  168467. }
  168468. /*
  168469. * Initialize for an output processing pass.
  168470. */
  168471. METHODDEF(void)
  168472. start_output_pass (j_decompress_ptr cinfo)
  168473. {
  168474. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168475. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168476. /* If multipass, check to see whether to use block smoothing on this pass */
  168477. if (coef->pub.coef_arrays != NULL) {
  168478. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168479. coef->pub.decompress_data = decompress_smooth_data;
  168480. else
  168481. coef->pub.decompress_data = decompress_data;
  168482. }
  168483. #endif
  168484. cinfo->output_iMCU_row = 0;
  168485. }
  168486. /*
  168487. * Decompress and return some data in the single-pass case.
  168488. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168489. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168490. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168491. *
  168492. * NB: output_buf contains a plane for each component in image,
  168493. * which we index according to the component's SOF position.
  168494. */
  168495. METHODDEF(int)
  168496. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168497. {
  168498. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168499. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168500. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168501. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168502. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168503. JSAMPARRAY output_ptr;
  168504. JDIMENSION start_col, output_col;
  168505. jpeg_component_info *compptr;
  168506. inverse_DCT_method_ptr inverse_DCT;
  168507. /* Loop to process as much as one whole iMCU row */
  168508. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168509. yoffset++) {
  168510. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168511. MCU_col_num++) {
  168512. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168513. jzero_far((void FAR *) coef->MCU_buffer[0],
  168514. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168515. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168516. /* Suspension forced; update state counters and exit */
  168517. coef->MCU_vert_offset = yoffset;
  168518. coef->MCU_ctr = MCU_col_num;
  168519. return JPEG_SUSPENDED;
  168520. }
  168521. /* Determine where data should go in output_buf and do the IDCT thing.
  168522. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168523. * incremented past them!). Note the inner loop relies on having
  168524. * allocated the MCU_buffer[] blocks sequentially.
  168525. */
  168526. blkn = 0; /* index of current DCT block within MCU */
  168527. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168528. compptr = cinfo->cur_comp_info[ci];
  168529. /* Don't bother to IDCT an uninteresting component. */
  168530. if (! compptr->component_needed) {
  168531. blkn += compptr->MCU_blocks;
  168532. continue;
  168533. }
  168534. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168535. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168536. : compptr->last_col_width;
  168537. output_ptr = output_buf[compptr->component_index] +
  168538. yoffset * compptr->DCT_scaled_size;
  168539. start_col = MCU_col_num * compptr->MCU_sample_width;
  168540. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168541. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168542. yoffset+yindex < compptr->last_row_height) {
  168543. output_col = start_col;
  168544. for (xindex = 0; xindex < useful_width; xindex++) {
  168545. (*inverse_DCT) (cinfo, compptr,
  168546. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168547. output_ptr, output_col);
  168548. output_col += compptr->DCT_scaled_size;
  168549. }
  168550. }
  168551. blkn += compptr->MCU_width;
  168552. output_ptr += compptr->DCT_scaled_size;
  168553. }
  168554. }
  168555. }
  168556. /* Completed an MCU row, but perhaps not an iMCU row */
  168557. coef->MCU_ctr = 0;
  168558. }
  168559. /* Completed the iMCU row, advance counters for next one */
  168560. cinfo->output_iMCU_row++;
  168561. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168562. start_iMCU_row3(cinfo);
  168563. return JPEG_ROW_COMPLETED;
  168564. }
  168565. /* Completed the scan */
  168566. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168567. return JPEG_SCAN_COMPLETED;
  168568. }
  168569. /*
  168570. * Dummy consume-input routine for single-pass operation.
  168571. */
  168572. METHODDEF(int)
  168573. dummy_consume_data (j_decompress_ptr)
  168574. {
  168575. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168576. }
  168577. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168578. /*
  168579. * Consume input data and store it in the full-image coefficient buffer.
  168580. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168581. * ie, v_samp_factor block rows for each component in the scan.
  168582. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168583. */
  168584. METHODDEF(int)
  168585. consume_data (j_decompress_ptr cinfo)
  168586. {
  168587. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168588. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168589. int blkn, ci, xindex, yindex, yoffset;
  168590. JDIMENSION start_col;
  168591. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168592. JBLOCKROW buffer_ptr;
  168593. jpeg_component_info *compptr;
  168594. /* Align the virtual buffers for the components used in this scan. */
  168595. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168596. compptr = cinfo->cur_comp_info[ci];
  168597. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168598. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168599. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168600. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168601. /* Note: entropy decoder expects buffer to be zeroed,
  168602. * but this is handled automatically by the memory manager
  168603. * because we requested a pre-zeroed array.
  168604. */
  168605. }
  168606. /* Loop to process one whole iMCU row */
  168607. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168608. yoffset++) {
  168609. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168610. MCU_col_num++) {
  168611. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168612. blkn = 0; /* index of current DCT block within MCU */
  168613. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168614. compptr = cinfo->cur_comp_info[ci];
  168615. start_col = MCU_col_num * compptr->MCU_width;
  168616. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168617. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168618. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168619. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168620. }
  168621. }
  168622. }
  168623. /* Try to fetch the MCU. */
  168624. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168625. /* Suspension forced; update state counters and exit */
  168626. coef->MCU_vert_offset = yoffset;
  168627. coef->MCU_ctr = MCU_col_num;
  168628. return JPEG_SUSPENDED;
  168629. }
  168630. }
  168631. /* Completed an MCU row, but perhaps not an iMCU row */
  168632. coef->MCU_ctr = 0;
  168633. }
  168634. /* Completed the iMCU row, advance counters for next one */
  168635. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168636. start_iMCU_row3(cinfo);
  168637. return JPEG_ROW_COMPLETED;
  168638. }
  168639. /* Completed the scan */
  168640. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168641. return JPEG_SCAN_COMPLETED;
  168642. }
  168643. /*
  168644. * Decompress and return some data in the multi-pass case.
  168645. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168646. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168647. *
  168648. * NB: output_buf contains a plane for each component in image.
  168649. */
  168650. METHODDEF(int)
  168651. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168652. {
  168653. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168654. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168655. JDIMENSION block_num;
  168656. int ci, block_row, block_rows;
  168657. JBLOCKARRAY buffer;
  168658. JBLOCKROW buffer_ptr;
  168659. JSAMPARRAY output_ptr;
  168660. JDIMENSION output_col;
  168661. jpeg_component_info *compptr;
  168662. inverse_DCT_method_ptr inverse_DCT;
  168663. /* Force some input to be done if we are getting ahead of the input. */
  168664. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168665. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168666. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168667. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168668. return JPEG_SUSPENDED;
  168669. }
  168670. /* OK, output from the virtual arrays. */
  168671. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168672. ci++, compptr++) {
  168673. /* Don't bother to IDCT an uninteresting component. */
  168674. if (! compptr->component_needed)
  168675. continue;
  168676. /* Align the virtual buffer for this component. */
  168677. buffer = (*cinfo->mem->access_virt_barray)
  168678. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168679. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168680. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168681. /* Count non-dummy DCT block rows in this iMCU row. */
  168682. if (cinfo->output_iMCU_row < last_iMCU_row)
  168683. block_rows = compptr->v_samp_factor;
  168684. else {
  168685. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168686. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168687. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168688. }
  168689. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168690. output_ptr = output_buf[ci];
  168691. /* Loop over all DCT blocks to be processed. */
  168692. for (block_row = 0; block_row < block_rows; block_row++) {
  168693. buffer_ptr = buffer[block_row];
  168694. output_col = 0;
  168695. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168696. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168697. output_ptr, output_col);
  168698. buffer_ptr++;
  168699. output_col += compptr->DCT_scaled_size;
  168700. }
  168701. output_ptr += compptr->DCT_scaled_size;
  168702. }
  168703. }
  168704. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168705. return JPEG_ROW_COMPLETED;
  168706. return JPEG_SCAN_COMPLETED;
  168707. }
  168708. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168709. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168710. /*
  168711. * This code applies interblock smoothing as described by section K.8
  168712. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168713. * the DC values of a DCT block and its 8 neighboring blocks.
  168714. * We apply smoothing only for progressive JPEG decoding, and only if
  168715. * the coefficients it can estimate are not yet known to full precision.
  168716. */
  168717. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168718. #define Q01_POS 1
  168719. #define Q10_POS 8
  168720. #define Q20_POS 16
  168721. #define Q11_POS 9
  168722. #define Q02_POS 2
  168723. /*
  168724. * Determine whether block smoothing is applicable and safe.
  168725. * We also latch the current states of the coef_bits[] entries for the
  168726. * AC coefficients; otherwise, if the input side of the decompressor
  168727. * advances into a new scan, we might think the coefficients are known
  168728. * more accurately than they really are.
  168729. */
  168730. LOCAL(boolean)
  168731. smoothing_ok (j_decompress_ptr cinfo)
  168732. {
  168733. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168734. boolean smoothing_useful = FALSE;
  168735. int ci, coefi;
  168736. jpeg_component_info *compptr;
  168737. JQUANT_TBL * qtable;
  168738. int * coef_bits;
  168739. int * coef_bits_latch;
  168740. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168741. return FALSE;
  168742. /* Allocate latch area if not already done */
  168743. if (coef->coef_bits_latch == NULL)
  168744. coef->coef_bits_latch = (int *)
  168745. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168746. cinfo->num_components *
  168747. (SAVED_COEFS * SIZEOF(int)));
  168748. coef_bits_latch = coef->coef_bits_latch;
  168749. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168750. ci++, compptr++) {
  168751. /* All components' quantization values must already be latched. */
  168752. if ((qtable = compptr->quant_table) == NULL)
  168753. return FALSE;
  168754. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168755. if (qtable->quantval[0] == 0 ||
  168756. qtable->quantval[Q01_POS] == 0 ||
  168757. qtable->quantval[Q10_POS] == 0 ||
  168758. qtable->quantval[Q20_POS] == 0 ||
  168759. qtable->quantval[Q11_POS] == 0 ||
  168760. qtable->quantval[Q02_POS] == 0)
  168761. return FALSE;
  168762. /* DC values must be at least partly known for all components. */
  168763. coef_bits = cinfo->coef_bits[ci];
  168764. if (coef_bits[0] < 0)
  168765. return FALSE;
  168766. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168767. for (coefi = 1; coefi <= 5; coefi++) {
  168768. coef_bits_latch[coefi] = coef_bits[coefi];
  168769. if (coef_bits[coefi] != 0)
  168770. smoothing_useful = TRUE;
  168771. }
  168772. coef_bits_latch += SAVED_COEFS;
  168773. }
  168774. return smoothing_useful;
  168775. }
  168776. /*
  168777. * Variant of decompress_data for use when doing block smoothing.
  168778. */
  168779. METHODDEF(int)
  168780. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168781. {
  168782. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168783. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168784. JDIMENSION block_num, last_block_column;
  168785. int ci, block_row, block_rows, access_rows;
  168786. JBLOCKARRAY buffer;
  168787. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168788. JSAMPARRAY output_ptr;
  168789. JDIMENSION output_col;
  168790. jpeg_component_info *compptr;
  168791. inverse_DCT_method_ptr inverse_DCT;
  168792. boolean first_row, last_row;
  168793. JBLOCK workspace;
  168794. int *coef_bits;
  168795. JQUANT_TBL *quanttbl;
  168796. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168797. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168798. int Al, pred;
  168799. /* Force some input to be done if we are getting ahead of the input. */
  168800. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168801. ! cinfo->inputctl->eoi_reached) {
  168802. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168803. /* If input is working on current scan, we ordinarily want it to
  168804. * have completed the current row. But if input scan is DC,
  168805. * we want it to keep one row ahead so that next block row's DC
  168806. * values are up to date.
  168807. */
  168808. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168809. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168810. break;
  168811. }
  168812. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168813. return JPEG_SUSPENDED;
  168814. }
  168815. /* OK, output from the virtual arrays. */
  168816. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168817. ci++, compptr++) {
  168818. /* Don't bother to IDCT an uninteresting component. */
  168819. if (! compptr->component_needed)
  168820. continue;
  168821. /* Count non-dummy DCT block rows in this iMCU row. */
  168822. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168823. block_rows = compptr->v_samp_factor;
  168824. access_rows = block_rows * 2; /* this and next iMCU row */
  168825. last_row = FALSE;
  168826. } else {
  168827. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168828. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168829. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168830. access_rows = block_rows; /* this iMCU row only */
  168831. last_row = TRUE;
  168832. }
  168833. /* Align the virtual buffer for this component. */
  168834. if (cinfo->output_iMCU_row > 0) {
  168835. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168836. buffer = (*cinfo->mem->access_virt_barray)
  168837. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168838. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168839. (JDIMENSION) access_rows, FALSE);
  168840. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168841. first_row = FALSE;
  168842. } else {
  168843. buffer = (*cinfo->mem->access_virt_barray)
  168844. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168845. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168846. first_row = TRUE;
  168847. }
  168848. /* Fetch component-dependent info */
  168849. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168850. quanttbl = compptr->quant_table;
  168851. Q00 = quanttbl->quantval[0];
  168852. Q01 = quanttbl->quantval[Q01_POS];
  168853. Q10 = quanttbl->quantval[Q10_POS];
  168854. Q20 = quanttbl->quantval[Q20_POS];
  168855. Q11 = quanttbl->quantval[Q11_POS];
  168856. Q02 = quanttbl->quantval[Q02_POS];
  168857. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168858. output_ptr = output_buf[ci];
  168859. /* Loop over all DCT blocks to be processed. */
  168860. for (block_row = 0; block_row < block_rows; block_row++) {
  168861. buffer_ptr = buffer[block_row];
  168862. if (first_row && block_row == 0)
  168863. prev_block_row = buffer_ptr;
  168864. else
  168865. prev_block_row = buffer[block_row-1];
  168866. if (last_row && block_row == block_rows-1)
  168867. next_block_row = buffer_ptr;
  168868. else
  168869. next_block_row = buffer[block_row+1];
  168870. /* We fetch the surrounding DC values using a sliding-register approach.
  168871. * Initialize all nine here so as to do the right thing on narrow pics.
  168872. */
  168873. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168874. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168875. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168876. output_col = 0;
  168877. last_block_column = compptr->width_in_blocks - 1;
  168878. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168879. /* Fetch current DCT block into workspace so we can modify it. */
  168880. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168881. /* Update DC values */
  168882. if (block_num < last_block_column) {
  168883. DC3 = (int) prev_block_row[1][0];
  168884. DC6 = (int) buffer_ptr[1][0];
  168885. DC9 = (int) next_block_row[1][0];
  168886. }
  168887. /* Compute coefficient estimates per K.8.
  168888. * An estimate is applied only if coefficient is still zero,
  168889. * and is not known to be fully accurate.
  168890. */
  168891. /* AC01 */
  168892. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168893. num = 36 * Q00 * (DC4 - DC6);
  168894. if (num >= 0) {
  168895. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168896. if (Al > 0 && pred >= (1<<Al))
  168897. pred = (1<<Al)-1;
  168898. } else {
  168899. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168900. if (Al > 0 && pred >= (1<<Al))
  168901. pred = (1<<Al)-1;
  168902. pred = -pred;
  168903. }
  168904. workspace[1] = (JCOEF) pred;
  168905. }
  168906. /* AC10 */
  168907. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168908. num = 36 * Q00 * (DC2 - DC8);
  168909. if (num >= 0) {
  168910. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168911. if (Al > 0 && pred >= (1<<Al))
  168912. pred = (1<<Al)-1;
  168913. } else {
  168914. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168915. if (Al > 0 && pred >= (1<<Al))
  168916. pred = (1<<Al)-1;
  168917. pred = -pred;
  168918. }
  168919. workspace[8] = (JCOEF) pred;
  168920. }
  168921. /* AC20 */
  168922. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168923. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168924. if (num >= 0) {
  168925. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168926. if (Al > 0 && pred >= (1<<Al))
  168927. pred = (1<<Al)-1;
  168928. } else {
  168929. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168930. if (Al > 0 && pred >= (1<<Al))
  168931. pred = (1<<Al)-1;
  168932. pred = -pred;
  168933. }
  168934. workspace[16] = (JCOEF) pred;
  168935. }
  168936. /* AC11 */
  168937. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168938. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168939. if (num >= 0) {
  168940. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168941. if (Al > 0 && pred >= (1<<Al))
  168942. pred = (1<<Al)-1;
  168943. } else {
  168944. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168945. if (Al > 0 && pred >= (1<<Al))
  168946. pred = (1<<Al)-1;
  168947. pred = -pred;
  168948. }
  168949. workspace[9] = (JCOEF) pred;
  168950. }
  168951. /* AC02 */
  168952. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168953. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168954. if (num >= 0) {
  168955. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168956. if (Al > 0 && pred >= (1<<Al))
  168957. pred = (1<<Al)-1;
  168958. } else {
  168959. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168960. if (Al > 0 && pred >= (1<<Al))
  168961. pred = (1<<Al)-1;
  168962. pred = -pred;
  168963. }
  168964. workspace[2] = (JCOEF) pred;
  168965. }
  168966. /* OK, do the IDCT */
  168967. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168968. output_ptr, output_col);
  168969. /* Advance for next column */
  168970. DC1 = DC2; DC2 = DC3;
  168971. DC4 = DC5; DC5 = DC6;
  168972. DC7 = DC8; DC8 = DC9;
  168973. buffer_ptr++, prev_block_row++, next_block_row++;
  168974. output_col += compptr->DCT_scaled_size;
  168975. }
  168976. output_ptr += compptr->DCT_scaled_size;
  168977. }
  168978. }
  168979. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168980. return JPEG_ROW_COMPLETED;
  168981. return JPEG_SCAN_COMPLETED;
  168982. }
  168983. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168984. /*
  168985. * Initialize coefficient buffer controller.
  168986. */
  168987. GLOBAL(void)
  168988. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168989. {
  168990. my_coef_ptr3 coef;
  168991. coef = (my_coef_ptr3)
  168992. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168993. SIZEOF(my_coef_controller3));
  168994. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168995. coef->pub.start_input_pass = start_input_pass;
  168996. coef->pub.start_output_pass = start_output_pass;
  168997. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168998. coef->coef_bits_latch = NULL;
  168999. #endif
  169000. /* Create the coefficient buffer. */
  169001. if (need_full_buffer) {
  169002. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169003. /* Allocate a full-image virtual array for each component, */
  169004. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169005. /* Note we ask for a pre-zeroed array. */
  169006. int ci, access_rows;
  169007. jpeg_component_info *compptr;
  169008. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169009. ci++, compptr++) {
  169010. access_rows = compptr->v_samp_factor;
  169011. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169012. /* If block smoothing could be used, need a bigger window */
  169013. if (cinfo->progressive_mode)
  169014. access_rows *= 3;
  169015. #endif
  169016. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169017. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169018. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169019. (long) compptr->h_samp_factor),
  169020. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169021. (long) compptr->v_samp_factor),
  169022. (JDIMENSION) access_rows);
  169023. }
  169024. coef->pub.consume_data = consume_data;
  169025. coef->pub.decompress_data = decompress_data;
  169026. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169027. #else
  169028. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169029. #endif
  169030. } else {
  169031. /* We only need a single-MCU buffer. */
  169032. JBLOCKROW buffer;
  169033. int i;
  169034. buffer = (JBLOCKROW)
  169035. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169036. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169037. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169038. coef->MCU_buffer[i] = buffer + i;
  169039. }
  169040. coef->pub.consume_data = dummy_consume_data;
  169041. coef->pub.decompress_data = decompress_onepass;
  169042. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169043. }
  169044. }
  169045. /*** End of inlined file: jdcoefct.c ***/
  169046. #undef FIX
  169047. /*** Start of inlined file: jdcolor.c ***/
  169048. #define JPEG_INTERNALS
  169049. /* Private subobject */
  169050. typedef struct {
  169051. struct jpeg_color_deconverter pub; /* public fields */
  169052. /* Private state for YCC->RGB conversion */
  169053. int * Cr_r_tab; /* => table for Cr to R conversion */
  169054. int * Cb_b_tab; /* => table for Cb to B conversion */
  169055. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169056. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169057. } my_color_deconverter2;
  169058. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169059. /**************** YCbCr -> RGB conversion: most common case **************/
  169060. /*
  169061. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169062. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169063. * The conversion equations to be implemented are therefore
  169064. * R = Y + 1.40200 * Cr
  169065. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169066. * B = Y + 1.77200 * Cb
  169067. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169068. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169069. *
  169070. * To avoid floating-point arithmetic, we represent the fractional constants
  169071. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169072. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169073. * Notice that Y, being an integral input, does not contribute any fraction
  169074. * so it need not participate in the rounding.
  169075. *
  169076. * For even more speed, we avoid doing any multiplications in the inner loop
  169077. * by precalculating the constants times Cb and Cr for all possible values.
  169078. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169079. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169080. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169081. * colorspace anyway.
  169082. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169083. * values for the G calculation are left scaled up, since we must add them
  169084. * together before rounding.
  169085. */
  169086. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169087. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169088. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169089. /*
  169090. * Initialize tables for YCC->RGB colorspace conversion.
  169091. */
  169092. LOCAL(void)
  169093. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169094. {
  169095. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169096. int i;
  169097. INT32 x;
  169098. SHIFT_TEMPS
  169099. cconvert->Cr_r_tab = (int *)
  169100. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169101. (MAXJSAMPLE+1) * SIZEOF(int));
  169102. cconvert->Cb_b_tab = (int *)
  169103. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169104. (MAXJSAMPLE+1) * SIZEOF(int));
  169105. cconvert->Cr_g_tab = (INT32 *)
  169106. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169107. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169108. cconvert->Cb_g_tab = (INT32 *)
  169109. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169110. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169111. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169112. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169113. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169114. /* Cr=>R value is nearest int to 1.40200 * x */
  169115. cconvert->Cr_r_tab[i] = (int)
  169116. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169117. /* Cb=>B value is nearest int to 1.77200 * x */
  169118. cconvert->Cb_b_tab[i] = (int)
  169119. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169120. /* Cr=>G value is scaled-up -0.71414 * x */
  169121. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169122. /* Cb=>G value is scaled-up -0.34414 * x */
  169123. /* We also add in ONE_HALF so that need not do it in inner loop */
  169124. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169125. }
  169126. }
  169127. /*
  169128. * Convert some rows of samples to the output colorspace.
  169129. *
  169130. * Note that we change from noninterleaved, one-plane-per-component format
  169131. * to interleaved-pixel format. The output buffer is therefore three times
  169132. * as wide as the input buffer.
  169133. * A starting row offset is provided only for the input buffer. The caller
  169134. * can easily adjust the passed output_buf value to accommodate any row
  169135. * offset required on that side.
  169136. */
  169137. METHODDEF(void)
  169138. ycc_rgb_convert (j_decompress_ptr cinfo,
  169139. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169140. JSAMPARRAY output_buf, int num_rows)
  169141. {
  169142. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169143. register int y, cb, cr;
  169144. register JSAMPROW outptr;
  169145. register JSAMPROW inptr0, inptr1, inptr2;
  169146. register JDIMENSION col;
  169147. JDIMENSION num_cols = cinfo->output_width;
  169148. /* copy these pointers into registers if possible */
  169149. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169150. register int * Crrtab = cconvert->Cr_r_tab;
  169151. register int * Cbbtab = cconvert->Cb_b_tab;
  169152. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169153. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169154. SHIFT_TEMPS
  169155. while (--num_rows >= 0) {
  169156. inptr0 = input_buf[0][input_row];
  169157. inptr1 = input_buf[1][input_row];
  169158. inptr2 = input_buf[2][input_row];
  169159. input_row++;
  169160. outptr = *output_buf++;
  169161. for (col = 0; col < num_cols; col++) {
  169162. y = GETJSAMPLE(inptr0[col]);
  169163. cb = GETJSAMPLE(inptr1[col]);
  169164. cr = GETJSAMPLE(inptr2[col]);
  169165. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169166. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169167. outptr[RGB_GREEN] = range_limit[y +
  169168. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169169. SCALEBITS))];
  169170. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169171. outptr += RGB_PIXELSIZE;
  169172. }
  169173. }
  169174. }
  169175. /**************** Cases other than YCbCr -> RGB **************/
  169176. /*
  169177. * Color conversion for no colorspace change: just copy the data,
  169178. * converting from separate-planes to interleaved representation.
  169179. */
  169180. METHODDEF(void)
  169181. null_convert2 (j_decompress_ptr cinfo,
  169182. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169183. JSAMPARRAY output_buf, int num_rows)
  169184. {
  169185. register JSAMPROW inptr, outptr;
  169186. register JDIMENSION count;
  169187. register int num_components = cinfo->num_components;
  169188. JDIMENSION num_cols = cinfo->output_width;
  169189. int ci;
  169190. while (--num_rows >= 0) {
  169191. for (ci = 0; ci < num_components; ci++) {
  169192. inptr = input_buf[ci][input_row];
  169193. outptr = output_buf[0] + ci;
  169194. for (count = num_cols; count > 0; count--) {
  169195. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169196. outptr += num_components;
  169197. }
  169198. }
  169199. input_row++;
  169200. output_buf++;
  169201. }
  169202. }
  169203. /*
  169204. * Color conversion for grayscale: just copy the data.
  169205. * This also works for YCbCr -> grayscale conversion, in which
  169206. * we just copy the Y (luminance) component and ignore chrominance.
  169207. */
  169208. METHODDEF(void)
  169209. grayscale_convert2 (j_decompress_ptr cinfo,
  169210. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169211. JSAMPARRAY output_buf, int num_rows)
  169212. {
  169213. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169214. num_rows, cinfo->output_width);
  169215. }
  169216. /*
  169217. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169218. * This is provided to support applications that don't want to cope
  169219. * with grayscale as a separate case.
  169220. */
  169221. METHODDEF(void)
  169222. gray_rgb_convert (j_decompress_ptr cinfo,
  169223. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169224. JSAMPARRAY output_buf, int num_rows)
  169225. {
  169226. register JSAMPROW inptr, outptr;
  169227. register JDIMENSION col;
  169228. JDIMENSION num_cols = cinfo->output_width;
  169229. while (--num_rows >= 0) {
  169230. inptr = input_buf[0][input_row++];
  169231. outptr = *output_buf++;
  169232. for (col = 0; col < num_cols; col++) {
  169233. /* We can dispense with GETJSAMPLE() here */
  169234. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169235. outptr += RGB_PIXELSIZE;
  169236. }
  169237. }
  169238. }
  169239. /*
  169240. * Adobe-style YCCK->CMYK conversion.
  169241. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169242. * conversion as above, while passing K (black) unchanged.
  169243. * We assume build_ycc_rgb_table has been called.
  169244. */
  169245. METHODDEF(void)
  169246. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169247. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169248. JSAMPARRAY output_buf, int num_rows)
  169249. {
  169250. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169251. register int y, cb, cr;
  169252. register JSAMPROW outptr;
  169253. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169254. register JDIMENSION col;
  169255. JDIMENSION num_cols = cinfo->output_width;
  169256. /* copy these pointers into registers if possible */
  169257. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169258. register int * Crrtab = cconvert->Cr_r_tab;
  169259. register int * Cbbtab = cconvert->Cb_b_tab;
  169260. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169261. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169262. SHIFT_TEMPS
  169263. while (--num_rows >= 0) {
  169264. inptr0 = input_buf[0][input_row];
  169265. inptr1 = input_buf[1][input_row];
  169266. inptr2 = input_buf[2][input_row];
  169267. inptr3 = input_buf[3][input_row];
  169268. input_row++;
  169269. outptr = *output_buf++;
  169270. for (col = 0; col < num_cols; col++) {
  169271. y = GETJSAMPLE(inptr0[col]);
  169272. cb = GETJSAMPLE(inptr1[col]);
  169273. cr = GETJSAMPLE(inptr2[col]);
  169274. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169275. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169276. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169277. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169278. SCALEBITS)))];
  169279. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169280. /* K passes through unchanged */
  169281. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169282. outptr += 4;
  169283. }
  169284. }
  169285. }
  169286. /*
  169287. * Empty method for start_pass.
  169288. */
  169289. METHODDEF(void)
  169290. start_pass_dcolor (j_decompress_ptr)
  169291. {
  169292. /* no work needed */
  169293. }
  169294. /*
  169295. * Module initialization routine for output colorspace conversion.
  169296. */
  169297. GLOBAL(void)
  169298. jinit_color_deconverter (j_decompress_ptr cinfo)
  169299. {
  169300. my_cconvert_ptr2 cconvert;
  169301. int ci;
  169302. cconvert = (my_cconvert_ptr2)
  169303. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169304. SIZEOF(my_color_deconverter2));
  169305. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169306. cconvert->pub.start_pass = start_pass_dcolor;
  169307. /* Make sure num_components agrees with jpeg_color_space */
  169308. switch (cinfo->jpeg_color_space) {
  169309. case JCS_GRAYSCALE:
  169310. if (cinfo->num_components != 1)
  169311. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169312. break;
  169313. case JCS_RGB:
  169314. case JCS_YCbCr:
  169315. if (cinfo->num_components != 3)
  169316. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169317. break;
  169318. case JCS_CMYK:
  169319. case JCS_YCCK:
  169320. if (cinfo->num_components != 4)
  169321. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169322. break;
  169323. default: /* JCS_UNKNOWN can be anything */
  169324. if (cinfo->num_components < 1)
  169325. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169326. break;
  169327. }
  169328. /* Set out_color_components and conversion method based on requested space.
  169329. * Also clear the component_needed flags for any unused components,
  169330. * so that earlier pipeline stages can avoid useless computation.
  169331. */
  169332. switch (cinfo->out_color_space) {
  169333. case JCS_GRAYSCALE:
  169334. cinfo->out_color_components = 1;
  169335. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169336. cinfo->jpeg_color_space == JCS_YCbCr) {
  169337. cconvert->pub.color_convert = grayscale_convert2;
  169338. /* For color->grayscale conversion, only the Y (0) component is needed */
  169339. for (ci = 1; ci < cinfo->num_components; ci++)
  169340. cinfo->comp_info[ci].component_needed = FALSE;
  169341. } else
  169342. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169343. break;
  169344. case JCS_RGB:
  169345. cinfo->out_color_components = RGB_PIXELSIZE;
  169346. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169347. cconvert->pub.color_convert = ycc_rgb_convert;
  169348. build_ycc_rgb_table(cinfo);
  169349. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169350. cconvert->pub.color_convert = gray_rgb_convert;
  169351. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169352. cconvert->pub.color_convert = null_convert2;
  169353. } else
  169354. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169355. break;
  169356. case JCS_CMYK:
  169357. cinfo->out_color_components = 4;
  169358. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169359. cconvert->pub.color_convert = ycck_cmyk_convert;
  169360. build_ycc_rgb_table(cinfo);
  169361. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169362. cconvert->pub.color_convert = null_convert2;
  169363. } else
  169364. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169365. break;
  169366. default:
  169367. /* Permit null conversion to same output space */
  169368. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169369. cinfo->out_color_components = cinfo->num_components;
  169370. cconvert->pub.color_convert = null_convert2;
  169371. } else /* unsupported non-null conversion */
  169372. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169373. break;
  169374. }
  169375. if (cinfo->quantize_colors)
  169376. cinfo->output_components = 1; /* single colormapped output component */
  169377. else
  169378. cinfo->output_components = cinfo->out_color_components;
  169379. }
  169380. /*** End of inlined file: jdcolor.c ***/
  169381. #undef FIX
  169382. /*** Start of inlined file: jddctmgr.c ***/
  169383. #define JPEG_INTERNALS
  169384. /*
  169385. * The decompressor input side (jdinput.c) saves away the appropriate
  169386. * quantization table for each component at the start of the first scan
  169387. * involving that component. (This is necessary in order to correctly
  169388. * decode files that reuse Q-table slots.)
  169389. * When we are ready to make an output pass, the saved Q-table is converted
  169390. * to a multiplier table that will actually be used by the IDCT routine.
  169391. * The multiplier table contents are IDCT-method-dependent. To support
  169392. * application changes in IDCT method between scans, we can remake the
  169393. * multiplier tables if necessary.
  169394. * In buffered-image mode, the first output pass may occur before any data
  169395. * has been seen for some components, and thus before their Q-tables have
  169396. * been saved away. To handle this case, multiplier tables are preset
  169397. * to zeroes; the result of the IDCT will be a neutral gray level.
  169398. */
  169399. /* Private subobject for this module */
  169400. typedef struct {
  169401. struct jpeg_inverse_dct pub; /* public fields */
  169402. /* This array contains the IDCT method code that each multiplier table
  169403. * is currently set up for, or -1 if it's not yet set up.
  169404. * The actual multiplier tables are pointed to by dct_table in the
  169405. * per-component comp_info structures.
  169406. */
  169407. int cur_method[MAX_COMPONENTS];
  169408. } my_idct_controller;
  169409. typedef my_idct_controller * my_idct_ptr;
  169410. /* Allocated multiplier tables: big enough for any supported variant */
  169411. typedef union {
  169412. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169413. #ifdef DCT_IFAST_SUPPORTED
  169414. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169415. #endif
  169416. #ifdef DCT_FLOAT_SUPPORTED
  169417. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169418. #endif
  169419. } multiplier_table;
  169420. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169421. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169422. */
  169423. #ifdef DCT_ISLOW_SUPPORTED
  169424. #define PROVIDE_ISLOW_TABLES
  169425. #else
  169426. #ifdef IDCT_SCALING_SUPPORTED
  169427. #define PROVIDE_ISLOW_TABLES
  169428. #endif
  169429. #endif
  169430. /*
  169431. * Prepare for an output pass.
  169432. * Here we select the proper IDCT routine for each component and build
  169433. * a matching multiplier table.
  169434. */
  169435. METHODDEF(void)
  169436. start_pass (j_decompress_ptr cinfo)
  169437. {
  169438. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169439. int ci, i;
  169440. jpeg_component_info *compptr;
  169441. int method = 0;
  169442. inverse_DCT_method_ptr method_ptr = NULL;
  169443. JQUANT_TBL * qtbl;
  169444. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169445. ci++, compptr++) {
  169446. /* Select the proper IDCT routine for this component's scaling */
  169447. switch (compptr->DCT_scaled_size) {
  169448. #ifdef IDCT_SCALING_SUPPORTED
  169449. case 1:
  169450. method_ptr = jpeg_idct_1x1;
  169451. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169452. break;
  169453. case 2:
  169454. method_ptr = jpeg_idct_2x2;
  169455. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169456. break;
  169457. case 4:
  169458. method_ptr = jpeg_idct_4x4;
  169459. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169460. break;
  169461. #endif
  169462. case DCTSIZE:
  169463. switch (cinfo->dct_method) {
  169464. #ifdef DCT_ISLOW_SUPPORTED
  169465. case JDCT_ISLOW:
  169466. method_ptr = jpeg_idct_islow;
  169467. method = JDCT_ISLOW;
  169468. break;
  169469. #endif
  169470. #ifdef DCT_IFAST_SUPPORTED
  169471. case JDCT_IFAST:
  169472. method_ptr = jpeg_idct_ifast;
  169473. method = JDCT_IFAST;
  169474. break;
  169475. #endif
  169476. #ifdef DCT_FLOAT_SUPPORTED
  169477. case JDCT_FLOAT:
  169478. method_ptr = jpeg_idct_float;
  169479. method = JDCT_FLOAT;
  169480. break;
  169481. #endif
  169482. default:
  169483. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169484. break;
  169485. }
  169486. break;
  169487. default:
  169488. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169489. break;
  169490. }
  169491. idct->pub.inverse_DCT[ci] = method_ptr;
  169492. /* Create multiplier table from quant table.
  169493. * However, we can skip this if the component is uninteresting
  169494. * or if we already built the table. Also, if no quant table
  169495. * has yet been saved for the component, we leave the
  169496. * multiplier table all-zero; we'll be reading zeroes from the
  169497. * coefficient controller's buffer anyway.
  169498. */
  169499. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169500. continue;
  169501. qtbl = compptr->quant_table;
  169502. if (qtbl == NULL) /* happens if no data yet for component */
  169503. continue;
  169504. idct->cur_method[ci] = method;
  169505. switch (method) {
  169506. #ifdef PROVIDE_ISLOW_TABLES
  169507. case JDCT_ISLOW:
  169508. {
  169509. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169510. * coefficients, but are stored as ints to ensure access efficiency.
  169511. */
  169512. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169513. for (i = 0; i < DCTSIZE2; i++) {
  169514. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169515. }
  169516. }
  169517. break;
  169518. #endif
  169519. #ifdef DCT_IFAST_SUPPORTED
  169520. case JDCT_IFAST:
  169521. {
  169522. /* For AA&N IDCT method, multipliers are equal to quantization
  169523. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169524. * scalefactor[0] = 1
  169525. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169526. * For integer operation, the multiplier table is to be scaled by
  169527. * IFAST_SCALE_BITS.
  169528. */
  169529. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169530. #define CONST_BITS 14
  169531. static const INT16 aanscales[DCTSIZE2] = {
  169532. /* precomputed values scaled up by 14 bits */
  169533. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169534. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169535. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169536. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169537. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169538. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169539. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169540. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169541. };
  169542. SHIFT_TEMPS
  169543. for (i = 0; i < DCTSIZE2; i++) {
  169544. ifmtbl[i] = (IFAST_MULT_TYPE)
  169545. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169546. (INT32) aanscales[i]),
  169547. CONST_BITS-IFAST_SCALE_BITS);
  169548. }
  169549. }
  169550. break;
  169551. #endif
  169552. #ifdef DCT_FLOAT_SUPPORTED
  169553. case JDCT_FLOAT:
  169554. {
  169555. /* For float AA&N IDCT method, multipliers are equal to quantization
  169556. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169557. * scalefactor[0] = 1
  169558. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169559. */
  169560. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169561. int row, col;
  169562. static const double aanscalefactor[DCTSIZE] = {
  169563. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169564. 1.0, 0.785694958, 0.541196100, 0.275899379
  169565. };
  169566. i = 0;
  169567. for (row = 0; row < DCTSIZE; row++) {
  169568. for (col = 0; col < DCTSIZE; col++) {
  169569. fmtbl[i] = (FLOAT_MULT_TYPE)
  169570. ((double) qtbl->quantval[i] *
  169571. aanscalefactor[row] * aanscalefactor[col]);
  169572. i++;
  169573. }
  169574. }
  169575. }
  169576. break;
  169577. #endif
  169578. default:
  169579. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169580. break;
  169581. }
  169582. }
  169583. }
  169584. /*
  169585. * Initialize IDCT manager.
  169586. */
  169587. GLOBAL(void)
  169588. jinit_inverse_dct (j_decompress_ptr cinfo)
  169589. {
  169590. my_idct_ptr idct;
  169591. int ci;
  169592. jpeg_component_info *compptr;
  169593. idct = (my_idct_ptr)
  169594. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169595. SIZEOF(my_idct_controller));
  169596. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169597. idct->pub.start_pass = start_pass;
  169598. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169599. ci++, compptr++) {
  169600. /* Allocate and pre-zero a multiplier table for each component */
  169601. compptr->dct_table =
  169602. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169603. SIZEOF(multiplier_table));
  169604. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169605. /* Mark multiplier table not yet set up for any method */
  169606. idct->cur_method[ci] = -1;
  169607. }
  169608. }
  169609. /*** End of inlined file: jddctmgr.c ***/
  169610. #undef CONST_BITS
  169611. #undef ASSIGN_STATE
  169612. /*** Start of inlined file: jdhuff.c ***/
  169613. #define JPEG_INTERNALS
  169614. /*** Start of inlined file: jdhuff.h ***/
  169615. /* Short forms of external names for systems with brain-damaged linkers. */
  169616. #ifndef __jdhuff_h__
  169617. #define __jdhuff_h__
  169618. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169619. #define jpeg_make_d_derived_tbl jMkDDerived
  169620. #define jpeg_fill_bit_buffer jFilBitBuf
  169621. #define jpeg_huff_decode jHufDecode
  169622. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169623. /* Derived data constructed for each Huffman table */
  169624. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169625. typedef struct {
  169626. /* Basic tables: (element [0] of each array is unused) */
  169627. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169628. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169629. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169630. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169631. * the smallest code of length k; so given a code of length k, the
  169632. * corresponding symbol is huffval[code + valoffset[k]]
  169633. */
  169634. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169635. JHUFF_TBL *pub;
  169636. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169637. * the input data stream. If the next Huffman code is no more
  169638. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169639. * the corresponding symbol directly from these tables.
  169640. */
  169641. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169642. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169643. } d_derived_tbl;
  169644. /* Expand a Huffman table definition into the derived format */
  169645. EXTERN(void) jpeg_make_d_derived_tbl
  169646. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169647. d_derived_tbl ** pdtbl));
  169648. /*
  169649. * Fetching the next N bits from the input stream is a time-critical operation
  169650. * for the Huffman decoders. We implement it with a combination of inline
  169651. * macros and out-of-line subroutines. Note that N (the number of bits
  169652. * demanded at one time) never exceeds 15 for JPEG use.
  169653. *
  169654. * We read source bytes into get_buffer and dole out bits as needed.
  169655. * If get_buffer already contains enough bits, they are fetched in-line
  169656. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169657. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169658. * as full as possible (not just to the number of bits needed; this
  169659. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169660. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169661. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169662. * at least the requested number of bits --- dummy zeroes are inserted if
  169663. * necessary.
  169664. */
  169665. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169666. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169667. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169668. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169669. * appropriately should be a win. Unfortunately we can't define the size
  169670. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169671. * because not all machines measure sizeof in 8-bit bytes.
  169672. */
  169673. typedef struct { /* Bitreading state saved across MCUs */
  169674. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169675. int bits_left; /* # of unused bits in it */
  169676. } bitread_perm_state;
  169677. typedef struct { /* Bitreading working state within an MCU */
  169678. /* Current data source location */
  169679. /* We need a copy, rather than munging the original, in case of suspension */
  169680. const JOCTET * next_input_byte; /* => next byte to read from source */
  169681. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169682. /* Bit input buffer --- note these values are kept in register variables,
  169683. * not in this struct, inside the inner loops.
  169684. */
  169685. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169686. int bits_left; /* # of unused bits in it */
  169687. /* Pointer needed by jpeg_fill_bit_buffer. */
  169688. j_decompress_ptr cinfo; /* back link to decompress master record */
  169689. } bitread_working_state;
  169690. /* Macros to declare and load/save bitread local variables. */
  169691. #define BITREAD_STATE_VARS \
  169692. register bit_buf_type get_buffer; \
  169693. register int bits_left; \
  169694. bitread_working_state br_state
  169695. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169696. br_state.cinfo = cinfop; \
  169697. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169698. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169699. get_buffer = permstate.get_buffer; \
  169700. bits_left = permstate.bits_left;
  169701. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169702. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169703. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169704. permstate.get_buffer = get_buffer; \
  169705. permstate.bits_left = bits_left
  169706. /*
  169707. * These macros provide the in-line portion of bit fetching.
  169708. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169709. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169710. * The variables get_buffer and bits_left are assumed to be locals,
  169711. * but the state struct might not be (jpeg_huff_decode needs this).
  169712. * CHECK_BIT_BUFFER(state,n,action);
  169713. * Ensure there are N bits in get_buffer; if suspend, take action.
  169714. * val = GET_BITS(n);
  169715. * Fetch next N bits.
  169716. * val = PEEK_BITS(n);
  169717. * Fetch next N bits without removing them from the buffer.
  169718. * DROP_BITS(n);
  169719. * Discard next N bits.
  169720. * The value N should be a simple variable, not an expression, because it
  169721. * is evaluated multiple times.
  169722. */
  169723. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169724. { if (bits_left < (nbits)) { \
  169725. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169726. { action; } \
  169727. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169728. #define GET_BITS(nbits) \
  169729. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169730. #define PEEK_BITS(nbits) \
  169731. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169732. #define DROP_BITS(nbits) \
  169733. (bits_left -= (nbits))
  169734. /* Load up the bit buffer to a depth of at least nbits */
  169735. EXTERN(boolean) jpeg_fill_bit_buffer
  169736. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169737. register int bits_left, int nbits));
  169738. /*
  169739. * Code for extracting next Huffman-coded symbol from input bit stream.
  169740. * Again, this is time-critical and we make the main paths be macros.
  169741. *
  169742. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169743. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169744. * or fewer bits long. The few overlength codes are handled with a loop,
  169745. * which need not be inline code.
  169746. *
  169747. * Notes about the HUFF_DECODE macro:
  169748. * 1. Near the end of the data segment, we may fail to get enough bits
  169749. * for a lookahead. In that case, we do it the hard way.
  169750. * 2. If the lookahead table contains no entry, the next code must be
  169751. * more than HUFF_LOOKAHEAD bits long.
  169752. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169753. */
  169754. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169755. { register int nb, look; \
  169756. if (bits_left < HUFF_LOOKAHEAD) { \
  169757. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169758. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169759. if (bits_left < HUFF_LOOKAHEAD) { \
  169760. nb = 1; goto slowlabel; \
  169761. } \
  169762. } \
  169763. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169764. if ((nb = htbl->look_nbits[look]) != 0) { \
  169765. DROP_BITS(nb); \
  169766. result = htbl->look_sym[look]; \
  169767. } else { \
  169768. nb = HUFF_LOOKAHEAD+1; \
  169769. slowlabel: \
  169770. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169771. { failaction; } \
  169772. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169773. } \
  169774. }
  169775. /* Out-of-line case for Huffman code fetching */
  169776. EXTERN(int) jpeg_huff_decode
  169777. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169778. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169779. #endif
  169780. /*** End of inlined file: jdhuff.h ***/
  169781. /* Declarations shared with jdphuff.c */
  169782. /*
  169783. * Expanded entropy decoder object for Huffman decoding.
  169784. *
  169785. * The savable_state subrecord contains fields that change within an MCU,
  169786. * but must not be updated permanently until we complete the MCU.
  169787. */
  169788. typedef struct {
  169789. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169790. } savable_state2;
  169791. /* This macro is to work around compilers with missing or broken
  169792. * structure assignment. You'll need to fix this code if you have
  169793. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169794. */
  169795. #ifndef NO_STRUCT_ASSIGN
  169796. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169797. #else
  169798. #if MAX_COMPS_IN_SCAN == 4
  169799. #define ASSIGN_STATE(dest,src) \
  169800. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169801. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169802. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169803. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169804. #endif
  169805. #endif
  169806. typedef struct {
  169807. struct jpeg_entropy_decoder pub; /* public fields */
  169808. /* These fields are loaded into local variables at start of each MCU.
  169809. * In case of suspension, we exit WITHOUT updating them.
  169810. */
  169811. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169812. savable_state2 saved; /* Other state at start of MCU */
  169813. /* These fields are NOT loaded into local working state. */
  169814. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169815. /* Pointers to derived tables (these workspaces have image lifespan) */
  169816. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169817. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169818. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169819. /* Pointers to derived tables to be used for each block within an MCU */
  169820. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169821. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169822. /* Whether we care about the DC and AC coefficient values for each block */
  169823. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169824. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169825. } huff_entropy_decoder2;
  169826. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169827. /*
  169828. * Initialize for a Huffman-compressed scan.
  169829. */
  169830. METHODDEF(void)
  169831. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169832. {
  169833. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169834. int ci, blkn, dctbl, actbl;
  169835. jpeg_component_info * compptr;
  169836. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169837. * This ought to be an error condition, but we make it a warning because
  169838. * there are some baseline files out there with all zeroes in these bytes.
  169839. */
  169840. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169841. cinfo->Ah != 0 || cinfo->Al != 0)
  169842. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169843. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169844. compptr = cinfo->cur_comp_info[ci];
  169845. dctbl = compptr->dc_tbl_no;
  169846. actbl = compptr->ac_tbl_no;
  169847. /* Compute derived values for Huffman tables */
  169848. /* We may do this more than once for a table, but it's not expensive */
  169849. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169850. & entropy->dc_derived_tbls[dctbl]);
  169851. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169852. & entropy->ac_derived_tbls[actbl]);
  169853. /* Initialize DC predictions to 0 */
  169854. entropy->saved.last_dc_val[ci] = 0;
  169855. }
  169856. /* Precalculate decoding info for each block in an MCU of this scan */
  169857. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169858. ci = cinfo->MCU_membership[blkn];
  169859. compptr = cinfo->cur_comp_info[ci];
  169860. /* Precalculate which table to use for each block */
  169861. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169862. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169863. /* Decide whether we really care about the coefficient values */
  169864. if (compptr->component_needed) {
  169865. entropy->dc_needed[blkn] = TRUE;
  169866. /* we don't need the ACs if producing a 1/8th-size image */
  169867. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169868. } else {
  169869. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169870. }
  169871. }
  169872. /* Initialize bitread state variables */
  169873. entropy->bitstate.bits_left = 0;
  169874. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169875. entropy->pub.insufficient_data = FALSE;
  169876. /* Initialize restart counter */
  169877. entropy->restarts_to_go = cinfo->restart_interval;
  169878. }
  169879. /*
  169880. * Compute the derived values for a Huffman table.
  169881. * This routine also performs some validation checks on the table.
  169882. *
  169883. * Note this is also used by jdphuff.c.
  169884. */
  169885. GLOBAL(void)
  169886. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169887. d_derived_tbl ** pdtbl)
  169888. {
  169889. JHUFF_TBL *htbl;
  169890. d_derived_tbl *dtbl;
  169891. int p, i, l, si, numsymbols;
  169892. int lookbits, ctr;
  169893. char huffsize[257];
  169894. unsigned int huffcode[257];
  169895. unsigned int code;
  169896. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169897. * paralleling the order of the symbols themselves in htbl->huffval[].
  169898. */
  169899. /* Find the input Huffman table */
  169900. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169901. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169902. htbl =
  169903. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169904. if (htbl == NULL)
  169905. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169906. /* Allocate a workspace if we haven't already done so. */
  169907. if (*pdtbl == NULL)
  169908. *pdtbl = (d_derived_tbl *)
  169909. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169910. SIZEOF(d_derived_tbl));
  169911. dtbl = *pdtbl;
  169912. dtbl->pub = htbl; /* fill in back link */
  169913. /* Figure C.1: make table of Huffman code length for each symbol */
  169914. p = 0;
  169915. for (l = 1; l <= 16; l++) {
  169916. i = (int) htbl->bits[l];
  169917. if (i < 0 || p + i > 256) /* protect against table overrun */
  169918. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169919. while (i--)
  169920. huffsize[p++] = (char) l;
  169921. }
  169922. huffsize[p] = 0;
  169923. numsymbols = p;
  169924. /* Figure C.2: generate the codes themselves */
  169925. /* We also validate that the counts represent a legal Huffman code tree. */
  169926. code = 0;
  169927. si = huffsize[0];
  169928. p = 0;
  169929. while (huffsize[p]) {
  169930. while (((int) huffsize[p]) == si) {
  169931. huffcode[p++] = code;
  169932. code++;
  169933. }
  169934. /* code is now 1 more than the last code used for codelength si; but
  169935. * it must still fit in si bits, since no code is allowed to be all ones.
  169936. */
  169937. if (((INT32) code) >= (((INT32) 1) << si))
  169938. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169939. code <<= 1;
  169940. si++;
  169941. }
  169942. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169943. p = 0;
  169944. for (l = 1; l <= 16; l++) {
  169945. if (htbl->bits[l]) {
  169946. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169947. * minus the minimum code of length l
  169948. */
  169949. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169950. p += htbl->bits[l];
  169951. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169952. } else {
  169953. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169954. }
  169955. }
  169956. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169957. /* Compute lookahead tables to speed up decoding.
  169958. * First we set all the table entries to 0, indicating "too long";
  169959. * then we iterate through the Huffman codes that are short enough and
  169960. * fill in all the entries that correspond to bit sequences starting
  169961. * with that code.
  169962. */
  169963. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169964. p = 0;
  169965. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169966. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169967. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169968. /* Generate left-justified code followed by all possible bit sequences */
  169969. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169970. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169971. dtbl->look_nbits[lookbits] = l;
  169972. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169973. lookbits++;
  169974. }
  169975. }
  169976. }
  169977. /* Validate symbols as being reasonable.
  169978. * For AC tables, we make no check, but accept all byte values 0..255.
  169979. * For DC tables, we require the symbols to be in range 0..15.
  169980. * (Tighter bounds could be applied depending on the data depth and mode,
  169981. * but this is sufficient to ensure safe decoding.)
  169982. */
  169983. if (isDC) {
  169984. for (i = 0; i < numsymbols; i++) {
  169985. int sym = htbl->huffval[i];
  169986. if (sym < 0 || sym > 15)
  169987. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169988. }
  169989. }
  169990. }
  169991. /*
  169992. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169993. * See jdhuff.h for info about usage.
  169994. * Note: current values of get_buffer and bits_left are passed as parameters,
  169995. * but are returned in the corresponding fields of the state struct.
  169996. *
  169997. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169998. * of get_buffer to be used. (On machines with wider words, an even larger
  169999. * buffer could be used.) However, on some machines 32-bit shifts are
  170000. * quite slow and take time proportional to the number of places shifted.
  170001. * (This is true with most PC compilers, for instance.) In this case it may
  170002. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170003. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170004. */
  170005. #ifdef SLOW_SHIFT_32
  170006. #define MIN_GET_BITS 15 /* minimum allowable value */
  170007. #else
  170008. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170009. #endif
  170010. GLOBAL(boolean)
  170011. jpeg_fill_bit_buffer (bitread_working_state * state,
  170012. register bit_buf_type get_buffer, register int bits_left,
  170013. int nbits)
  170014. /* Load up the bit buffer to a depth of at least nbits */
  170015. {
  170016. /* Copy heavily used state fields into locals (hopefully registers) */
  170017. register const JOCTET * next_input_byte = state->next_input_byte;
  170018. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170019. j_decompress_ptr cinfo = state->cinfo;
  170020. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170021. /* (It is assumed that no request will be for more than that many bits.) */
  170022. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170023. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170024. while (bits_left < MIN_GET_BITS) {
  170025. register int c;
  170026. /* Attempt to read a byte */
  170027. if (bytes_in_buffer == 0) {
  170028. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170029. return FALSE;
  170030. next_input_byte = cinfo->src->next_input_byte;
  170031. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170032. }
  170033. bytes_in_buffer--;
  170034. c = GETJOCTET(*next_input_byte++);
  170035. /* If it's 0xFF, check and discard stuffed zero byte */
  170036. if (c == 0xFF) {
  170037. /* Loop here to discard any padding FF's on terminating marker,
  170038. * so that we can save a valid unread_marker value. NOTE: we will
  170039. * accept multiple FF's followed by a 0 as meaning a single FF data
  170040. * byte. This data pattern is not valid according to the standard.
  170041. */
  170042. do {
  170043. if (bytes_in_buffer == 0) {
  170044. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170045. return FALSE;
  170046. next_input_byte = cinfo->src->next_input_byte;
  170047. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170048. }
  170049. bytes_in_buffer--;
  170050. c = GETJOCTET(*next_input_byte++);
  170051. } while (c == 0xFF);
  170052. if (c == 0) {
  170053. /* Found FF/00, which represents an FF data byte */
  170054. c = 0xFF;
  170055. } else {
  170056. /* Oops, it's actually a marker indicating end of compressed data.
  170057. * Save the marker code for later use.
  170058. * Fine point: it might appear that we should save the marker into
  170059. * bitread working state, not straight into permanent state. But
  170060. * once we have hit a marker, we cannot need to suspend within the
  170061. * current MCU, because we will read no more bytes from the data
  170062. * source. So it is OK to update permanent state right away.
  170063. */
  170064. cinfo->unread_marker = c;
  170065. /* See if we need to insert some fake zero bits. */
  170066. goto no_more_bytes;
  170067. }
  170068. }
  170069. /* OK, load c into get_buffer */
  170070. get_buffer = (get_buffer << 8) | c;
  170071. bits_left += 8;
  170072. } /* end while */
  170073. } else {
  170074. no_more_bytes:
  170075. /* We get here if we've read the marker that terminates the compressed
  170076. * data segment. There should be enough bits in the buffer register
  170077. * to satisfy the request; if so, no problem.
  170078. */
  170079. if (nbits > bits_left) {
  170080. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170081. * the data stream, so that we can produce some kind of image.
  170082. * We use a nonvolatile flag to ensure that only one warning message
  170083. * appears per data segment.
  170084. */
  170085. if (! cinfo->entropy->insufficient_data) {
  170086. WARNMS(cinfo, JWRN_HIT_MARKER);
  170087. cinfo->entropy->insufficient_data = TRUE;
  170088. }
  170089. /* Fill the buffer with zero bits */
  170090. get_buffer <<= MIN_GET_BITS - bits_left;
  170091. bits_left = MIN_GET_BITS;
  170092. }
  170093. }
  170094. /* Unload the local registers */
  170095. state->next_input_byte = next_input_byte;
  170096. state->bytes_in_buffer = bytes_in_buffer;
  170097. state->get_buffer = get_buffer;
  170098. state->bits_left = bits_left;
  170099. return TRUE;
  170100. }
  170101. /*
  170102. * Out-of-line code for Huffman code decoding.
  170103. * See jdhuff.h for info about usage.
  170104. */
  170105. GLOBAL(int)
  170106. jpeg_huff_decode (bitread_working_state * state,
  170107. register bit_buf_type get_buffer, register int bits_left,
  170108. d_derived_tbl * htbl, int min_bits)
  170109. {
  170110. register int l = min_bits;
  170111. register INT32 code;
  170112. /* HUFF_DECODE has determined that the code is at least min_bits */
  170113. /* bits long, so fetch that many bits in one swoop. */
  170114. CHECK_BIT_BUFFER(*state, l, return -1);
  170115. code = GET_BITS(l);
  170116. /* Collect the rest of the Huffman code one bit at a time. */
  170117. /* This is per Figure F.16 in the JPEG spec. */
  170118. while (code > htbl->maxcode[l]) {
  170119. code <<= 1;
  170120. CHECK_BIT_BUFFER(*state, 1, return -1);
  170121. code |= GET_BITS(1);
  170122. l++;
  170123. }
  170124. /* Unload the local registers */
  170125. state->get_buffer = get_buffer;
  170126. state->bits_left = bits_left;
  170127. /* With garbage input we may reach the sentinel value l = 17. */
  170128. if (l > 16) {
  170129. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170130. return 0; /* fake a zero as the safest result */
  170131. }
  170132. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170133. }
  170134. /*
  170135. * Check for a restart marker & resynchronize decoder.
  170136. * Returns FALSE if must suspend.
  170137. */
  170138. LOCAL(boolean)
  170139. process_restart (j_decompress_ptr cinfo)
  170140. {
  170141. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170142. int ci;
  170143. /* Throw away any unused bits remaining in bit buffer; */
  170144. /* include any full bytes in next_marker's count of discarded bytes */
  170145. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170146. entropy->bitstate.bits_left = 0;
  170147. /* Advance past the RSTn marker */
  170148. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170149. return FALSE;
  170150. /* Re-initialize DC predictions to 0 */
  170151. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170152. entropy->saved.last_dc_val[ci] = 0;
  170153. /* Reset restart counter */
  170154. entropy->restarts_to_go = cinfo->restart_interval;
  170155. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170156. * against a marker. In that case we will end up treating the next data
  170157. * segment as empty, and we can avoid producing bogus output pixels by
  170158. * leaving the flag set.
  170159. */
  170160. if (cinfo->unread_marker == 0)
  170161. entropy->pub.insufficient_data = FALSE;
  170162. return TRUE;
  170163. }
  170164. /*
  170165. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170166. * The coefficients are reordered from zigzag order into natural array order,
  170167. * but are not dequantized.
  170168. *
  170169. * The i'th block of the MCU is stored into the block pointed to by
  170170. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170171. * (Wholesale zeroing is usually a little faster than retail...)
  170172. *
  170173. * Returns FALSE if data source requested suspension. In that case no
  170174. * changes have been made to permanent state. (Exception: some output
  170175. * coefficients may already have been assigned. This is harmless for
  170176. * this module, since we'll just re-assign them on the next call.)
  170177. */
  170178. METHODDEF(boolean)
  170179. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170180. {
  170181. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170182. int blkn;
  170183. BITREAD_STATE_VARS;
  170184. savable_state2 state;
  170185. /* Process restart marker if needed; may have to suspend */
  170186. if (cinfo->restart_interval) {
  170187. if (entropy->restarts_to_go == 0)
  170188. if (! process_restart(cinfo))
  170189. return FALSE;
  170190. }
  170191. /* If we've run out of data, just leave the MCU set to zeroes.
  170192. * This way, we return uniform gray for the remainder of the segment.
  170193. */
  170194. if (! entropy->pub.insufficient_data) {
  170195. /* Load up working state */
  170196. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170197. ASSIGN_STATE(state, entropy->saved);
  170198. /* Outer loop handles each block in the MCU */
  170199. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170200. JBLOCKROW block = MCU_data[blkn];
  170201. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170202. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170203. register int s, k, r;
  170204. /* Decode a single block's worth of coefficients */
  170205. /* Section F.2.2.1: decode the DC coefficient difference */
  170206. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170207. if (s) {
  170208. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170209. r = GET_BITS(s);
  170210. s = HUFF_EXTEND(r, s);
  170211. }
  170212. if (entropy->dc_needed[blkn]) {
  170213. /* Convert DC difference to actual value, update last_dc_val */
  170214. int ci = cinfo->MCU_membership[blkn];
  170215. s += state.last_dc_val[ci];
  170216. state.last_dc_val[ci] = s;
  170217. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170218. (*block)[0] = (JCOEF) s;
  170219. }
  170220. if (entropy->ac_needed[blkn]) {
  170221. /* Section F.2.2.2: decode the AC coefficients */
  170222. /* Since zeroes are skipped, output area must be cleared beforehand */
  170223. for (k = 1; k < DCTSIZE2; k++) {
  170224. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170225. r = s >> 4;
  170226. s &= 15;
  170227. if (s) {
  170228. k += r;
  170229. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170230. r = GET_BITS(s);
  170231. s = HUFF_EXTEND(r, s);
  170232. /* Output coefficient in natural (dezigzagged) order.
  170233. * Note: the extra entries in jpeg_natural_order[] will save us
  170234. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170235. */
  170236. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170237. } else {
  170238. if (r != 15)
  170239. break;
  170240. k += 15;
  170241. }
  170242. }
  170243. } else {
  170244. /* Section F.2.2.2: decode the AC coefficients */
  170245. /* In this path we just discard the values */
  170246. for (k = 1; k < DCTSIZE2; k++) {
  170247. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170248. r = s >> 4;
  170249. s &= 15;
  170250. if (s) {
  170251. k += r;
  170252. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170253. DROP_BITS(s);
  170254. } else {
  170255. if (r != 15)
  170256. break;
  170257. k += 15;
  170258. }
  170259. }
  170260. }
  170261. }
  170262. /* Completed MCU, so update state */
  170263. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170264. ASSIGN_STATE(entropy->saved, state);
  170265. }
  170266. /* Account for restart interval (no-op if not using restarts) */
  170267. entropy->restarts_to_go--;
  170268. return TRUE;
  170269. }
  170270. /*
  170271. * Module initialization routine for Huffman entropy decoding.
  170272. */
  170273. GLOBAL(void)
  170274. jinit_huff_decoder (j_decompress_ptr cinfo)
  170275. {
  170276. huff_entropy_ptr2 entropy;
  170277. int i;
  170278. entropy = (huff_entropy_ptr2)
  170279. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170280. SIZEOF(huff_entropy_decoder2));
  170281. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170282. entropy->pub.start_pass = start_pass_huff_decoder;
  170283. entropy->pub.decode_mcu = decode_mcu;
  170284. /* Mark tables unallocated */
  170285. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170286. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170287. }
  170288. }
  170289. /*** End of inlined file: jdhuff.c ***/
  170290. /*** Start of inlined file: jdinput.c ***/
  170291. #define JPEG_INTERNALS
  170292. /* Private state */
  170293. typedef struct {
  170294. struct jpeg_input_controller pub; /* public fields */
  170295. boolean inheaders; /* TRUE until first SOS is reached */
  170296. } my_input_controller;
  170297. typedef my_input_controller * my_inputctl_ptr;
  170298. /* Forward declarations */
  170299. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170300. /*
  170301. * Routines to calculate various quantities related to the size of the image.
  170302. */
  170303. LOCAL(void)
  170304. initial_setup2 (j_decompress_ptr cinfo)
  170305. /* Called once, when first SOS marker is reached */
  170306. {
  170307. int ci;
  170308. jpeg_component_info *compptr;
  170309. /* Make sure image isn't bigger than I can handle */
  170310. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170311. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170312. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170313. /* For now, precision must match compiled-in value... */
  170314. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170315. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170316. /* Check that number of components won't exceed internal array sizes */
  170317. if (cinfo->num_components > MAX_COMPONENTS)
  170318. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170319. MAX_COMPONENTS);
  170320. /* Compute maximum sampling factors; check factor validity */
  170321. cinfo->max_h_samp_factor = 1;
  170322. cinfo->max_v_samp_factor = 1;
  170323. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170324. ci++, compptr++) {
  170325. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170326. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170327. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170328. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170329. compptr->h_samp_factor);
  170330. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170331. compptr->v_samp_factor);
  170332. }
  170333. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170334. * In the full decompressor, this will be overridden by jdmaster.c;
  170335. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170336. */
  170337. cinfo->min_DCT_scaled_size = DCTSIZE;
  170338. /* Compute dimensions of components */
  170339. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170340. ci++, compptr++) {
  170341. compptr->DCT_scaled_size = DCTSIZE;
  170342. /* Size in DCT blocks */
  170343. compptr->width_in_blocks = (JDIMENSION)
  170344. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170345. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170346. compptr->height_in_blocks = (JDIMENSION)
  170347. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170348. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170349. /* downsampled_width and downsampled_height will also be overridden by
  170350. * jdmaster.c if we are doing full decompression. The transcoder library
  170351. * doesn't use these values, but the calling application might.
  170352. */
  170353. /* Size in samples */
  170354. compptr->downsampled_width = (JDIMENSION)
  170355. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170356. (long) cinfo->max_h_samp_factor);
  170357. compptr->downsampled_height = (JDIMENSION)
  170358. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170359. (long) cinfo->max_v_samp_factor);
  170360. /* Mark component needed, until color conversion says otherwise */
  170361. compptr->component_needed = TRUE;
  170362. /* Mark no quantization table yet saved for component */
  170363. compptr->quant_table = NULL;
  170364. }
  170365. /* Compute number of fully interleaved MCU rows. */
  170366. cinfo->total_iMCU_rows = (JDIMENSION)
  170367. jdiv_round_up((long) cinfo->image_height,
  170368. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170369. /* Decide whether file contains multiple scans */
  170370. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170371. cinfo->inputctl->has_multiple_scans = TRUE;
  170372. else
  170373. cinfo->inputctl->has_multiple_scans = FALSE;
  170374. }
  170375. LOCAL(void)
  170376. per_scan_setup2 (j_decompress_ptr cinfo)
  170377. /* Do computations that are needed before processing a JPEG scan */
  170378. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170379. {
  170380. int ci, mcublks, tmp;
  170381. jpeg_component_info *compptr;
  170382. if (cinfo->comps_in_scan == 1) {
  170383. /* Noninterleaved (single-component) scan */
  170384. compptr = cinfo->cur_comp_info[0];
  170385. /* Overall image size in MCUs */
  170386. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170387. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170388. /* For noninterleaved scan, always one block per MCU */
  170389. compptr->MCU_width = 1;
  170390. compptr->MCU_height = 1;
  170391. compptr->MCU_blocks = 1;
  170392. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170393. compptr->last_col_width = 1;
  170394. /* For noninterleaved scans, it is convenient to define last_row_height
  170395. * as the number of block rows present in the last iMCU row.
  170396. */
  170397. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170398. if (tmp == 0) tmp = compptr->v_samp_factor;
  170399. compptr->last_row_height = tmp;
  170400. /* Prepare array describing MCU composition */
  170401. cinfo->blocks_in_MCU = 1;
  170402. cinfo->MCU_membership[0] = 0;
  170403. } else {
  170404. /* Interleaved (multi-component) scan */
  170405. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170406. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170407. MAX_COMPS_IN_SCAN);
  170408. /* Overall image size in MCUs */
  170409. cinfo->MCUs_per_row = (JDIMENSION)
  170410. jdiv_round_up((long) cinfo->image_width,
  170411. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170412. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170413. jdiv_round_up((long) cinfo->image_height,
  170414. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170415. cinfo->blocks_in_MCU = 0;
  170416. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170417. compptr = cinfo->cur_comp_info[ci];
  170418. /* Sampling factors give # of blocks of component in each MCU */
  170419. compptr->MCU_width = compptr->h_samp_factor;
  170420. compptr->MCU_height = compptr->v_samp_factor;
  170421. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170422. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170423. /* Figure number of non-dummy blocks in last MCU column & row */
  170424. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170425. if (tmp == 0) tmp = compptr->MCU_width;
  170426. compptr->last_col_width = tmp;
  170427. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170428. if (tmp == 0) tmp = compptr->MCU_height;
  170429. compptr->last_row_height = tmp;
  170430. /* Prepare array describing MCU composition */
  170431. mcublks = compptr->MCU_blocks;
  170432. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170433. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170434. while (mcublks-- > 0) {
  170435. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170436. }
  170437. }
  170438. }
  170439. }
  170440. /*
  170441. * Save away a copy of the Q-table referenced by each component present
  170442. * in the current scan, unless already saved during a prior scan.
  170443. *
  170444. * In a multiple-scan JPEG file, the encoder could assign different components
  170445. * the same Q-table slot number, but change table definitions between scans
  170446. * so that each component uses a different Q-table. (The IJG encoder is not
  170447. * currently capable of doing this, but other encoders might.) Since we want
  170448. * to be able to dequantize all the components at the end of the file, this
  170449. * means that we have to save away the table actually used for each component.
  170450. * We do this by copying the table at the start of the first scan containing
  170451. * the component.
  170452. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170453. * slot between scans of a component using that slot. If the encoder does so
  170454. * anyway, this decoder will simply use the Q-table values that were current
  170455. * at the start of the first scan for the component.
  170456. *
  170457. * The decompressor output side looks only at the saved quant tables,
  170458. * not at the current Q-table slots.
  170459. */
  170460. LOCAL(void)
  170461. latch_quant_tables (j_decompress_ptr cinfo)
  170462. {
  170463. int ci, qtblno;
  170464. jpeg_component_info *compptr;
  170465. JQUANT_TBL * qtbl;
  170466. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170467. compptr = cinfo->cur_comp_info[ci];
  170468. /* No work if we already saved Q-table for this component */
  170469. if (compptr->quant_table != NULL)
  170470. continue;
  170471. /* Make sure specified quantization table is present */
  170472. qtblno = compptr->quant_tbl_no;
  170473. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170474. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170475. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170476. /* OK, save away the quantization table */
  170477. qtbl = (JQUANT_TBL *)
  170478. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170479. SIZEOF(JQUANT_TBL));
  170480. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170481. compptr->quant_table = qtbl;
  170482. }
  170483. }
  170484. /*
  170485. * Initialize the input modules to read a scan of compressed data.
  170486. * The first call to this is done by jdmaster.c after initializing
  170487. * the entire decompressor (during jpeg_start_decompress).
  170488. * Subsequent calls come from consume_markers, below.
  170489. */
  170490. METHODDEF(void)
  170491. start_input_pass2 (j_decompress_ptr cinfo)
  170492. {
  170493. per_scan_setup2(cinfo);
  170494. latch_quant_tables(cinfo);
  170495. (*cinfo->entropy->start_pass) (cinfo);
  170496. (*cinfo->coef->start_input_pass) (cinfo);
  170497. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170498. }
  170499. /*
  170500. * Finish up after inputting a compressed-data scan.
  170501. * This is called by the coefficient controller after it's read all
  170502. * the expected data of the scan.
  170503. */
  170504. METHODDEF(void)
  170505. finish_input_pass (j_decompress_ptr cinfo)
  170506. {
  170507. cinfo->inputctl->consume_input = consume_markers;
  170508. }
  170509. /*
  170510. * Read JPEG markers before, between, or after compressed-data scans.
  170511. * Change state as necessary when a new scan is reached.
  170512. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170513. *
  170514. * The consume_input method pointer points either here or to the
  170515. * coefficient controller's consume_data routine, depending on whether
  170516. * we are reading a compressed data segment or inter-segment markers.
  170517. */
  170518. METHODDEF(int)
  170519. consume_markers (j_decompress_ptr cinfo)
  170520. {
  170521. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170522. int val;
  170523. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170524. return JPEG_REACHED_EOI;
  170525. val = (*cinfo->marker->read_markers) (cinfo);
  170526. switch (val) {
  170527. case JPEG_REACHED_SOS: /* Found SOS */
  170528. if (inputctl->inheaders) { /* 1st SOS */
  170529. initial_setup2(cinfo);
  170530. inputctl->inheaders = FALSE;
  170531. /* Note: start_input_pass must be called by jdmaster.c
  170532. * before any more input can be consumed. jdapimin.c is
  170533. * responsible for enforcing this sequencing.
  170534. */
  170535. } else { /* 2nd or later SOS marker */
  170536. if (! inputctl->pub.has_multiple_scans)
  170537. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170538. start_input_pass2(cinfo);
  170539. }
  170540. break;
  170541. case JPEG_REACHED_EOI: /* Found EOI */
  170542. inputctl->pub.eoi_reached = TRUE;
  170543. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170544. if (cinfo->marker->saw_SOF)
  170545. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170546. } else {
  170547. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170548. * if user set output_scan_number larger than number of scans.
  170549. */
  170550. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170551. cinfo->output_scan_number = cinfo->input_scan_number;
  170552. }
  170553. break;
  170554. case JPEG_SUSPENDED:
  170555. break;
  170556. }
  170557. return val;
  170558. }
  170559. /*
  170560. * Reset state to begin a fresh datastream.
  170561. */
  170562. METHODDEF(void)
  170563. reset_input_controller (j_decompress_ptr cinfo)
  170564. {
  170565. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170566. inputctl->pub.consume_input = consume_markers;
  170567. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170568. inputctl->pub.eoi_reached = FALSE;
  170569. inputctl->inheaders = TRUE;
  170570. /* Reset other modules */
  170571. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170572. (*cinfo->marker->reset_marker_reader) (cinfo);
  170573. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170574. cinfo->coef_bits = NULL;
  170575. }
  170576. /*
  170577. * Initialize the input controller module.
  170578. * This is called only once, when the decompression object is created.
  170579. */
  170580. GLOBAL(void)
  170581. jinit_input_controller (j_decompress_ptr cinfo)
  170582. {
  170583. my_inputctl_ptr inputctl;
  170584. /* Create subobject in permanent pool */
  170585. inputctl = (my_inputctl_ptr)
  170586. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170587. SIZEOF(my_input_controller));
  170588. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170589. /* Initialize method pointers */
  170590. inputctl->pub.consume_input = consume_markers;
  170591. inputctl->pub.reset_input_controller = reset_input_controller;
  170592. inputctl->pub.start_input_pass = start_input_pass2;
  170593. inputctl->pub.finish_input_pass = finish_input_pass;
  170594. /* Initialize state: can't use reset_input_controller since we don't
  170595. * want to try to reset other modules yet.
  170596. */
  170597. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170598. inputctl->pub.eoi_reached = FALSE;
  170599. inputctl->inheaders = TRUE;
  170600. }
  170601. /*** End of inlined file: jdinput.c ***/
  170602. /*** Start of inlined file: jdmainct.c ***/
  170603. #define JPEG_INTERNALS
  170604. /*
  170605. * In the current system design, the main buffer need never be a full-image
  170606. * buffer; any full-height buffers will be found inside the coefficient or
  170607. * postprocessing controllers. Nonetheless, the main controller is not
  170608. * trivial. Its responsibility is to provide context rows for upsampling/
  170609. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170610. *
  170611. * Postprocessor input data is counted in "row groups". A row group
  170612. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170613. * sample rows of each component. (We require DCT_scaled_size values to be
  170614. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170615. * values will likely be powers of two, so we actually have the stronger
  170616. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170617. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170618. * row group (times any additional scale factor that the upsampler is
  170619. * applying).
  170620. *
  170621. * The coefficient controller will deliver data to us one iMCU row at a time;
  170622. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170623. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170624. * to one row of MCUs when the image is fully interleaved.) Note that the
  170625. * number of sample rows varies across components, but the number of row
  170626. * groups does not. Some garbage sample rows may be included in the last iMCU
  170627. * row at the bottom of the image.
  170628. *
  170629. * Depending on the vertical scaling algorithm used, the upsampler may need
  170630. * access to the sample row(s) above and below its current input row group.
  170631. * The upsampler is required to set need_context_rows TRUE at global selection
  170632. * time if so. When need_context_rows is FALSE, this controller can simply
  170633. * obtain one iMCU row at a time from the coefficient controller and dole it
  170634. * out as row groups to the postprocessor.
  170635. *
  170636. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170637. * passed to postprocessing contains at least one row group's worth of samples
  170638. * above and below the row group(s) being processed. Note that the context
  170639. * rows "above" the first passed row group appear at negative row offsets in
  170640. * the passed buffer. At the top and bottom of the image, the required
  170641. * context rows are manufactured by duplicating the first or last real sample
  170642. * row; this avoids having special cases in the upsampling inner loops.
  170643. *
  170644. * The amount of context is fixed at one row group just because that's a
  170645. * convenient number for this controller to work with. The existing
  170646. * upsamplers really only need one sample row of context. An upsampler
  170647. * supporting arbitrary output rescaling might wish for more than one row
  170648. * group of context when shrinking the image; tough, we don't handle that.
  170649. * (This is justified by the assumption that downsizing will be handled mostly
  170650. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170651. * the upsample step needn't be much less than one.)
  170652. *
  170653. * To provide the desired context, we have to retain the last two row groups
  170654. * of one iMCU row while reading in the next iMCU row. (The last row group
  170655. * can't be processed until we have another row group for its below-context,
  170656. * and so we have to save the next-to-last group too for its above-context.)
  170657. * We could do this most simply by copying data around in our buffer, but
  170658. * that'd be very slow. We can avoid copying any data by creating a rather
  170659. * strange pointer structure. Here's how it works. We allocate a workspace
  170660. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170661. * of row groups per iMCU row). We create two sets of redundant pointers to
  170662. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170663. * pointer lists look like this:
  170664. * M+1 M-1
  170665. * master pointer --> 0 master pointer --> 0
  170666. * 1 1
  170667. * ... ...
  170668. * M-3 M-3
  170669. * M-2 M
  170670. * M-1 M+1
  170671. * M M-2
  170672. * M+1 M-1
  170673. * 0 0
  170674. * We read alternate iMCU rows using each master pointer; thus the last two
  170675. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170676. * The pointer lists are set up so that the required context rows appear to
  170677. * be adjacent to the proper places when we pass the pointer lists to the
  170678. * upsampler.
  170679. *
  170680. * The above pictures describe the normal state of the pointer lists.
  170681. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170682. * the first or last sample row as necessary (this is cheaper than copying
  170683. * sample rows around).
  170684. *
  170685. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170686. * situation each iMCU row provides only one row group so the buffering logic
  170687. * must be different (eg, we must read two iMCU rows before we can emit the
  170688. * first row group). For now, we simply do not support providing context
  170689. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170690. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170691. * want it quick and dirty, so a context-free upsampler is sufficient.
  170692. */
  170693. /* Private buffer controller object */
  170694. typedef struct {
  170695. struct jpeg_d_main_controller pub; /* public fields */
  170696. /* Pointer to allocated workspace (M or M+2 row groups). */
  170697. JSAMPARRAY buffer[MAX_COMPONENTS];
  170698. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170699. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170700. /* Remaining fields are only used in the context case. */
  170701. /* These are the master pointers to the funny-order pointer lists. */
  170702. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170703. int whichptr; /* indicates which pointer set is now in use */
  170704. int context_state; /* process_data state machine status */
  170705. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170706. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170707. } my_main_controller4;
  170708. typedef my_main_controller4 * my_main_ptr4;
  170709. /* context_state values: */
  170710. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170711. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170712. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170713. /* Forward declarations */
  170714. METHODDEF(void) process_data_simple_main2
  170715. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170716. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170717. METHODDEF(void) process_data_context_main
  170718. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170719. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170720. #ifdef QUANT_2PASS_SUPPORTED
  170721. METHODDEF(void) process_data_crank_post
  170722. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170723. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170724. #endif
  170725. LOCAL(void)
  170726. alloc_funny_pointers (j_decompress_ptr cinfo)
  170727. /* Allocate space for the funny pointer lists.
  170728. * This is done only once, not once per pass.
  170729. */
  170730. {
  170731. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170732. int ci, rgroup;
  170733. int M = cinfo->min_DCT_scaled_size;
  170734. jpeg_component_info *compptr;
  170735. JSAMPARRAY xbuf;
  170736. /* Get top-level space for component array pointers.
  170737. * We alloc both arrays with one call to save a few cycles.
  170738. */
  170739. main_->xbuffer[0] = (JSAMPIMAGE)
  170740. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170741. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170742. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170743. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170744. ci++, compptr++) {
  170745. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170746. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170747. /* Get space for pointer lists --- M+4 row groups in each list.
  170748. * We alloc both pointer lists with one call to save a few cycles.
  170749. */
  170750. xbuf = (JSAMPARRAY)
  170751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170752. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170753. xbuf += rgroup; /* want one row group at negative offsets */
  170754. main_->xbuffer[0][ci] = xbuf;
  170755. xbuf += rgroup * (M + 4);
  170756. main_->xbuffer[1][ci] = xbuf;
  170757. }
  170758. }
  170759. LOCAL(void)
  170760. make_funny_pointers (j_decompress_ptr cinfo)
  170761. /* Create the funny pointer lists discussed in the comments above.
  170762. * The actual workspace is already allocated (in main->buffer),
  170763. * and the space for the pointer lists is allocated too.
  170764. * This routine just fills in the curiously ordered lists.
  170765. * This will be repeated at the beginning of each pass.
  170766. */
  170767. {
  170768. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170769. int ci, i, rgroup;
  170770. int M = cinfo->min_DCT_scaled_size;
  170771. jpeg_component_info *compptr;
  170772. JSAMPARRAY buf, xbuf0, xbuf1;
  170773. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170774. ci++, compptr++) {
  170775. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170776. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170777. xbuf0 = main_->xbuffer[0][ci];
  170778. xbuf1 = main_->xbuffer[1][ci];
  170779. /* First copy the workspace pointers as-is */
  170780. buf = main_->buffer[ci];
  170781. for (i = 0; i < rgroup * (M + 2); i++) {
  170782. xbuf0[i] = xbuf1[i] = buf[i];
  170783. }
  170784. /* In the second list, put the last four row groups in swapped order */
  170785. for (i = 0; i < rgroup * 2; i++) {
  170786. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170787. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170788. }
  170789. /* The wraparound pointers at top and bottom will be filled later
  170790. * (see set_wraparound_pointers, below). Initially we want the "above"
  170791. * pointers to duplicate the first actual data line. This only needs
  170792. * to happen in xbuffer[0].
  170793. */
  170794. for (i = 0; i < rgroup; i++) {
  170795. xbuf0[i - rgroup] = xbuf0[0];
  170796. }
  170797. }
  170798. }
  170799. LOCAL(void)
  170800. set_wraparound_pointers (j_decompress_ptr cinfo)
  170801. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170802. * This changes the pointer list state from top-of-image to the normal state.
  170803. */
  170804. {
  170805. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170806. int ci, i, rgroup;
  170807. int M = cinfo->min_DCT_scaled_size;
  170808. jpeg_component_info *compptr;
  170809. JSAMPARRAY xbuf0, xbuf1;
  170810. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170811. ci++, compptr++) {
  170812. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170813. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170814. xbuf0 = main_->xbuffer[0][ci];
  170815. xbuf1 = main_->xbuffer[1][ci];
  170816. for (i = 0; i < rgroup; i++) {
  170817. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170818. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170819. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170820. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170821. }
  170822. }
  170823. }
  170824. LOCAL(void)
  170825. set_bottom_pointers (j_decompress_ptr cinfo)
  170826. /* Change the pointer lists to duplicate the last sample row at the bottom
  170827. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170828. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170829. */
  170830. {
  170831. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170832. int ci, i, rgroup, iMCUheight, rows_left;
  170833. jpeg_component_info *compptr;
  170834. JSAMPARRAY xbuf;
  170835. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170836. ci++, compptr++) {
  170837. /* Count sample rows in one iMCU row and in one row group */
  170838. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170839. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170840. /* Count nondummy sample rows remaining for this component */
  170841. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170842. if (rows_left == 0) rows_left = iMCUheight;
  170843. /* Count nondummy row groups. Should get same answer for each component,
  170844. * so we need only do it once.
  170845. */
  170846. if (ci == 0) {
  170847. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170848. }
  170849. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170850. * last partial rowgroup and ensures at least one full rowgroup of context.
  170851. */
  170852. xbuf = main_->xbuffer[main_->whichptr][ci];
  170853. for (i = 0; i < rgroup * 2; i++) {
  170854. xbuf[rows_left + i] = xbuf[rows_left-1];
  170855. }
  170856. }
  170857. }
  170858. /*
  170859. * Initialize for a processing pass.
  170860. */
  170861. METHODDEF(void)
  170862. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170863. {
  170864. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170865. switch (pass_mode) {
  170866. case JBUF_PASS_THRU:
  170867. if (cinfo->upsample->need_context_rows) {
  170868. main_->pub.process_data = process_data_context_main;
  170869. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170870. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170871. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170872. main_->iMCU_row_ctr = 0;
  170873. } else {
  170874. /* Simple case with no context needed */
  170875. main_->pub.process_data = process_data_simple_main2;
  170876. }
  170877. main_->buffer_full = FALSE; /* Mark buffer empty */
  170878. main_->rowgroup_ctr = 0;
  170879. break;
  170880. #ifdef QUANT_2PASS_SUPPORTED
  170881. case JBUF_CRANK_DEST:
  170882. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170883. main_->pub.process_data = process_data_crank_post;
  170884. break;
  170885. #endif
  170886. default:
  170887. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170888. break;
  170889. }
  170890. }
  170891. /*
  170892. * Process some data.
  170893. * This handles the simple case where no context is required.
  170894. */
  170895. METHODDEF(void)
  170896. process_data_simple_main2 (j_decompress_ptr cinfo,
  170897. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170898. JDIMENSION out_rows_avail)
  170899. {
  170900. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170901. JDIMENSION rowgroups_avail;
  170902. /* Read input data if we haven't filled the main buffer yet */
  170903. if (! main_->buffer_full) {
  170904. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170905. return; /* suspension forced, can do nothing more */
  170906. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170907. }
  170908. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170909. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170910. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170911. * to the postprocessor. The postprocessor has to check for bottom
  170912. * of image anyway (at row resolution), so no point in us doing it too.
  170913. */
  170914. /* Feed the postprocessor */
  170915. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170916. &main_->rowgroup_ctr, rowgroups_avail,
  170917. output_buf, out_row_ctr, out_rows_avail);
  170918. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170919. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170920. main_->buffer_full = FALSE;
  170921. main_->rowgroup_ctr = 0;
  170922. }
  170923. }
  170924. /*
  170925. * Process some data.
  170926. * This handles the case where context rows must be provided.
  170927. */
  170928. METHODDEF(void)
  170929. process_data_context_main (j_decompress_ptr cinfo,
  170930. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170931. JDIMENSION out_rows_avail)
  170932. {
  170933. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170934. /* Read input data if we haven't filled the main buffer yet */
  170935. if (! main_->buffer_full) {
  170936. if (! (*cinfo->coef->decompress_data) (cinfo,
  170937. main_->xbuffer[main_->whichptr]))
  170938. return; /* suspension forced, can do nothing more */
  170939. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170940. main_->iMCU_row_ctr++; /* count rows received */
  170941. }
  170942. /* Postprocessor typically will not swallow all the input data it is handed
  170943. * in one call (due to filling the output buffer first). Must be prepared
  170944. * to exit and restart. This switch lets us keep track of how far we got.
  170945. * Note that each case falls through to the next on successful completion.
  170946. */
  170947. switch (main_->context_state) {
  170948. case CTX_POSTPONED_ROW:
  170949. /* Call postprocessor using previously set pointers for postponed row */
  170950. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170951. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170952. output_buf, out_row_ctr, out_rows_avail);
  170953. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170954. return; /* Need to suspend */
  170955. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170956. if (*out_row_ctr >= out_rows_avail)
  170957. return; /* Postprocessor exactly filled output buf */
  170958. /*FALLTHROUGH*/
  170959. case CTX_PREPARE_FOR_IMCU:
  170960. /* Prepare to process first M-1 row groups of this iMCU row */
  170961. main_->rowgroup_ctr = 0;
  170962. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170963. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170964. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170965. */
  170966. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170967. set_bottom_pointers(cinfo);
  170968. main_->context_state = CTX_PROCESS_IMCU;
  170969. /*FALLTHROUGH*/
  170970. case CTX_PROCESS_IMCU:
  170971. /* Call postprocessor using previously set pointers */
  170972. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170973. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170974. output_buf, out_row_ctr, out_rows_avail);
  170975. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170976. return; /* Need to suspend */
  170977. /* After the first iMCU, change wraparound pointers to normal state */
  170978. if (main_->iMCU_row_ctr == 1)
  170979. set_wraparound_pointers(cinfo);
  170980. /* Prepare to load new iMCU row using other xbuffer list */
  170981. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170982. main_->buffer_full = FALSE;
  170983. /* Still need to process last row group of this iMCU row, */
  170984. /* which is saved at index M+1 of the other xbuffer */
  170985. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170986. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170987. main_->context_state = CTX_POSTPONED_ROW;
  170988. }
  170989. }
  170990. /*
  170991. * Process some data.
  170992. * Final pass of two-pass quantization: just call the postprocessor.
  170993. * Source data will be the postprocessor controller's internal buffer.
  170994. */
  170995. #ifdef QUANT_2PASS_SUPPORTED
  170996. METHODDEF(void)
  170997. process_data_crank_post (j_decompress_ptr cinfo,
  170998. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170999. JDIMENSION out_rows_avail)
  171000. {
  171001. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171002. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171003. output_buf, out_row_ctr, out_rows_avail);
  171004. }
  171005. #endif /* QUANT_2PASS_SUPPORTED */
  171006. /*
  171007. * Initialize main buffer controller.
  171008. */
  171009. GLOBAL(void)
  171010. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171011. {
  171012. my_main_ptr4 main_;
  171013. int ci, rgroup, ngroups;
  171014. jpeg_component_info *compptr;
  171015. main_ = (my_main_ptr4)
  171016. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171017. SIZEOF(my_main_controller4));
  171018. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171019. main_->pub.start_pass = start_pass_main2;
  171020. if (need_full_buffer) /* shouldn't happen */
  171021. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171022. /* Allocate the workspace.
  171023. * ngroups is the number of row groups we need.
  171024. */
  171025. if (cinfo->upsample->need_context_rows) {
  171026. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171027. ERREXIT(cinfo, JERR_NOTIMPL);
  171028. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171029. ngroups = cinfo->min_DCT_scaled_size + 2;
  171030. } else {
  171031. ngroups = cinfo->min_DCT_scaled_size;
  171032. }
  171033. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171034. ci++, compptr++) {
  171035. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171036. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171037. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171038. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171039. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171040. (JDIMENSION) (rgroup * ngroups));
  171041. }
  171042. }
  171043. /*** End of inlined file: jdmainct.c ***/
  171044. /*** Start of inlined file: jdmarker.c ***/
  171045. #define JPEG_INTERNALS
  171046. /* Private state */
  171047. typedef struct {
  171048. struct jpeg_marker_reader pub; /* public fields */
  171049. /* Application-overridable marker processing methods */
  171050. jpeg_marker_parser_method process_COM;
  171051. jpeg_marker_parser_method process_APPn[16];
  171052. /* Limit on marker data length to save for each marker type */
  171053. unsigned int length_limit_COM;
  171054. unsigned int length_limit_APPn[16];
  171055. /* Status of COM/APPn marker saving */
  171056. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171057. unsigned int bytes_read; /* data bytes read so far in marker */
  171058. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171059. } my_marker_reader;
  171060. typedef my_marker_reader * my_marker_ptr2;
  171061. /*
  171062. * Macros for fetching data from the data source module.
  171063. *
  171064. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171065. * the current restart point; we update them only when we have reached a
  171066. * suitable place to restart if a suspension occurs.
  171067. */
  171068. /* Declare and initialize local copies of input pointer/count */
  171069. #define INPUT_VARS(cinfo) \
  171070. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171071. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171072. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171073. /* Unload the local copies --- do this only at a restart boundary */
  171074. #define INPUT_SYNC(cinfo) \
  171075. ( datasrc->next_input_byte = next_input_byte, \
  171076. datasrc->bytes_in_buffer = bytes_in_buffer )
  171077. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171078. #define INPUT_RELOAD(cinfo) \
  171079. ( next_input_byte = datasrc->next_input_byte, \
  171080. bytes_in_buffer = datasrc->bytes_in_buffer )
  171081. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171082. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171083. * but we must reload the local copies after a successful fill.
  171084. */
  171085. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171086. if (bytes_in_buffer == 0) { \
  171087. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171088. { action; } \
  171089. INPUT_RELOAD(cinfo); \
  171090. }
  171091. /* Read a byte into variable V.
  171092. * If must suspend, take the specified action (typically "return FALSE").
  171093. */
  171094. #define INPUT_BYTE(cinfo,V,action) \
  171095. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171096. bytes_in_buffer--; \
  171097. V = GETJOCTET(*next_input_byte++); )
  171098. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171099. * V should be declared unsigned int or perhaps INT32.
  171100. */
  171101. #define INPUT_2BYTES(cinfo,V,action) \
  171102. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171103. bytes_in_buffer--; \
  171104. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171105. MAKE_BYTE_AVAIL(cinfo,action); \
  171106. bytes_in_buffer--; \
  171107. V += GETJOCTET(*next_input_byte++); )
  171108. /*
  171109. * Routines to process JPEG markers.
  171110. *
  171111. * Entry condition: JPEG marker itself has been read and its code saved
  171112. * in cinfo->unread_marker; input restart point is just after the marker.
  171113. *
  171114. * Exit: if return TRUE, have read and processed any parameters, and have
  171115. * updated the restart point to point after the parameters.
  171116. * If return FALSE, was forced to suspend before reaching end of
  171117. * marker parameters; restart point has not been moved. Same routine
  171118. * will be called again after application supplies more input data.
  171119. *
  171120. * This approach to suspension assumes that all of a marker's parameters
  171121. * can fit into a single input bufferload. This should hold for "normal"
  171122. * markers. Some COM/APPn markers might have large parameter segments
  171123. * that might not fit. If we are simply dropping such a marker, we use
  171124. * skip_input_data to get past it, and thereby put the problem on the
  171125. * source manager's shoulders. If we are saving the marker's contents
  171126. * into memory, we use a slightly different convention: when forced to
  171127. * suspend, the marker processor updates the restart point to the end of
  171128. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171129. * On resumption, cinfo->unread_marker still contains the marker code,
  171130. * but the data source will point to the next chunk of marker data.
  171131. * The marker processor must retain internal state to deal with this.
  171132. *
  171133. * Note that we don't bother to avoid duplicate trace messages if a
  171134. * suspension occurs within marker parameters. Other side effects
  171135. * require more care.
  171136. */
  171137. LOCAL(boolean)
  171138. get_soi (j_decompress_ptr cinfo)
  171139. /* Process an SOI marker */
  171140. {
  171141. int i;
  171142. TRACEMS(cinfo, 1, JTRC_SOI);
  171143. if (cinfo->marker->saw_SOI)
  171144. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171145. /* Reset all parameters that are defined to be reset by SOI */
  171146. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171147. cinfo->arith_dc_L[i] = 0;
  171148. cinfo->arith_dc_U[i] = 1;
  171149. cinfo->arith_ac_K[i] = 5;
  171150. }
  171151. cinfo->restart_interval = 0;
  171152. /* Set initial assumptions for colorspace etc */
  171153. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171154. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171155. cinfo->saw_JFIF_marker = FALSE;
  171156. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171157. cinfo->JFIF_minor_version = 1;
  171158. cinfo->density_unit = 0;
  171159. cinfo->X_density = 1;
  171160. cinfo->Y_density = 1;
  171161. cinfo->saw_Adobe_marker = FALSE;
  171162. cinfo->Adobe_transform = 0;
  171163. cinfo->marker->saw_SOI = TRUE;
  171164. return TRUE;
  171165. }
  171166. LOCAL(boolean)
  171167. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171168. /* Process a SOFn marker */
  171169. {
  171170. INT32 length;
  171171. int c, ci;
  171172. jpeg_component_info * compptr;
  171173. INPUT_VARS(cinfo);
  171174. cinfo->progressive_mode = is_prog;
  171175. cinfo->arith_code = is_arith;
  171176. INPUT_2BYTES(cinfo, length, return FALSE);
  171177. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171178. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171179. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171180. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171181. length -= 8;
  171182. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171183. (int) cinfo->image_width, (int) cinfo->image_height,
  171184. cinfo->num_components);
  171185. if (cinfo->marker->saw_SOF)
  171186. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171187. /* We don't support files in which the image height is initially specified */
  171188. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171189. /* might as well have a general sanity check. */
  171190. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171191. || cinfo->num_components <= 0)
  171192. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171193. if (length != (cinfo->num_components * 3))
  171194. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171195. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171196. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171197. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171198. cinfo->num_components * SIZEOF(jpeg_component_info));
  171199. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171200. ci++, compptr++) {
  171201. compptr->component_index = ci;
  171202. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171203. INPUT_BYTE(cinfo, c, return FALSE);
  171204. compptr->h_samp_factor = (c >> 4) & 15;
  171205. compptr->v_samp_factor = (c ) & 15;
  171206. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171207. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171208. compptr->component_id, compptr->h_samp_factor,
  171209. compptr->v_samp_factor, compptr->quant_tbl_no);
  171210. }
  171211. cinfo->marker->saw_SOF = TRUE;
  171212. INPUT_SYNC(cinfo);
  171213. return TRUE;
  171214. }
  171215. LOCAL(boolean)
  171216. get_sos (j_decompress_ptr cinfo)
  171217. /* Process a SOS marker */
  171218. {
  171219. INT32 length;
  171220. int i, ci, n, c, cc;
  171221. jpeg_component_info * compptr;
  171222. INPUT_VARS(cinfo);
  171223. if (! cinfo->marker->saw_SOF)
  171224. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171225. INPUT_2BYTES(cinfo, length, return FALSE);
  171226. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171227. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171228. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171229. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171230. cinfo->comps_in_scan = n;
  171231. /* Collect the component-spec parameters */
  171232. for (i = 0; i < n; i++) {
  171233. INPUT_BYTE(cinfo, cc, return FALSE);
  171234. INPUT_BYTE(cinfo, c, return FALSE);
  171235. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171236. ci++, compptr++) {
  171237. if (cc == compptr->component_id)
  171238. goto id_found;
  171239. }
  171240. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171241. id_found:
  171242. cinfo->cur_comp_info[i] = compptr;
  171243. compptr->dc_tbl_no = (c >> 4) & 15;
  171244. compptr->ac_tbl_no = (c ) & 15;
  171245. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171246. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171247. }
  171248. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171249. INPUT_BYTE(cinfo, c, return FALSE);
  171250. cinfo->Ss = c;
  171251. INPUT_BYTE(cinfo, c, return FALSE);
  171252. cinfo->Se = c;
  171253. INPUT_BYTE(cinfo, c, return FALSE);
  171254. cinfo->Ah = (c >> 4) & 15;
  171255. cinfo->Al = (c ) & 15;
  171256. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171257. cinfo->Ah, cinfo->Al);
  171258. /* Prepare to scan data & restart markers */
  171259. cinfo->marker->next_restart_num = 0;
  171260. /* Count another SOS marker */
  171261. cinfo->input_scan_number++;
  171262. INPUT_SYNC(cinfo);
  171263. return TRUE;
  171264. }
  171265. #ifdef D_ARITH_CODING_SUPPORTED
  171266. LOCAL(boolean)
  171267. get_dac (j_decompress_ptr cinfo)
  171268. /* Process a DAC marker */
  171269. {
  171270. INT32 length;
  171271. int index, val;
  171272. INPUT_VARS(cinfo);
  171273. INPUT_2BYTES(cinfo, length, return FALSE);
  171274. length -= 2;
  171275. while (length > 0) {
  171276. INPUT_BYTE(cinfo, index, return FALSE);
  171277. INPUT_BYTE(cinfo, val, return FALSE);
  171278. length -= 2;
  171279. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171280. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171281. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171282. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171283. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171284. } else { /* define DC table */
  171285. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171286. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171287. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171288. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171289. }
  171290. }
  171291. if (length != 0)
  171292. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171293. INPUT_SYNC(cinfo);
  171294. return TRUE;
  171295. }
  171296. #else /* ! D_ARITH_CODING_SUPPORTED */
  171297. #define get_dac(cinfo) skip_variable(cinfo)
  171298. #endif /* D_ARITH_CODING_SUPPORTED */
  171299. LOCAL(boolean)
  171300. get_dht (j_decompress_ptr cinfo)
  171301. /* Process a DHT marker */
  171302. {
  171303. INT32 length;
  171304. UINT8 bits[17];
  171305. UINT8 huffval[256];
  171306. int i, index, count;
  171307. JHUFF_TBL **htblptr;
  171308. INPUT_VARS(cinfo);
  171309. INPUT_2BYTES(cinfo, length, return FALSE);
  171310. length -= 2;
  171311. while (length > 16) {
  171312. INPUT_BYTE(cinfo, index, return FALSE);
  171313. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171314. bits[0] = 0;
  171315. count = 0;
  171316. for (i = 1; i <= 16; i++) {
  171317. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171318. count += bits[i];
  171319. }
  171320. length -= 1 + 16;
  171321. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171322. bits[1], bits[2], bits[3], bits[4],
  171323. bits[5], bits[6], bits[7], bits[8]);
  171324. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171325. bits[9], bits[10], bits[11], bits[12],
  171326. bits[13], bits[14], bits[15], bits[16]);
  171327. /* Here we just do minimal validation of the counts to avoid walking
  171328. * off the end of our table space. jdhuff.c will check more carefully.
  171329. */
  171330. if (count > 256 || ((INT32) count) > length)
  171331. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171332. for (i = 0; i < count; i++)
  171333. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171334. length -= count;
  171335. if (index & 0x10) { /* AC table definition */
  171336. index -= 0x10;
  171337. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171338. } else { /* DC table definition */
  171339. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171340. }
  171341. if (index < 0 || index >= NUM_HUFF_TBLS)
  171342. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171343. if (*htblptr == NULL)
  171344. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171345. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171346. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171347. }
  171348. if (length != 0)
  171349. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171350. INPUT_SYNC(cinfo);
  171351. return TRUE;
  171352. }
  171353. LOCAL(boolean)
  171354. get_dqt (j_decompress_ptr cinfo)
  171355. /* Process a DQT marker */
  171356. {
  171357. INT32 length;
  171358. int n, i, prec;
  171359. unsigned int tmp;
  171360. JQUANT_TBL *quant_ptr;
  171361. INPUT_VARS(cinfo);
  171362. INPUT_2BYTES(cinfo, length, return FALSE);
  171363. length -= 2;
  171364. while (length > 0) {
  171365. INPUT_BYTE(cinfo, n, return FALSE);
  171366. prec = n >> 4;
  171367. n &= 0x0F;
  171368. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171369. if (n >= NUM_QUANT_TBLS)
  171370. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171371. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171372. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171373. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171374. for (i = 0; i < DCTSIZE2; i++) {
  171375. if (prec)
  171376. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171377. else
  171378. INPUT_BYTE(cinfo, tmp, return FALSE);
  171379. /* We convert the zigzag-order table to natural array order. */
  171380. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171381. }
  171382. if (cinfo->err->trace_level >= 2) {
  171383. for (i = 0; i < DCTSIZE2; i += 8) {
  171384. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171385. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171386. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171387. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171388. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171389. }
  171390. }
  171391. length -= DCTSIZE2+1;
  171392. if (prec) length -= DCTSIZE2;
  171393. }
  171394. if (length != 0)
  171395. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171396. INPUT_SYNC(cinfo);
  171397. return TRUE;
  171398. }
  171399. LOCAL(boolean)
  171400. get_dri (j_decompress_ptr cinfo)
  171401. /* Process a DRI marker */
  171402. {
  171403. INT32 length;
  171404. unsigned int tmp;
  171405. INPUT_VARS(cinfo);
  171406. INPUT_2BYTES(cinfo, length, return FALSE);
  171407. if (length != 4)
  171408. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171409. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171410. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171411. cinfo->restart_interval = tmp;
  171412. INPUT_SYNC(cinfo);
  171413. return TRUE;
  171414. }
  171415. /*
  171416. * Routines for processing APPn and COM markers.
  171417. * These are either saved in memory or discarded, per application request.
  171418. * APP0 and APP14 are specially checked to see if they are
  171419. * JFIF and Adobe markers, respectively.
  171420. */
  171421. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171422. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171423. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171424. LOCAL(void)
  171425. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171426. unsigned int datalen, INT32 remaining)
  171427. /* Examine first few bytes from an APP0.
  171428. * Take appropriate action if it is a JFIF marker.
  171429. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171430. */
  171431. {
  171432. INT32 totallen = (INT32) datalen + remaining;
  171433. if (datalen >= APP0_DATA_LEN &&
  171434. GETJOCTET(data[0]) == 0x4A &&
  171435. GETJOCTET(data[1]) == 0x46 &&
  171436. GETJOCTET(data[2]) == 0x49 &&
  171437. GETJOCTET(data[3]) == 0x46 &&
  171438. GETJOCTET(data[4]) == 0) {
  171439. /* Found JFIF APP0 marker: save info */
  171440. cinfo->saw_JFIF_marker = TRUE;
  171441. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171442. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171443. cinfo->density_unit = GETJOCTET(data[7]);
  171444. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171445. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171446. /* Check version.
  171447. * Major version must be 1, anything else signals an incompatible change.
  171448. * (We used to treat this as an error, but now it's a nonfatal warning,
  171449. * because some bozo at Hijaak couldn't read the spec.)
  171450. * Minor version should be 0..2, but process anyway if newer.
  171451. */
  171452. if (cinfo->JFIF_major_version != 1)
  171453. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171454. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171455. /* Generate trace messages */
  171456. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171457. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171458. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171459. /* Validate thumbnail dimensions and issue appropriate messages */
  171460. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171461. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171462. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171463. totallen -= APP0_DATA_LEN;
  171464. if (totallen !=
  171465. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171466. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171467. } else if (datalen >= 6 &&
  171468. GETJOCTET(data[0]) == 0x4A &&
  171469. GETJOCTET(data[1]) == 0x46 &&
  171470. GETJOCTET(data[2]) == 0x58 &&
  171471. GETJOCTET(data[3]) == 0x58 &&
  171472. GETJOCTET(data[4]) == 0) {
  171473. /* Found JFIF "JFXX" extension APP0 marker */
  171474. /* The library doesn't actually do anything with these,
  171475. * but we try to produce a helpful trace message.
  171476. */
  171477. switch (GETJOCTET(data[5])) {
  171478. case 0x10:
  171479. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171480. break;
  171481. case 0x11:
  171482. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171483. break;
  171484. case 0x13:
  171485. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171486. break;
  171487. default:
  171488. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171489. GETJOCTET(data[5]), (int) totallen);
  171490. break;
  171491. }
  171492. } else {
  171493. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171494. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171495. }
  171496. }
  171497. LOCAL(void)
  171498. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171499. unsigned int datalen, INT32 remaining)
  171500. /* Examine first few bytes from an APP14.
  171501. * Take appropriate action if it is an Adobe marker.
  171502. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171503. */
  171504. {
  171505. unsigned int version, flags0, flags1, transform;
  171506. if (datalen >= APP14_DATA_LEN &&
  171507. GETJOCTET(data[0]) == 0x41 &&
  171508. GETJOCTET(data[1]) == 0x64 &&
  171509. GETJOCTET(data[2]) == 0x6F &&
  171510. GETJOCTET(data[3]) == 0x62 &&
  171511. GETJOCTET(data[4]) == 0x65) {
  171512. /* Found Adobe APP14 marker */
  171513. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171514. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171515. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171516. transform = GETJOCTET(data[11]);
  171517. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171518. cinfo->saw_Adobe_marker = TRUE;
  171519. cinfo->Adobe_transform = (UINT8) transform;
  171520. } else {
  171521. /* Start of APP14 does not match "Adobe", or too short */
  171522. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171523. }
  171524. }
  171525. METHODDEF(boolean)
  171526. get_interesting_appn (j_decompress_ptr cinfo)
  171527. /* Process an APP0 or APP14 marker without saving it */
  171528. {
  171529. INT32 length;
  171530. JOCTET b[APPN_DATA_LEN];
  171531. unsigned int i, numtoread;
  171532. INPUT_VARS(cinfo);
  171533. INPUT_2BYTES(cinfo, length, return FALSE);
  171534. length -= 2;
  171535. /* get the interesting part of the marker data */
  171536. if (length >= APPN_DATA_LEN)
  171537. numtoread = APPN_DATA_LEN;
  171538. else if (length > 0)
  171539. numtoread = (unsigned int) length;
  171540. else
  171541. numtoread = 0;
  171542. for (i = 0; i < numtoread; i++)
  171543. INPUT_BYTE(cinfo, b[i], return FALSE);
  171544. length -= numtoread;
  171545. /* process it */
  171546. switch (cinfo->unread_marker) {
  171547. case M_APP0:
  171548. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171549. break;
  171550. case M_APP14:
  171551. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171552. break;
  171553. default:
  171554. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171555. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171556. break;
  171557. }
  171558. /* skip any remaining data -- could be lots */
  171559. INPUT_SYNC(cinfo);
  171560. if (length > 0)
  171561. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171562. return TRUE;
  171563. }
  171564. #ifdef SAVE_MARKERS_SUPPORTED
  171565. METHODDEF(boolean)
  171566. save_marker (j_decompress_ptr cinfo)
  171567. /* Save an APPn or COM marker into the marker list */
  171568. {
  171569. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171570. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171571. unsigned int bytes_read, data_length;
  171572. JOCTET FAR * data;
  171573. INT32 length = 0;
  171574. INPUT_VARS(cinfo);
  171575. if (cur_marker == NULL) {
  171576. /* begin reading a marker */
  171577. INPUT_2BYTES(cinfo, length, return FALSE);
  171578. length -= 2;
  171579. if (length >= 0) { /* watch out for bogus length word */
  171580. /* figure out how much we want to save */
  171581. unsigned int limit;
  171582. if (cinfo->unread_marker == (int) M_COM)
  171583. limit = marker->length_limit_COM;
  171584. else
  171585. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171586. if ((unsigned int) length < limit)
  171587. limit = (unsigned int) length;
  171588. /* allocate and initialize the marker item */
  171589. cur_marker = (jpeg_saved_marker_ptr)
  171590. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171591. SIZEOF(struct jpeg_marker_struct) + limit);
  171592. cur_marker->next = NULL;
  171593. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171594. cur_marker->original_length = (unsigned int) length;
  171595. cur_marker->data_length = limit;
  171596. /* data area is just beyond the jpeg_marker_struct */
  171597. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171598. marker->cur_marker = cur_marker;
  171599. marker->bytes_read = 0;
  171600. bytes_read = 0;
  171601. data_length = limit;
  171602. } else {
  171603. /* deal with bogus length word */
  171604. bytes_read = data_length = 0;
  171605. data = NULL;
  171606. }
  171607. } else {
  171608. /* resume reading a marker */
  171609. bytes_read = marker->bytes_read;
  171610. data_length = cur_marker->data_length;
  171611. data = cur_marker->data + bytes_read;
  171612. }
  171613. while (bytes_read < data_length) {
  171614. INPUT_SYNC(cinfo); /* move the restart point to here */
  171615. marker->bytes_read = bytes_read;
  171616. /* If there's not at least one byte in buffer, suspend */
  171617. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171618. /* Copy bytes with reasonable rapidity */
  171619. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171620. *data++ = *next_input_byte++;
  171621. bytes_in_buffer--;
  171622. bytes_read++;
  171623. }
  171624. }
  171625. /* Done reading what we want to read */
  171626. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171627. /* Add new marker to end of list */
  171628. if (cinfo->marker_list == NULL) {
  171629. cinfo->marker_list = cur_marker;
  171630. } else {
  171631. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171632. while (prev->next != NULL)
  171633. prev = prev->next;
  171634. prev->next = cur_marker;
  171635. }
  171636. /* Reset pointer & calc remaining data length */
  171637. data = cur_marker->data;
  171638. length = cur_marker->original_length - data_length;
  171639. }
  171640. /* Reset to initial state for next marker */
  171641. marker->cur_marker = NULL;
  171642. /* Process the marker if interesting; else just make a generic trace msg */
  171643. switch (cinfo->unread_marker) {
  171644. case M_APP0:
  171645. examine_app0(cinfo, data, data_length, length);
  171646. break;
  171647. case M_APP14:
  171648. examine_app14(cinfo, data, data_length, length);
  171649. break;
  171650. default:
  171651. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171652. (int) (data_length + length));
  171653. break;
  171654. }
  171655. /* skip any remaining data -- could be lots */
  171656. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171657. if (length > 0)
  171658. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171659. return TRUE;
  171660. }
  171661. #endif /* SAVE_MARKERS_SUPPORTED */
  171662. METHODDEF(boolean)
  171663. skip_variable (j_decompress_ptr cinfo)
  171664. /* Skip over an unknown or uninteresting variable-length marker */
  171665. {
  171666. INT32 length;
  171667. INPUT_VARS(cinfo);
  171668. INPUT_2BYTES(cinfo, length, return FALSE);
  171669. length -= 2;
  171670. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171671. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171672. if (length > 0)
  171673. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171674. return TRUE;
  171675. }
  171676. /*
  171677. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171678. * Returns FALSE if had to suspend before reaching a marker;
  171679. * in that case cinfo->unread_marker is unchanged.
  171680. *
  171681. * Note that the result might not be a valid marker code,
  171682. * but it will never be 0 or FF.
  171683. */
  171684. LOCAL(boolean)
  171685. next_marker (j_decompress_ptr cinfo)
  171686. {
  171687. int c;
  171688. INPUT_VARS(cinfo);
  171689. for (;;) {
  171690. INPUT_BYTE(cinfo, c, return FALSE);
  171691. /* Skip any non-FF bytes.
  171692. * This may look a bit inefficient, but it will not occur in a valid file.
  171693. * We sync after each discarded byte so that a suspending data source
  171694. * can discard the byte from its buffer.
  171695. */
  171696. while (c != 0xFF) {
  171697. cinfo->marker->discarded_bytes++;
  171698. INPUT_SYNC(cinfo);
  171699. INPUT_BYTE(cinfo, c, return FALSE);
  171700. }
  171701. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171702. * pad bytes, so don't count them in discarded_bytes. We assume there
  171703. * will not be so many consecutive FF bytes as to overflow a suspending
  171704. * data source's input buffer.
  171705. */
  171706. do {
  171707. INPUT_BYTE(cinfo, c, return FALSE);
  171708. } while (c == 0xFF);
  171709. if (c != 0)
  171710. break; /* found a valid marker, exit loop */
  171711. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171712. * Discard it and loop back to try again.
  171713. */
  171714. cinfo->marker->discarded_bytes += 2;
  171715. INPUT_SYNC(cinfo);
  171716. }
  171717. if (cinfo->marker->discarded_bytes != 0) {
  171718. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171719. cinfo->marker->discarded_bytes = 0;
  171720. }
  171721. cinfo->unread_marker = c;
  171722. INPUT_SYNC(cinfo);
  171723. return TRUE;
  171724. }
  171725. LOCAL(boolean)
  171726. first_marker (j_decompress_ptr cinfo)
  171727. /* Like next_marker, but used to obtain the initial SOI marker. */
  171728. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171729. * we might well scan an entire input file before realizing it ain't JPEG.
  171730. * If an application wants to process non-JFIF files, it must seek to the
  171731. * SOI before calling the JPEG library.
  171732. */
  171733. {
  171734. int c, c2;
  171735. INPUT_VARS(cinfo);
  171736. INPUT_BYTE(cinfo, c, return FALSE);
  171737. INPUT_BYTE(cinfo, c2, return FALSE);
  171738. if (c != 0xFF || c2 != (int) M_SOI)
  171739. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171740. cinfo->unread_marker = c2;
  171741. INPUT_SYNC(cinfo);
  171742. return TRUE;
  171743. }
  171744. /*
  171745. * Read markers until SOS or EOI.
  171746. *
  171747. * Returns same codes as are defined for jpeg_consume_input:
  171748. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171749. */
  171750. METHODDEF(int)
  171751. read_markers (j_decompress_ptr cinfo)
  171752. {
  171753. /* Outer loop repeats once for each marker. */
  171754. for (;;) {
  171755. /* Collect the marker proper, unless we already did. */
  171756. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171757. if (cinfo->unread_marker == 0) {
  171758. if (! cinfo->marker->saw_SOI) {
  171759. if (! first_marker(cinfo))
  171760. return JPEG_SUSPENDED;
  171761. } else {
  171762. if (! next_marker(cinfo))
  171763. return JPEG_SUSPENDED;
  171764. }
  171765. }
  171766. /* At this point cinfo->unread_marker contains the marker code and the
  171767. * input point is just past the marker proper, but before any parameters.
  171768. * A suspension will cause us to return with this state still true.
  171769. */
  171770. switch (cinfo->unread_marker) {
  171771. case M_SOI:
  171772. if (! get_soi(cinfo))
  171773. return JPEG_SUSPENDED;
  171774. break;
  171775. case M_SOF0: /* Baseline */
  171776. case M_SOF1: /* Extended sequential, Huffman */
  171777. if (! get_sof(cinfo, FALSE, FALSE))
  171778. return JPEG_SUSPENDED;
  171779. break;
  171780. case M_SOF2: /* Progressive, Huffman */
  171781. if (! get_sof(cinfo, TRUE, FALSE))
  171782. return JPEG_SUSPENDED;
  171783. break;
  171784. case M_SOF9: /* Extended sequential, arithmetic */
  171785. if (! get_sof(cinfo, FALSE, TRUE))
  171786. return JPEG_SUSPENDED;
  171787. break;
  171788. case M_SOF10: /* Progressive, arithmetic */
  171789. if (! get_sof(cinfo, TRUE, TRUE))
  171790. return JPEG_SUSPENDED;
  171791. break;
  171792. /* Currently unsupported SOFn types */
  171793. case M_SOF3: /* Lossless, Huffman */
  171794. case M_SOF5: /* Differential sequential, Huffman */
  171795. case M_SOF6: /* Differential progressive, Huffman */
  171796. case M_SOF7: /* Differential lossless, Huffman */
  171797. case M_JPG: /* Reserved for JPEG extensions */
  171798. case M_SOF11: /* Lossless, arithmetic */
  171799. case M_SOF13: /* Differential sequential, arithmetic */
  171800. case M_SOF14: /* Differential progressive, arithmetic */
  171801. case M_SOF15: /* Differential lossless, arithmetic */
  171802. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171803. break;
  171804. case M_SOS:
  171805. if (! get_sos(cinfo))
  171806. return JPEG_SUSPENDED;
  171807. cinfo->unread_marker = 0; /* processed the marker */
  171808. return JPEG_REACHED_SOS;
  171809. case M_EOI:
  171810. TRACEMS(cinfo, 1, JTRC_EOI);
  171811. cinfo->unread_marker = 0; /* processed the marker */
  171812. return JPEG_REACHED_EOI;
  171813. case M_DAC:
  171814. if (! get_dac(cinfo))
  171815. return JPEG_SUSPENDED;
  171816. break;
  171817. case M_DHT:
  171818. if (! get_dht(cinfo))
  171819. return JPEG_SUSPENDED;
  171820. break;
  171821. case M_DQT:
  171822. if (! get_dqt(cinfo))
  171823. return JPEG_SUSPENDED;
  171824. break;
  171825. case M_DRI:
  171826. if (! get_dri(cinfo))
  171827. return JPEG_SUSPENDED;
  171828. break;
  171829. case M_APP0:
  171830. case M_APP1:
  171831. case M_APP2:
  171832. case M_APP3:
  171833. case M_APP4:
  171834. case M_APP5:
  171835. case M_APP6:
  171836. case M_APP7:
  171837. case M_APP8:
  171838. case M_APP9:
  171839. case M_APP10:
  171840. case M_APP11:
  171841. case M_APP12:
  171842. case M_APP13:
  171843. case M_APP14:
  171844. case M_APP15:
  171845. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171846. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171847. return JPEG_SUSPENDED;
  171848. break;
  171849. case M_COM:
  171850. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171851. return JPEG_SUSPENDED;
  171852. break;
  171853. case M_RST0: /* these are all parameterless */
  171854. case M_RST1:
  171855. case M_RST2:
  171856. case M_RST3:
  171857. case M_RST4:
  171858. case M_RST5:
  171859. case M_RST6:
  171860. case M_RST7:
  171861. case M_TEM:
  171862. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171863. break;
  171864. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171865. if (! skip_variable(cinfo))
  171866. return JPEG_SUSPENDED;
  171867. break;
  171868. default: /* must be DHP, EXP, JPGn, or RESn */
  171869. /* For now, we treat the reserved markers as fatal errors since they are
  171870. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171871. * Once the JPEG 3 version-number marker is well defined, this code
  171872. * ought to change!
  171873. */
  171874. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171875. break;
  171876. }
  171877. /* Successfully processed marker, so reset state variable */
  171878. cinfo->unread_marker = 0;
  171879. } /* end loop */
  171880. }
  171881. /*
  171882. * Read a restart marker, which is expected to appear next in the datastream;
  171883. * if the marker is not there, take appropriate recovery action.
  171884. * Returns FALSE if suspension is required.
  171885. *
  171886. * This is called by the entropy decoder after it has read an appropriate
  171887. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171888. * has already read a marker from the data source. Under normal conditions
  171889. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171890. * it holds a marker which the decoder will be unable to read past.
  171891. */
  171892. METHODDEF(boolean)
  171893. read_restart_marker (j_decompress_ptr cinfo)
  171894. {
  171895. /* Obtain a marker unless we already did. */
  171896. /* Note that next_marker will complain if it skips any data. */
  171897. if (cinfo->unread_marker == 0) {
  171898. if (! next_marker(cinfo))
  171899. return FALSE;
  171900. }
  171901. if (cinfo->unread_marker ==
  171902. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171903. /* Normal case --- swallow the marker and let entropy decoder continue */
  171904. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171905. cinfo->unread_marker = 0;
  171906. } else {
  171907. /* Uh-oh, the restart markers have been messed up. */
  171908. /* Let the data source manager determine how to resync. */
  171909. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171910. cinfo->marker->next_restart_num))
  171911. return FALSE;
  171912. }
  171913. /* Update next-restart state */
  171914. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171915. return TRUE;
  171916. }
  171917. /*
  171918. * This is the default resync_to_restart method for data source managers
  171919. * to use if they don't have any better approach. Some data source managers
  171920. * may be able to back up, or may have additional knowledge about the data
  171921. * which permits a more intelligent recovery strategy; such managers would
  171922. * presumably supply their own resync method.
  171923. *
  171924. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171925. * the restart marker it was expecting. (This code is *not* used unless
  171926. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171927. * the marker code actually found (might be anything, except 0 or FF).
  171928. * The desired restart marker number (0..7) is passed as a parameter.
  171929. * This routine is supposed to apply whatever error recovery strategy seems
  171930. * appropriate in order to position the input stream to the next data segment.
  171931. * Note that cinfo->unread_marker is treated as a marker appearing before
  171932. * the current data-source input point; usually it should be reset to zero
  171933. * before returning.
  171934. * Returns FALSE if suspension is required.
  171935. *
  171936. * This implementation is substantially constrained by wanting to treat the
  171937. * input as a data stream; this means we can't back up. Therefore, we have
  171938. * only the following actions to work with:
  171939. * 1. Simply discard the marker and let the entropy decoder resume at next
  171940. * byte of file.
  171941. * 2. Read forward until we find another marker, discarding intervening
  171942. * data. (In theory we could look ahead within the current bufferload,
  171943. * without having to discard data if we don't find the desired marker.
  171944. * This idea is not implemented here, in part because it makes behavior
  171945. * dependent on buffer size and chance buffer-boundary positions.)
  171946. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171947. * This will cause the entropy decoder to process an empty data segment,
  171948. * inserting dummy zeroes, and then we will reprocess the marker.
  171949. *
  171950. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171951. * appropriate if the found marker is a future restart marker (indicating
  171952. * that we have missed the desired restart marker, probably because it got
  171953. * corrupted).
  171954. * We apply #2 or #3 if the found marker is a restart marker no more than
  171955. * two counts behind or ahead of the expected one. We also apply #2 if the
  171956. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171957. * If the found marker is a restart marker more than 2 counts away, we do #1
  171958. * (too much risk that the marker is erroneous; with luck we will be able to
  171959. * resync at some future point).
  171960. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171961. * overrunning the end of a scan. An implementation limited to single-scan
  171962. * files might find it better to apply #2 for markers other than EOI, since
  171963. * any other marker would have to be bogus data in that case.
  171964. */
  171965. GLOBAL(boolean)
  171966. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171967. {
  171968. int marker = cinfo->unread_marker;
  171969. int action = 1;
  171970. /* Always put up a warning. */
  171971. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171972. /* Outer loop handles repeated decision after scanning forward. */
  171973. for (;;) {
  171974. if (marker < (int) M_SOF0)
  171975. action = 2; /* invalid marker */
  171976. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171977. action = 3; /* valid non-restart marker */
  171978. else {
  171979. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171980. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171981. action = 3; /* one of the next two expected restarts */
  171982. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171983. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171984. action = 2; /* a prior restart, so advance */
  171985. else
  171986. action = 1; /* desired restart or too far away */
  171987. }
  171988. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171989. switch (action) {
  171990. case 1:
  171991. /* Discard marker and let entropy decoder resume processing. */
  171992. cinfo->unread_marker = 0;
  171993. return TRUE;
  171994. case 2:
  171995. /* Scan to the next marker, and repeat the decision loop. */
  171996. if (! next_marker(cinfo))
  171997. return FALSE;
  171998. marker = cinfo->unread_marker;
  171999. break;
  172000. case 3:
  172001. /* Return without advancing past this marker. */
  172002. /* Entropy decoder will be forced to process an empty segment. */
  172003. return TRUE;
  172004. }
  172005. } /* end loop */
  172006. }
  172007. /*
  172008. * Reset marker processing state to begin a fresh datastream.
  172009. */
  172010. METHODDEF(void)
  172011. reset_marker_reader (j_decompress_ptr cinfo)
  172012. {
  172013. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172014. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172015. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172016. cinfo->unread_marker = 0; /* no pending marker */
  172017. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172018. marker->pub.saw_SOF = FALSE;
  172019. marker->pub.discarded_bytes = 0;
  172020. marker->cur_marker = NULL;
  172021. }
  172022. /*
  172023. * Initialize the marker reader module.
  172024. * This is called only once, when the decompression object is created.
  172025. */
  172026. GLOBAL(void)
  172027. jinit_marker_reader (j_decompress_ptr cinfo)
  172028. {
  172029. my_marker_ptr2 marker;
  172030. int i;
  172031. /* Create subobject in permanent pool */
  172032. marker = (my_marker_ptr2)
  172033. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172034. SIZEOF(my_marker_reader));
  172035. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172036. /* Initialize public method pointers */
  172037. marker->pub.reset_marker_reader = reset_marker_reader;
  172038. marker->pub.read_markers = read_markers;
  172039. marker->pub.read_restart_marker = read_restart_marker;
  172040. /* Initialize COM/APPn processing.
  172041. * By default, we examine and then discard APP0 and APP14,
  172042. * but simply discard COM and all other APPn.
  172043. */
  172044. marker->process_COM = skip_variable;
  172045. marker->length_limit_COM = 0;
  172046. for (i = 0; i < 16; i++) {
  172047. marker->process_APPn[i] = skip_variable;
  172048. marker->length_limit_APPn[i] = 0;
  172049. }
  172050. marker->process_APPn[0] = get_interesting_appn;
  172051. marker->process_APPn[14] = get_interesting_appn;
  172052. /* Reset marker processing state */
  172053. reset_marker_reader(cinfo);
  172054. }
  172055. /*
  172056. * Control saving of COM and APPn markers into marker_list.
  172057. */
  172058. #ifdef SAVE_MARKERS_SUPPORTED
  172059. GLOBAL(void)
  172060. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172061. unsigned int length_limit)
  172062. {
  172063. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172064. long maxlength;
  172065. jpeg_marker_parser_method processor;
  172066. /* Length limit mustn't be larger than what we can allocate
  172067. * (should only be a concern in a 16-bit environment).
  172068. */
  172069. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172070. if (((long) length_limit) > maxlength)
  172071. length_limit = (unsigned int) maxlength;
  172072. /* Choose processor routine to use.
  172073. * APP0/APP14 have special requirements.
  172074. */
  172075. if (length_limit) {
  172076. processor = save_marker;
  172077. /* If saving APP0/APP14, save at least enough for our internal use. */
  172078. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172079. length_limit = APP0_DATA_LEN;
  172080. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172081. length_limit = APP14_DATA_LEN;
  172082. } else {
  172083. processor = skip_variable;
  172084. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172085. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172086. processor = get_interesting_appn;
  172087. }
  172088. if (marker_code == (int) M_COM) {
  172089. marker->process_COM = processor;
  172090. marker->length_limit_COM = length_limit;
  172091. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172092. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172093. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172094. } else
  172095. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172096. }
  172097. #endif /* SAVE_MARKERS_SUPPORTED */
  172098. /*
  172099. * Install a special processing method for COM or APPn markers.
  172100. */
  172101. GLOBAL(void)
  172102. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172103. jpeg_marker_parser_method routine)
  172104. {
  172105. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172106. if (marker_code == (int) M_COM)
  172107. marker->process_COM = routine;
  172108. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172109. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172110. else
  172111. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172112. }
  172113. /*** End of inlined file: jdmarker.c ***/
  172114. /*** Start of inlined file: jdmaster.c ***/
  172115. #define JPEG_INTERNALS
  172116. /* Private state */
  172117. typedef struct {
  172118. struct jpeg_decomp_master pub; /* public fields */
  172119. int pass_number; /* # of passes completed */
  172120. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172121. /* Saved references to initialized quantizer modules,
  172122. * in case we need to switch modes.
  172123. */
  172124. struct jpeg_color_quantizer * quantizer_1pass;
  172125. struct jpeg_color_quantizer * quantizer_2pass;
  172126. } my_decomp_master;
  172127. typedef my_decomp_master * my_master_ptr6;
  172128. /*
  172129. * Determine whether merged upsample/color conversion should be used.
  172130. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172131. */
  172132. LOCAL(boolean)
  172133. use_merged_upsample (j_decompress_ptr cinfo)
  172134. {
  172135. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172136. /* Merging is the equivalent of plain box-filter upsampling */
  172137. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172138. return FALSE;
  172139. /* jdmerge.c only supports YCC=>RGB color conversion */
  172140. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172141. cinfo->out_color_space != JCS_RGB ||
  172142. cinfo->out_color_components != RGB_PIXELSIZE)
  172143. return FALSE;
  172144. /* and it only handles 2h1v or 2h2v sampling ratios */
  172145. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172146. cinfo->comp_info[1].h_samp_factor != 1 ||
  172147. cinfo->comp_info[2].h_samp_factor != 1 ||
  172148. cinfo->comp_info[0].v_samp_factor > 2 ||
  172149. cinfo->comp_info[1].v_samp_factor != 1 ||
  172150. cinfo->comp_info[2].v_samp_factor != 1)
  172151. return FALSE;
  172152. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172153. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172154. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172155. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172156. return FALSE;
  172157. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172158. return TRUE; /* by golly, it'll work... */
  172159. #else
  172160. return FALSE;
  172161. #endif
  172162. }
  172163. /*
  172164. * Compute output image dimensions and related values.
  172165. * NOTE: this is exported for possible use by application.
  172166. * Hence it mustn't do anything that can't be done twice.
  172167. * Also note that it may be called before the master module is initialized!
  172168. */
  172169. GLOBAL(void)
  172170. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172171. /* Do computations that are needed before master selection phase */
  172172. {
  172173. #ifdef IDCT_SCALING_SUPPORTED
  172174. int ci;
  172175. jpeg_component_info *compptr;
  172176. #endif
  172177. /* Prevent application from calling me at wrong times */
  172178. if (cinfo->global_state != DSTATE_READY)
  172179. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172180. #ifdef IDCT_SCALING_SUPPORTED
  172181. /* Compute actual output image dimensions and DCT scaling choices. */
  172182. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172183. /* Provide 1/8 scaling */
  172184. cinfo->output_width = (JDIMENSION)
  172185. jdiv_round_up((long) cinfo->image_width, 8L);
  172186. cinfo->output_height = (JDIMENSION)
  172187. jdiv_round_up((long) cinfo->image_height, 8L);
  172188. cinfo->min_DCT_scaled_size = 1;
  172189. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172190. /* Provide 1/4 scaling */
  172191. cinfo->output_width = (JDIMENSION)
  172192. jdiv_round_up((long) cinfo->image_width, 4L);
  172193. cinfo->output_height = (JDIMENSION)
  172194. jdiv_round_up((long) cinfo->image_height, 4L);
  172195. cinfo->min_DCT_scaled_size = 2;
  172196. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172197. /* Provide 1/2 scaling */
  172198. cinfo->output_width = (JDIMENSION)
  172199. jdiv_round_up((long) cinfo->image_width, 2L);
  172200. cinfo->output_height = (JDIMENSION)
  172201. jdiv_round_up((long) cinfo->image_height, 2L);
  172202. cinfo->min_DCT_scaled_size = 4;
  172203. } else {
  172204. /* Provide 1/1 scaling */
  172205. cinfo->output_width = cinfo->image_width;
  172206. cinfo->output_height = cinfo->image_height;
  172207. cinfo->min_DCT_scaled_size = DCTSIZE;
  172208. }
  172209. /* In selecting the actual DCT scaling for each component, we try to
  172210. * scale up the chroma components via IDCT scaling rather than upsampling.
  172211. * This saves time if the upsampler gets to use 1:1 scaling.
  172212. * Note this code assumes that the supported DCT scalings are powers of 2.
  172213. */
  172214. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172215. ci++, compptr++) {
  172216. int ssize = cinfo->min_DCT_scaled_size;
  172217. while (ssize < DCTSIZE &&
  172218. (compptr->h_samp_factor * ssize * 2 <=
  172219. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172220. (compptr->v_samp_factor * ssize * 2 <=
  172221. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172222. ssize = ssize * 2;
  172223. }
  172224. compptr->DCT_scaled_size = ssize;
  172225. }
  172226. /* Recompute downsampled dimensions of components;
  172227. * application needs to know these if using raw downsampled data.
  172228. */
  172229. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172230. ci++, compptr++) {
  172231. /* Size in samples, after IDCT scaling */
  172232. compptr->downsampled_width = (JDIMENSION)
  172233. jdiv_round_up((long) cinfo->image_width *
  172234. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172235. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172236. compptr->downsampled_height = (JDIMENSION)
  172237. jdiv_round_up((long) cinfo->image_height *
  172238. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172239. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172240. }
  172241. #else /* !IDCT_SCALING_SUPPORTED */
  172242. /* Hardwire it to "no scaling" */
  172243. cinfo->output_width = cinfo->image_width;
  172244. cinfo->output_height = cinfo->image_height;
  172245. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172246. * and has computed unscaled downsampled_width and downsampled_height.
  172247. */
  172248. #endif /* IDCT_SCALING_SUPPORTED */
  172249. /* Report number of components in selected colorspace. */
  172250. /* Probably this should be in the color conversion module... */
  172251. switch (cinfo->out_color_space) {
  172252. case JCS_GRAYSCALE:
  172253. cinfo->out_color_components = 1;
  172254. break;
  172255. case JCS_RGB:
  172256. #if RGB_PIXELSIZE != 3
  172257. cinfo->out_color_components = RGB_PIXELSIZE;
  172258. break;
  172259. #endif /* else share code with YCbCr */
  172260. case JCS_YCbCr:
  172261. cinfo->out_color_components = 3;
  172262. break;
  172263. case JCS_CMYK:
  172264. case JCS_YCCK:
  172265. cinfo->out_color_components = 4;
  172266. break;
  172267. default: /* else must be same colorspace as in file */
  172268. cinfo->out_color_components = cinfo->num_components;
  172269. break;
  172270. }
  172271. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172272. cinfo->out_color_components);
  172273. /* See if upsampler will want to emit more than one row at a time */
  172274. if (use_merged_upsample(cinfo))
  172275. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172276. else
  172277. cinfo->rec_outbuf_height = 1;
  172278. }
  172279. /*
  172280. * Several decompression processes need to range-limit values to the range
  172281. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172282. * due to noise introduced by quantization, roundoff error, etc. These
  172283. * processes are inner loops and need to be as fast as possible. On most
  172284. * machines, particularly CPUs with pipelines or instruction prefetch,
  172285. * a (subscript-check-less) C table lookup
  172286. * x = sample_range_limit[x];
  172287. * is faster than explicit tests
  172288. * if (x < 0) x = 0;
  172289. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172290. * These processes all use a common table prepared by the routine below.
  172291. *
  172292. * For most steps we can mathematically guarantee that the initial value
  172293. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172294. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172295. * limiting step (just after the IDCT), a wildly out-of-range value is
  172296. * possible if the input data is corrupt. To avoid any chance of indexing
  172297. * off the end of memory and getting a bad-pointer trap, we perform the
  172298. * post-IDCT limiting thus:
  172299. * x = range_limit[x & MASK];
  172300. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172301. * samples. Under normal circumstances this is more than enough range and
  172302. * a correct output will be generated; with bogus input data the mask will
  172303. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172304. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172305. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172306. * So the post-IDCT limiting table ends up looking like this:
  172307. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172308. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172309. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172310. * 0,1,...,CENTERJSAMPLE-1
  172311. * Negative inputs select values from the upper half of the table after
  172312. * masking.
  172313. *
  172314. * We can save some space by overlapping the start of the post-IDCT table
  172315. * with the simpler range limiting table. The post-IDCT table begins at
  172316. * sample_range_limit + CENTERJSAMPLE.
  172317. *
  172318. * Note that the table is allocated in near data space on PCs; it's small
  172319. * enough and used often enough to justify this.
  172320. */
  172321. LOCAL(void)
  172322. prepare_range_limit_table (j_decompress_ptr cinfo)
  172323. /* Allocate and fill in the sample_range_limit table */
  172324. {
  172325. JSAMPLE * table;
  172326. int i;
  172327. table = (JSAMPLE *)
  172328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172329. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172330. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172331. cinfo->sample_range_limit = table;
  172332. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172333. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172334. /* Main part of "simple" table: limit[x] = x */
  172335. for (i = 0; i <= MAXJSAMPLE; i++)
  172336. table[i] = (JSAMPLE) i;
  172337. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172338. /* End of simple table, rest of first half of post-IDCT table */
  172339. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172340. table[i] = MAXJSAMPLE;
  172341. /* Second half of post-IDCT table */
  172342. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172343. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172344. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172345. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172346. }
  172347. /*
  172348. * Master selection of decompression modules.
  172349. * This is done once at jpeg_start_decompress time. We determine
  172350. * which modules will be used and give them appropriate initialization calls.
  172351. * We also initialize the decompressor input side to begin consuming data.
  172352. *
  172353. * Since jpeg_read_header has finished, we know what is in the SOF
  172354. * and (first) SOS markers. We also have all the application parameter
  172355. * settings.
  172356. */
  172357. LOCAL(void)
  172358. master_selection (j_decompress_ptr cinfo)
  172359. {
  172360. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172361. boolean use_c_buffer;
  172362. long samplesperrow;
  172363. JDIMENSION jd_samplesperrow;
  172364. /* Initialize dimensions and other stuff */
  172365. jpeg_calc_output_dimensions(cinfo);
  172366. prepare_range_limit_table(cinfo);
  172367. /* Width of an output scanline must be representable as JDIMENSION. */
  172368. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172369. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172370. if ((long) jd_samplesperrow != samplesperrow)
  172371. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172372. /* Initialize my private state */
  172373. master->pass_number = 0;
  172374. master->using_merged_upsample = use_merged_upsample(cinfo);
  172375. /* Color quantizer selection */
  172376. master->quantizer_1pass = NULL;
  172377. master->quantizer_2pass = NULL;
  172378. /* No mode changes if not using buffered-image mode. */
  172379. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172380. cinfo->enable_1pass_quant = FALSE;
  172381. cinfo->enable_external_quant = FALSE;
  172382. cinfo->enable_2pass_quant = FALSE;
  172383. }
  172384. if (cinfo->quantize_colors) {
  172385. if (cinfo->raw_data_out)
  172386. ERREXIT(cinfo, JERR_NOTIMPL);
  172387. /* 2-pass quantizer only works in 3-component color space. */
  172388. if (cinfo->out_color_components != 3) {
  172389. cinfo->enable_1pass_quant = TRUE;
  172390. cinfo->enable_external_quant = FALSE;
  172391. cinfo->enable_2pass_quant = FALSE;
  172392. cinfo->colormap = NULL;
  172393. } else if (cinfo->colormap != NULL) {
  172394. cinfo->enable_external_quant = TRUE;
  172395. } else if (cinfo->two_pass_quantize) {
  172396. cinfo->enable_2pass_quant = TRUE;
  172397. } else {
  172398. cinfo->enable_1pass_quant = TRUE;
  172399. }
  172400. if (cinfo->enable_1pass_quant) {
  172401. #ifdef QUANT_1PASS_SUPPORTED
  172402. jinit_1pass_quantizer(cinfo);
  172403. master->quantizer_1pass = cinfo->cquantize;
  172404. #else
  172405. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172406. #endif
  172407. }
  172408. /* We use the 2-pass code to map to external colormaps. */
  172409. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172410. #ifdef QUANT_2PASS_SUPPORTED
  172411. jinit_2pass_quantizer(cinfo);
  172412. master->quantizer_2pass = cinfo->cquantize;
  172413. #else
  172414. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172415. #endif
  172416. }
  172417. /* If both quantizers are initialized, the 2-pass one is left active;
  172418. * this is necessary for starting with quantization to an external map.
  172419. */
  172420. }
  172421. /* Post-processing: in particular, color conversion first */
  172422. if (! cinfo->raw_data_out) {
  172423. if (master->using_merged_upsample) {
  172424. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172425. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172426. #else
  172427. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172428. #endif
  172429. } else {
  172430. jinit_color_deconverter(cinfo);
  172431. jinit_upsampler(cinfo);
  172432. }
  172433. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172434. }
  172435. /* Inverse DCT */
  172436. jinit_inverse_dct(cinfo);
  172437. /* Entropy decoding: either Huffman or arithmetic coding. */
  172438. if (cinfo->arith_code) {
  172439. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172440. } else {
  172441. if (cinfo->progressive_mode) {
  172442. #ifdef D_PROGRESSIVE_SUPPORTED
  172443. jinit_phuff_decoder(cinfo);
  172444. #else
  172445. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172446. #endif
  172447. } else
  172448. jinit_huff_decoder(cinfo);
  172449. }
  172450. /* Initialize principal buffer controllers. */
  172451. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172452. jinit_d_coef_controller(cinfo, use_c_buffer);
  172453. if (! cinfo->raw_data_out)
  172454. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172455. /* We can now tell the memory manager to allocate virtual arrays. */
  172456. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172457. /* Initialize input side of decompressor to consume first scan. */
  172458. (*cinfo->inputctl->start_input_pass) (cinfo);
  172459. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172460. /* If jpeg_start_decompress will read the whole file, initialize
  172461. * progress monitoring appropriately. The input step is counted
  172462. * as one pass.
  172463. */
  172464. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172465. cinfo->inputctl->has_multiple_scans) {
  172466. int nscans;
  172467. /* Estimate number of scans to set pass_limit. */
  172468. if (cinfo->progressive_mode) {
  172469. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172470. nscans = 2 + 3 * cinfo->num_components;
  172471. } else {
  172472. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172473. nscans = cinfo->num_components;
  172474. }
  172475. cinfo->progress->pass_counter = 0L;
  172476. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172477. cinfo->progress->completed_passes = 0;
  172478. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172479. /* Count the input pass as done */
  172480. master->pass_number++;
  172481. }
  172482. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172483. }
  172484. /*
  172485. * Per-pass setup.
  172486. * This is called at the beginning of each output pass. We determine which
  172487. * modules will be active during this pass and give them appropriate
  172488. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172489. * is a "real" output pass or a dummy pass for color quantization.
  172490. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172491. */
  172492. METHODDEF(void)
  172493. prepare_for_output_pass (j_decompress_ptr cinfo)
  172494. {
  172495. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172496. if (master->pub.is_dummy_pass) {
  172497. #ifdef QUANT_2PASS_SUPPORTED
  172498. /* Final pass of 2-pass quantization */
  172499. master->pub.is_dummy_pass = FALSE;
  172500. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172501. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172502. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172503. #else
  172504. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172505. #endif /* QUANT_2PASS_SUPPORTED */
  172506. } else {
  172507. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172508. /* Select new quantization method */
  172509. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172510. cinfo->cquantize = master->quantizer_2pass;
  172511. master->pub.is_dummy_pass = TRUE;
  172512. } else if (cinfo->enable_1pass_quant) {
  172513. cinfo->cquantize = master->quantizer_1pass;
  172514. } else {
  172515. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172516. }
  172517. }
  172518. (*cinfo->idct->start_pass) (cinfo);
  172519. (*cinfo->coef->start_output_pass) (cinfo);
  172520. if (! cinfo->raw_data_out) {
  172521. if (! master->using_merged_upsample)
  172522. (*cinfo->cconvert->start_pass) (cinfo);
  172523. (*cinfo->upsample->start_pass) (cinfo);
  172524. if (cinfo->quantize_colors)
  172525. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172526. (*cinfo->post->start_pass) (cinfo,
  172527. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172528. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172529. }
  172530. }
  172531. /* Set up progress monitor's pass info if present */
  172532. if (cinfo->progress != NULL) {
  172533. cinfo->progress->completed_passes = master->pass_number;
  172534. cinfo->progress->total_passes = master->pass_number +
  172535. (master->pub.is_dummy_pass ? 2 : 1);
  172536. /* In buffered-image mode, we assume one more output pass if EOI not
  172537. * yet reached, but no more passes if EOI has been reached.
  172538. */
  172539. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172540. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172541. }
  172542. }
  172543. }
  172544. /*
  172545. * Finish up at end of an output pass.
  172546. */
  172547. METHODDEF(void)
  172548. finish_output_pass (j_decompress_ptr cinfo)
  172549. {
  172550. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172551. if (cinfo->quantize_colors)
  172552. (*cinfo->cquantize->finish_pass) (cinfo);
  172553. master->pass_number++;
  172554. }
  172555. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172556. /*
  172557. * Switch to a new external colormap between output passes.
  172558. */
  172559. GLOBAL(void)
  172560. jpeg_new_colormap (j_decompress_ptr cinfo)
  172561. {
  172562. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172563. /* Prevent application from calling me at wrong times */
  172564. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172565. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172566. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172567. cinfo->colormap != NULL) {
  172568. /* Select 2-pass quantizer for external colormap use */
  172569. cinfo->cquantize = master->quantizer_2pass;
  172570. /* Notify quantizer of colormap change */
  172571. (*cinfo->cquantize->new_color_map) (cinfo);
  172572. master->pub.is_dummy_pass = FALSE; /* just in case */
  172573. } else
  172574. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172575. }
  172576. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172577. /*
  172578. * Initialize master decompression control and select active modules.
  172579. * This is performed at the start of jpeg_start_decompress.
  172580. */
  172581. GLOBAL(void)
  172582. jinit_master_decompress (j_decompress_ptr cinfo)
  172583. {
  172584. my_master_ptr6 master;
  172585. master = (my_master_ptr6)
  172586. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172587. SIZEOF(my_decomp_master));
  172588. cinfo->master = (struct jpeg_decomp_master *) master;
  172589. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172590. master->pub.finish_output_pass = finish_output_pass;
  172591. master->pub.is_dummy_pass = FALSE;
  172592. master_selection(cinfo);
  172593. }
  172594. /*** End of inlined file: jdmaster.c ***/
  172595. #undef FIX
  172596. /*** Start of inlined file: jdmerge.c ***/
  172597. #define JPEG_INTERNALS
  172598. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172599. /* Private subobject */
  172600. typedef struct {
  172601. struct jpeg_upsampler pub; /* public fields */
  172602. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172603. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172604. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172605. JSAMPARRAY output_buf));
  172606. /* Private state for YCC->RGB conversion */
  172607. int * Cr_r_tab; /* => table for Cr to R conversion */
  172608. int * Cb_b_tab; /* => table for Cb to B conversion */
  172609. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172610. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172611. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172612. * We need a "spare" row buffer to hold the second output row if the
  172613. * application provides just a one-row buffer; we also use the spare
  172614. * to discard the dummy last row if the image height is odd.
  172615. */
  172616. JSAMPROW spare_row;
  172617. boolean spare_full; /* T if spare buffer is occupied */
  172618. JDIMENSION out_row_width; /* samples per output row */
  172619. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172620. } my_upsampler;
  172621. typedef my_upsampler * my_upsample_ptr;
  172622. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172623. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172624. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172625. /*
  172626. * Initialize tables for YCC->RGB colorspace conversion.
  172627. * This is taken directly from jdcolor.c; see that file for more info.
  172628. */
  172629. LOCAL(void)
  172630. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172631. {
  172632. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172633. int i;
  172634. INT32 x;
  172635. SHIFT_TEMPS
  172636. upsample->Cr_r_tab = (int *)
  172637. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172638. (MAXJSAMPLE+1) * SIZEOF(int));
  172639. upsample->Cb_b_tab = (int *)
  172640. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172641. (MAXJSAMPLE+1) * SIZEOF(int));
  172642. upsample->Cr_g_tab = (INT32 *)
  172643. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172644. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172645. upsample->Cb_g_tab = (INT32 *)
  172646. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172647. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172648. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172649. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172650. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172651. /* Cr=>R value is nearest int to 1.40200 * x */
  172652. upsample->Cr_r_tab[i] = (int)
  172653. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172654. /* Cb=>B value is nearest int to 1.77200 * x */
  172655. upsample->Cb_b_tab[i] = (int)
  172656. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172657. /* Cr=>G value is scaled-up -0.71414 * x */
  172658. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172659. /* Cb=>G value is scaled-up -0.34414 * x */
  172660. /* We also add in ONE_HALF so that need not do it in inner loop */
  172661. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172662. }
  172663. }
  172664. /*
  172665. * Initialize for an upsampling pass.
  172666. */
  172667. METHODDEF(void)
  172668. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172669. {
  172670. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172671. /* Mark the spare buffer empty */
  172672. upsample->spare_full = FALSE;
  172673. /* Initialize total-height counter for detecting bottom of image */
  172674. upsample->rows_to_go = cinfo->output_height;
  172675. }
  172676. /*
  172677. * Control routine to do upsampling (and color conversion).
  172678. *
  172679. * The control routine just handles the row buffering considerations.
  172680. */
  172681. METHODDEF(void)
  172682. merged_2v_upsample (j_decompress_ptr cinfo,
  172683. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172684. JDIMENSION,
  172685. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172686. JDIMENSION out_rows_avail)
  172687. /* 2:1 vertical sampling case: may need a spare row. */
  172688. {
  172689. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172690. JSAMPROW work_ptrs[2];
  172691. JDIMENSION num_rows; /* number of rows returned to caller */
  172692. if (upsample->spare_full) {
  172693. /* If we have a spare row saved from a previous cycle, just return it. */
  172694. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172695. 1, upsample->out_row_width);
  172696. num_rows = 1;
  172697. upsample->spare_full = FALSE;
  172698. } else {
  172699. /* Figure number of rows to return to caller. */
  172700. num_rows = 2;
  172701. /* Not more than the distance to the end of the image. */
  172702. if (num_rows > upsample->rows_to_go)
  172703. num_rows = upsample->rows_to_go;
  172704. /* And not more than what the client can accept: */
  172705. out_rows_avail -= *out_row_ctr;
  172706. if (num_rows > out_rows_avail)
  172707. num_rows = out_rows_avail;
  172708. /* Create output pointer array for upsampler. */
  172709. work_ptrs[0] = output_buf[*out_row_ctr];
  172710. if (num_rows > 1) {
  172711. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172712. } else {
  172713. work_ptrs[1] = upsample->spare_row;
  172714. upsample->spare_full = TRUE;
  172715. }
  172716. /* Now do the upsampling. */
  172717. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172718. }
  172719. /* Adjust counts */
  172720. *out_row_ctr += num_rows;
  172721. upsample->rows_to_go -= num_rows;
  172722. /* When the buffer is emptied, declare this input row group consumed */
  172723. if (! upsample->spare_full)
  172724. (*in_row_group_ctr)++;
  172725. }
  172726. METHODDEF(void)
  172727. merged_1v_upsample (j_decompress_ptr cinfo,
  172728. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172729. JDIMENSION,
  172730. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172731. JDIMENSION)
  172732. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172733. {
  172734. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172735. /* Just do the upsampling. */
  172736. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172737. output_buf + *out_row_ctr);
  172738. /* Adjust counts */
  172739. (*out_row_ctr)++;
  172740. (*in_row_group_ctr)++;
  172741. }
  172742. /*
  172743. * These are the routines invoked by the control routines to do
  172744. * the actual upsampling/conversion. One row group is processed per call.
  172745. *
  172746. * Note: since we may be writing directly into application-supplied buffers,
  172747. * we have to be honest about the output width; we can't assume the buffer
  172748. * has been rounded up to an even width.
  172749. */
  172750. /*
  172751. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172752. */
  172753. METHODDEF(void)
  172754. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172755. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172756. JSAMPARRAY output_buf)
  172757. {
  172758. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172759. register int y, cred, cgreen, cblue;
  172760. int cb, cr;
  172761. register JSAMPROW outptr;
  172762. JSAMPROW inptr0, inptr1, inptr2;
  172763. JDIMENSION col;
  172764. /* copy these pointers into registers if possible */
  172765. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172766. int * Crrtab = upsample->Cr_r_tab;
  172767. int * Cbbtab = upsample->Cb_b_tab;
  172768. INT32 * Crgtab = upsample->Cr_g_tab;
  172769. INT32 * Cbgtab = upsample->Cb_g_tab;
  172770. SHIFT_TEMPS
  172771. inptr0 = input_buf[0][in_row_group_ctr];
  172772. inptr1 = input_buf[1][in_row_group_ctr];
  172773. inptr2 = input_buf[2][in_row_group_ctr];
  172774. outptr = output_buf[0];
  172775. /* Loop for each pair of output pixels */
  172776. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172777. /* Do the chroma part of the calculation */
  172778. cb = GETJSAMPLE(*inptr1++);
  172779. cr = GETJSAMPLE(*inptr2++);
  172780. cred = Crrtab[cr];
  172781. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172782. cblue = Cbbtab[cb];
  172783. /* Fetch 2 Y values and emit 2 pixels */
  172784. y = GETJSAMPLE(*inptr0++);
  172785. outptr[RGB_RED] = range_limit[y + cred];
  172786. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172787. outptr[RGB_BLUE] = range_limit[y + cblue];
  172788. outptr += RGB_PIXELSIZE;
  172789. y = GETJSAMPLE(*inptr0++);
  172790. outptr[RGB_RED] = range_limit[y + cred];
  172791. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172792. outptr[RGB_BLUE] = range_limit[y + cblue];
  172793. outptr += RGB_PIXELSIZE;
  172794. }
  172795. /* If image width is odd, do the last output column separately */
  172796. if (cinfo->output_width & 1) {
  172797. cb = GETJSAMPLE(*inptr1);
  172798. cr = GETJSAMPLE(*inptr2);
  172799. cred = Crrtab[cr];
  172800. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172801. cblue = Cbbtab[cb];
  172802. y = GETJSAMPLE(*inptr0);
  172803. outptr[RGB_RED] = range_limit[y + cred];
  172804. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172805. outptr[RGB_BLUE] = range_limit[y + cblue];
  172806. }
  172807. }
  172808. /*
  172809. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172810. */
  172811. METHODDEF(void)
  172812. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172813. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172814. JSAMPARRAY output_buf)
  172815. {
  172816. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172817. register int y, cred, cgreen, cblue;
  172818. int cb, cr;
  172819. register JSAMPROW outptr0, outptr1;
  172820. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172821. JDIMENSION col;
  172822. /* copy these pointers into registers if possible */
  172823. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172824. int * Crrtab = upsample->Cr_r_tab;
  172825. int * Cbbtab = upsample->Cb_b_tab;
  172826. INT32 * Crgtab = upsample->Cr_g_tab;
  172827. INT32 * Cbgtab = upsample->Cb_g_tab;
  172828. SHIFT_TEMPS
  172829. inptr00 = input_buf[0][in_row_group_ctr*2];
  172830. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172831. inptr1 = input_buf[1][in_row_group_ctr];
  172832. inptr2 = input_buf[2][in_row_group_ctr];
  172833. outptr0 = output_buf[0];
  172834. outptr1 = output_buf[1];
  172835. /* Loop for each group of output pixels */
  172836. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172837. /* Do the chroma part of the calculation */
  172838. cb = GETJSAMPLE(*inptr1++);
  172839. cr = GETJSAMPLE(*inptr2++);
  172840. cred = Crrtab[cr];
  172841. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172842. cblue = Cbbtab[cb];
  172843. /* Fetch 4 Y values and emit 4 pixels */
  172844. y = GETJSAMPLE(*inptr00++);
  172845. outptr0[RGB_RED] = range_limit[y + cred];
  172846. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172847. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172848. outptr0 += RGB_PIXELSIZE;
  172849. y = GETJSAMPLE(*inptr00++);
  172850. outptr0[RGB_RED] = range_limit[y + cred];
  172851. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172852. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172853. outptr0 += RGB_PIXELSIZE;
  172854. y = GETJSAMPLE(*inptr01++);
  172855. outptr1[RGB_RED] = range_limit[y + cred];
  172856. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172857. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172858. outptr1 += RGB_PIXELSIZE;
  172859. y = GETJSAMPLE(*inptr01++);
  172860. outptr1[RGB_RED] = range_limit[y + cred];
  172861. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172862. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172863. outptr1 += RGB_PIXELSIZE;
  172864. }
  172865. /* If image width is odd, do the last output column separately */
  172866. if (cinfo->output_width & 1) {
  172867. cb = GETJSAMPLE(*inptr1);
  172868. cr = GETJSAMPLE(*inptr2);
  172869. cred = Crrtab[cr];
  172870. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172871. cblue = Cbbtab[cb];
  172872. y = GETJSAMPLE(*inptr00);
  172873. outptr0[RGB_RED] = range_limit[y + cred];
  172874. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172875. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172876. y = GETJSAMPLE(*inptr01);
  172877. outptr1[RGB_RED] = range_limit[y + cred];
  172878. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172879. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172880. }
  172881. }
  172882. /*
  172883. * Module initialization routine for merged upsampling/color conversion.
  172884. *
  172885. * NB: this is called under the conditions determined by use_merged_upsample()
  172886. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172887. * of this module; no safety checks are made here.
  172888. */
  172889. GLOBAL(void)
  172890. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172891. {
  172892. my_upsample_ptr upsample;
  172893. upsample = (my_upsample_ptr)
  172894. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172895. SIZEOF(my_upsampler));
  172896. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172897. upsample->pub.start_pass = start_pass_merged_upsample;
  172898. upsample->pub.need_context_rows = FALSE;
  172899. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172900. if (cinfo->max_v_samp_factor == 2) {
  172901. upsample->pub.upsample = merged_2v_upsample;
  172902. upsample->upmethod = h2v2_merged_upsample;
  172903. /* Allocate a spare row buffer */
  172904. upsample->spare_row = (JSAMPROW)
  172905. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172906. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172907. } else {
  172908. upsample->pub.upsample = merged_1v_upsample;
  172909. upsample->upmethod = h2v1_merged_upsample;
  172910. /* No spare row needed */
  172911. upsample->spare_row = NULL;
  172912. }
  172913. build_ycc_rgb_table2(cinfo);
  172914. }
  172915. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172916. /*** End of inlined file: jdmerge.c ***/
  172917. #undef ASSIGN_STATE
  172918. /*** Start of inlined file: jdphuff.c ***/
  172919. #define JPEG_INTERNALS
  172920. #ifdef D_PROGRESSIVE_SUPPORTED
  172921. /*
  172922. * Expanded entropy decoder object for progressive Huffman decoding.
  172923. *
  172924. * The savable_state subrecord contains fields that change within an MCU,
  172925. * but must not be updated permanently until we complete the MCU.
  172926. */
  172927. typedef struct {
  172928. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172929. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172930. } savable_state3;
  172931. /* This macro is to work around compilers with missing or broken
  172932. * structure assignment. You'll need to fix this code if you have
  172933. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172934. */
  172935. #ifndef NO_STRUCT_ASSIGN
  172936. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172937. #else
  172938. #if MAX_COMPS_IN_SCAN == 4
  172939. #define ASSIGN_STATE(dest,src) \
  172940. ((dest).EOBRUN = (src).EOBRUN, \
  172941. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172942. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172943. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172944. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172945. #endif
  172946. #endif
  172947. typedef struct {
  172948. struct jpeg_entropy_decoder pub; /* public fields */
  172949. /* These fields are loaded into local variables at start of each MCU.
  172950. * In case of suspension, we exit WITHOUT updating them.
  172951. */
  172952. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172953. savable_state3 saved; /* Other state at start of MCU */
  172954. /* These fields are NOT loaded into local working state. */
  172955. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172956. /* Pointers to derived tables (these workspaces have image lifespan) */
  172957. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172958. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172959. } phuff_entropy_decoder;
  172960. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172961. /* Forward declarations */
  172962. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172963. JBLOCKROW *MCU_data));
  172964. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172965. JBLOCKROW *MCU_data));
  172966. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172967. JBLOCKROW *MCU_data));
  172968. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172969. JBLOCKROW *MCU_data));
  172970. /*
  172971. * Initialize for a Huffman-compressed scan.
  172972. */
  172973. METHODDEF(void)
  172974. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172975. {
  172976. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172977. boolean is_DC_band, bad;
  172978. int ci, coefi, tbl;
  172979. int *coef_bit_ptr;
  172980. jpeg_component_info * compptr;
  172981. is_DC_band = (cinfo->Ss == 0);
  172982. /* Validate scan parameters */
  172983. bad = FALSE;
  172984. if (is_DC_band) {
  172985. if (cinfo->Se != 0)
  172986. bad = TRUE;
  172987. } else {
  172988. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172989. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172990. bad = TRUE;
  172991. /* AC scans may have only one component */
  172992. if (cinfo->comps_in_scan != 1)
  172993. bad = TRUE;
  172994. }
  172995. if (cinfo->Ah != 0) {
  172996. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172997. if (cinfo->Al != cinfo->Ah-1)
  172998. bad = TRUE;
  172999. }
  173000. if (cinfo->Al > 13) /* need not check for < 0 */
  173001. bad = TRUE;
  173002. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173003. * but the spec doesn't say so, and we try to be liberal about what we
  173004. * accept. Note: large Al values could result in out-of-range DC
  173005. * coefficients during early scans, leading to bizarre displays due to
  173006. * overflows in the IDCT math. But we won't crash.
  173007. */
  173008. if (bad)
  173009. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173010. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173011. /* Update progression status, and verify that scan order is legal.
  173012. * Note that inter-scan inconsistencies are treated as warnings
  173013. * not fatal errors ... not clear if this is right way to behave.
  173014. */
  173015. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173016. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173017. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173018. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173019. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173020. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173021. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173022. if (cinfo->Ah != expected)
  173023. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173024. coef_bit_ptr[coefi] = cinfo->Al;
  173025. }
  173026. }
  173027. /* Select MCU decoding routine */
  173028. if (cinfo->Ah == 0) {
  173029. if (is_DC_band)
  173030. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173031. else
  173032. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173033. } else {
  173034. if (is_DC_band)
  173035. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173036. else
  173037. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173038. }
  173039. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173040. compptr = cinfo->cur_comp_info[ci];
  173041. /* Make sure requested tables are present, and compute derived tables.
  173042. * We may build same derived table more than once, but it's not expensive.
  173043. */
  173044. if (is_DC_band) {
  173045. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173046. tbl = compptr->dc_tbl_no;
  173047. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173048. & entropy->derived_tbls[tbl]);
  173049. }
  173050. } else {
  173051. tbl = compptr->ac_tbl_no;
  173052. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173053. & entropy->derived_tbls[tbl]);
  173054. /* remember the single active table */
  173055. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173056. }
  173057. /* Initialize DC predictions to 0 */
  173058. entropy->saved.last_dc_val[ci] = 0;
  173059. }
  173060. /* Initialize bitread state variables */
  173061. entropy->bitstate.bits_left = 0;
  173062. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173063. entropy->pub.insufficient_data = FALSE;
  173064. /* Initialize private state variables */
  173065. entropy->saved.EOBRUN = 0;
  173066. /* Initialize restart counter */
  173067. entropy->restarts_to_go = cinfo->restart_interval;
  173068. }
  173069. /*
  173070. * Check for a restart marker & resynchronize decoder.
  173071. * Returns FALSE if must suspend.
  173072. */
  173073. LOCAL(boolean)
  173074. process_restartp (j_decompress_ptr cinfo)
  173075. {
  173076. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173077. int ci;
  173078. /* Throw away any unused bits remaining in bit buffer; */
  173079. /* include any full bytes in next_marker's count of discarded bytes */
  173080. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173081. entropy->bitstate.bits_left = 0;
  173082. /* Advance past the RSTn marker */
  173083. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173084. return FALSE;
  173085. /* Re-initialize DC predictions to 0 */
  173086. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173087. entropy->saved.last_dc_val[ci] = 0;
  173088. /* Re-init EOB run count, too */
  173089. entropy->saved.EOBRUN = 0;
  173090. /* Reset restart counter */
  173091. entropy->restarts_to_go = cinfo->restart_interval;
  173092. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173093. * against a marker. In that case we will end up treating the next data
  173094. * segment as empty, and we can avoid producing bogus output pixels by
  173095. * leaving the flag set.
  173096. */
  173097. if (cinfo->unread_marker == 0)
  173098. entropy->pub.insufficient_data = FALSE;
  173099. return TRUE;
  173100. }
  173101. /*
  173102. * Huffman MCU decoding.
  173103. * Each of these routines decodes and returns one MCU's worth of
  173104. * Huffman-compressed coefficients.
  173105. * The coefficients are reordered from zigzag order into natural array order,
  173106. * but are not dequantized.
  173107. *
  173108. * The i'th block of the MCU is stored into the block pointed to by
  173109. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173110. *
  173111. * We return FALSE if data source requested suspension. In that case no
  173112. * changes have been made to permanent state. (Exception: some output
  173113. * coefficients may already have been assigned. This is harmless for
  173114. * spectral selection, since we'll just re-assign them on the next call.
  173115. * Successive approximation AC refinement has to be more careful, however.)
  173116. */
  173117. /*
  173118. * MCU decoding for DC initial scan (either spectral selection,
  173119. * or first pass of successive approximation).
  173120. */
  173121. METHODDEF(boolean)
  173122. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173123. {
  173124. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173125. int Al = cinfo->Al;
  173126. register int s, r;
  173127. int blkn, ci;
  173128. JBLOCKROW block;
  173129. BITREAD_STATE_VARS;
  173130. savable_state3 state;
  173131. d_derived_tbl * tbl;
  173132. jpeg_component_info * compptr;
  173133. /* Process restart marker if needed; may have to suspend */
  173134. if (cinfo->restart_interval) {
  173135. if (entropy->restarts_to_go == 0)
  173136. if (! process_restartp(cinfo))
  173137. return FALSE;
  173138. }
  173139. /* If we've run out of data, just leave the MCU set to zeroes.
  173140. * This way, we return uniform gray for the remainder of the segment.
  173141. */
  173142. if (! entropy->pub.insufficient_data) {
  173143. /* Load up working state */
  173144. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173145. ASSIGN_STATE(state, entropy->saved);
  173146. /* Outer loop handles each block in the MCU */
  173147. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173148. block = MCU_data[blkn];
  173149. ci = cinfo->MCU_membership[blkn];
  173150. compptr = cinfo->cur_comp_info[ci];
  173151. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173152. /* Decode a single block's worth of coefficients */
  173153. /* Section F.2.2.1: decode the DC coefficient difference */
  173154. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173155. if (s) {
  173156. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173157. r = GET_BITS(s);
  173158. s = HUFF_EXTEND(r, s);
  173159. }
  173160. /* Convert DC difference to actual value, update last_dc_val */
  173161. s += state.last_dc_val[ci];
  173162. state.last_dc_val[ci] = s;
  173163. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173164. (*block)[0] = (JCOEF) (s << Al);
  173165. }
  173166. /* Completed MCU, so update state */
  173167. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173168. ASSIGN_STATE(entropy->saved, state);
  173169. }
  173170. /* Account for restart interval (no-op if not using restarts) */
  173171. entropy->restarts_to_go--;
  173172. return TRUE;
  173173. }
  173174. /*
  173175. * MCU decoding for AC initial scan (either spectral selection,
  173176. * or first pass of successive approximation).
  173177. */
  173178. METHODDEF(boolean)
  173179. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173180. {
  173181. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173182. int Se = cinfo->Se;
  173183. int Al = cinfo->Al;
  173184. register int s, k, r;
  173185. unsigned int EOBRUN;
  173186. JBLOCKROW block;
  173187. BITREAD_STATE_VARS;
  173188. d_derived_tbl * tbl;
  173189. /* Process restart marker if needed; may have to suspend */
  173190. if (cinfo->restart_interval) {
  173191. if (entropy->restarts_to_go == 0)
  173192. if (! process_restartp(cinfo))
  173193. return FALSE;
  173194. }
  173195. /* If we've run out of data, just leave the MCU set to zeroes.
  173196. * This way, we return uniform gray for the remainder of the segment.
  173197. */
  173198. if (! entropy->pub.insufficient_data) {
  173199. /* Load up working state.
  173200. * We can avoid loading/saving bitread state if in an EOB run.
  173201. */
  173202. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173203. /* There is always only one block per MCU */
  173204. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173205. EOBRUN--; /* ...process it now (we do nothing) */
  173206. else {
  173207. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173208. block = MCU_data[0];
  173209. tbl = entropy->ac_derived_tbl;
  173210. for (k = cinfo->Ss; k <= Se; k++) {
  173211. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173212. r = s >> 4;
  173213. s &= 15;
  173214. if (s) {
  173215. k += r;
  173216. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173217. r = GET_BITS(s);
  173218. s = HUFF_EXTEND(r, s);
  173219. /* Scale and output coefficient in natural (dezigzagged) order */
  173220. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173221. } else {
  173222. if (r == 15) { /* ZRL */
  173223. k += 15; /* skip 15 zeroes in band */
  173224. } else { /* EOBr, run length is 2^r + appended bits */
  173225. EOBRUN = 1 << r;
  173226. if (r) { /* EOBr, r > 0 */
  173227. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173228. r = GET_BITS(r);
  173229. EOBRUN += r;
  173230. }
  173231. EOBRUN--; /* this band is processed at this moment */
  173232. break; /* force end-of-band */
  173233. }
  173234. }
  173235. }
  173236. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173237. }
  173238. /* Completed MCU, so update state */
  173239. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173240. }
  173241. /* Account for restart interval (no-op if not using restarts) */
  173242. entropy->restarts_to_go--;
  173243. return TRUE;
  173244. }
  173245. /*
  173246. * MCU decoding for DC successive approximation refinement scan.
  173247. * Note: we assume such scans can be multi-component, although the spec
  173248. * is not very clear on the point.
  173249. */
  173250. METHODDEF(boolean)
  173251. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173252. {
  173253. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173254. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173255. int blkn;
  173256. JBLOCKROW block;
  173257. BITREAD_STATE_VARS;
  173258. /* Process restart marker if needed; may have to suspend */
  173259. if (cinfo->restart_interval) {
  173260. if (entropy->restarts_to_go == 0)
  173261. if (! process_restartp(cinfo))
  173262. return FALSE;
  173263. }
  173264. /* Not worth the cycles to check insufficient_data here,
  173265. * since we will not change the data anyway if we read zeroes.
  173266. */
  173267. /* Load up working state */
  173268. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173269. /* Outer loop handles each block in the MCU */
  173270. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173271. block = MCU_data[blkn];
  173272. /* Encoded data is simply the next bit of the two's-complement DC value */
  173273. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173274. if (GET_BITS(1))
  173275. (*block)[0] |= p1;
  173276. /* Note: since we use |=, repeating the assignment later is safe */
  173277. }
  173278. /* Completed MCU, so update state */
  173279. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173280. /* Account for restart interval (no-op if not using restarts) */
  173281. entropy->restarts_to_go--;
  173282. return TRUE;
  173283. }
  173284. /*
  173285. * MCU decoding for AC successive approximation refinement scan.
  173286. */
  173287. METHODDEF(boolean)
  173288. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173289. {
  173290. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173291. int Se = cinfo->Se;
  173292. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173293. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173294. register int s, k, r;
  173295. unsigned int EOBRUN;
  173296. JBLOCKROW block;
  173297. JCOEFPTR thiscoef;
  173298. BITREAD_STATE_VARS;
  173299. d_derived_tbl * tbl;
  173300. int num_newnz;
  173301. int newnz_pos[DCTSIZE2];
  173302. /* Process restart marker if needed; may have to suspend */
  173303. if (cinfo->restart_interval) {
  173304. if (entropy->restarts_to_go == 0)
  173305. if (! process_restartp(cinfo))
  173306. return FALSE;
  173307. }
  173308. /* If we've run out of data, don't modify the MCU.
  173309. */
  173310. if (! entropy->pub.insufficient_data) {
  173311. /* Load up working state */
  173312. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173313. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173314. /* There is always only one block per MCU */
  173315. block = MCU_data[0];
  173316. tbl = entropy->ac_derived_tbl;
  173317. /* If we are forced to suspend, we must undo the assignments to any newly
  173318. * nonzero coefficients in the block, because otherwise we'd get confused
  173319. * next time about which coefficients were already nonzero.
  173320. * But we need not undo addition of bits to already-nonzero coefficients;
  173321. * instead, we can test the current bit to see if we already did it.
  173322. */
  173323. num_newnz = 0;
  173324. /* initialize coefficient loop counter to start of band */
  173325. k = cinfo->Ss;
  173326. if (EOBRUN == 0) {
  173327. for (; k <= Se; k++) {
  173328. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173329. r = s >> 4;
  173330. s &= 15;
  173331. if (s) {
  173332. if (s != 1) /* size of new coef should always be 1 */
  173333. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173334. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173335. if (GET_BITS(1))
  173336. s = p1; /* newly nonzero coef is positive */
  173337. else
  173338. s = m1; /* newly nonzero coef is negative */
  173339. } else {
  173340. if (r != 15) {
  173341. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173342. if (r) {
  173343. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173344. r = GET_BITS(r);
  173345. EOBRUN += r;
  173346. }
  173347. break; /* rest of block is handled by EOB logic */
  173348. }
  173349. /* note s = 0 for processing ZRL */
  173350. }
  173351. /* Advance over already-nonzero coefs and r still-zero coefs,
  173352. * appending correction bits to the nonzeroes. A correction bit is 1
  173353. * if the absolute value of the coefficient must be increased.
  173354. */
  173355. do {
  173356. thiscoef = *block + jpeg_natural_order[k];
  173357. if (*thiscoef != 0) {
  173358. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173359. if (GET_BITS(1)) {
  173360. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173361. if (*thiscoef >= 0)
  173362. *thiscoef += p1;
  173363. else
  173364. *thiscoef += m1;
  173365. }
  173366. }
  173367. } else {
  173368. if (--r < 0)
  173369. break; /* reached target zero coefficient */
  173370. }
  173371. k++;
  173372. } while (k <= Se);
  173373. if (s) {
  173374. int pos = jpeg_natural_order[k];
  173375. /* Output newly nonzero coefficient */
  173376. (*block)[pos] = (JCOEF) s;
  173377. /* Remember its position in case we have to suspend */
  173378. newnz_pos[num_newnz++] = pos;
  173379. }
  173380. }
  173381. }
  173382. if (EOBRUN > 0) {
  173383. /* Scan any remaining coefficient positions after the end-of-band
  173384. * (the last newly nonzero coefficient, if any). Append a correction
  173385. * bit to each already-nonzero coefficient. A correction bit is 1
  173386. * if the absolute value of the coefficient must be increased.
  173387. */
  173388. for (; k <= Se; k++) {
  173389. thiscoef = *block + jpeg_natural_order[k];
  173390. if (*thiscoef != 0) {
  173391. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173392. if (GET_BITS(1)) {
  173393. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173394. if (*thiscoef >= 0)
  173395. *thiscoef += p1;
  173396. else
  173397. *thiscoef += m1;
  173398. }
  173399. }
  173400. }
  173401. }
  173402. /* Count one block completed in EOB run */
  173403. EOBRUN--;
  173404. }
  173405. /* Completed MCU, so update state */
  173406. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173407. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173408. }
  173409. /* Account for restart interval (no-op if not using restarts) */
  173410. entropy->restarts_to_go--;
  173411. return TRUE;
  173412. undoit:
  173413. /* Re-zero any output coefficients that we made newly nonzero */
  173414. while (num_newnz > 0)
  173415. (*block)[newnz_pos[--num_newnz]] = 0;
  173416. return FALSE;
  173417. }
  173418. /*
  173419. * Module initialization routine for progressive Huffman entropy decoding.
  173420. */
  173421. GLOBAL(void)
  173422. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173423. {
  173424. phuff_entropy_ptr2 entropy;
  173425. int *coef_bit_ptr;
  173426. int ci, i;
  173427. entropy = (phuff_entropy_ptr2)
  173428. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173429. SIZEOF(phuff_entropy_decoder));
  173430. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173431. entropy->pub.start_pass = start_pass_phuff_decoder;
  173432. /* Mark derived tables unallocated */
  173433. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173434. entropy->derived_tbls[i] = NULL;
  173435. }
  173436. /* Create progression status table */
  173437. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173438. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173439. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173440. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173441. for (ci = 0; ci < cinfo->num_components; ci++)
  173442. for (i = 0; i < DCTSIZE2; i++)
  173443. *coef_bit_ptr++ = -1;
  173444. }
  173445. #endif /* D_PROGRESSIVE_SUPPORTED */
  173446. /*** End of inlined file: jdphuff.c ***/
  173447. /*** Start of inlined file: jdpostct.c ***/
  173448. #define JPEG_INTERNALS
  173449. /* Private buffer controller object */
  173450. typedef struct {
  173451. struct jpeg_d_post_controller pub; /* public fields */
  173452. /* Color quantization source buffer: this holds output data from
  173453. * the upsample/color conversion step to be passed to the quantizer.
  173454. * For two-pass color quantization, we need a full-image buffer;
  173455. * for one-pass operation, a strip buffer is sufficient.
  173456. */
  173457. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173458. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173459. JDIMENSION strip_height; /* buffer size in rows */
  173460. /* for two-pass mode only: */
  173461. JDIMENSION starting_row; /* row # of first row in current strip */
  173462. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173463. } my_post_controller;
  173464. typedef my_post_controller * my_post_ptr;
  173465. /* Forward declarations */
  173466. METHODDEF(void) post_process_1pass
  173467. JPP((j_decompress_ptr cinfo,
  173468. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173469. JDIMENSION in_row_groups_avail,
  173470. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173471. JDIMENSION out_rows_avail));
  173472. #ifdef QUANT_2PASS_SUPPORTED
  173473. METHODDEF(void) post_process_prepass
  173474. JPP((j_decompress_ptr cinfo,
  173475. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173476. JDIMENSION in_row_groups_avail,
  173477. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173478. JDIMENSION out_rows_avail));
  173479. METHODDEF(void) post_process_2pass
  173480. JPP((j_decompress_ptr cinfo,
  173481. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173482. JDIMENSION in_row_groups_avail,
  173483. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173484. JDIMENSION out_rows_avail));
  173485. #endif
  173486. /*
  173487. * Initialize for a processing pass.
  173488. */
  173489. METHODDEF(void)
  173490. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173491. {
  173492. my_post_ptr post = (my_post_ptr) cinfo->post;
  173493. switch (pass_mode) {
  173494. case JBUF_PASS_THRU:
  173495. if (cinfo->quantize_colors) {
  173496. /* Single-pass processing with color quantization. */
  173497. post->pub.post_process_data = post_process_1pass;
  173498. /* We could be doing buffered-image output before starting a 2-pass
  173499. * color quantization; in that case, jinit_d_post_controller did not
  173500. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173501. */
  173502. if (post->buffer == NULL) {
  173503. post->buffer = (*cinfo->mem->access_virt_sarray)
  173504. ((j_common_ptr) cinfo, post->whole_image,
  173505. (JDIMENSION) 0, post->strip_height, TRUE);
  173506. }
  173507. } else {
  173508. /* For single-pass processing without color quantization,
  173509. * I have no work to do; just call the upsampler directly.
  173510. */
  173511. post->pub.post_process_data = cinfo->upsample->upsample;
  173512. }
  173513. break;
  173514. #ifdef QUANT_2PASS_SUPPORTED
  173515. case JBUF_SAVE_AND_PASS:
  173516. /* First pass of 2-pass quantization */
  173517. if (post->whole_image == NULL)
  173518. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173519. post->pub.post_process_data = post_process_prepass;
  173520. break;
  173521. case JBUF_CRANK_DEST:
  173522. /* Second pass of 2-pass quantization */
  173523. if (post->whole_image == NULL)
  173524. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173525. post->pub.post_process_data = post_process_2pass;
  173526. break;
  173527. #endif /* QUANT_2PASS_SUPPORTED */
  173528. default:
  173529. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173530. break;
  173531. }
  173532. post->starting_row = post->next_row = 0;
  173533. }
  173534. /*
  173535. * Process some data in the one-pass (strip buffer) case.
  173536. * This is used for color precision reduction as well as one-pass quantization.
  173537. */
  173538. METHODDEF(void)
  173539. post_process_1pass (j_decompress_ptr cinfo,
  173540. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173541. JDIMENSION in_row_groups_avail,
  173542. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173543. JDIMENSION out_rows_avail)
  173544. {
  173545. my_post_ptr post = (my_post_ptr) cinfo->post;
  173546. JDIMENSION num_rows, max_rows;
  173547. /* Fill the buffer, but not more than what we can dump out in one go. */
  173548. /* Note we rely on the upsampler to detect bottom of image. */
  173549. max_rows = out_rows_avail - *out_row_ctr;
  173550. if (max_rows > post->strip_height)
  173551. max_rows = post->strip_height;
  173552. num_rows = 0;
  173553. (*cinfo->upsample->upsample) (cinfo,
  173554. input_buf, in_row_group_ctr, in_row_groups_avail,
  173555. post->buffer, &num_rows, max_rows);
  173556. /* Quantize and emit data. */
  173557. (*cinfo->cquantize->color_quantize) (cinfo,
  173558. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173559. *out_row_ctr += num_rows;
  173560. }
  173561. #ifdef QUANT_2PASS_SUPPORTED
  173562. /*
  173563. * Process some data in the first pass of 2-pass quantization.
  173564. */
  173565. METHODDEF(void)
  173566. post_process_prepass (j_decompress_ptr cinfo,
  173567. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173568. JDIMENSION in_row_groups_avail,
  173569. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173570. JDIMENSION)
  173571. {
  173572. my_post_ptr post = (my_post_ptr) cinfo->post;
  173573. JDIMENSION old_next_row, num_rows;
  173574. /* Reposition virtual buffer if at start of strip. */
  173575. if (post->next_row == 0) {
  173576. post->buffer = (*cinfo->mem->access_virt_sarray)
  173577. ((j_common_ptr) cinfo, post->whole_image,
  173578. post->starting_row, post->strip_height, TRUE);
  173579. }
  173580. /* Upsample some data (up to a strip height's worth). */
  173581. old_next_row = post->next_row;
  173582. (*cinfo->upsample->upsample) (cinfo,
  173583. input_buf, in_row_group_ctr, in_row_groups_avail,
  173584. post->buffer, &post->next_row, post->strip_height);
  173585. /* Allow quantizer to scan new data. No data is emitted, */
  173586. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173587. if (post->next_row > old_next_row) {
  173588. num_rows = post->next_row - old_next_row;
  173589. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173590. (JSAMPARRAY) NULL, (int) num_rows);
  173591. *out_row_ctr += num_rows;
  173592. }
  173593. /* Advance if we filled the strip. */
  173594. if (post->next_row >= post->strip_height) {
  173595. post->starting_row += post->strip_height;
  173596. post->next_row = 0;
  173597. }
  173598. }
  173599. /*
  173600. * Process some data in the second pass of 2-pass quantization.
  173601. */
  173602. METHODDEF(void)
  173603. post_process_2pass (j_decompress_ptr cinfo,
  173604. JSAMPIMAGE, JDIMENSION *,
  173605. JDIMENSION,
  173606. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173607. JDIMENSION out_rows_avail)
  173608. {
  173609. my_post_ptr post = (my_post_ptr) cinfo->post;
  173610. JDIMENSION num_rows, max_rows;
  173611. /* Reposition virtual buffer if at start of strip. */
  173612. if (post->next_row == 0) {
  173613. post->buffer = (*cinfo->mem->access_virt_sarray)
  173614. ((j_common_ptr) cinfo, post->whole_image,
  173615. post->starting_row, post->strip_height, FALSE);
  173616. }
  173617. /* Determine number of rows to emit. */
  173618. num_rows = post->strip_height - post->next_row; /* available in strip */
  173619. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173620. if (num_rows > max_rows)
  173621. num_rows = max_rows;
  173622. /* We have to check bottom of image here, can't depend on upsampler. */
  173623. max_rows = cinfo->output_height - post->starting_row;
  173624. if (num_rows > max_rows)
  173625. num_rows = max_rows;
  173626. /* Quantize and emit data. */
  173627. (*cinfo->cquantize->color_quantize) (cinfo,
  173628. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173629. (int) num_rows);
  173630. *out_row_ctr += num_rows;
  173631. /* Advance if we filled the strip. */
  173632. post->next_row += num_rows;
  173633. if (post->next_row >= post->strip_height) {
  173634. post->starting_row += post->strip_height;
  173635. post->next_row = 0;
  173636. }
  173637. }
  173638. #endif /* QUANT_2PASS_SUPPORTED */
  173639. /*
  173640. * Initialize postprocessing controller.
  173641. */
  173642. GLOBAL(void)
  173643. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173644. {
  173645. my_post_ptr post;
  173646. post = (my_post_ptr)
  173647. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173648. SIZEOF(my_post_controller));
  173649. cinfo->post = (struct jpeg_d_post_controller *) post;
  173650. post->pub.start_pass = start_pass_dpost;
  173651. post->whole_image = NULL; /* flag for no virtual arrays */
  173652. post->buffer = NULL; /* flag for no strip buffer */
  173653. /* Create the quantization buffer, if needed */
  173654. if (cinfo->quantize_colors) {
  173655. /* The buffer strip height is max_v_samp_factor, which is typically
  173656. * an efficient number of rows for upsampling to return.
  173657. * (In the presence of output rescaling, we might want to be smarter?)
  173658. */
  173659. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173660. if (need_full_buffer) {
  173661. /* Two-pass color quantization: need full-image storage. */
  173662. /* We round up the number of rows to a multiple of the strip height. */
  173663. #ifdef QUANT_2PASS_SUPPORTED
  173664. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173665. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173666. cinfo->output_width * cinfo->out_color_components,
  173667. (JDIMENSION) jround_up((long) cinfo->output_height,
  173668. (long) post->strip_height),
  173669. post->strip_height);
  173670. #else
  173671. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173672. #endif /* QUANT_2PASS_SUPPORTED */
  173673. } else {
  173674. /* One-pass color quantization: just make a strip buffer. */
  173675. post->buffer = (*cinfo->mem->alloc_sarray)
  173676. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173677. cinfo->output_width * cinfo->out_color_components,
  173678. post->strip_height);
  173679. }
  173680. }
  173681. }
  173682. /*** End of inlined file: jdpostct.c ***/
  173683. #undef FIX
  173684. /*** Start of inlined file: jdsample.c ***/
  173685. #define JPEG_INTERNALS
  173686. /* Pointer to routine to upsample a single component */
  173687. typedef JMETHOD(void, upsample1_ptr,
  173688. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173689. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173690. /* Private subobject */
  173691. typedef struct {
  173692. struct jpeg_upsampler pub; /* public fields */
  173693. /* Color conversion buffer. When using separate upsampling and color
  173694. * conversion steps, this buffer holds one upsampled row group until it
  173695. * has been color converted and output.
  173696. * Note: we do not allocate any storage for component(s) which are full-size,
  173697. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173698. * simply set to point to the input data array, thereby avoiding copying.
  173699. */
  173700. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173701. /* Per-component upsampling method pointers */
  173702. upsample1_ptr methods[MAX_COMPONENTS];
  173703. int next_row_out; /* counts rows emitted from color_buf */
  173704. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173705. /* Height of an input row group for each component. */
  173706. int rowgroup_height[MAX_COMPONENTS];
  173707. /* These arrays save pixel expansion factors so that int_expand need not
  173708. * recompute them each time. They are unused for other upsampling methods.
  173709. */
  173710. UINT8 h_expand[MAX_COMPONENTS];
  173711. UINT8 v_expand[MAX_COMPONENTS];
  173712. } my_upsampler2;
  173713. typedef my_upsampler2 * my_upsample_ptr2;
  173714. /*
  173715. * Initialize for an upsampling pass.
  173716. */
  173717. METHODDEF(void)
  173718. start_pass_upsample (j_decompress_ptr cinfo)
  173719. {
  173720. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173721. /* Mark the conversion buffer empty */
  173722. upsample->next_row_out = cinfo->max_v_samp_factor;
  173723. /* Initialize total-height counter for detecting bottom of image */
  173724. upsample->rows_to_go = cinfo->output_height;
  173725. }
  173726. /*
  173727. * Control routine to do upsampling (and color conversion).
  173728. *
  173729. * In this version we upsample each component independently.
  173730. * We upsample one row group into the conversion buffer, then apply
  173731. * color conversion a row at a time.
  173732. */
  173733. METHODDEF(void)
  173734. sep_upsample (j_decompress_ptr cinfo,
  173735. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173736. JDIMENSION,
  173737. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173738. JDIMENSION out_rows_avail)
  173739. {
  173740. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173741. int ci;
  173742. jpeg_component_info * compptr;
  173743. JDIMENSION num_rows;
  173744. /* Fill the conversion buffer, if it's empty */
  173745. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173746. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173747. ci++, compptr++) {
  173748. /* Invoke per-component upsample method. Notice we pass a POINTER
  173749. * to color_buf[ci], so that fullsize_upsample can change it.
  173750. */
  173751. (*upsample->methods[ci]) (cinfo, compptr,
  173752. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173753. upsample->color_buf + ci);
  173754. }
  173755. upsample->next_row_out = 0;
  173756. }
  173757. /* Color-convert and emit rows */
  173758. /* How many we have in the buffer: */
  173759. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173760. /* Not more than the distance to the end of the image. Need this test
  173761. * in case the image height is not a multiple of max_v_samp_factor:
  173762. */
  173763. if (num_rows > upsample->rows_to_go)
  173764. num_rows = upsample->rows_to_go;
  173765. /* And not more than what the client can accept: */
  173766. out_rows_avail -= *out_row_ctr;
  173767. if (num_rows > out_rows_avail)
  173768. num_rows = out_rows_avail;
  173769. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173770. (JDIMENSION) upsample->next_row_out,
  173771. output_buf + *out_row_ctr,
  173772. (int) num_rows);
  173773. /* Adjust counts */
  173774. *out_row_ctr += num_rows;
  173775. upsample->rows_to_go -= num_rows;
  173776. upsample->next_row_out += num_rows;
  173777. /* When the buffer is emptied, declare this input row group consumed */
  173778. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173779. (*in_row_group_ctr)++;
  173780. }
  173781. /*
  173782. * These are the routines invoked by sep_upsample to upsample pixel values
  173783. * of a single component. One row group is processed per call.
  173784. */
  173785. /*
  173786. * For full-size components, we just make color_buf[ci] point at the
  173787. * input buffer, and thus avoid copying any data. Note that this is
  173788. * safe only because sep_upsample doesn't declare the input row group
  173789. * "consumed" until we are done color converting and emitting it.
  173790. */
  173791. METHODDEF(void)
  173792. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173793. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173794. {
  173795. *output_data_ptr = input_data;
  173796. }
  173797. /*
  173798. * This is a no-op version used for "uninteresting" components.
  173799. * These components will not be referenced by color conversion.
  173800. */
  173801. METHODDEF(void)
  173802. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173803. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173804. {
  173805. *output_data_ptr = NULL; /* safety check */
  173806. }
  173807. /*
  173808. * This version handles any integral sampling ratios.
  173809. * This is not used for typical JPEG files, so it need not be fast.
  173810. * Nor, for that matter, is it particularly accurate: the algorithm is
  173811. * simple replication of the input pixel onto the corresponding output
  173812. * pixels. The hi-falutin sampling literature refers to this as a
  173813. * "box filter". A box filter tends to introduce visible artifacts,
  173814. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173815. * you would be well advised to improve this code.
  173816. */
  173817. METHODDEF(void)
  173818. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173819. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173820. {
  173821. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173822. JSAMPARRAY output_data = *output_data_ptr;
  173823. register JSAMPROW inptr, outptr;
  173824. register JSAMPLE invalue;
  173825. register int h;
  173826. JSAMPROW outend;
  173827. int h_expand, v_expand;
  173828. int inrow, outrow;
  173829. h_expand = upsample->h_expand[compptr->component_index];
  173830. v_expand = upsample->v_expand[compptr->component_index];
  173831. inrow = outrow = 0;
  173832. while (outrow < cinfo->max_v_samp_factor) {
  173833. /* Generate one output row with proper horizontal expansion */
  173834. inptr = input_data[inrow];
  173835. outptr = output_data[outrow];
  173836. outend = outptr + cinfo->output_width;
  173837. while (outptr < outend) {
  173838. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173839. for (h = h_expand; h > 0; h--) {
  173840. *outptr++ = invalue;
  173841. }
  173842. }
  173843. /* Generate any additional output rows by duplicating the first one */
  173844. if (v_expand > 1) {
  173845. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173846. v_expand-1, cinfo->output_width);
  173847. }
  173848. inrow++;
  173849. outrow += v_expand;
  173850. }
  173851. }
  173852. /*
  173853. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173854. * It's still a box filter.
  173855. */
  173856. METHODDEF(void)
  173857. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173858. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173859. {
  173860. JSAMPARRAY output_data = *output_data_ptr;
  173861. register JSAMPROW inptr, outptr;
  173862. register JSAMPLE invalue;
  173863. JSAMPROW outend;
  173864. int inrow;
  173865. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173866. inptr = input_data[inrow];
  173867. outptr = output_data[inrow];
  173868. outend = outptr + cinfo->output_width;
  173869. while (outptr < outend) {
  173870. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173871. *outptr++ = invalue;
  173872. *outptr++ = invalue;
  173873. }
  173874. }
  173875. }
  173876. /*
  173877. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173878. * It's still a box filter.
  173879. */
  173880. METHODDEF(void)
  173881. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173882. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173883. {
  173884. JSAMPARRAY output_data = *output_data_ptr;
  173885. register JSAMPROW inptr, outptr;
  173886. register JSAMPLE invalue;
  173887. JSAMPROW outend;
  173888. int inrow, outrow;
  173889. inrow = outrow = 0;
  173890. while (outrow < cinfo->max_v_samp_factor) {
  173891. inptr = input_data[inrow];
  173892. outptr = output_data[outrow];
  173893. outend = outptr + cinfo->output_width;
  173894. while (outptr < outend) {
  173895. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173896. *outptr++ = invalue;
  173897. *outptr++ = invalue;
  173898. }
  173899. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173900. 1, cinfo->output_width);
  173901. inrow++;
  173902. outrow += 2;
  173903. }
  173904. }
  173905. /*
  173906. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173907. *
  173908. * The upsampling algorithm is linear interpolation between pixel centers,
  173909. * also known as a "triangle filter". This is a good compromise between
  173910. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173911. * of the way between input pixel centers.
  173912. *
  173913. * A note about the "bias" calculations: when rounding fractional values to
  173914. * integer, we do not want to always round 0.5 up to the next integer.
  173915. * If we did that, we'd introduce a noticeable bias towards larger values.
  173916. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173917. * alternate pixel locations (a simple ordered dither pattern).
  173918. */
  173919. METHODDEF(void)
  173920. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173921. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173922. {
  173923. JSAMPARRAY output_data = *output_data_ptr;
  173924. register JSAMPROW inptr, outptr;
  173925. register int invalue;
  173926. register JDIMENSION colctr;
  173927. int inrow;
  173928. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173929. inptr = input_data[inrow];
  173930. outptr = output_data[inrow];
  173931. /* Special case for first column */
  173932. invalue = GETJSAMPLE(*inptr++);
  173933. *outptr++ = (JSAMPLE) invalue;
  173934. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173935. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173936. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173937. invalue = GETJSAMPLE(*inptr++) * 3;
  173938. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173939. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173940. }
  173941. /* Special case for last column */
  173942. invalue = GETJSAMPLE(*inptr);
  173943. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173944. *outptr++ = (JSAMPLE) invalue;
  173945. }
  173946. }
  173947. /*
  173948. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173949. * Again a triangle filter; see comments for h2v1 case, above.
  173950. *
  173951. * It is OK for us to reference the adjacent input rows because we demanded
  173952. * context from the main buffer controller (see initialization code).
  173953. */
  173954. METHODDEF(void)
  173955. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173956. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173957. {
  173958. JSAMPARRAY output_data = *output_data_ptr;
  173959. register JSAMPROW inptr0, inptr1, outptr;
  173960. #if BITS_IN_JSAMPLE == 8
  173961. register int thiscolsum, lastcolsum, nextcolsum;
  173962. #else
  173963. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173964. #endif
  173965. register JDIMENSION colctr;
  173966. int inrow, outrow, v;
  173967. inrow = outrow = 0;
  173968. while (outrow < cinfo->max_v_samp_factor) {
  173969. for (v = 0; v < 2; v++) {
  173970. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173971. inptr0 = input_data[inrow];
  173972. if (v == 0) /* next nearest is row above */
  173973. inptr1 = input_data[inrow-1];
  173974. else /* next nearest is row below */
  173975. inptr1 = input_data[inrow+1];
  173976. outptr = output_data[outrow++];
  173977. /* Special case for first column */
  173978. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173979. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173980. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173981. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173982. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173983. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173984. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173985. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173986. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173987. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173988. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173989. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173990. }
  173991. /* Special case for last column */
  173992. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173993. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173994. }
  173995. inrow++;
  173996. }
  173997. }
  173998. /*
  173999. * Module initialization routine for upsampling.
  174000. */
  174001. GLOBAL(void)
  174002. jinit_upsampler (j_decompress_ptr cinfo)
  174003. {
  174004. my_upsample_ptr2 upsample;
  174005. int ci;
  174006. jpeg_component_info * compptr;
  174007. boolean need_buffer, do_fancy;
  174008. int h_in_group, v_in_group, h_out_group, v_out_group;
  174009. upsample = (my_upsample_ptr2)
  174010. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174011. SIZEOF(my_upsampler2));
  174012. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174013. upsample->pub.start_pass = start_pass_upsample;
  174014. upsample->pub.upsample = sep_upsample;
  174015. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174016. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174017. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174018. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174019. * so don't ask for it.
  174020. */
  174021. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174022. /* Verify we can handle the sampling factors, select per-component methods,
  174023. * and create storage as needed.
  174024. */
  174025. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174026. ci++, compptr++) {
  174027. /* Compute size of an "input group" after IDCT scaling. This many samples
  174028. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174029. */
  174030. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174031. cinfo->min_DCT_scaled_size;
  174032. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174033. cinfo->min_DCT_scaled_size;
  174034. h_out_group = cinfo->max_h_samp_factor;
  174035. v_out_group = cinfo->max_v_samp_factor;
  174036. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174037. need_buffer = TRUE;
  174038. if (! compptr->component_needed) {
  174039. /* Don't bother to upsample an uninteresting component. */
  174040. upsample->methods[ci] = noop_upsample;
  174041. need_buffer = FALSE;
  174042. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174043. /* Fullsize components can be processed without any work. */
  174044. upsample->methods[ci] = fullsize_upsample;
  174045. need_buffer = FALSE;
  174046. } else if (h_in_group * 2 == h_out_group &&
  174047. v_in_group == v_out_group) {
  174048. /* Special cases for 2h1v upsampling */
  174049. if (do_fancy && compptr->downsampled_width > 2)
  174050. upsample->methods[ci] = h2v1_fancy_upsample;
  174051. else
  174052. upsample->methods[ci] = h2v1_upsample;
  174053. } else if (h_in_group * 2 == h_out_group &&
  174054. v_in_group * 2 == v_out_group) {
  174055. /* Special cases for 2h2v upsampling */
  174056. if (do_fancy && compptr->downsampled_width > 2) {
  174057. upsample->methods[ci] = h2v2_fancy_upsample;
  174058. upsample->pub.need_context_rows = TRUE;
  174059. } else
  174060. upsample->methods[ci] = h2v2_upsample;
  174061. } else if ((h_out_group % h_in_group) == 0 &&
  174062. (v_out_group % v_in_group) == 0) {
  174063. /* Generic integral-factors upsampling method */
  174064. upsample->methods[ci] = int_upsample;
  174065. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174066. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174067. } else
  174068. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174069. if (need_buffer) {
  174070. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174071. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174072. (JDIMENSION) jround_up((long) cinfo->output_width,
  174073. (long) cinfo->max_h_samp_factor),
  174074. (JDIMENSION) cinfo->max_v_samp_factor);
  174075. }
  174076. }
  174077. }
  174078. /*** End of inlined file: jdsample.c ***/
  174079. /*** Start of inlined file: jdtrans.c ***/
  174080. #define JPEG_INTERNALS
  174081. /* Forward declarations */
  174082. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174083. /*
  174084. * Read the coefficient arrays from a JPEG file.
  174085. * jpeg_read_header must be completed before calling this.
  174086. *
  174087. * The entire image is read into a set of virtual coefficient-block arrays,
  174088. * one per component. The return value is a pointer to the array of
  174089. * virtual-array descriptors. These can be manipulated directly via the
  174090. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174091. * To release the memory occupied by the virtual arrays, call
  174092. * jpeg_finish_decompress() when done with the data.
  174093. *
  174094. * An alternative usage is to simply obtain access to the coefficient arrays
  174095. * during a buffered-image-mode decompression operation. This is allowed
  174096. * after any jpeg_finish_output() call. The arrays can be accessed until
  174097. * jpeg_finish_decompress() is called. (Note that any call to the library
  174098. * may reposition the arrays, so don't rely on access_virt_barray() results
  174099. * to stay valid across library calls.)
  174100. *
  174101. * Returns NULL if suspended. This case need be checked only if
  174102. * a suspending data source is used.
  174103. */
  174104. GLOBAL(jvirt_barray_ptr *)
  174105. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174106. {
  174107. if (cinfo->global_state == DSTATE_READY) {
  174108. /* First call: initialize active modules */
  174109. transdecode_master_selection(cinfo);
  174110. cinfo->global_state = DSTATE_RDCOEFS;
  174111. }
  174112. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174113. /* Absorb whole file into the coef buffer */
  174114. for (;;) {
  174115. int retcode;
  174116. /* Call progress monitor hook if present */
  174117. if (cinfo->progress != NULL)
  174118. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174119. /* Absorb some more input */
  174120. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174121. if (retcode == JPEG_SUSPENDED)
  174122. return NULL;
  174123. if (retcode == JPEG_REACHED_EOI)
  174124. break;
  174125. /* Advance progress counter if appropriate */
  174126. if (cinfo->progress != NULL &&
  174127. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174128. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174129. /* startup underestimated number of scans; ratchet up one scan */
  174130. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174131. }
  174132. }
  174133. }
  174134. /* Set state so that jpeg_finish_decompress does the right thing */
  174135. cinfo->global_state = DSTATE_STOPPING;
  174136. }
  174137. /* At this point we should be in state DSTATE_STOPPING if being used
  174138. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174139. * to the coefficients during a full buffered-image-mode decompression.
  174140. */
  174141. if ((cinfo->global_state == DSTATE_STOPPING ||
  174142. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174143. return cinfo->coef->coef_arrays;
  174144. }
  174145. /* Oops, improper usage */
  174146. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174147. return NULL; /* keep compiler happy */
  174148. }
  174149. /*
  174150. * Master selection of decompression modules for transcoding.
  174151. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174152. */
  174153. LOCAL(void)
  174154. transdecode_master_selection (j_decompress_ptr cinfo)
  174155. {
  174156. /* This is effectively a buffered-image operation. */
  174157. cinfo->buffered_image = TRUE;
  174158. /* Entropy decoding: either Huffman or arithmetic coding. */
  174159. if (cinfo->arith_code) {
  174160. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174161. } else {
  174162. if (cinfo->progressive_mode) {
  174163. #ifdef D_PROGRESSIVE_SUPPORTED
  174164. jinit_phuff_decoder(cinfo);
  174165. #else
  174166. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174167. #endif
  174168. } else
  174169. jinit_huff_decoder(cinfo);
  174170. }
  174171. /* Always get a full-image coefficient buffer. */
  174172. jinit_d_coef_controller(cinfo, TRUE);
  174173. /* We can now tell the memory manager to allocate virtual arrays. */
  174174. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174175. /* Initialize input side of decompressor to consume first scan. */
  174176. (*cinfo->inputctl->start_input_pass) (cinfo);
  174177. /* Initialize progress monitoring. */
  174178. if (cinfo->progress != NULL) {
  174179. int nscans;
  174180. /* Estimate number of scans to set pass_limit. */
  174181. if (cinfo->progressive_mode) {
  174182. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174183. nscans = 2 + 3 * cinfo->num_components;
  174184. } else if (cinfo->inputctl->has_multiple_scans) {
  174185. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174186. nscans = cinfo->num_components;
  174187. } else {
  174188. nscans = 1;
  174189. }
  174190. cinfo->progress->pass_counter = 0L;
  174191. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174192. cinfo->progress->completed_passes = 0;
  174193. cinfo->progress->total_passes = 1;
  174194. }
  174195. }
  174196. /*** End of inlined file: jdtrans.c ***/
  174197. /*** Start of inlined file: jfdctflt.c ***/
  174198. #define JPEG_INTERNALS
  174199. #ifdef DCT_FLOAT_SUPPORTED
  174200. /*
  174201. * This module is specialized to the case DCTSIZE = 8.
  174202. */
  174203. #if DCTSIZE != 8
  174204. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174205. #endif
  174206. /*
  174207. * Perform the forward DCT on one block of samples.
  174208. */
  174209. GLOBAL(void)
  174210. jpeg_fdct_float (FAST_FLOAT * data)
  174211. {
  174212. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174213. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174214. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174215. FAST_FLOAT *dataptr;
  174216. int ctr;
  174217. /* Pass 1: process rows. */
  174218. dataptr = data;
  174219. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174220. tmp0 = dataptr[0] + dataptr[7];
  174221. tmp7 = dataptr[0] - dataptr[7];
  174222. tmp1 = dataptr[1] + dataptr[6];
  174223. tmp6 = dataptr[1] - dataptr[6];
  174224. tmp2 = dataptr[2] + dataptr[5];
  174225. tmp5 = dataptr[2] - dataptr[5];
  174226. tmp3 = dataptr[3] + dataptr[4];
  174227. tmp4 = dataptr[3] - dataptr[4];
  174228. /* Even part */
  174229. tmp10 = tmp0 + tmp3; /* phase 2 */
  174230. tmp13 = tmp0 - tmp3;
  174231. tmp11 = tmp1 + tmp2;
  174232. tmp12 = tmp1 - tmp2;
  174233. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174234. dataptr[4] = tmp10 - tmp11;
  174235. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174236. dataptr[2] = tmp13 + z1; /* phase 5 */
  174237. dataptr[6] = tmp13 - z1;
  174238. /* Odd part */
  174239. tmp10 = tmp4 + tmp5; /* phase 2 */
  174240. tmp11 = tmp5 + tmp6;
  174241. tmp12 = tmp6 + tmp7;
  174242. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174243. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174244. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174245. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174246. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174247. z11 = tmp7 + z3; /* phase 5 */
  174248. z13 = tmp7 - z3;
  174249. dataptr[5] = z13 + z2; /* phase 6 */
  174250. dataptr[3] = z13 - z2;
  174251. dataptr[1] = z11 + z4;
  174252. dataptr[7] = z11 - z4;
  174253. dataptr += DCTSIZE; /* advance pointer to next row */
  174254. }
  174255. /* Pass 2: process columns. */
  174256. dataptr = data;
  174257. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174258. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174259. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174260. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174261. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174262. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174263. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174264. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174265. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174266. /* Even part */
  174267. tmp10 = tmp0 + tmp3; /* phase 2 */
  174268. tmp13 = tmp0 - tmp3;
  174269. tmp11 = tmp1 + tmp2;
  174270. tmp12 = tmp1 - tmp2;
  174271. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174272. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174273. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174274. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174275. dataptr[DCTSIZE*6] = tmp13 - z1;
  174276. /* Odd part */
  174277. tmp10 = tmp4 + tmp5; /* phase 2 */
  174278. tmp11 = tmp5 + tmp6;
  174279. tmp12 = tmp6 + tmp7;
  174280. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174281. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174282. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174283. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174284. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174285. z11 = tmp7 + z3; /* phase 5 */
  174286. z13 = tmp7 - z3;
  174287. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174288. dataptr[DCTSIZE*3] = z13 - z2;
  174289. dataptr[DCTSIZE*1] = z11 + z4;
  174290. dataptr[DCTSIZE*7] = z11 - z4;
  174291. dataptr++; /* advance pointer to next column */
  174292. }
  174293. }
  174294. #endif /* DCT_FLOAT_SUPPORTED */
  174295. /*** End of inlined file: jfdctflt.c ***/
  174296. /*** Start of inlined file: jfdctint.c ***/
  174297. #define JPEG_INTERNALS
  174298. #ifdef DCT_ISLOW_SUPPORTED
  174299. /*
  174300. * This module is specialized to the case DCTSIZE = 8.
  174301. */
  174302. #if DCTSIZE != 8
  174303. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174304. #endif
  174305. /*
  174306. * The poop on this scaling stuff is as follows:
  174307. *
  174308. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174309. * larger than the true DCT outputs. The final outputs are therefore
  174310. * a factor of N larger than desired; since N=8 this can be cured by
  174311. * a simple right shift at the end of the algorithm. The advantage of
  174312. * this arrangement is that we save two multiplications per 1-D DCT,
  174313. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174314. * In the IJG code, this factor of 8 is removed by the quantization step
  174315. * (in jcdctmgr.c), NOT in this module.
  174316. *
  174317. * We have to do addition and subtraction of the integer inputs, which
  174318. * is no problem, and multiplication by fractional constants, which is
  174319. * a problem to do in integer arithmetic. We multiply all the constants
  174320. * by CONST_SCALE and convert them to integer constants (thus retaining
  174321. * CONST_BITS bits of precision in the constants). After doing a
  174322. * multiplication we have to divide the product by CONST_SCALE, with proper
  174323. * rounding, to produce the correct output. This division can be done
  174324. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174325. * as long as possible so that partial sums can be added together with
  174326. * full fractional precision.
  174327. *
  174328. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174329. * they are represented to better-than-integral precision. These outputs
  174330. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174331. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174332. * array is INT32 anyway.)
  174333. *
  174334. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174335. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174336. * shows that the values given below are the most effective.
  174337. */
  174338. #if BITS_IN_JSAMPLE == 8
  174339. #define CONST_BITS 13
  174340. #define PASS1_BITS 2
  174341. #else
  174342. #define CONST_BITS 13
  174343. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174344. #endif
  174345. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174346. * causing a lot of useless floating-point operations at run time.
  174347. * To get around this we use the following pre-calculated constants.
  174348. * If you change CONST_BITS you may want to add appropriate values.
  174349. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174350. */
  174351. #if CONST_BITS == 13
  174352. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174353. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174354. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174355. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174356. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174357. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174358. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174359. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174360. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174361. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174362. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174363. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174364. #else
  174365. #define FIX_0_298631336 FIX(0.298631336)
  174366. #define FIX_0_390180644 FIX(0.390180644)
  174367. #define FIX_0_541196100 FIX(0.541196100)
  174368. #define FIX_0_765366865 FIX(0.765366865)
  174369. #define FIX_0_899976223 FIX(0.899976223)
  174370. #define FIX_1_175875602 FIX(1.175875602)
  174371. #define FIX_1_501321110 FIX(1.501321110)
  174372. #define FIX_1_847759065 FIX(1.847759065)
  174373. #define FIX_1_961570560 FIX(1.961570560)
  174374. #define FIX_2_053119869 FIX(2.053119869)
  174375. #define FIX_2_562915447 FIX(2.562915447)
  174376. #define FIX_3_072711026 FIX(3.072711026)
  174377. #endif
  174378. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174379. * For 8-bit samples with the recommended scaling, all the variable
  174380. * and constant values involved are no more than 16 bits wide, so a
  174381. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174382. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174383. */
  174384. #if BITS_IN_JSAMPLE == 8
  174385. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174386. #else
  174387. #define MULTIPLY(var,const) ((var) * (const))
  174388. #endif
  174389. /*
  174390. * Perform the forward DCT on one block of samples.
  174391. */
  174392. GLOBAL(void)
  174393. jpeg_fdct_islow (DCTELEM * data)
  174394. {
  174395. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174396. INT32 tmp10, tmp11, tmp12, tmp13;
  174397. INT32 z1, z2, z3, z4, z5;
  174398. DCTELEM *dataptr;
  174399. int ctr;
  174400. SHIFT_TEMPS
  174401. /* Pass 1: process rows. */
  174402. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174403. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174404. dataptr = data;
  174405. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174406. tmp0 = dataptr[0] + dataptr[7];
  174407. tmp7 = dataptr[0] - dataptr[7];
  174408. tmp1 = dataptr[1] + dataptr[6];
  174409. tmp6 = dataptr[1] - dataptr[6];
  174410. tmp2 = dataptr[2] + dataptr[5];
  174411. tmp5 = dataptr[2] - dataptr[5];
  174412. tmp3 = dataptr[3] + dataptr[4];
  174413. tmp4 = dataptr[3] - dataptr[4];
  174414. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174415. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174416. */
  174417. tmp10 = tmp0 + tmp3;
  174418. tmp13 = tmp0 - tmp3;
  174419. tmp11 = tmp1 + tmp2;
  174420. tmp12 = tmp1 - tmp2;
  174421. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174422. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174423. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174424. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174425. CONST_BITS-PASS1_BITS);
  174426. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174427. CONST_BITS-PASS1_BITS);
  174428. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174429. * cK represents cos(K*pi/16).
  174430. * i0..i3 in the paper are tmp4..tmp7 here.
  174431. */
  174432. z1 = tmp4 + tmp7;
  174433. z2 = tmp5 + tmp6;
  174434. z3 = tmp4 + tmp6;
  174435. z4 = tmp5 + tmp7;
  174436. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174437. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174438. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174439. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174440. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174441. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174442. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174443. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174444. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174445. z3 += z5;
  174446. z4 += z5;
  174447. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174448. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174449. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174450. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174451. dataptr += DCTSIZE; /* advance pointer to next row */
  174452. }
  174453. /* Pass 2: process columns.
  174454. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174455. * by an overall factor of 8.
  174456. */
  174457. dataptr = data;
  174458. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174459. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174460. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174461. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174462. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174463. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174464. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174465. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174466. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174467. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174468. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174469. */
  174470. tmp10 = tmp0 + tmp3;
  174471. tmp13 = tmp0 - tmp3;
  174472. tmp11 = tmp1 + tmp2;
  174473. tmp12 = tmp1 - tmp2;
  174474. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174475. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174476. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174477. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174478. CONST_BITS+PASS1_BITS);
  174479. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174480. CONST_BITS+PASS1_BITS);
  174481. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174482. * cK represents cos(K*pi/16).
  174483. * i0..i3 in the paper are tmp4..tmp7 here.
  174484. */
  174485. z1 = tmp4 + tmp7;
  174486. z2 = tmp5 + tmp6;
  174487. z3 = tmp4 + tmp6;
  174488. z4 = tmp5 + tmp7;
  174489. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174490. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174491. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174492. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174493. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174494. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174495. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174496. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174497. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174498. z3 += z5;
  174499. z4 += z5;
  174500. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174501. CONST_BITS+PASS1_BITS);
  174502. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174503. CONST_BITS+PASS1_BITS);
  174504. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174505. CONST_BITS+PASS1_BITS);
  174506. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174507. CONST_BITS+PASS1_BITS);
  174508. dataptr++; /* advance pointer to next column */
  174509. }
  174510. }
  174511. #endif /* DCT_ISLOW_SUPPORTED */
  174512. /*** End of inlined file: jfdctint.c ***/
  174513. #undef CONST_BITS
  174514. #undef MULTIPLY
  174515. #undef FIX_0_541196100
  174516. /*** Start of inlined file: jfdctfst.c ***/
  174517. #define JPEG_INTERNALS
  174518. #ifdef DCT_IFAST_SUPPORTED
  174519. /*
  174520. * This module is specialized to the case DCTSIZE = 8.
  174521. */
  174522. #if DCTSIZE != 8
  174523. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174524. #endif
  174525. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174526. * see jfdctint.c for more details. However, we choose to descale
  174527. * (right shift) multiplication products as soon as they are formed,
  174528. * rather than carrying additional fractional bits into subsequent additions.
  174529. * This compromises accuracy slightly, but it lets us save a few shifts.
  174530. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174531. * everywhere except in the multiplications proper; this saves a good deal
  174532. * of work on 16-bit-int machines.
  174533. *
  174534. * Again to save a few shifts, the intermediate results between pass 1 and
  174535. * pass 2 are not upscaled, but are represented only to integral precision.
  174536. *
  174537. * A final compromise is to represent the multiplicative constants to only
  174538. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174539. * machines, and may also reduce the cost of multiplication (since there
  174540. * are fewer one-bits in the constants).
  174541. */
  174542. #define CONST_BITS 8
  174543. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174544. * causing a lot of useless floating-point operations at run time.
  174545. * To get around this we use the following pre-calculated constants.
  174546. * If you change CONST_BITS you may want to add appropriate values.
  174547. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174548. */
  174549. #if CONST_BITS == 8
  174550. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174551. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174552. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174553. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174554. #else
  174555. #define FIX_0_382683433 FIX(0.382683433)
  174556. #define FIX_0_541196100 FIX(0.541196100)
  174557. #define FIX_0_707106781 FIX(0.707106781)
  174558. #define FIX_1_306562965 FIX(1.306562965)
  174559. #endif
  174560. /* We can gain a little more speed, with a further compromise in accuracy,
  174561. * by omitting the addition in a descaling shift. This yields an incorrectly
  174562. * rounded result half the time...
  174563. */
  174564. #ifndef USE_ACCURATE_ROUNDING
  174565. #undef DESCALE
  174566. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174567. #endif
  174568. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174569. * descale to yield a DCTELEM result.
  174570. */
  174571. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174572. /*
  174573. * Perform the forward DCT on one block of samples.
  174574. */
  174575. GLOBAL(void)
  174576. jpeg_fdct_ifast (DCTELEM * data)
  174577. {
  174578. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174579. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174580. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174581. DCTELEM *dataptr;
  174582. int ctr;
  174583. SHIFT_TEMPS
  174584. /* Pass 1: process rows. */
  174585. dataptr = data;
  174586. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174587. tmp0 = dataptr[0] + dataptr[7];
  174588. tmp7 = dataptr[0] - dataptr[7];
  174589. tmp1 = dataptr[1] + dataptr[6];
  174590. tmp6 = dataptr[1] - dataptr[6];
  174591. tmp2 = dataptr[2] + dataptr[5];
  174592. tmp5 = dataptr[2] - dataptr[5];
  174593. tmp3 = dataptr[3] + dataptr[4];
  174594. tmp4 = dataptr[3] - dataptr[4];
  174595. /* Even part */
  174596. tmp10 = tmp0 + tmp3; /* phase 2 */
  174597. tmp13 = tmp0 - tmp3;
  174598. tmp11 = tmp1 + tmp2;
  174599. tmp12 = tmp1 - tmp2;
  174600. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174601. dataptr[4] = tmp10 - tmp11;
  174602. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174603. dataptr[2] = tmp13 + z1; /* phase 5 */
  174604. dataptr[6] = tmp13 - z1;
  174605. /* Odd part */
  174606. tmp10 = tmp4 + tmp5; /* phase 2 */
  174607. tmp11 = tmp5 + tmp6;
  174608. tmp12 = tmp6 + tmp7;
  174609. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174610. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174611. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174612. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174613. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174614. z11 = tmp7 + z3; /* phase 5 */
  174615. z13 = tmp7 - z3;
  174616. dataptr[5] = z13 + z2; /* phase 6 */
  174617. dataptr[3] = z13 - z2;
  174618. dataptr[1] = z11 + z4;
  174619. dataptr[7] = z11 - z4;
  174620. dataptr += DCTSIZE; /* advance pointer to next row */
  174621. }
  174622. /* Pass 2: process columns. */
  174623. dataptr = data;
  174624. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174625. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174626. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174627. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174628. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174629. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174630. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174631. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174632. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174633. /* Even part */
  174634. tmp10 = tmp0 + tmp3; /* phase 2 */
  174635. tmp13 = tmp0 - tmp3;
  174636. tmp11 = tmp1 + tmp2;
  174637. tmp12 = tmp1 - tmp2;
  174638. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174639. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174640. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174641. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174642. dataptr[DCTSIZE*6] = tmp13 - z1;
  174643. /* Odd part */
  174644. tmp10 = tmp4 + tmp5; /* phase 2 */
  174645. tmp11 = tmp5 + tmp6;
  174646. tmp12 = tmp6 + tmp7;
  174647. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174648. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174649. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174650. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174651. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174652. z11 = tmp7 + z3; /* phase 5 */
  174653. z13 = tmp7 - z3;
  174654. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174655. dataptr[DCTSIZE*3] = z13 - z2;
  174656. dataptr[DCTSIZE*1] = z11 + z4;
  174657. dataptr[DCTSIZE*7] = z11 - z4;
  174658. dataptr++; /* advance pointer to next column */
  174659. }
  174660. }
  174661. #endif /* DCT_IFAST_SUPPORTED */
  174662. /*** End of inlined file: jfdctfst.c ***/
  174663. #undef FIX_0_541196100
  174664. /*** Start of inlined file: jidctflt.c ***/
  174665. #define JPEG_INTERNALS
  174666. #ifdef DCT_FLOAT_SUPPORTED
  174667. /*
  174668. * This module is specialized to the case DCTSIZE = 8.
  174669. */
  174670. #if DCTSIZE != 8
  174671. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174672. #endif
  174673. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174674. * entry; produce a float result.
  174675. */
  174676. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174677. /*
  174678. * Perform dequantization and inverse DCT on one block of coefficients.
  174679. */
  174680. GLOBAL(void)
  174681. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174682. JCOEFPTR coef_block,
  174683. JSAMPARRAY output_buf, JDIMENSION output_col)
  174684. {
  174685. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174686. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174687. FAST_FLOAT z5, z10, z11, z12, z13;
  174688. JCOEFPTR inptr;
  174689. FLOAT_MULT_TYPE * quantptr;
  174690. FAST_FLOAT * wsptr;
  174691. JSAMPROW outptr;
  174692. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174693. int ctr;
  174694. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174695. SHIFT_TEMPS
  174696. /* Pass 1: process columns from input, store into work array. */
  174697. inptr = coef_block;
  174698. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174699. wsptr = workspace;
  174700. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174701. /* Due to quantization, we will usually find that many of the input
  174702. * coefficients are zero, especially the AC terms. We can exploit this
  174703. * by short-circuiting the IDCT calculation for any column in which all
  174704. * the AC terms are zero. In that case each output is equal to the
  174705. * DC coefficient (with scale factor as needed).
  174706. * With typical images and quantization tables, half or more of the
  174707. * column DCT calculations can be simplified this way.
  174708. */
  174709. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174710. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174711. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174712. inptr[DCTSIZE*7] == 0) {
  174713. /* AC terms all zero */
  174714. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174715. wsptr[DCTSIZE*0] = dcval;
  174716. wsptr[DCTSIZE*1] = dcval;
  174717. wsptr[DCTSIZE*2] = dcval;
  174718. wsptr[DCTSIZE*3] = dcval;
  174719. wsptr[DCTSIZE*4] = dcval;
  174720. wsptr[DCTSIZE*5] = dcval;
  174721. wsptr[DCTSIZE*6] = dcval;
  174722. wsptr[DCTSIZE*7] = dcval;
  174723. inptr++; /* advance pointers to next column */
  174724. quantptr++;
  174725. wsptr++;
  174726. continue;
  174727. }
  174728. /* Even part */
  174729. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174730. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174731. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174732. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174733. tmp10 = tmp0 + tmp2; /* phase 3 */
  174734. tmp11 = tmp0 - tmp2;
  174735. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174736. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174737. tmp0 = tmp10 + tmp13; /* phase 2 */
  174738. tmp3 = tmp10 - tmp13;
  174739. tmp1 = tmp11 + tmp12;
  174740. tmp2 = tmp11 - tmp12;
  174741. /* Odd part */
  174742. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174743. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174744. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174745. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174746. z13 = tmp6 + tmp5; /* phase 6 */
  174747. z10 = tmp6 - tmp5;
  174748. z11 = tmp4 + tmp7;
  174749. z12 = tmp4 - tmp7;
  174750. tmp7 = z11 + z13; /* phase 5 */
  174751. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174752. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174753. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174754. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174755. tmp6 = tmp12 - tmp7; /* phase 2 */
  174756. tmp5 = tmp11 - tmp6;
  174757. tmp4 = tmp10 + tmp5;
  174758. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174759. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174760. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174761. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174762. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174763. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174764. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174765. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174766. inptr++; /* advance pointers to next column */
  174767. quantptr++;
  174768. wsptr++;
  174769. }
  174770. /* Pass 2: process rows from work array, store into output array. */
  174771. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174772. wsptr = workspace;
  174773. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174774. outptr = output_buf[ctr] + output_col;
  174775. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174776. * However, the column calculation has created many nonzero AC terms, so
  174777. * the simplification applies less often (typically 5% to 10% of the time).
  174778. * And testing floats for zero is relatively expensive, so we don't bother.
  174779. */
  174780. /* Even part */
  174781. tmp10 = wsptr[0] + wsptr[4];
  174782. tmp11 = wsptr[0] - wsptr[4];
  174783. tmp13 = wsptr[2] + wsptr[6];
  174784. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174785. tmp0 = tmp10 + tmp13;
  174786. tmp3 = tmp10 - tmp13;
  174787. tmp1 = tmp11 + tmp12;
  174788. tmp2 = tmp11 - tmp12;
  174789. /* Odd part */
  174790. z13 = wsptr[5] + wsptr[3];
  174791. z10 = wsptr[5] - wsptr[3];
  174792. z11 = wsptr[1] + wsptr[7];
  174793. z12 = wsptr[1] - wsptr[7];
  174794. tmp7 = z11 + z13;
  174795. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174796. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174797. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174798. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174799. tmp6 = tmp12 - tmp7;
  174800. tmp5 = tmp11 - tmp6;
  174801. tmp4 = tmp10 + tmp5;
  174802. /* Final output stage: scale down by a factor of 8 and range-limit */
  174803. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174804. & RANGE_MASK];
  174805. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174806. & RANGE_MASK];
  174807. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174808. & RANGE_MASK];
  174809. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174810. & RANGE_MASK];
  174811. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174812. & RANGE_MASK];
  174813. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174814. & RANGE_MASK];
  174815. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174816. & RANGE_MASK];
  174817. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174818. & RANGE_MASK];
  174819. wsptr += DCTSIZE; /* advance pointer to next row */
  174820. }
  174821. }
  174822. #endif /* DCT_FLOAT_SUPPORTED */
  174823. /*** End of inlined file: jidctflt.c ***/
  174824. #undef CONST_BITS
  174825. #undef FIX_1_847759065
  174826. #undef MULTIPLY
  174827. #undef DEQUANTIZE
  174828. #undef DESCALE
  174829. /*** Start of inlined file: jidctfst.c ***/
  174830. #define JPEG_INTERNALS
  174831. #ifdef DCT_IFAST_SUPPORTED
  174832. /*
  174833. * This module is specialized to the case DCTSIZE = 8.
  174834. */
  174835. #if DCTSIZE != 8
  174836. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174837. #endif
  174838. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174839. * see jidctint.c for more details. However, we choose to descale
  174840. * (right shift) multiplication products as soon as they are formed,
  174841. * rather than carrying additional fractional bits into subsequent additions.
  174842. * This compromises accuracy slightly, but it lets us save a few shifts.
  174843. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174844. * everywhere except in the multiplications proper; this saves a good deal
  174845. * of work on 16-bit-int machines.
  174846. *
  174847. * The dequantized coefficients are not integers because the AA&N scaling
  174848. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174849. * so that the first and second IDCT rounds have the same input scaling.
  174850. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174851. * avoid a descaling shift; this compromises accuracy rather drastically
  174852. * for small quantization table entries, but it saves a lot of shifts.
  174853. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174854. * so we use a much larger scaling factor to preserve accuracy.
  174855. *
  174856. * A final compromise is to represent the multiplicative constants to only
  174857. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174858. * machines, and may also reduce the cost of multiplication (since there
  174859. * are fewer one-bits in the constants).
  174860. */
  174861. #if BITS_IN_JSAMPLE == 8
  174862. #define CONST_BITS 8
  174863. #define PASS1_BITS 2
  174864. #else
  174865. #define CONST_BITS 8
  174866. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174867. #endif
  174868. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174869. * causing a lot of useless floating-point operations at run time.
  174870. * To get around this we use the following pre-calculated constants.
  174871. * If you change CONST_BITS you may want to add appropriate values.
  174872. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174873. */
  174874. #if CONST_BITS == 8
  174875. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174876. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174877. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174878. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174879. #else
  174880. #define FIX_1_082392200 FIX(1.082392200)
  174881. #define FIX_1_414213562 FIX(1.414213562)
  174882. #define FIX_1_847759065 FIX(1.847759065)
  174883. #define FIX_2_613125930 FIX(2.613125930)
  174884. #endif
  174885. /* We can gain a little more speed, with a further compromise in accuracy,
  174886. * by omitting the addition in a descaling shift. This yields an incorrectly
  174887. * rounded result half the time...
  174888. */
  174889. #ifndef USE_ACCURATE_ROUNDING
  174890. #undef DESCALE
  174891. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174892. #endif
  174893. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174894. * descale to yield a DCTELEM result.
  174895. */
  174896. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174897. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174898. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174899. * multiplication will do. For 12-bit data, the multiplier table is
  174900. * declared INT32, so a 32-bit multiply will be used.
  174901. */
  174902. #if BITS_IN_JSAMPLE == 8
  174903. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174904. #else
  174905. #define DEQUANTIZE(coef,quantval) \
  174906. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174907. #endif
  174908. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174909. * We assume that int right shift is unsigned if INT32 right shift is.
  174910. */
  174911. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174912. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174913. #if BITS_IN_JSAMPLE == 8
  174914. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174915. #else
  174916. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174917. #endif
  174918. #define IRIGHT_SHIFT(x,shft) \
  174919. ((ishift_temp = (x)) < 0 ? \
  174920. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174921. (ishift_temp >> (shft)))
  174922. #else
  174923. #define ISHIFT_TEMPS
  174924. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174925. #endif
  174926. #ifdef USE_ACCURATE_ROUNDING
  174927. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174928. #else
  174929. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174930. #endif
  174931. /*
  174932. * Perform dequantization and inverse DCT on one block of coefficients.
  174933. */
  174934. GLOBAL(void)
  174935. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174936. JCOEFPTR coef_block,
  174937. JSAMPARRAY output_buf, JDIMENSION output_col)
  174938. {
  174939. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174940. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174941. DCTELEM z5, z10, z11, z12, z13;
  174942. JCOEFPTR inptr;
  174943. IFAST_MULT_TYPE * quantptr;
  174944. int * wsptr;
  174945. JSAMPROW outptr;
  174946. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174947. int ctr;
  174948. int workspace[DCTSIZE2]; /* buffers data between passes */
  174949. SHIFT_TEMPS /* for DESCALE */
  174950. ISHIFT_TEMPS /* for IDESCALE */
  174951. /* Pass 1: process columns from input, store into work array. */
  174952. inptr = coef_block;
  174953. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174954. wsptr = workspace;
  174955. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174956. /* Due to quantization, we will usually find that many of the input
  174957. * coefficients are zero, especially the AC terms. We can exploit this
  174958. * by short-circuiting the IDCT calculation for any column in which all
  174959. * the AC terms are zero. In that case each output is equal to the
  174960. * DC coefficient (with scale factor as needed).
  174961. * With typical images and quantization tables, half or more of the
  174962. * column DCT calculations can be simplified this way.
  174963. */
  174964. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174965. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174966. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174967. inptr[DCTSIZE*7] == 0) {
  174968. /* AC terms all zero */
  174969. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174970. wsptr[DCTSIZE*0] = dcval;
  174971. wsptr[DCTSIZE*1] = dcval;
  174972. wsptr[DCTSIZE*2] = dcval;
  174973. wsptr[DCTSIZE*3] = dcval;
  174974. wsptr[DCTSIZE*4] = dcval;
  174975. wsptr[DCTSIZE*5] = dcval;
  174976. wsptr[DCTSIZE*6] = dcval;
  174977. wsptr[DCTSIZE*7] = dcval;
  174978. inptr++; /* advance pointers to next column */
  174979. quantptr++;
  174980. wsptr++;
  174981. continue;
  174982. }
  174983. /* Even part */
  174984. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174985. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174986. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174987. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174988. tmp10 = tmp0 + tmp2; /* phase 3 */
  174989. tmp11 = tmp0 - tmp2;
  174990. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174991. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174992. tmp0 = tmp10 + tmp13; /* phase 2 */
  174993. tmp3 = tmp10 - tmp13;
  174994. tmp1 = tmp11 + tmp12;
  174995. tmp2 = tmp11 - tmp12;
  174996. /* Odd part */
  174997. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174998. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174999. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175000. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175001. z13 = tmp6 + tmp5; /* phase 6 */
  175002. z10 = tmp6 - tmp5;
  175003. z11 = tmp4 + tmp7;
  175004. z12 = tmp4 - tmp7;
  175005. tmp7 = z11 + z13; /* phase 5 */
  175006. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175007. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175008. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175009. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175010. tmp6 = tmp12 - tmp7; /* phase 2 */
  175011. tmp5 = tmp11 - tmp6;
  175012. tmp4 = tmp10 + tmp5;
  175013. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175014. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175015. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175016. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175017. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175018. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175019. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175020. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175021. inptr++; /* advance pointers to next column */
  175022. quantptr++;
  175023. wsptr++;
  175024. }
  175025. /* Pass 2: process rows from work array, store into output array. */
  175026. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175027. /* and also undo the PASS1_BITS scaling. */
  175028. wsptr = workspace;
  175029. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175030. outptr = output_buf[ctr] + output_col;
  175031. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175032. * However, the column calculation has created many nonzero AC terms, so
  175033. * the simplification applies less often (typically 5% to 10% of the time).
  175034. * On machines with very fast multiplication, it's possible that the
  175035. * test takes more time than it's worth. In that case this section
  175036. * may be commented out.
  175037. */
  175038. #ifndef NO_ZERO_ROW_TEST
  175039. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175040. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175041. /* AC terms all zero */
  175042. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175043. & RANGE_MASK];
  175044. outptr[0] = dcval;
  175045. outptr[1] = dcval;
  175046. outptr[2] = dcval;
  175047. outptr[3] = dcval;
  175048. outptr[4] = dcval;
  175049. outptr[5] = dcval;
  175050. outptr[6] = dcval;
  175051. outptr[7] = dcval;
  175052. wsptr += DCTSIZE; /* advance pointer to next row */
  175053. continue;
  175054. }
  175055. #endif
  175056. /* Even part */
  175057. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175058. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175059. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175060. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175061. - tmp13;
  175062. tmp0 = tmp10 + tmp13;
  175063. tmp3 = tmp10 - tmp13;
  175064. tmp1 = tmp11 + tmp12;
  175065. tmp2 = tmp11 - tmp12;
  175066. /* Odd part */
  175067. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175068. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175069. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175070. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175071. tmp7 = z11 + z13; /* phase 5 */
  175072. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175073. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175074. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175075. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175076. tmp6 = tmp12 - tmp7; /* phase 2 */
  175077. tmp5 = tmp11 - tmp6;
  175078. tmp4 = tmp10 + tmp5;
  175079. /* Final output stage: scale down by a factor of 8 and range-limit */
  175080. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175081. & RANGE_MASK];
  175082. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175083. & RANGE_MASK];
  175084. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175085. & RANGE_MASK];
  175086. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175087. & RANGE_MASK];
  175088. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175089. & RANGE_MASK];
  175090. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175091. & RANGE_MASK];
  175092. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175093. & RANGE_MASK];
  175094. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175095. & RANGE_MASK];
  175096. wsptr += DCTSIZE; /* advance pointer to next row */
  175097. }
  175098. }
  175099. #endif /* DCT_IFAST_SUPPORTED */
  175100. /*** End of inlined file: jidctfst.c ***/
  175101. #undef CONST_BITS
  175102. #undef FIX_1_847759065
  175103. #undef MULTIPLY
  175104. #undef DEQUANTIZE
  175105. /*** Start of inlined file: jidctint.c ***/
  175106. #define JPEG_INTERNALS
  175107. #ifdef DCT_ISLOW_SUPPORTED
  175108. /*
  175109. * This module is specialized to the case DCTSIZE = 8.
  175110. */
  175111. #if DCTSIZE != 8
  175112. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175113. #endif
  175114. /*
  175115. * The poop on this scaling stuff is as follows:
  175116. *
  175117. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175118. * larger than the true IDCT outputs. The final outputs are therefore
  175119. * a factor of N larger than desired; since N=8 this can be cured by
  175120. * a simple right shift at the end of the algorithm. The advantage of
  175121. * this arrangement is that we save two multiplications per 1-D IDCT,
  175122. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175123. *
  175124. * We have to do addition and subtraction of the integer inputs, which
  175125. * is no problem, and multiplication by fractional constants, which is
  175126. * a problem to do in integer arithmetic. We multiply all the constants
  175127. * by CONST_SCALE and convert them to integer constants (thus retaining
  175128. * CONST_BITS bits of precision in the constants). After doing a
  175129. * multiplication we have to divide the product by CONST_SCALE, with proper
  175130. * rounding, to produce the correct output. This division can be done
  175131. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175132. * as long as possible so that partial sums can be added together with
  175133. * full fractional precision.
  175134. *
  175135. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175136. * they are represented to better-than-integral precision. These outputs
  175137. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175138. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175139. * intermediate INT32 array would be needed.)
  175140. *
  175141. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175142. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175143. * shows that the values given below are the most effective.
  175144. */
  175145. #if BITS_IN_JSAMPLE == 8
  175146. #define CONST_BITS 13
  175147. #define PASS1_BITS 2
  175148. #else
  175149. #define CONST_BITS 13
  175150. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175151. #endif
  175152. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175153. * causing a lot of useless floating-point operations at run time.
  175154. * To get around this we use the following pre-calculated constants.
  175155. * If you change CONST_BITS you may want to add appropriate values.
  175156. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175157. */
  175158. #if CONST_BITS == 13
  175159. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175160. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175161. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175162. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175163. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175164. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175165. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175166. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175167. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175168. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175169. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175170. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175171. #else
  175172. #define FIX_0_298631336 FIX(0.298631336)
  175173. #define FIX_0_390180644 FIX(0.390180644)
  175174. #define FIX_0_541196100 FIX(0.541196100)
  175175. #define FIX_0_765366865 FIX(0.765366865)
  175176. #define FIX_0_899976223 FIX(0.899976223)
  175177. #define FIX_1_175875602 FIX(1.175875602)
  175178. #define FIX_1_501321110 FIX(1.501321110)
  175179. #define FIX_1_847759065 FIX(1.847759065)
  175180. #define FIX_1_961570560 FIX(1.961570560)
  175181. #define FIX_2_053119869 FIX(2.053119869)
  175182. #define FIX_2_562915447 FIX(2.562915447)
  175183. #define FIX_3_072711026 FIX(3.072711026)
  175184. #endif
  175185. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175186. * For 8-bit samples with the recommended scaling, all the variable
  175187. * and constant values involved are no more than 16 bits wide, so a
  175188. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175189. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175190. */
  175191. #if BITS_IN_JSAMPLE == 8
  175192. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175193. #else
  175194. #define MULTIPLY(var,const) ((var) * (const))
  175195. #endif
  175196. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175197. * entry; produce an int result. In this module, both inputs and result
  175198. * are 16 bits or less, so either int or short multiply will work.
  175199. */
  175200. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175201. /*
  175202. * Perform dequantization and inverse DCT on one block of coefficients.
  175203. */
  175204. GLOBAL(void)
  175205. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175206. JCOEFPTR coef_block,
  175207. JSAMPARRAY output_buf, JDIMENSION output_col)
  175208. {
  175209. INT32 tmp0, tmp1, tmp2, tmp3;
  175210. INT32 tmp10, tmp11, tmp12, tmp13;
  175211. INT32 z1, z2, z3, z4, z5;
  175212. JCOEFPTR inptr;
  175213. ISLOW_MULT_TYPE * quantptr;
  175214. int * wsptr;
  175215. JSAMPROW outptr;
  175216. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175217. int ctr;
  175218. int workspace[DCTSIZE2]; /* buffers data between passes */
  175219. SHIFT_TEMPS
  175220. /* Pass 1: process columns from input, store into work array. */
  175221. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175222. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175223. inptr = coef_block;
  175224. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175225. wsptr = workspace;
  175226. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175227. /* Due to quantization, we will usually find that many of the input
  175228. * coefficients are zero, especially the AC terms. We can exploit this
  175229. * by short-circuiting the IDCT calculation for any column in which all
  175230. * the AC terms are zero. In that case each output is equal to the
  175231. * DC coefficient (with scale factor as needed).
  175232. * With typical images and quantization tables, half or more of the
  175233. * column DCT calculations can be simplified this way.
  175234. */
  175235. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175236. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175237. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175238. inptr[DCTSIZE*7] == 0) {
  175239. /* AC terms all zero */
  175240. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175241. wsptr[DCTSIZE*0] = dcval;
  175242. wsptr[DCTSIZE*1] = dcval;
  175243. wsptr[DCTSIZE*2] = dcval;
  175244. wsptr[DCTSIZE*3] = dcval;
  175245. wsptr[DCTSIZE*4] = dcval;
  175246. wsptr[DCTSIZE*5] = dcval;
  175247. wsptr[DCTSIZE*6] = dcval;
  175248. wsptr[DCTSIZE*7] = dcval;
  175249. inptr++; /* advance pointers to next column */
  175250. quantptr++;
  175251. wsptr++;
  175252. continue;
  175253. }
  175254. /* Even part: reverse the even part of the forward DCT. */
  175255. /* The rotator is sqrt(2)*c(-6). */
  175256. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175257. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175258. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175259. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175260. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175261. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175262. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175263. tmp0 = (z2 + z3) << CONST_BITS;
  175264. tmp1 = (z2 - z3) << CONST_BITS;
  175265. tmp10 = tmp0 + tmp3;
  175266. tmp13 = tmp0 - tmp3;
  175267. tmp11 = tmp1 + tmp2;
  175268. tmp12 = tmp1 - tmp2;
  175269. /* Odd part per figure 8; the matrix is unitary and hence its
  175270. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175271. */
  175272. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175273. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175274. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175275. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175276. z1 = tmp0 + tmp3;
  175277. z2 = tmp1 + tmp2;
  175278. z3 = tmp0 + tmp2;
  175279. z4 = tmp1 + tmp3;
  175280. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175281. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175282. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175283. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175284. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175285. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175286. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175287. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175288. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175289. z3 += z5;
  175290. z4 += z5;
  175291. tmp0 += z1 + z3;
  175292. tmp1 += z2 + z4;
  175293. tmp2 += z2 + z3;
  175294. tmp3 += z1 + z4;
  175295. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175296. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175297. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175298. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175299. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175300. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175301. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175302. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175303. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175304. inptr++; /* advance pointers to next column */
  175305. quantptr++;
  175306. wsptr++;
  175307. }
  175308. /* Pass 2: process rows from work array, store into output array. */
  175309. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175310. /* and also undo the PASS1_BITS scaling. */
  175311. wsptr = workspace;
  175312. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175313. outptr = output_buf[ctr] + output_col;
  175314. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175315. * However, the column calculation has created many nonzero AC terms, so
  175316. * the simplification applies less often (typically 5% to 10% of the time).
  175317. * On machines with very fast multiplication, it's possible that the
  175318. * test takes more time than it's worth. In that case this section
  175319. * may be commented out.
  175320. */
  175321. #ifndef NO_ZERO_ROW_TEST
  175322. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175323. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175324. /* AC terms all zero */
  175325. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175326. & RANGE_MASK];
  175327. outptr[0] = dcval;
  175328. outptr[1] = dcval;
  175329. outptr[2] = dcval;
  175330. outptr[3] = dcval;
  175331. outptr[4] = dcval;
  175332. outptr[5] = dcval;
  175333. outptr[6] = dcval;
  175334. outptr[7] = dcval;
  175335. wsptr += DCTSIZE; /* advance pointer to next row */
  175336. continue;
  175337. }
  175338. #endif
  175339. /* Even part: reverse the even part of the forward DCT. */
  175340. /* The rotator is sqrt(2)*c(-6). */
  175341. z2 = (INT32) wsptr[2];
  175342. z3 = (INT32) wsptr[6];
  175343. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175344. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175345. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175346. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175347. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175348. tmp10 = tmp0 + tmp3;
  175349. tmp13 = tmp0 - tmp3;
  175350. tmp11 = tmp1 + tmp2;
  175351. tmp12 = tmp1 - tmp2;
  175352. /* Odd part per figure 8; the matrix is unitary and hence its
  175353. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175354. */
  175355. tmp0 = (INT32) wsptr[7];
  175356. tmp1 = (INT32) wsptr[5];
  175357. tmp2 = (INT32) wsptr[3];
  175358. tmp3 = (INT32) wsptr[1];
  175359. z1 = tmp0 + tmp3;
  175360. z2 = tmp1 + tmp2;
  175361. z3 = tmp0 + tmp2;
  175362. z4 = tmp1 + tmp3;
  175363. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175364. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175365. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175366. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175367. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175368. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175369. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175370. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175371. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175372. z3 += z5;
  175373. z4 += z5;
  175374. tmp0 += z1 + z3;
  175375. tmp1 += z2 + z4;
  175376. tmp2 += z2 + z3;
  175377. tmp3 += z1 + z4;
  175378. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175379. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175380. CONST_BITS+PASS1_BITS+3)
  175381. & RANGE_MASK];
  175382. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175383. CONST_BITS+PASS1_BITS+3)
  175384. & RANGE_MASK];
  175385. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175386. CONST_BITS+PASS1_BITS+3)
  175387. & RANGE_MASK];
  175388. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175389. CONST_BITS+PASS1_BITS+3)
  175390. & RANGE_MASK];
  175391. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175392. CONST_BITS+PASS1_BITS+3)
  175393. & RANGE_MASK];
  175394. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175395. CONST_BITS+PASS1_BITS+3)
  175396. & RANGE_MASK];
  175397. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175398. CONST_BITS+PASS1_BITS+3)
  175399. & RANGE_MASK];
  175400. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175401. CONST_BITS+PASS1_BITS+3)
  175402. & RANGE_MASK];
  175403. wsptr += DCTSIZE; /* advance pointer to next row */
  175404. }
  175405. }
  175406. #endif /* DCT_ISLOW_SUPPORTED */
  175407. /*** End of inlined file: jidctint.c ***/
  175408. /*** Start of inlined file: jidctred.c ***/
  175409. #define JPEG_INTERNALS
  175410. #ifdef IDCT_SCALING_SUPPORTED
  175411. /*
  175412. * This module is specialized to the case DCTSIZE = 8.
  175413. */
  175414. #if DCTSIZE != 8
  175415. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175416. #endif
  175417. /* Scaling is the same as in jidctint.c. */
  175418. #if BITS_IN_JSAMPLE == 8
  175419. #define CONST_BITS 13
  175420. #define PASS1_BITS 2
  175421. #else
  175422. #define CONST_BITS 13
  175423. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175424. #endif
  175425. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175426. * causing a lot of useless floating-point operations at run time.
  175427. * To get around this we use the following pre-calculated constants.
  175428. * If you change CONST_BITS you may want to add appropriate values.
  175429. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175430. */
  175431. #if CONST_BITS == 13
  175432. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175433. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175434. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175435. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175436. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175437. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175438. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175439. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175440. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175441. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175442. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175443. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175444. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175445. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175446. #else
  175447. #define FIX_0_211164243 FIX(0.211164243)
  175448. #define FIX_0_509795579 FIX(0.509795579)
  175449. #define FIX_0_601344887 FIX(0.601344887)
  175450. #define FIX_0_720959822 FIX(0.720959822)
  175451. #define FIX_0_765366865 FIX(0.765366865)
  175452. #define FIX_0_850430095 FIX(0.850430095)
  175453. #define FIX_0_899976223 FIX(0.899976223)
  175454. #define FIX_1_061594337 FIX(1.061594337)
  175455. #define FIX_1_272758580 FIX(1.272758580)
  175456. #define FIX_1_451774981 FIX(1.451774981)
  175457. #define FIX_1_847759065 FIX(1.847759065)
  175458. #define FIX_2_172734803 FIX(2.172734803)
  175459. #define FIX_2_562915447 FIX(2.562915447)
  175460. #define FIX_3_624509785 FIX(3.624509785)
  175461. #endif
  175462. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175463. * For 8-bit samples with the recommended scaling, all the variable
  175464. * and constant values involved are no more than 16 bits wide, so a
  175465. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175466. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175467. */
  175468. #if BITS_IN_JSAMPLE == 8
  175469. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175470. #else
  175471. #define MULTIPLY(var,const) ((var) * (const))
  175472. #endif
  175473. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175474. * entry; produce an int result. In this module, both inputs and result
  175475. * are 16 bits or less, so either int or short multiply will work.
  175476. */
  175477. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175478. /*
  175479. * Perform dequantization and inverse DCT on one block of coefficients,
  175480. * producing a reduced-size 4x4 output block.
  175481. */
  175482. GLOBAL(void)
  175483. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175484. JCOEFPTR coef_block,
  175485. JSAMPARRAY output_buf, JDIMENSION output_col)
  175486. {
  175487. INT32 tmp0, tmp2, tmp10, tmp12;
  175488. INT32 z1, z2, z3, z4;
  175489. JCOEFPTR inptr;
  175490. ISLOW_MULT_TYPE * quantptr;
  175491. int * wsptr;
  175492. JSAMPROW outptr;
  175493. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175494. int ctr;
  175495. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175496. SHIFT_TEMPS
  175497. /* Pass 1: process columns from input, store into work array. */
  175498. inptr = coef_block;
  175499. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175500. wsptr = workspace;
  175501. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175502. /* Don't bother to process column 4, because second pass won't use it */
  175503. if (ctr == DCTSIZE-4)
  175504. continue;
  175505. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175506. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175507. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175508. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175509. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175510. wsptr[DCTSIZE*0] = dcval;
  175511. wsptr[DCTSIZE*1] = dcval;
  175512. wsptr[DCTSIZE*2] = dcval;
  175513. wsptr[DCTSIZE*3] = dcval;
  175514. continue;
  175515. }
  175516. /* Even part */
  175517. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175518. tmp0 <<= (CONST_BITS+1);
  175519. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175520. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175521. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175522. tmp10 = tmp0 + tmp2;
  175523. tmp12 = tmp0 - tmp2;
  175524. /* Odd part */
  175525. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175526. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175527. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175528. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175529. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175530. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175531. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175532. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175533. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175534. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175535. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175536. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175537. /* Final output stage */
  175538. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175539. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175540. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175541. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175542. }
  175543. /* Pass 2: process 4 rows from work array, store into output array. */
  175544. wsptr = workspace;
  175545. for (ctr = 0; ctr < 4; ctr++) {
  175546. outptr = output_buf[ctr] + output_col;
  175547. /* It's not clear whether a zero row test is worthwhile here ... */
  175548. #ifndef NO_ZERO_ROW_TEST
  175549. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175550. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175551. /* AC terms all zero */
  175552. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175553. & RANGE_MASK];
  175554. outptr[0] = dcval;
  175555. outptr[1] = dcval;
  175556. outptr[2] = dcval;
  175557. outptr[3] = dcval;
  175558. wsptr += DCTSIZE; /* advance pointer to next row */
  175559. continue;
  175560. }
  175561. #endif
  175562. /* Even part */
  175563. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175564. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175565. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175566. tmp10 = tmp0 + tmp2;
  175567. tmp12 = tmp0 - tmp2;
  175568. /* Odd part */
  175569. z1 = (INT32) wsptr[7];
  175570. z2 = (INT32) wsptr[5];
  175571. z3 = (INT32) wsptr[3];
  175572. z4 = (INT32) wsptr[1];
  175573. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175574. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175575. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175576. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175577. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175578. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175579. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175580. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175581. /* Final output stage */
  175582. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175583. CONST_BITS+PASS1_BITS+3+1)
  175584. & RANGE_MASK];
  175585. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175586. CONST_BITS+PASS1_BITS+3+1)
  175587. & RANGE_MASK];
  175588. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175589. CONST_BITS+PASS1_BITS+3+1)
  175590. & RANGE_MASK];
  175591. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175592. CONST_BITS+PASS1_BITS+3+1)
  175593. & RANGE_MASK];
  175594. wsptr += DCTSIZE; /* advance pointer to next row */
  175595. }
  175596. }
  175597. /*
  175598. * Perform dequantization and inverse DCT on one block of coefficients,
  175599. * producing a reduced-size 2x2 output block.
  175600. */
  175601. GLOBAL(void)
  175602. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175603. JCOEFPTR coef_block,
  175604. JSAMPARRAY output_buf, JDIMENSION output_col)
  175605. {
  175606. INT32 tmp0, tmp10, z1;
  175607. JCOEFPTR inptr;
  175608. ISLOW_MULT_TYPE * quantptr;
  175609. int * wsptr;
  175610. JSAMPROW outptr;
  175611. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175612. int ctr;
  175613. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175614. SHIFT_TEMPS
  175615. /* Pass 1: process columns from input, store into work array. */
  175616. inptr = coef_block;
  175617. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175618. wsptr = workspace;
  175619. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175620. /* Don't bother to process columns 2,4,6 */
  175621. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175622. continue;
  175623. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175624. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175625. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175626. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175627. wsptr[DCTSIZE*0] = dcval;
  175628. wsptr[DCTSIZE*1] = dcval;
  175629. continue;
  175630. }
  175631. /* Even part */
  175632. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175633. tmp10 = z1 << (CONST_BITS+2);
  175634. /* Odd part */
  175635. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175636. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175637. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175638. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175639. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175640. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175641. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175642. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175643. /* Final output stage */
  175644. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175645. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175646. }
  175647. /* Pass 2: process 2 rows from work array, store into output array. */
  175648. wsptr = workspace;
  175649. for (ctr = 0; ctr < 2; ctr++) {
  175650. outptr = output_buf[ctr] + output_col;
  175651. /* It's not clear whether a zero row test is worthwhile here ... */
  175652. #ifndef NO_ZERO_ROW_TEST
  175653. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175654. /* AC terms all zero */
  175655. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175656. & RANGE_MASK];
  175657. outptr[0] = dcval;
  175658. outptr[1] = dcval;
  175659. wsptr += DCTSIZE; /* advance pointer to next row */
  175660. continue;
  175661. }
  175662. #endif
  175663. /* Even part */
  175664. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175665. /* Odd part */
  175666. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175667. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175668. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175669. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175670. /* Final output stage */
  175671. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175672. CONST_BITS+PASS1_BITS+3+2)
  175673. & RANGE_MASK];
  175674. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175675. CONST_BITS+PASS1_BITS+3+2)
  175676. & RANGE_MASK];
  175677. wsptr += DCTSIZE; /* advance pointer to next row */
  175678. }
  175679. }
  175680. /*
  175681. * Perform dequantization and inverse DCT on one block of coefficients,
  175682. * producing a reduced-size 1x1 output block.
  175683. */
  175684. GLOBAL(void)
  175685. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175686. JCOEFPTR coef_block,
  175687. JSAMPARRAY output_buf, JDIMENSION output_col)
  175688. {
  175689. int dcval;
  175690. ISLOW_MULT_TYPE * quantptr;
  175691. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175692. SHIFT_TEMPS
  175693. /* We hardly need an inverse DCT routine for this: just take the
  175694. * average pixel value, which is one-eighth of the DC coefficient.
  175695. */
  175696. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175697. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175698. dcval = (int) DESCALE((INT32) dcval, 3);
  175699. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175700. }
  175701. #endif /* IDCT_SCALING_SUPPORTED */
  175702. /*** End of inlined file: jidctred.c ***/
  175703. /*** Start of inlined file: jmemmgr.c ***/
  175704. #define JPEG_INTERNALS
  175705. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175706. /*** Start of inlined file: jmemsys.h ***/
  175707. #ifndef __jmemsys_h__
  175708. #define __jmemsys_h__
  175709. /* Short forms of external names for systems with brain-damaged linkers. */
  175710. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175711. #define jpeg_get_small jGetSmall
  175712. #define jpeg_free_small jFreeSmall
  175713. #define jpeg_get_large jGetLarge
  175714. #define jpeg_free_large jFreeLarge
  175715. #define jpeg_mem_available jMemAvail
  175716. #define jpeg_open_backing_store jOpenBackStore
  175717. #define jpeg_mem_init jMemInit
  175718. #define jpeg_mem_term jMemTerm
  175719. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175720. /*
  175721. * These two functions are used to allocate and release small chunks of
  175722. * memory. (Typically the total amount requested through jpeg_get_small is
  175723. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175724. * Behavior should be the same as for the standard library functions malloc
  175725. * and free; in particular, jpeg_get_small must return NULL on failure.
  175726. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175727. * size of the object being freed, just in case it's needed.
  175728. * On an 80x86 machine using small-data memory model, these manage near heap.
  175729. */
  175730. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175731. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175732. size_t sizeofobject));
  175733. /*
  175734. * These two functions are used to allocate and release large chunks of
  175735. * memory (up to the total free space designated by jpeg_mem_available).
  175736. * The interface is the same as above, except that on an 80x86 machine,
  175737. * far pointers are used. On most other machines these are identical to
  175738. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175739. * in case a different allocation strategy is desirable for large chunks.
  175740. */
  175741. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175742. size_t sizeofobject));
  175743. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175744. size_t sizeofobject));
  175745. /*
  175746. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175747. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175748. * matter, but that case should never come into play). This macro is needed
  175749. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175750. * On those machines, we expect that jconfig.h will provide a proper value.
  175751. * On machines with 32-bit flat address spaces, any large constant may be used.
  175752. *
  175753. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175754. * size_t and will be a multiple of sizeof(align_type).
  175755. */
  175756. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175757. #define MAX_ALLOC_CHUNK 1000000000L
  175758. #endif
  175759. /*
  175760. * This routine computes the total space still available for allocation by
  175761. * jpeg_get_large. If more space than this is needed, backing store will be
  175762. * used. NOTE: any memory already allocated must not be counted.
  175763. *
  175764. * There is a minimum space requirement, corresponding to the minimum
  175765. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175766. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175767. * all working storage in memory, is also passed in case it is useful.
  175768. * Finally, the total space already allocated is passed. If no better
  175769. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175770. * is often a suitable calculation.
  175771. *
  175772. * It is OK for jpeg_mem_available to underestimate the space available
  175773. * (that'll just lead to more backing-store access than is really necessary).
  175774. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175775. * a slop factor from the true available space. 5% should be enough.
  175776. *
  175777. * On machines with lots of virtual memory, any large constant may be returned.
  175778. * Conversely, zero may be returned to always use the minimum amount of memory.
  175779. */
  175780. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175781. long min_bytes_needed,
  175782. long max_bytes_needed,
  175783. long already_allocated));
  175784. /*
  175785. * This structure holds whatever state is needed to access a single
  175786. * backing-store object. The read/write/close method pointers are called
  175787. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175788. * are private to the system-dependent backing store routines.
  175789. */
  175790. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175791. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175792. typedef unsigned short XMSH; /* type of extended-memory handles */
  175793. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175794. typedef union {
  175795. short file_handle; /* DOS file handle if it's a temp file */
  175796. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175797. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175798. } handle_union;
  175799. #endif /* USE_MSDOS_MEMMGR */
  175800. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175801. #include <Files.h>
  175802. #endif /* USE_MAC_MEMMGR */
  175803. //typedef struct backing_store_struct * backing_store_ptr;
  175804. typedef struct backing_store_struct {
  175805. /* Methods for reading/writing/closing this backing-store object */
  175806. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175807. struct backing_store_struct *info,
  175808. void FAR * buffer_address,
  175809. long file_offset, long byte_count));
  175810. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175811. struct backing_store_struct *info,
  175812. void FAR * buffer_address,
  175813. long file_offset, long byte_count));
  175814. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175815. struct backing_store_struct *info));
  175816. /* Private fields for system-dependent backing-store management */
  175817. #ifdef USE_MSDOS_MEMMGR
  175818. /* For the MS-DOS manager (jmemdos.c), we need: */
  175819. handle_union handle; /* reference to backing-store storage object */
  175820. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175821. #else
  175822. #ifdef USE_MAC_MEMMGR
  175823. /* For the Mac manager (jmemmac.c), we need: */
  175824. short temp_file; /* file reference number to temp file */
  175825. FSSpec tempSpec; /* the FSSpec for the temp file */
  175826. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175827. #else
  175828. /* For a typical implementation with temp files, we need: */
  175829. FILE * temp_file; /* stdio reference to temp file */
  175830. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175831. #endif
  175832. #endif
  175833. } backing_store_info;
  175834. /*
  175835. * Initial opening of a backing-store object. This must fill in the
  175836. * read/write/close pointers in the object. The read/write routines
  175837. * may take an error exit if the specified maximum file size is exceeded.
  175838. * (If jpeg_mem_available always returns a large value, this routine can
  175839. * just take an error exit.)
  175840. */
  175841. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175842. struct backing_store_struct *info,
  175843. long total_bytes_needed));
  175844. /*
  175845. * These routines take care of any system-dependent initialization and
  175846. * cleanup required. jpeg_mem_init will be called before anything is
  175847. * allocated (and, therefore, nothing in cinfo is of use except the error
  175848. * manager pointer). It should return a suitable default value for
  175849. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175850. * application. (Note that max_memory_to_use is only important if
  175851. * jpeg_mem_available chooses to consult it ... no one else will.)
  175852. * jpeg_mem_term may assume that all requested memory has been freed and that
  175853. * all opened backing-store objects have been closed.
  175854. */
  175855. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175856. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175857. #endif
  175858. /*** End of inlined file: jmemsys.h ***/
  175859. /* import the system-dependent declarations */
  175860. #ifndef NO_GETENV
  175861. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175862. extern char * getenv JPP((const char * name));
  175863. #endif
  175864. #endif
  175865. /*
  175866. * Some important notes:
  175867. * The allocation routines provided here must never return NULL.
  175868. * They should exit to error_exit if unsuccessful.
  175869. *
  175870. * It's not a good idea to try to merge the sarray and barray routines,
  175871. * even though they are textually almost the same, because samples are
  175872. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175873. * in machines where byte pointers have a different representation from
  175874. * word pointers, the resulting machine code could not be the same.
  175875. */
  175876. /*
  175877. * Many machines require storage alignment: longs must start on 4-byte
  175878. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175879. * always returns pointers that are multiples of the worst-case alignment
  175880. * requirement, and we had better do so too.
  175881. * There isn't any really portable way to determine the worst-case alignment
  175882. * requirement. This module assumes that the alignment requirement is
  175883. * multiples of sizeof(ALIGN_TYPE).
  175884. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175885. * workstations (where doubles really do need 8-byte alignment) and will work
  175886. * fine on nearly everything. If your machine has lesser alignment needs,
  175887. * you can save a few bytes by making ALIGN_TYPE smaller.
  175888. * The only place I know of where this will NOT work is certain Macintosh
  175889. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175890. * Doing 10-byte alignment is counterproductive because longwords won't be
  175891. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175892. * such a compiler.
  175893. */
  175894. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175895. #define ALIGN_TYPE double
  175896. #endif
  175897. /*
  175898. * We allocate objects from "pools", where each pool is gotten with a single
  175899. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175900. * overhead within a pool, except for alignment padding. Each pool has a
  175901. * header with a link to the next pool of the same class.
  175902. * Small and large pool headers are identical except that the latter's
  175903. * link pointer must be FAR on 80x86 machines.
  175904. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175905. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175906. * of the alignment requirement of ALIGN_TYPE.
  175907. */
  175908. typedef union small_pool_struct * small_pool_ptr;
  175909. typedef union small_pool_struct {
  175910. struct {
  175911. small_pool_ptr next; /* next in list of pools */
  175912. size_t bytes_used; /* how many bytes already used within pool */
  175913. size_t bytes_left; /* bytes still available in this pool */
  175914. } hdr;
  175915. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175916. } small_pool_hdr;
  175917. typedef union large_pool_struct FAR * large_pool_ptr;
  175918. typedef union large_pool_struct {
  175919. struct {
  175920. large_pool_ptr next; /* next in list of pools */
  175921. size_t bytes_used; /* how many bytes already used within pool */
  175922. size_t bytes_left; /* bytes still available in this pool */
  175923. } hdr;
  175924. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175925. } large_pool_hdr;
  175926. /*
  175927. * Here is the full definition of a memory manager object.
  175928. */
  175929. typedef struct {
  175930. struct jpeg_memory_mgr pub; /* public fields */
  175931. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175932. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175933. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175934. /* Since we only have one lifetime class of virtual arrays, only one
  175935. * linked list is necessary (for each datatype). Note that the virtual
  175936. * array control blocks being linked together are actually stored somewhere
  175937. * in the small-pool list.
  175938. */
  175939. jvirt_sarray_ptr virt_sarray_list;
  175940. jvirt_barray_ptr virt_barray_list;
  175941. /* This counts total space obtained from jpeg_get_small/large */
  175942. long total_space_allocated;
  175943. /* alloc_sarray and alloc_barray set this value for use by virtual
  175944. * array routines.
  175945. */
  175946. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175947. } my_memory_mgr;
  175948. typedef my_memory_mgr * my_mem_ptr;
  175949. /*
  175950. * The control blocks for virtual arrays.
  175951. * Note that these blocks are allocated in the "small" pool area.
  175952. * System-dependent info for the associated backing store (if any) is hidden
  175953. * inside the backing_store_info struct.
  175954. */
  175955. struct jvirt_sarray_control {
  175956. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175957. JDIMENSION rows_in_array; /* total virtual array height */
  175958. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175959. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175960. JDIMENSION rows_in_mem; /* height of memory buffer */
  175961. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175962. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175963. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175964. boolean pre_zero; /* pre-zero mode requested? */
  175965. boolean dirty; /* do current buffer contents need written? */
  175966. boolean b_s_open; /* is backing-store data valid? */
  175967. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175968. backing_store_info b_s_info; /* System-dependent control info */
  175969. };
  175970. struct jvirt_barray_control {
  175971. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175972. JDIMENSION rows_in_array; /* total virtual array height */
  175973. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175974. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175975. JDIMENSION rows_in_mem; /* height of memory buffer */
  175976. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175977. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175978. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175979. boolean pre_zero; /* pre-zero mode requested? */
  175980. boolean dirty; /* do current buffer contents need written? */
  175981. boolean b_s_open; /* is backing-store data valid? */
  175982. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175983. backing_store_info b_s_info; /* System-dependent control info */
  175984. };
  175985. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175986. LOCAL(void)
  175987. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175988. {
  175989. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175990. small_pool_ptr shdr_ptr;
  175991. large_pool_ptr lhdr_ptr;
  175992. /* Since this is only a debugging stub, we can cheat a little by using
  175993. * fprintf directly rather than going through the trace message code.
  175994. * This is helpful because message parm array can't handle longs.
  175995. */
  175996. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175997. pool_id, mem->total_space_allocated);
  175998. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175999. lhdr_ptr = lhdr_ptr->hdr.next) {
  176000. fprintf(stderr, " Large chunk used %ld\n",
  176001. (long) lhdr_ptr->hdr.bytes_used);
  176002. }
  176003. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176004. shdr_ptr = shdr_ptr->hdr.next) {
  176005. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176006. (long) shdr_ptr->hdr.bytes_used,
  176007. (long) shdr_ptr->hdr.bytes_left);
  176008. }
  176009. }
  176010. #endif /* MEM_STATS */
  176011. LOCAL(void)
  176012. out_of_memory (j_common_ptr cinfo, int which)
  176013. /* Report an out-of-memory error and stop execution */
  176014. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176015. {
  176016. #ifdef MEM_STATS
  176017. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176018. #endif
  176019. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176020. }
  176021. /*
  176022. * Allocation of "small" objects.
  176023. *
  176024. * For these, we use pooled storage. When a new pool must be created,
  176025. * we try to get enough space for the current request plus a "slop" factor,
  176026. * where the slop will be the amount of leftover space in the new pool.
  176027. * The speed vs. space tradeoff is largely determined by the slop values.
  176028. * A different slop value is provided for each pool class (lifetime),
  176029. * and we also distinguish the first pool of a class from later ones.
  176030. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176031. * machines, but may be too small if longs are 64 bits or more.
  176032. */
  176033. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176034. {
  176035. 1600, /* first PERMANENT pool */
  176036. 16000 /* first IMAGE pool */
  176037. };
  176038. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176039. {
  176040. 0, /* additional PERMANENT pools */
  176041. 5000 /* additional IMAGE pools */
  176042. };
  176043. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176044. METHODDEF(void *)
  176045. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176046. /* Allocate a "small" object */
  176047. {
  176048. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176049. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176050. char * data_ptr;
  176051. size_t odd_bytes, min_request, slop;
  176052. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176053. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176054. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176055. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176056. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176057. if (odd_bytes > 0)
  176058. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176059. /* See if space is available in any existing pool */
  176060. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176061. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176062. prev_hdr_ptr = NULL;
  176063. hdr_ptr = mem->small_list[pool_id];
  176064. while (hdr_ptr != NULL) {
  176065. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176066. break; /* found pool with enough space */
  176067. prev_hdr_ptr = hdr_ptr;
  176068. hdr_ptr = hdr_ptr->hdr.next;
  176069. }
  176070. /* Time to make a new pool? */
  176071. if (hdr_ptr == NULL) {
  176072. /* min_request is what we need now, slop is what will be leftover */
  176073. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176074. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176075. slop = first_pool_slop[pool_id];
  176076. else
  176077. slop = extra_pool_slop[pool_id];
  176078. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176079. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176080. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176081. /* Try to get space, if fail reduce slop and try again */
  176082. for (;;) {
  176083. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176084. if (hdr_ptr != NULL)
  176085. break;
  176086. slop /= 2;
  176087. if (slop < MIN_SLOP) /* give up when it gets real small */
  176088. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176089. }
  176090. mem->total_space_allocated += min_request + slop;
  176091. /* Success, initialize the new pool header and add to end of list */
  176092. hdr_ptr->hdr.next = NULL;
  176093. hdr_ptr->hdr.bytes_used = 0;
  176094. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176095. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176096. mem->small_list[pool_id] = hdr_ptr;
  176097. else
  176098. prev_hdr_ptr->hdr.next = hdr_ptr;
  176099. }
  176100. /* OK, allocate the object from the current pool */
  176101. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176102. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176103. hdr_ptr->hdr.bytes_used += sizeofobject;
  176104. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176105. return (void *) data_ptr;
  176106. }
  176107. /*
  176108. * Allocation of "large" objects.
  176109. *
  176110. * The external semantics of these are the same as "small" objects,
  176111. * except that FAR pointers are used on 80x86. However the pool
  176112. * management heuristics are quite different. We assume that each
  176113. * request is large enough that it may as well be passed directly to
  176114. * jpeg_get_large; the pool management just links everything together
  176115. * so that we can free it all on demand.
  176116. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176117. * structures. The routines that create these structures (see below)
  176118. * deliberately bunch rows together to ensure a large request size.
  176119. */
  176120. METHODDEF(void FAR *)
  176121. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176122. /* Allocate a "large" object */
  176123. {
  176124. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176125. large_pool_ptr hdr_ptr;
  176126. size_t odd_bytes;
  176127. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176128. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176129. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176130. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176131. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176132. if (odd_bytes > 0)
  176133. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176134. /* Always make a new pool */
  176135. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176136. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176137. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176138. SIZEOF(large_pool_hdr));
  176139. if (hdr_ptr == NULL)
  176140. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176141. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176142. /* Success, initialize the new pool header and add to list */
  176143. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176144. /* We maintain space counts in each pool header for statistical purposes,
  176145. * even though they are not needed for allocation.
  176146. */
  176147. hdr_ptr->hdr.bytes_used = sizeofobject;
  176148. hdr_ptr->hdr.bytes_left = 0;
  176149. mem->large_list[pool_id] = hdr_ptr;
  176150. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176151. }
  176152. /*
  176153. * Creation of 2-D sample arrays.
  176154. * The pointers are in near heap, the samples themselves in FAR heap.
  176155. *
  176156. * To minimize allocation overhead and to allow I/O of large contiguous
  176157. * blocks, we allocate the sample rows in groups of as many rows as possible
  176158. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176159. * NB: the virtual array control routines, later in this file, know about
  176160. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176161. * object so that it can be saved away if this sarray is the workspace for
  176162. * a virtual array.
  176163. */
  176164. METHODDEF(JSAMPARRAY)
  176165. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176166. JDIMENSION samplesperrow, JDIMENSION numrows)
  176167. /* Allocate a 2-D sample array */
  176168. {
  176169. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176170. JSAMPARRAY result;
  176171. JSAMPROW workspace;
  176172. JDIMENSION rowsperchunk, currow, i;
  176173. long ltemp;
  176174. /* Calculate max # of rows allowed in one allocation chunk */
  176175. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176176. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176177. if (ltemp <= 0)
  176178. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176179. if (ltemp < (long) numrows)
  176180. rowsperchunk = (JDIMENSION) ltemp;
  176181. else
  176182. rowsperchunk = numrows;
  176183. mem->last_rowsperchunk = rowsperchunk;
  176184. /* Get space for row pointers (small object) */
  176185. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176186. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176187. /* Get the rows themselves (large objects) */
  176188. currow = 0;
  176189. while (currow < numrows) {
  176190. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176191. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176192. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176193. * SIZEOF(JSAMPLE)));
  176194. for (i = rowsperchunk; i > 0; i--) {
  176195. result[currow++] = workspace;
  176196. workspace += samplesperrow;
  176197. }
  176198. }
  176199. return result;
  176200. }
  176201. /*
  176202. * Creation of 2-D coefficient-block arrays.
  176203. * This is essentially the same as the code for sample arrays, above.
  176204. */
  176205. METHODDEF(JBLOCKARRAY)
  176206. alloc_barray (j_common_ptr cinfo, int pool_id,
  176207. JDIMENSION blocksperrow, JDIMENSION numrows)
  176208. /* Allocate a 2-D coefficient-block array */
  176209. {
  176210. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176211. JBLOCKARRAY result;
  176212. JBLOCKROW workspace;
  176213. JDIMENSION rowsperchunk, currow, i;
  176214. long ltemp;
  176215. /* Calculate max # of rows allowed in one allocation chunk */
  176216. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176217. ((long) blocksperrow * SIZEOF(JBLOCK));
  176218. if (ltemp <= 0)
  176219. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176220. if (ltemp < (long) numrows)
  176221. rowsperchunk = (JDIMENSION) ltemp;
  176222. else
  176223. rowsperchunk = numrows;
  176224. mem->last_rowsperchunk = rowsperchunk;
  176225. /* Get space for row pointers (small object) */
  176226. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176227. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176228. /* Get the rows themselves (large objects) */
  176229. currow = 0;
  176230. while (currow < numrows) {
  176231. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176232. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176233. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176234. * SIZEOF(JBLOCK)));
  176235. for (i = rowsperchunk; i > 0; i--) {
  176236. result[currow++] = workspace;
  176237. workspace += blocksperrow;
  176238. }
  176239. }
  176240. return result;
  176241. }
  176242. /*
  176243. * About virtual array management:
  176244. *
  176245. * The above "normal" array routines are only used to allocate strip buffers
  176246. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176247. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176248. * time, but the memory manager must save the whole array for repeated
  176249. * accesses. The intended implementation is that there is a strip buffer in
  176250. * memory (as high as is possible given the desired memory limit), plus a
  176251. * backing file that holds the rest of the array.
  176252. *
  176253. * The request_virt_array routines are told the total size of the image and
  176254. * the maximum number of rows that will be accessed at once. The in-memory
  176255. * buffer must be at least as large as the maxaccess value.
  176256. *
  176257. * The request routines create control blocks but not the in-memory buffers.
  176258. * That is postponed until realize_virt_arrays is called. At that time the
  176259. * total amount of space needed is known (approximately, anyway), so free
  176260. * memory can be divided up fairly.
  176261. *
  176262. * The access_virt_array routines are responsible for making a specific strip
  176263. * area accessible (after reading or writing the backing file, if necessary).
  176264. * Note that the access routines are told whether the caller intends to modify
  176265. * the accessed strip; during a read-only pass this saves having to rewrite
  176266. * data to disk. The access routines are also responsible for pre-zeroing
  176267. * any newly accessed rows, if pre-zeroing was requested.
  176268. *
  176269. * In current usage, the access requests are usually for nonoverlapping
  176270. * strips; that is, successive access start_row numbers differ by exactly
  176271. * num_rows = maxaccess. This means we can get good performance with simple
  176272. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176273. * of the access height; then there will never be accesses across bufferload
  176274. * boundaries. The code will still work with overlapping access requests,
  176275. * but it doesn't handle bufferload overlaps very efficiently.
  176276. */
  176277. METHODDEF(jvirt_sarray_ptr)
  176278. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176279. JDIMENSION samplesperrow, JDIMENSION numrows,
  176280. JDIMENSION maxaccess)
  176281. /* Request a virtual 2-D sample array */
  176282. {
  176283. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176284. jvirt_sarray_ptr result;
  176285. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176286. if (pool_id != JPOOL_IMAGE)
  176287. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176288. /* get control block */
  176289. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176290. SIZEOF(struct jvirt_sarray_control));
  176291. result->mem_buffer = NULL; /* marks array not yet realized */
  176292. result->rows_in_array = numrows;
  176293. result->samplesperrow = samplesperrow;
  176294. result->maxaccess = maxaccess;
  176295. result->pre_zero = pre_zero;
  176296. result->b_s_open = FALSE; /* no associated backing-store object */
  176297. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176298. mem->virt_sarray_list = result;
  176299. return result;
  176300. }
  176301. METHODDEF(jvirt_barray_ptr)
  176302. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176303. JDIMENSION blocksperrow, JDIMENSION numrows,
  176304. JDIMENSION maxaccess)
  176305. /* Request a virtual 2-D coefficient-block array */
  176306. {
  176307. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176308. jvirt_barray_ptr result;
  176309. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176310. if (pool_id != JPOOL_IMAGE)
  176311. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176312. /* get control block */
  176313. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176314. SIZEOF(struct jvirt_barray_control));
  176315. result->mem_buffer = NULL; /* marks array not yet realized */
  176316. result->rows_in_array = numrows;
  176317. result->blocksperrow = blocksperrow;
  176318. result->maxaccess = maxaccess;
  176319. result->pre_zero = pre_zero;
  176320. result->b_s_open = FALSE; /* no associated backing-store object */
  176321. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176322. mem->virt_barray_list = result;
  176323. return result;
  176324. }
  176325. METHODDEF(void)
  176326. realize_virt_arrays (j_common_ptr cinfo)
  176327. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176328. {
  176329. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176330. long space_per_minheight, maximum_space, avail_mem;
  176331. long minheights, max_minheights;
  176332. jvirt_sarray_ptr sptr;
  176333. jvirt_barray_ptr bptr;
  176334. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176335. * and the maximum space needed (full image height in each buffer).
  176336. * These may be of use to the system-dependent jpeg_mem_available routine.
  176337. */
  176338. space_per_minheight = 0;
  176339. maximum_space = 0;
  176340. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176341. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176342. space_per_minheight += (long) sptr->maxaccess *
  176343. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176344. maximum_space += (long) sptr->rows_in_array *
  176345. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176346. }
  176347. }
  176348. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176349. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176350. space_per_minheight += (long) bptr->maxaccess *
  176351. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176352. maximum_space += (long) bptr->rows_in_array *
  176353. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176354. }
  176355. }
  176356. if (space_per_minheight <= 0)
  176357. return; /* no unrealized arrays, no work */
  176358. /* Determine amount of memory to actually use; this is system-dependent. */
  176359. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176360. mem->total_space_allocated);
  176361. /* If the maximum space needed is available, make all the buffers full
  176362. * height; otherwise parcel it out with the same number of minheights
  176363. * in each buffer.
  176364. */
  176365. if (avail_mem >= maximum_space)
  176366. max_minheights = 1000000000L;
  176367. else {
  176368. max_minheights = avail_mem / space_per_minheight;
  176369. /* If there doesn't seem to be enough space, try to get the minimum
  176370. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176371. */
  176372. if (max_minheights <= 0)
  176373. max_minheights = 1;
  176374. }
  176375. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176376. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176377. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176378. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176379. if (minheights <= max_minheights) {
  176380. /* This buffer fits in memory */
  176381. sptr->rows_in_mem = sptr->rows_in_array;
  176382. } else {
  176383. /* It doesn't fit in memory, create backing store. */
  176384. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176385. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176386. (long) sptr->rows_in_array *
  176387. (long) sptr->samplesperrow *
  176388. (long) SIZEOF(JSAMPLE));
  176389. sptr->b_s_open = TRUE;
  176390. }
  176391. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176392. sptr->samplesperrow, sptr->rows_in_mem);
  176393. sptr->rowsperchunk = mem->last_rowsperchunk;
  176394. sptr->cur_start_row = 0;
  176395. sptr->first_undef_row = 0;
  176396. sptr->dirty = FALSE;
  176397. }
  176398. }
  176399. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176400. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176401. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176402. if (minheights <= max_minheights) {
  176403. /* This buffer fits in memory */
  176404. bptr->rows_in_mem = bptr->rows_in_array;
  176405. } else {
  176406. /* It doesn't fit in memory, create backing store. */
  176407. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176408. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176409. (long) bptr->rows_in_array *
  176410. (long) bptr->blocksperrow *
  176411. (long) SIZEOF(JBLOCK));
  176412. bptr->b_s_open = TRUE;
  176413. }
  176414. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176415. bptr->blocksperrow, bptr->rows_in_mem);
  176416. bptr->rowsperchunk = mem->last_rowsperchunk;
  176417. bptr->cur_start_row = 0;
  176418. bptr->first_undef_row = 0;
  176419. bptr->dirty = FALSE;
  176420. }
  176421. }
  176422. }
  176423. LOCAL(void)
  176424. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176425. /* Do backing store read or write of a virtual sample array */
  176426. {
  176427. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176428. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176429. file_offset = ptr->cur_start_row * bytesperrow;
  176430. /* Loop to read or write each allocation chunk in mem_buffer */
  176431. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176432. /* One chunk, but check for short chunk at end of buffer */
  176433. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176434. /* Transfer no more than is currently defined */
  176435. thisrow = (long) ptr->cur_start_row + i;
  176436. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176437. /* Transfer no more than fits in file */
  176438. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176439. if (rows <= 0) /* this chunk might be past end of file! */
  176440. break;
  176441. byte_count = rows * bytesperrow;
  176442. if (writing)
  176443. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176444. (void FAR *) ptr->mem_buffer[i],
  176445. file_offset, byte_count);
  176446. else
  176447. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176448. (void FAR *) ptr->mem_buffer[i],
  176449. file_offset, byte_count);
  176450. file_offset += byte_count;
  176451. }
  176452. }
  176453. LOCAL(void)
  176454. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176455. /* Do backing store read or write of a virtual coefficient-block array */
  176456. {
  176457. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176458. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176459. file_offset = ptr->cur_start_row * bytesperrow;
  176460. /* Loop to read or write each allocation chunk in mem_buffer */
  176461. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176462. /* One chunk, but check for short chunk at end of buffer */
  176463. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176464. /* Transfer no more than is currently defined */
  176465. thisrow = (long) ptr->cur_start_row + i;
  176466. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176467. /* Transfer no more than fits in file */
  176468. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176469. if (rows <= 0) /* this chunk might be past end of file! */
  176470. break;
  176471. byte_count = rows * bytesperrow;
  176472. if (writing)
  176473. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176474. (void FAR *) ptr->mem_buffer[i],
  176475. file_offset, byte_count);
  176476. else
  176477. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176478. (void FAR *) ptr->mem_buffer[i],
  176479. file_offset, byte_count);
  176480. file_offset += byte_count;
  176481. }
  176482. }
  176483. METHODDEF(JSAMPARRAY)
  176484. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176485. JDIMENSION start_row, JDIMENSION num_rows,
  176486. boolean writable)
  176487. /* Access the part of a virtual sample array starting at start_row */
  176488. /* and extending for num_rows rows. writable is true if */
  176489. /* caller intends to modify the accessed area. */
  176490. {
  176491. JDIMENSION end_row = start_row + num_rows;
  176492. JDIMENSION undef_row;
  176493. /* debugging check */
  176494. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176495. ptr->mem_buffer == NULL)
  176496. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176497. /* Make the desired part of the virtual array accessible */
  176498. if (start_row < ptr->cur_start_row ||
  176499. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176500. if (! ptr->b_s_open)
  176501. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176502. /* Flush old buffer contents if necessary */
  176503. if (ptr->dirty) {
  176504. do_sarray_io(cinfo, ptr, TRUE);
  176505. ptr->dirty = FALSE;
  176506. }
  176507. /* Decide what part of virtual array to access.
  176508. * Algorithm: if target address > current window, assume forward scan,
  176509. * load starting at target address. If target address < current window,
  176510. * assume backward scan, load so that target area is top of window.
  176511. * Note that when switching from forward write to forward read, will have
  176512. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176513. */
  176514. if (start_row > ptr->cur_start_row) {
  176515. ptr->cur_start_row = start_row;
  176516. } else {
  176517. /* use long arithmetic here to avoid overflow & unsigned problems */
  176518. long ltemp;
  176519. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176520. if (ltemp < 0)
  176521. ltemp = 0; /* don't fall off front end of file */
  176522. ptr->cur_start_row = (JDIMENSION) ltemp;
  176523. }
  176524. /* Read in the selected part of the array.
  176525. * During the initial write pass, we will do no actual read
  176526. * because the selected part is all undefined.
  176527. */
  176528. do_sarray_io(cinfo, ptr, FALSE);
  176529. }
  176530. /* Ensure the accessed part of the array is defined; prezero if needed.
  176531. * To improve locality of access, we only prezero the part of the array
  176532. * that the caller is about to access, not the entire in-memory array.
  176533. */
  176534. if (ptr->first_undef_row < end_row) {
  176535. if (ptr->first_undef_row < start_row) {
  176536. if (writable) /* writer skipped over a section of array */
  176537. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176538. undef_row = start_row; /* but reader is allowed to read ahead */
  176539. } else {
  176540. undef_row = ptr->first_undef_row;
  176541. }
  176542. if (writable)
  176543. ptr->first_undef_row = end_row;
  176544. if (ptr->pre_zero) {
  176545. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176546. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176547. end_row -= ptr->cur_start_row;
  176548. while (undef_row < end_row) {
  176549. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176550. undef_row++;
  176551. }
  176552. } else {
  176553. if (! writable) /* reader looking at undefined data */
  176554. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176555. }
  176556. }
  176557. /* Flag the buffer dirty if caller will write in it */
  176558. if (writable)
  176559. ptr->dirty = TRUE;
  176560. /* Return address of proper part of the buffer */
  176561. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176562. }
  176563. METHODDEF(JBLOCKARRAY)
  176564. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176565. JDIMENSION start_row, JDIMENSION num_rows,
  176566. boolean writable)
  176567. /* Access the part of a virtual block array starting at start_row */
  176568. /* and extending for num_rows rows. writable is true if */
  176569. /* caller intends to modify the accessed area. */
  176570. {
  176571. JDIMENSION end_row = start_row + num_rows;
  176572. JDIMENSION undef_row;
  176573. /* debugging check */
  176574. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176575. ptr->mem_buffer == NULL)
  176576. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176577. /* Make the desired part of the virtual array accessible */
  176578. if (start_row < ptr->cur_start_row ||
  176579. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176580. if (! ptr->b_s_open)
  176581. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176582. /* Flush old buffer contents if necessary */
  176583. if (ptr->dirty) {
  176584. do_barray_io(cinfo, ptr, TRUE);
  176585. ptr->dirty = FALSE;
  176586. }
  176587. /* Decide what part of virtual array to access.
  176588. * Algorithm: if target address > current window, assume forward scan,
  176589. * load starting at target address. If target address < current window,
  176590. * assume backward scan, load so that target area is top of window.
  176591. * Note that when switching from forward write to forward read, will have
  176592. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176593. */
  176594. if (start_row > ptr->cur_start_row) {
  176595. ptr->cur_start_row = start_row;
  176596. } else {
  176597. /* use long arithmetic here to avoid overflow & unsigned problems */
  176598. long ltemp;
  176599. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176600. if (ltemp < 0)
  176601. ltemp = 0; /* don't fall off front end of file */
  176602. ptr->cur_start_row = (JDIMENSION) ltemp;
  176603. }
  176604. /* Read in the selected part of the array.
  176605. * During the initial write pass, we will do no actual read
  176606. * because the selected part is all undefined.
  176607. */
  176608. do_barray_io(cinfo, ptr, FALSE);
  176609. }
  176610. /* Ensure the accessed part of the array is defined; prezero if needed.
  176611. * To improve locality of access, we only prezero the part of the array
  176612. * that the caller is about to access, not the entire in-memory array.
  176613. */
  176614. if (ptr->first_undef_row < end_row) {
  176615. if (ptr->first_undef_row < start_row) {
  176616. if (writable) /* writer skipped over a section of array */
  176617. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176618. undef_row = start_row; /* but reader is allowed to read ahead */
  176619. } else {
  176620. undef_row = ptr->first_undef_row;
  176621. }
  176622. if (writable)
  176623. ptr->first_undef_row = end_row;
  176624. if (ptr->pre_zero) {
  176625. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176626. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176627. end_row -= ptr->cur_start_row;
  176628. while (undef_row < end_row) {
  176629. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176630. undef_row++;
  176631. }
  176632. } else {
  176633. if (! writable) /* reader looking at undefined data */
  176634. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176635. }
  176636. }
  176637. /* Flag the buffer dirty if caller will write in it */
  176638. if (writable)
  176639. ptr->dirty = TRUE;
  176640. /* Return address of proper part of the buffer */
  176641. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176642. }
  176643. /*
  176644. * Release all objects belonging to a specified pool.
  176645. */
  176646. METHODDEF(void)
  176647. free_pool (j_common_ptr cinfo, int pool_id)
  176648. {
  176649. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176650. small_pool_ptr shdr_ptr;
  176651. large_pool_ptr lhdr_ptr;
  176652. size_t space_freed;
  176653. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176654. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176655. #ifdef MEM_STATS
  176656. if (cinfo->err->trace_level > 1)
  176657. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176658. #endif
  176659. /* If freeing IMAGE pool, close any virtual arrays first */
  176660. if (pool_id == JPOOL_IMAGE) {
  176661. jvirt_sarray_ptr sptr;
  176662. jvirt_barray_ptr bptr;
  176663. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176664. if (sptr->b_s_open) { /* there may be no backing store */
  176665. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176666. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176667. }
  176668. }
  176669. mem->virt_sarray_list = NULL;
  176670. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176671. if (bptr->b_s_open) { /* there may be no backing store */
  176672. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176673. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176674. }
  176675. }
  176676. mem->virt_barray_list = NULL;
  176677. }
  176678. /* Release large objects */
  176679. lhdr_ptr = mem->large_list[pool_id];
  176680. mem->large_list[pool_id] = NULL;
  176681. while (lhdr_ptr != NULL) {
  176682. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176683. space_freed = lhdr_ptr->hdr.bytes_used +
  176684. lhdr_ptr->hdr.bytes_left +
  176685. SIZEOF(large_pool_hdr);
  176686. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176687. mem->total_space_allocated -= space_freed;
  176688. lhdr_ptr = next_lhdr_ptr;
  176689. }
  176690. /* Release small objects */
  176691. shdr_ptr = mem->small_list[pool_id];
  176692. mem->small_list[pool_id] = NULL;
  176693. while (shdr_ptr != NULL) {
  176694. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176695. space_freed = shdr_ptr->hdr.bytes_used +
  176696. shdr_ptr->hdr.bytes_left +
  176697. SIZEOF(small_pool_hdr);
  176698. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176699. mem->total_space_allocated -= space_freed;
  176700. shdr_ptr = next_shdr_ptr;
  176701. }
  176702. }
  176703. /*
  176704. * Close up shop entirely.
  176705. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176706. */
  176707. METHODDEF(void)
  176708. self_destruct (j_common_ptr cinfo)
  176709. {
  176710. int pool;
  176711. /* Close all backing store, release all memory.
  176712. * Releasing pools in reverse order might help avoid fragmentation
  176713. * with some (brain-damaged) malloc libraries.
  176714. */
  176715. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176716. free_pool(cinfo, pool);
  176717. }
  176718. /* Release the memory manager control block too. */
  176719. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176720. cinfo->mem = NULL; /* ensures I will be called only once */
  176721. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176722. }
  176723. /*
  176724. * Memory manager initialization.
  176725. * When this is called, only the error manager pointer is valid in cinfo!
  176726. */
  176727. GLOBAL(void)
  176728. jinit_memory_mgr (j_common_ptr cinfo)
  176729. {
  176730. my_mem_ptr mem;
  176731. long max_to_use;
  176732. int pool;
  176733. size_t test_mac;
  176734. cinfo->mem = NULL; /* for safety if init fails */
  176735. /* Check for configuration errors.
  176736. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176737. * doesn't reflect any real hardware alignment requirement.
  176738. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176739. * in common if and only if X is a power of 2, ie has only one one-bit.
  176740. * Some compilers may give an "unreachable code" warning here; ignore it.
  176741. */
  176742. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176743. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176744. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176745. * a multiple of SIZEOF(ALIGN_TYPE).
  176746. * Again, an "unreachable code" warning may be ignored here.
  176747. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176748. */
  176749. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176750. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176751. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176752. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176753. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176754. /* Attempt to allocate memory manager's control block */
  176755. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176756. if (mem == NULL) {
  176757. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176758. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176759. }
  176760. /* OK, fill in the method pointers */
  176761. mem->pub.alloc_small = alloc_small;
  176762. mem->pub.alloc_large = alloc_large;
  176763. mem->pub.alloc_sarray = alloc_sarray;
  176764. mem->pub.alloc_barray = alloc_barray;
  176765. mem->pub.request_virt_sarray = request_virt_sarray;
  176766. mem->pub.request_virt_barray = request_virt_barray;
  176767. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176768. mem->pub.access_virt_sarray = access_virt_sarray;
  176769. mem->pub.access_virt_barray = access_virt_barray;
  176770. mem->pub.free_pool = free_pool;
  176771. mem->pub.self_destruct = self_destruct;
  176772. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176773. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176774. /* Initialize working state */
  176775. mem->pub.max_memory_to_use = max_to_use;
  176776. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176777. mem->small_list[pool] = NULL;
  176778. mem->large_list[pool] = NULL;
  176779. }
  176780. mem->virt_sarray_list = NULL;
  176781. mem->virt_barray_list = NULL;
  176782. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176783. /* Declare ourselves open for business */
  176784. cinfo->mem = & mem->pub;
  176785. /* Check for an environment variable JPEGMEM; if found, override the
  176786. * default max_memory setting from jpeg_mem_init. Note that the
  176787. * surrounding application may again override this value.
  176788. * If your system doesn't support getenv(), define NO_GETENV to disable
  176789. * this feature.
  176790. */
  176791. #ifndef NO_GETENV
  176792. { char * memenv;
  176793. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176794. char ch = 'x';
  176795. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176796. if (ch == 'm' || ch == 'M')
  176797. max_to_use *= 1000L;
  176798. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176799. }
  176800. }
  176801. }
  176802. #endif
  176803. }
  176804. /*** End of inlined file: jmemmgr.c ***/
  176805. /*** Start of inlined file: jmemnobs.c ***/
  176806. #define JPEG_INTERNALS
  176807. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176808. extern void * malloc JPP((size_t size));
  176809. extern void free JPP((void *ptr));
  176810. #endif
  176811. /*
  176812. * Memory allocation and freeing are controlled by the regular library
  176813. * routines malloc() and free().
  176814. */
  176815. GLOBAL(void *)
  176816. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176817. {
  176818. return (void *) malloc(sizeofobject);
  176819. }
  176820. GLOBAL(void)
  176821. jpeg_free_small (j_common_ptr , void * object, size_t)
  176822. {
  176823. free(object);
  176824. }
  176825. /*
  176826. * "Large" objects are treated the same as "small" ones.
  176827. * NB: although we include FAR keywords in the routine declarations,
  176828. * this file won't actually work in 80x86 small/medium model; at least,
  176829. * you probably won't be able to process useful-size images in only 64KB.
  176830. */
  176831. GLOBAL(void FAR *)
  176832. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176833. {
  176834. return (void FAR *) malloc(sizeofobject);
  176835. }
  176836. GLOBAL(void)
  176837. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176838. {
  176839. free(object);
  176840. }
  176841. /*
  176842. * This routine computes the total memory space available for allocation.
  176843. * Here we always say, "we got all you want bud!"
  176844. */
  176845. GLOBAL(long)
  176846. jpeg_mem_available (j_common_ptr, long,
  176847. long max_bytes_needed, long)
  176848. {
  176849. return max_bytes_needed;
  176850. }
  176851. /*
  176852. * Backing store (temporary file) management.
  176853. * Since jpeg_mem_available always promised the moon,
  176854. * this should never be called and we can just error out.
  176855. */
  176856. GLOBAL(void)
  176857. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176858. long )
  176859. {
  176860. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176861. }
  176862. /*
  176863. * These routines take care of any system-dependent initialization and
  176864. * cleanup required. Here, there isn't any.
  176865. */
  176866. GLOBAL(long)
  176867. jpeg_mem_init (j_common_ptr)
  176868. {
  176869. return 0; /* just set max_memory_to_use to 0 */
  176870. }
  176871. GLOBAL(void)
  176872. jpeg_mem_term (j_common_ptr)
  176873. {
  176874. /* no work */
  176875. }
  176876. /*** End of inlined file: jmemnobs.c ***/
  176877. /*** Start of inlined file: jquant1.c ***/
  176878. #define JPEG_INTERNALS
  176879. #ifdef QUANT_1PASS_SUPPORTED
  176880. /*
  176881. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176882. * high quality, colormapped output capability. A 2-pass quantizer usually
  176883. * gives better visual quality; however, for quantized grayscale output this
  176884. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176885. * quantizer, though you can turn it off if you really want to.
  176886. *
  176887. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176888. * image. We use a map consisting of all combinations of Ncolors[i] color
  176889. * values for the i'th component. The Ncolors[] values are chosen so that
  176890. * their product, the total number of colors, is no more than that requested.
  176891. * (In most cases, the product will be somewhat less.)
  176892. *
  176893. * Since the colormap is orthogonal, the representative value for each color
  176894. * component can be determined without considering the other components;
  176895. * then these indexes can be combined into a colormap index by a standard
  176896. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176897. * can be precalculated and stored in the lookup table colorindex[].
  176898. * colorindex[i][j] maps pixel value j in component i to the nearest
  176899. * representative value (grid plane) for that component; this index is
  176900. * multiplied by the array stride for component i, so that the
  176901. * index of the colormap entry closest to a given pixel value is just
  176902. * sum( colorindex[component-number][pixel-component-value] )
  176903. * Aside from being fast, this scheme allows for variable spacing between
  176904. * representative values with no additional lookup cost.
  176905. *
  176906. * If gamma correction has been applied in color conversion, it might be wise
  176907. * to adjust the color grid spacing so that the representative colors are
  176908. * equidistant in linear space. At this writing, gamma correction is not
  176909. * implemented by jdcolor, so nothing is done here.
  176910. */
  176911. /* Declarations for ordered dithering.
  176912. *
  176913. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176914. * dithering is described in many references, for instance Dale Schumacher's
  176915. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176916. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176917. * "dither" value to the input pixel and then round the result to the nearest
  176918. * output value. The dither value is equivalent to (0.5 - threshold) times
  176919. * the distance between output values. For ordered dithering, we assume that
  176920. * the output colors are equally spaced; if not, results will probably be
  176921. * worse, since the dither may be too much or too little at a given point.
  176922. *
  176923. * The normal calculation would be to form pixel value + dither, range-limit
  176924. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176925. * We can skip the separate range-limiting step by extending the colorindex
  176926. * table in both directions.
  176927. */
  176928. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176929. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176930. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176931. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176932. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176933. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176934. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176935. /* Bayer's order-4 dither array. Generated by the code given in
  176936. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176937. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176938. */
  176939. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176940. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176941. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176942. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176943. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176944. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176945. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176946. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176947. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176948. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176949. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176950. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176951. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176952. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176953. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176954. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176955. };
  176956. /* Declarations for Floyd-Steinberg dithering.
  176957. *
  176958. * Errors are accumulated into the array fserrors[], at a resolution of
  176959. * 1/16th of a pixel count. The error at a given pixel is propagated
  176960. * to its not-yet-processed neighbors using the standard F-S fractions,
  176961. * ... (here) 7/16
  176962. * 3/16 5/16 1/16
  176963. * We work left-to-right on even rows, right-to-left on odd rows.
  176964. *
  176965. * We can get away with a single array (holding one row's worth of errors)
  176966. * by using it to store the current row's errors at pixel columns not yet
  176967. * processed, but the next row's errors at columns already processed. We
  176968. * need only a few extra variables to hold the errors immediately around the
  176969. * current column. (If we are lucky, those variables are in registers, but
  176970. * even if not, they're probably cheaper to access than array elements are.)
  176971. *
  176972. * The fserrors[] array is indexed [component#][position].
  176973. * We provide (#columns + 2) entries per component; the extra entry at each
  176974. * end saves us from special-casing the first and last pixels.
  176975. *
  176976. * Note: on a wide image, we might not have enough room in a PC's near data
  176977. * segment to hold the error array; so it is allocated with alloc_large.
  176978. */
  176979. #if BITS_IN_JSAMPLE == 8
  176980. typedef INT16 FSERROR; /* 16 bits should be enough */
  176981. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176982. #else
  176983. typedef INT32 FSERROR; /* may need more than 16 bits */
  176984. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176985. #endif
  176986. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176987. /* Private subobject */
  176988. #define MAX_Q_COMPS 4 /* max components I can handle */
  176989. typedef struct {
  176990. struct jpeg_color_quantizer pub; /* public fields */
  176991. /* Initially allocated colormap is saved here */
  176992. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176993. int sv_actual; /* number of entries in use */
  176994. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176995. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176996. * premultiplied as described above. Since colormap indexes must fit into
  176997. * JSAMPLEs, the entries of this array will too.
  176998. */
  176999. boolean is_padded; /* is the colorindex padded for odither? */
  177000. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177001. /* Variables for ordered dithering */
  177002. int row_index; /* cur row's vertical index in dither matrix */
  177003. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177004. /* Variables for Floyd-Steinberg dithering */
  177005. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177006. boolean on_odd_row; /* flag to remember which row we are on */
  177007. } my_cquantizer;
  177008. typedef my_cquantizer * my_cquantize_ptr;
  177009. /*
  177010. * Policy-making subroutines for create_colormap and create_colorindex.
  177011. * These routines determine the colormap to be used. The rest of the module
  177012. * only assumes that the colormap is orthogonal.
  177013. *
  177014. * * select_ncolors decides how to divvy up the available colors
  177015. * among the components.
  177016. * * output_value defines the set of representative values for a component.
  177017. * * largest_input_value defines the mapping from input values to
  177018. * representative values for a component.
  177019. * Note that the latter two routines may impose different policies for
  177020. * different components, though this is not currently done.
  177021. */
  177022. LOCAL(int)
  177023. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177024. /* Determine allocation of desired colors to components, */
  177025. /* and fill in Ncolors[] array to indicate choice. */
  177026. /* Return value is total number of colors (product of Ncolors[] values). */
  177027. {
  177028. int nc = cinfo->out_color_components; /* number of color components */
  177029. int max_colors = cinfo->desired_number_of_colors;
  177030. int total_colors, iroot, i, j;
  177031. boolean changed;
  177032. long temp;
  177033. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177034. /* We can allocate at least the nc'th root of max_colors per component. */
  177035. /* Compute floor(nc'th root of max_colors). */
  177036. iroot = 1;
  177037. do {
  177038. iroot++;
  177039. temp = iroot; /* set temp = iroot ** nc */
  177040. for (i = 1; i < nc; i++)
  177041. temp *= iroot;
  177042. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177043. iroot--; /* now iroot = floor(root) */
  177044. /* Must have at least 2 color values per component */
  177045. if (iroot < 2)
  177046. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177047. /* Initialize to iroot color values for each component */
  177048. total_colors = 1;
  177049. for (i = 0; i < nc; i++) {
  177050. Ncolors[i] = iroot;
  177051. total_colors *= iroot;
  177052. }
  177053. /* We may be able to increment the count for one or more components without
  177054. * exceeding max_colors, though we know not all can be incremented.
  177055. * Sometimes, the first component can be incremented more than once!
  177056. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177057. * In RGB colorspace, try to increment G first, then R, then B.
  177058. */
  177059. do {
  177060. changed = FALSE;
  177061. for (i = 0; i < nc; i++) {
  177062. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177063. /* calculate new total_colors if Ncolors[j] is incremented */
  177064. temp = total_colors / Ncolors[j];
  177065. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177066. if (temp > (long) max_colors)
  177067. break; /* won't fit, done with this pass */
  177068. Ncolors[j]++; /* OK, apply the increment */
  177069. total_colors = (int) temp;
  177070. changed = TRUE;
  177071. }
  177072. } while (changed);
  177073. return total_colors;
  177074. }
  177075. LOCAL(int)
  177076. output_value (j_decompress_ptr, int, int j, int maxj)
  177077. /* Return j'th output value, where j will range from 0 to maxj */
  177078. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177079. {
  177080. /* We always provide values 0 and MAXJSAMPLE for each component;
  177081. * any additional values are equally spaced between these limits.
  177082. * (Forcing the upper and lower values to the limits ensures that
  177083. * dithering can't produce a color outside the selected gamut.)
  177084. */
  177085. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177086. }
  177087. LOCAL(int)
  177088. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177089. /* Return largest input value that should map to j'th output value */
  177090. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177091. {
  177092. /* Breakpoints are halfway between values returned by output_value */
  177093. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177094. }
  177095. /*
  177096. * Create the colormap.
  177097. */
  177098. LOCAL(void)
  177099. create_colormap (j_decompress_ptr cinfo)
  177100. {
  177101. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177102. JSAMPARRAY colormap; /* Created colormap */
  177103. int total_colors; /* Number of distinct output colors */
  177104. int i,j,k, nci, blksize, blkdist, ptr, val;
  177105. /* Select number of colors for each component */
  177106. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177107. /* Report selected color counts */
  177108. if (cinfo->out_color_components == 3)
  177109. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177110. total_colors, cquantize->Ncolors[0],
  177111. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177112. else
  177113. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177114. /* Allocate and fill in the colormap. */
  177115. /* The colors are ordered in the map in standard row-major order, */
  177116. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177117. colormap = (*cinfo->mem->alloc_sarray)
  177118. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177119. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177120. /* blksize is number of adjacent repeated entries for a component */
  177121. /* blkdist is distance between groups of identical entries for a component */
  177122. blkdist = total_colors;
  177123. for (i = 0; i < cinfo->out_color_components; i++) {
  177124. /* fill in colormap entries for i'th color component */
  177125. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177126. blksize = blkdist / nci;
  177127. for (j = 0; j < nci; j++) {
  177128. /* Compute j'th output value (out of nci) for component */
  177129. val = output_value(cinfo, i, j, nci-1);
  177130. /* Fill in all colormap entries that have this value of this component */
  177131. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177132. /* fill in blksize entries beginning at ptr */
  177133. for (k = 0; k < blksize; k++)
  177134. colormap[i][ptr+k] = (JSAMPLE) val;
  177135. }
  177136. }
  177137. blkdist = blksize; /* blksize of this color is blkdist of next */
  177138. }
  177139. /* Save the colormap in private storage,
  177140. * where it will survive color quantization mode changes.
  177141. */
  177142. cquantize->sv_colormap = colormap;
  177143. cquantize->sv_actual = total_colors;
  177144. }
  177145. /*
  177146. * Create the color index table.
  177147. */
  177148. LOCAL(void)
  177149. create_colorindex (j_decompress_ptr cinfo)
  177150. {
  177151. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177152. JSAMPROW indexptr;
  177153. int i,j,k, nci, blksize, val, pad;
  177154. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177155. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177156. * This is not necessary in the other dithering modes. However, we
  177157. * flag whether it was done in case user changes dithering mode.
  177158. */
  177159. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177160. pad = MAXJSAMPLE*2;
  177161. cquantize->is_padded = TRUE;
  177162. } else {
  177163. pad = 0;
  177164. cquantize->is_padded = FALSE;
  177165. }
  177166. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177167. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177168. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177169. (JDIMENSION) cinfo->out_color_components);
  177170. /* blksize is number of adjacent repeated entries for a component */
  177171. blksize = cquantize->sv_actual;
  177172. for (i = 0; i < cinfo->out_color_components; i++) {
  177173. /* fill in colorindex entries for i'th color component */
  177174. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177175. blksize = blksize / nci;
  177176. /* adjust colorindex pointers to provide padding at negative indexes. */
  177177. if (pad)
  177178. cquantize->colorindex[i] += MAXJSAMPLE;
  177179. /* in loop, val = index of current output value, */
  177180. /* and k = largest j that maps to current val */
  177181. indexptr = cquantize->colorindex[i];
  177182. val = 0;
  177183. k = largest_input_value(cinfo, i, 0, nci-1);
  177184. for (j = 0; j <= MAXJSAMPLE; j++) {
  177185. while (j > k) /* advance val if past boundary */
  177186. k = largest_input_value(cinfo, i, ++val, nci-1);
  177187. /* premultiply so that no multiplication needed in main processing */
  177188. indexptr[j] = (JSAMPLE) (val * blksize);
  177189. }
  177190. /* Pad at both ends if necessary */
  177191. if (pad)
  177192. for (j = 1; j <= MAXJSAMPLE; j++) {
  177193. indexptr[-j] = indexptr[0];
  177194. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177195. }
  177196. }
  177197. }
  177198. /*
  177199. * Create an ordered-dither array for a component having ncolors
  177200. * distinct output values.
  177201. */
  177202. LOCAL(ODITHER_MATRIX_PTR)
  177203. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177204. {
  177205. ODITHER_MATRIX_PTR odither;
  177206. int j,k;
  177207. INT32 num,den;
  177208. odither = (ODITHER_MATRIX_PTR)
  177209. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177210. SIZEOF(ODITHER_MATRIX));
  177211. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177212. * Hence the dither value for the matrix cell with fill order f
  177213. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177214. * On 16-bit-int machine, be careful to avoid overflow.
  177215. */
  177216. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177217. for (j = 0; j < ODITHER_SIZE; j++) {
  177218. for (k = 0; k < ODITHER_SIZE; k++) {
  177219. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177220. * MAXJSAMPLE;
  177221. /* Ensure round towards zero despite C's lack of consistency
  177222. * about rounding negative values in integer division...
  177223. */
  177224. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177225. }
  177226. }
  177227. return odither;
  177228. }
  177229. /*
  177230. * Create the ordered-dither tables.
  177231. * Components having the same number of representative colors may
  177232. * share a dither table.
  177233. */
  177234. LOCAL(void)
  177235. create_odither_tables (j_decompress_ptr cinfo)
  177236. {
  177237. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177238. ODITHER_MATRIX_PTR odither;
  177239. int i, j, nci;
  177240. for (i = 0; i < cinfo->out_color_components; i++) {
  177241. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177242. odither = NULL; /* search for matching prior component */
  177243. for (j = 0; j < i; j++) {
  177244. if (nci == cquantize->Ncolors[j]) {
  177245. odither = cquantize->odither[j];
  177246. break;
  177247. }
  177248. }
  177249. if (odither == NULL) /* need a new table? */
  177250. odither = make_odither_array(cinfo, nci);
  177251. cquantize->odither[i] = odither;
  177252. }
  177253. }
  177254. /*
  177255. * Map some rows of pixels to the output colormapped representation.
  177256. */
  177257. METHODDEF(void)
  177258. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177259. JSAMPARRAY output_buf, int num_rows)
  177260. /* General case, no dithering */
  177261. {
  177262. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177263. JSAMPARRAY colorindex = cquantize->colorindex;
  177264. register int pixcode, ci;
  177265. register JSAMPROW ptrin, ptrout;
  177266. int row;
  177267. JDIMENSION col;
  177268. JDIMENSION width = cinfo->output_width;
  177269. register int nc = cinfo->out_color_components;
  177270. for (row = 0; row < num_rows; row++) {
  177271. ptrin = input_buf[row];
  177272. ptrout = output_buf[row];
  177273. for (col = width; col > 0; col--) {
  177274. pixcode = 0;
  177275. for (ci = 0; ci < nc; ci++) {
  177276. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177277. }
  177278. *ptrout++ = (JSAMPLE) pixcode;
  177279. }
  177280. }
  177281. }
  177282. METHODDEF(void)
  177283. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177284. JSAMPARRAY output_buf, int num_rows)
  177285. /* Fast path for out_color_components==3, no dithering */
  177286. {
  177287. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177288. register int pixcode;
  177289. register JSAMPROW ptrin, ptrout;
  177290. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177291. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177292. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177293. int row;
  177294. JDIMENSION col;
  177295. JDIMENSION width = cinfo->output_width;
  177296. for (row = 0; row < num_rows; row++) {
  177297. ptrin = input_buf[row];
  177298. ptrout = output_buf[row];
  177299. for (col = width; col > 0; col--) {
  177300. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177301. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177302. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177303. *ptrout++ = (JSAMPLE) pixcode;
  177304. }
  177305. }
  177306. }
  177307. METHODDEF(void)
  177308. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177309. JSAMPARRAY output_buf, int num_rows)
  177310. /* General case, with ordered dithering */
  177311. {
  177312. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177313. register JSAMPROW input_ptr;
  177314. register JSAMPROW output_ptr;
  177315. JSAMPROW colorindex_ci;
  177316. int * dither; /* points to active row of dither matrix */
  177317. int row_index, col_index; /* current indexes into dither matrix */
  177318. int nc = cinfo->out_color_components;
  177319. int ci;
  177320. int row;
  177321. JDIMENSION col;
  177322. JDIMENSION width = cinfo->output_width;
  177323. for (row = 0; row < num_rows; row++) {
  177324. /* Initialize output values to 0 so can process components separately */
  177325. jzero_far((void FAR *) output_buf[row],
  177326. (size_t) (width * SIZEOF(JSAMPLE)));
  177327. row_index = cquantize->row_index;
  177328. for (ci = 0; ci < nc; ci++) {
  177329. input_ptr = input_buf[row] + ci;
  177330. output_ptr = output_buf[row];
  177331. colorindex_ci = cquantize->colorindex[ci];
  177332. dither = cquantize->odither[ci][row_index];
  177333. col_index = 0;
  177334. for (col = width; col > 0; col--) {
  177335. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177336. * select output value, accumulate into output code for this pixel.
  177337. * Range-limiting need not be done explicitly, as we have extended
  177338. * the colorindex table to produce the right answers for out-of-range
  177339. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177340. * required amount of padding.
  177341. */
  177342. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177343. input_ptr += nc;
  177344. output_ptr++;
  177345. col_index = (col_index + 1) & ODITHER_MASK;
  177346. }
  177347. }
  177348. /* Advance row index for next row */
  177349. row_index = (row_index + 1) & ODITHER_MASK;
  177350. cquantize->row_index = row_index;
  177351. }
  177352. }
  177353. METHODDEF(void)
  177354. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177355. JSAMPARRAY output_buf, int num_rows)
  177356. /* Fast path for out_color_components==3, with ordered dithering */
  177357. {
  177358. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177359. register int pixcode;
  177360. register JSAMPROW input_ptr;
  177361. register JSAMPROW output_ptr;
  177362. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177363. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177364. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177365. int * dither0; /* points to active row of dither matrix */
  177366. int * dither1;
  177367. int * dither2;
  177368. int row_index, col_index; /* current indexes into dither matrix */
  177369. int row;
  177370. JDIMENSION col;
  177371. JDIMENSION width = cinfo->output_width;
  177372. for (row = 0; row < num_rows; row++) {
  177373. row_index = cquantize->row_index;
  177374. input_ptr = input_buf[row];
  177375. output_ptr = output_buf[row];
  177376. dither0 = cquantize->odither[0][row_index];
  177377. dither1 = cquantize->odither[1][row_index];
  177378. dither2 = cquantize->odither[2][row_index];
  177379. col_index = 0;
  177380. for (col = width; col > 0; col--) {
  177381. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177382. dither0[col_index]]);
  177383. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177384. dither1[col_index]]);
  177385. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177386. dither2[col_index]]);
  177387. *output_ptr++ = (JSAMPLE) pixcode;
  177388. col_index = (col_index + 1) & ODITHER_MASK;
  177389. }
  177390. row_index = (row_index + 1) & ODITHER_MASK;
  177391. cquantize->row_index = row_index;
  177392. }
  177393. }
  177394. METHODDEF(void)
  177395. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177396. JSAMPARRAY output_buf, int num_rows)
  177397. /* General case, with Floyd-Steinberg dithering */
  177398. {
  177399. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177400. register LOCFSERROR cur; /* current error or pixel value */
  177401. LOCFSERROR belowerr; /* error for pixel below cur */
  177402. LOCFSERROR bpreverr; /* error for below/prev col */
  177403. LOCFSERROR bnexterr; /* error for below/next col */
  177404. LOCFSERROR delta;
  177405. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177406. register JSAMPROW input_ptr;
  177407. register JSAMPROW output_ptr;
  177408. JSAMPROW colorindex_ci;
  177409. JSAMPROW colormap_ci;
  177410. int pixcode;
  177411. int nc = cinfo->out_color_components;
  177412. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177413. int dirnc; /* dir * nc */
  177414. int ci;
  177415. int row;
  177416. JDIMENSION col;
  177417. JDIMENSION width = cinfo->output_width;
  177418. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177419. SHIFT_TEMPS
  177420. for (row = 0; row < num_rows; row++) {
  177421. /* Initialize output values to 0 so can process components separately */
  177422. jzero_far((void FAR *) output_buf[row],
  177423. (size_t) (width * SIZEOF(JSAMPLE)));
  177424. for (ci = 0; ci < nc; ci++) {
  177425. input_ptr = input_buf[row] + ci;
  177426. output_ptr = output_buf[row];
  177427. if (cquantize->on_odd_row) {
  177428. /* work right to left in this row */
  177429. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177430. output_ptr += width-1;
  177431. dir = -1;
  177432. dirnc = -nc;
  177433. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177434. } else {
  177435. /* work left to right in this row */
  177436. dir = 1;
  177437. dirnc = nc;
  177438. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177439. }
  177440. colorindex_ci = cquantize->colorindex[ci];
  177441. colormap_ci = cquantize->sv_colormap[ci];
  177442. /* Preset error values: no error propagated to first pixel from left */
  177443. cur = 0;
  177444. /* and no error propagated to row below yet */
  177445. belowerr = bpreverr = 0;
  177446. for (col = width; col > 0; col--) {
  177447. /* cur holds the error propagated from the previous pixel on the
  177448. * current line. Add the error propagated from the previous line
  177449. * to form the complete error correction term for this pixel, and
  177450. * round the error term (which is expressed * 16) to an integer.
  177451. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177452. * for either sign of the error value.
  177453. * Note: errorptr points to *previous* column's array entry.
  177454. */
  177455. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177456. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177457. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177458. * of the range_limit array.
  177459. */
  177460. cur += GETJSAMPLE(*input_ptr);
  177461. cur = GETJSAMPLE(range_limit[cur]);
  177462. /* Select output value, accumulate into output code for this pixel */
  177463. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177464. *output_ptr += (JSAMPLE) pixcode;
  177465. /* Compute actual representation error at this pixel */
  177466. /* Note: we can do this even though we don't have the final */
  177467. /* pixel code, because the colormap is orthogonal. */
  177468. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177469. /* Compute error fractions to be propagated to adjacent pixels.
  177470. * Add these into the running sums, and simultaneously shift the
  177471. * next-line error sums left by 1 column.
  177472. */
  177473. bnexterr = cur;
  177474. delta = cur * 2;
  177475. cur += delta; /* form error * 3 */
  177476. errorptr[0] = (FSERROR) (bpreverr + cur);
  177477. cur += delta; /* form error * 5 */
  177478. bpreverr = belowerr + cur;
  177479. belowerr = bnexterr;
  177480. cur += delta; /* form error * 7 */
  177481. /* At this point cur contains the 7/16 error value to be propagated
  177482. * to the next pixel on the current line, and all the errors for the
  177483. * next line have been shifted over. We are therefore ready to move on.
  177484. */
  177485. input_ptr += dirnc; /* advance input ptr to next column */
  177486. output_ptr += dir; /* advance output ptr to next column */
  177487. errorptr += dir; /* advance errorptr to current column */
  177488. }
  177489. /* Post-loop cleanup: we must unload the final error value into the
  177490. * final fserrors[] entry. Note we need not unload belowerr because
  177491. * it is for the dummy column before or after the actual array.
  177492. */
  177493. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177494. }
  177495. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177496. }
  177497. }
  177498. /*
  177499. * Allocate workspace for Floyd-Steinberg errors.
  177500. */
  177501. LOCAL(void)
  177502. alloc_fs_workspace (j_decompress_ptr cinfo)
  177503. {
  177504. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177505. size_t arraysize;
  177506. int i;
  177507. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177508. for (i = 0; i < cinfo->out_color_components; i++) {
  177509. cquantize->fserrors[i] = (FSERRPTR)
  177510. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177511. }
  177512. }
  177513. /*
  177514. * Initialize for one-pass color quantization.
  177515. */
  177516. METHODDEF(void)
  177517. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177518. {
  177519. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177520. size_t arraysize;
  177521. int i;
  177522. /* Install my colormap. */
  177523. cinfo->colormap = cquantize->sv_colormap;
  177524. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177525. /* Initialize for desired dithering mode. */
  177526. switch (cinfo->dither_mode) {
  177527. case JDITHER_NONE:
  177528. if (cinfo->out_color_components == 3)
  177529. cquantize->pub.color_quantize = color_quantize3;
  177530. else
  177531. cquantize->pub.color_quantize = color_quantize;
  177532. break;
  177533. case JDITHER_ORDERED:
  177534. if (cinfo->out_color_components == 3)
  177535. cquantize->pub.color_quantize = quantize3_ord_dither;
  177536. else
  177537. cquantize->pub.color_quantize = quantize_ord_dither;
  177538. cquantize->row_index = 0; /* initialize state for ordered dither */
  177539. /* If user changed to ordered dither from another mode,
  177540. * we must recreate the color index table with padding.
  177541. * This will cost extra space, but probably isn't very likely.
  177542. */
  177543. if (! cquantize->is_padded)
  177544. create_colorindex(cinfo);
  177545. /* Create ordered-dither tables if we didn't already. */
  177546. if (cquantize->odither[0] == NULL)
  177547. create_odither_tables(cinfo);
  177548. break;
  177549. case JDITHER_FS:
  177550. cquantize->pub.color_quantize = quantize_fs_dither;
  177551. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177552. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177553. if (cquantize->fserrors[0] == NULL)
  177554. alloc_fs_workspace(cinfo);
  177555. /* Initialize the propagated errors to zero. */
  177556. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177557. for (i = 0; i < cinfo->out_color_components; i++)
  177558. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177559. break;
  177560. default:
  177561. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177562. break;
  177563. }
  177564. }
  177565. /*
  177566. * Finish up at the end of the pass.
  177567. */
  177568. METHODDEF(void)
  177569. finish_pass_1_quant (j_decompress_ptr)
  177570. {
  177571. /* no work in 1-pass case */
  177572. }
  177573. /*
  177574. * Switch to a new external colormap between output passes.
  177575. * Shouldn't get to this module!
  177576. */
  177577. METHODDEF(void)
  177578. new_color_map_1_quant (j_decompress_ptr cinfo)
  177579. {
  177580. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177581. }
  177582. /*
  177583. * Module initialization routine for 1-pass color quantization.
  177584. */
  177585. GLOBAL(void)
  177586. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177587. {
  177588. my_cquantize_ptr cquantize;
  177589. cquantize = (my_cquantize_ptr)
  177590. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177591. SIZEOF(my_cquantizer));
  177592. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177593. cquantize->pub.start_pass = start_pass_1_quant;
  177594. cquantize->pub.finish_pass = finish_pass_1_quant;
  177595. cquantize->pub.new_color_map = new_color_map_1_quant;
  177596. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177597. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177598. /* Make sure my internal arrays won't overflow */
  177599. if (cinfo->out_color_components > MAX_Q_COMPS)
  177600. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177601. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177602. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177603. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177604. /* Create the colormap and color index table. */
  177605. create_colormap(cinfo);
  177606. create_colorindex(cinfo);
  177607. /* Allocate Floyd-Steinberg workspace now if requested.
  177608. * We do this now since it is FAR storage and may affect the memory
  177609. * manager's space calculations. If the user changes to FS dither
  177610. * mode in a later pass, we will allocate the space then, and will
  177611. * possibly overrun the max_memory_to_use setting.
  177612. */
  177613. if (cinfo->dither_mode == JDITHER_FS)
  177614. alloc_fs_workspace(cinfo);
  177615. }
  177616. #endif /* QUANT_1PASS_SUPPORTED */
  177617. /*** End of inlined file: jquant1.c ***/
  177618. /*** Start of inlined file: jquant2.c ***/
  177619. #define JPEG_INTERNALS
  177620. #ifdef QUANT_2PASS_SUPPORTED
  177621. /*
  177622. * This module implements the well-known Heckbert paradigm for color
  177623. * quantization. Most of the ideas used here can be traced back to
  177624. * Heckbert's seminal paper
  177625. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177626. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177627. *
  177628. * In the first pass over the image, we accumulate a histogram showing the
  177629. * usage count of each possible color. To keep the histogram to a reasonable
  177630. * size, we reduce the precision of the input; typical practice is to retain
  177631. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177632. * in the same histogram cell.
  177633. *
  177634. * Next, the color-selection step begins with a box representing the whole
  177635. * color space, and repeatedly splits the "largest" remaining box until we
  177636. * have as many boxes as desired colors. Then the mean color in each
  177637. * remaining box becomes one of the possible output colors.
  177638. *
  177639. * The second pass over the image maps each input pixel to the closest output
  177640. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177641. * This mapping is logically trivial, but making it go fast enough requires
  177642. * considerable care.
  177643. *
  177644. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177645. * the "largest" box and deciding where to cut it. The particular policies
  177646. * used here have proved out well in experimental comparisons, but better ones
  177647. * may yet be found.
  177648. *
  177649. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177650. * space, processing the raw upsampled data without a color conversion step.
  177651. * This allowed the color conversion math to be done only once per colormap
  177652. * entry, not once per pixel. However, that optimization precluded other
  177653. * useful optimizations (such as merging color conversion with upsampling)
  177654. * and it also interfered with desired capabilities such as quantizing to an
  177655. * externally-supplied colormap. We have therefore abandoned that approach.
  177656. * The present code works in the post-conversion color space, typically RGB.
  177657. *
  177658. * To improve the visual quality of the results, we actually work in scaled
  177659. * RGB space, giving G distances more weight than R, and R in turn more than
  177660. * B. To do everything in integer math, we must use integer scale factors.
  177661. * The 2/3/1 scale factors used here correspond loosely to the relative
  177662. * weights of the colors in the NTSC grayscale equation.
  177663. * If you want to use this code to quantize a non-RGB color space, you'll
  177664. * probably need to change these scale factors.
  177665. */
  177666. #define R_SCALE 2 /* scale R distances by this much */
  177667. #define G_SCALE 3 /* scale G distances by this much */
  177668. #define B_SCALE 1 /* and B by this much */
  177669. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177670. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177671. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177672. * you'll get compile errors until you extend this logic. In that case
  177673. * you'll probably want to tweak the histogram sizes too.
  177674. */
  177675. #if RGB_RED == 0
  177676. #define C0_SCALE R_SCALE
  177677. #endif
  177678. #if RGB_BLUE == 0
  177679. #define C0_SCALE B_SCALE
  177680. #endif
  177681. #if RGB_GREEN == 1
  177682. #define C1_SCALE G_SCALE
  177683. #endif
  177684. #if RGB_RED == 2
  177685. #define C2_SCALE R_SCALE
  177686. #endif
  177687. #if RGB_BLUE == 2
  177688. #define C2_SCALE B_SCALE
  177689. #endif
  177690. /*
  177691. * First we have the histogram data structure and routines for creating it.
  177692. *
  177693. * The number of bits of precision can be adjusted by changing these symbols.
  177694. * We recommend keeping 6 bits for G and 5 each for R and B.
  177695. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177696. * better results; if you are short of memory, 5 bits all around will save
  177697. * some space but degrade the results.
  177698. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177699. * (preferably unsigned long) for each cell. In practice this is overkill;
  177700. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177701. * and clamping those that do overflow to the maximum value will give close-
  177702. * enough results. This reduces the recommended histogram size from 256Kb
  177703. * to 128Kb, which is a useful savings on PC-class machines.
  177704. * (In the second pass the histogram space is re-used for pixel mapping data;
  177705. * in that capacity, each cell must be able to store zero to the number of
  177706. * desired colors. 16 bits/cell is plenty for that too.)
  177707. * Since the JPEG code is intended to run in small memory model on 80x86
  177708. * machines, we can't just allocate the histogram in one chunk. Instead
  177709. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177710. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177711. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177712. * on 80x86 machines, the pointer row is in near memory but the actual
  177713. * arrays are in far memory (same arrangement as we use for image arrays).
  177714. */
  177715. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177716. /* These will do the right thing for either R,G,B or B,G,R color order,
  177717. * but you may not like the results for other color orders.
  177718. */
  177719. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177720. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177721. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177722. /* Number of elements along histogram axes. */
  177723. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177724. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177725. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177726. /* These are the amounts to shift an input value to get a histogram index. */
  177727. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177728. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177729. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177730. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177731. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177732. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177733. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177734. typedef hist2d * hist3d; /* type for top-level pointer */
  177735. /* Declarations for Floyd-Steinberg dithering.
  177736. *
  177737. * Errors are accumulated into the array fserrors[], at a resolution of
  177738. * 1/16th of a pixel count. The error at a given pixel is propagated
  177739. * to its not-yet-processed neighbors using the standard F-S fractions,
  177740. * ... (here) 7/16
  177741. * 3/16 5/16 1/16
  177742. * We work left-to-right on even rows, right-to-left on odd rows.
  177743. *
  177744. * We can get away with a single array (holding one row's worth of errors)
  177745. * by using it to store the current row's errors at pixel columns not yet
  177746. * processed, but the next row's errors at columns already processed. We
  177747. * need only a few extra variables to hold the errors immediately around the
  177748. * current column. (If we are lucky, those variables are in registers, but
  177749. * even if not, they're probably cheaper to access than array elements are.)
  177750. *
  177751. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177752. * each end saves us from special-casing the first and last pixels.
  177753. * Each entry is three values long, one value for each color component.
  177754. *
  177755. * Note: on a wide image, we might not have enough room in a PC's near data
  177756. * segment to hold the error array; so it is allocated with alloc_large.
  177757. */
  177758. #if BITS_IN_JSAMPLE == 8
  177759. typedef INT16 FSERROR; /* 16 bits should be enough */
  177760. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177761. #else
  177762. typedef INT32 FSERROR; /* may need more than 16 bits */
  177763. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177764. #endif
  177765. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177766. /* Private subobject */
  177767. typedef struct {
  177768. struct jpeg_color_quantizer pub; /* public fields */
  177769. /* Space for the eventually created colormap is stashed here */
  177770. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177771. int desired; /* desired # of colors = size of colormap */
  177772. /* Variables for accumulating image statistics */
  177773. hist3d histogram; /* pointer to the histogram */
  177774. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177775. /* Variables for Floyd-Steinberg dithering */
  177776. FSERRPTR fserrors; /* accumulated errors */
  177777. boolean on_odd_row; /* flag to remember which row we are on */
  177778. int * error_limiter; /* table for clamping the applied error */
  177779. } my_cquantizer2;
  177780. typedef my_cquantizer2 * my_cquantize_ptr2;
  177781. /*
  177782. * Prescan some rows of pixels.
  177783. * In this module the prescan simply updates the histogram, which has been
  177784. * initialized to zeroes by start_pass.
  177785. * An output_buf parameter is required by the method signature, but no data
  177786. * is actually output (in fact the buffer controller is probably passing a
  177787. * NULL pointer).
  177788. */
  177789. METHODDEF(void)
  177790. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177791. JSAMPARRAY, int num_rows)
  177792. {
  177793. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177794. register JSAMPROW ptr;
  177795. register histptr histp;
  177796. register hist3d histogram = cquantize->histogram;
  177797. int row;
  177798. JDIMENSION col;
  177799. JDIMENSION width = cinfo->output_width;
  177800. for (row = 0; row < num_rows; row++) {
  177801. ptr = input_buf[row];
  177802. for (col = width; col > 0; col--) {
  177803. /* get pixel value and index into the histogram */
  177804. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177805. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177806. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177807. /* increment, check for overflow and undo increment if so. */
  177808. if (++(*histp) <= 0)
  177809. (*histp)--;
  177810. ptr += 3;
  177811. }
  177812. }
  177813. }
  177814. /*
  177815. * Next we have the really interesting routines: selection of a colormap
  177816. * given the completed histogram.
  177817. * These routines work with a list of "boxes", each representing a rectangular
  177818. * subset of the input color space (to histogram precision).
  177819. */
  177820. typedef struct {
  177821. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177822. int c0min, c0max;
  177823. int c1min, c1max;
  177824. int c2min, c2max;
  177825. /* The volume (actually 2-norm) of the box */
  177826. INT32 volume;
  177827. /* The number of nonzero histogram cells within this box */
  177828. long colorcount;
  177829. } box;
  177830. typedef box * boxptr;
  177831. LOCAL(boxptr)
  177832. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177833. /* Find the splittable box with the largest color population */
  177834. /* Returns NULL if no splittable boxes remain */
  177835. {
  177836. register boxptr boxp;
  177837. register int i;
  177838. register long maxc = 0;
  177839. boxptr which = NULL;
  177840. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177841. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177842. which = boxp;
  177843. maxc = boxp->colorcount;
  177844. }
  177845. }
  177846. return which;
  177847. }
  177848. LOCAL(boxptr)
  177849. find_biggest_volume (boxptr boxlist, int numboxes)
  177850. /* Find the splittable box with the largest (scaled) volume */
  177851. /* Returns NULL if no splittable boxes remain */
  177852. {
  177853. register boxptr boxp;
  177854. register int i;
  177855. register INT32 maxv = 0;
  177856. boxptr which = NULL;
  177857. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177858. if (boxp->volume > maxv) {
  177859. which = boxp;
  177860. maxv = boxp->volume;
  177861. }
  177862. }
  177863. return which;
  177864. }
  177865. LOCAL(void)
  177866. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177867. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177868. /* and recompute its volume and population */
  177869. {
  177870. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177871. hist3d histogram = cquantize->histogram;
  177872. histptr histp;
  177873. int c0,c1,c2;
  177874. int c0min,c0max,c1min,c1max,c2min,c2max;
  177875. INT32 dist0,dist1,dist2;
  177876. long ccount;
  177877. c0min = boxp->c0min; c0max = boxp->c0max;
  177878. c1min = boxp->c1min; c1max = boxp->c1max;
  177879. c2min = boxp->c2min; c2max = boxp->c2max;
  177880. if (c0max > c0min)
  177881. for (c0 = c0min; c0 <= c0max; c0++)
  177882. for (c1 = c1min; c1 <= c1max; c1++) {
  177883. histp = & histogram[c0][c1][c2min];
  177884. for (c2 = c2min; c2 <= c2max; c2++)
  177885. if (*histp++ != 0) {
  177886. boxp->c0min = c0min = c0;
  177887. goto have_c0min;
  177888. }
  177889. }
  177890. have_c0min:
  177891. if (c0max > c0min)
  177892. for (c0 = c0max; c0 >= c0min; c0--)
  177893. for (c1 = c1min; c1 <= c1max; c1++) {
  177894. histp = & histogram[c0][c1][c2min];
  177895. for (c2 = c2min; c2 <= c2max; c2++)
  177896. if (*histp++ != 0) {
  177897. boxp->c0max = c0max = c0;
  177898. goto have_c0max;
  177899. }
  177900. }
  177901. have_c0max:
  177902. if (c1max > c1min)
  177903. for (c1 = c1min; c1 <= c1max; c1++)
  177904. for (c0 = c0min; c0 <= c0max; c0++) {
  177905. histp = & histogram[c0][c1][c2min];
  177906. for (c2 = c2min; c2 <= c2max; c2++)
  177907. if (*histp++ != 0) {
  177908. boxp->c1min = c1min = c1;
  177909. goto have_c1min;
  177910. }
  177911. }
  177912. have_c1min:
  177913. if (c1max > c1min)
  177914. for (c1 = c1max; c1 >= c1min; c1--)
  177915. for (c0 = c0min; c0 <= c0max; c0++) {
  177916. histp = & histogram[c0][c1][c2min];
  177917. for (c2 = c2min; c2 <= c2max; c2++)
  177918. if (*histp++ != 0) {
  177919. boxp->c1max = c1max = c1;
  177920. goto have_c1max;
  177921. }
  177922. }
  177923. have_c1max:
  177924. if (c2max > c2min)
  177925. for (c2 = c2min; c2 <= c2max; c2++)
  177926. for (c0 = c0min; c0 <= c0max; c0++) {
  177927. histp = & histogram[c0][c1min][c2];
  177928. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177929. if (*histp != 0) {
  177930. boxp->c2min = c2min = c2;
  177931. goto have_c2min;
  177932. }
  177933. }
  177934. have_c2min:
  177935. if (c2max > c2min)
  177936. for (c2 = c2max; c2 >= c2min; c2--)
  177937. for (c0 = c0min; c0 <= c0max; c0++) {
  177938. histp = & histogram[c0][c1min][c2];
  177939. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177940. if (*histp != 0) {
  177941. boxp->c2max = c2max = c2;
  177942. goto have_c2max;
  177943. }
  177944. }
  177945. have_c2max:
  177946. /* Update box volume.
  177947. * We use 2-norm rather than real volume here; this biases the method
  177948. * against making long narrow boxes, and it has the side benefit that
  177949. * a box is splittable iff norm > 0.
  177950. * Since the differences are expressed in histogram-cell units,
  177951. * we have to shift back to JSAMPLE units to get consistent distances;
  177952. * after which, we scale according to the selected distance scale factors.
  177953. */
  177954. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177955. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177956. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177957. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177958. /* Now scan remaining volume of box and compute population */
  177959. ccount = 0;
  177960. for (c0 = c0min; c0 <= c0max; c0++)
  177961. for (c1 = c1min; c1 <= c1max; c1++) {
  177962. histp = & histogram[c0][c1][c2min];
  177963. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177964. if (*histp != 0) {
  177965. ccount++;
  177966. }
  177967. }
  177968. boxp->colorcount = ccount;
  177969. }
  177970. LOCAL(int)
  177971. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177972. int desired_colors)
  177973. /* Repeatedly select and split the largest box until we have enough boxes */
  177974. {
  177975. int n,lb;
  177976. int c0,c1,c2,cmax;
  177977. register boxptr b1,b2;
  177978. while (numboxes < desired_colors) {
  177979. /* Select box to split.
  177980. * Current algorithm: by population for first half, then by volume.
  177981. */
  177982. if (numboxes*2 <= desired_colors) {
  177983. b1 = find_biggest_color_pop(boxlist, numboxes);
  177984. } else {
  177985. b1 = find_biggest_volume(boxlist, numboxes);
  177986. }
  177987. if (b1 == NULL) /* no splittable boxes left! */
  177988. break;
  177989. b2 = &boxlist[numboxes]; /* where new box will go */
  177990. /* Copy the color bounds to the new box. */
  177991. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177992. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177993. /* Choose which axis to split the box on.
  177994. * Current algorithm: longest scaled axis.
  177995. * See notes in update_box about scaling distances.
  177996. */
  177997. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177998. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177999. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178000. /* We want to break any ties in favor of green, then red, blue last.
  178001. * This code does the right thing for R,G,B or B,G,R color orders only.
  178002. */
  178003. #if RGB_RED == 0
  178004. cmax = c1; n = 1;
  178005. if (c0 > cmax) { cmax = c0; n = 0; }
  178006. if (c2 > cmax) { n = 2; }
  178007. #else
  178008. cmax = c1; n = 1;
  178009. if (c2 > cmax) { cmax = c2; n = 2; }
  178010. if (c0 > cmax) { n = 0; }
  178011. #endif
  178012. /* Choose split point along selected axis, and update box bounds.
  178013. * Current algorithm: split at halfway point.
  178014. * (Since the box has been shrunk to minimum volume,
  178015. * any split will produce two nonempty subboxes.)
  178016. * Note that lb value is max for lower box, so must be < old max.
  178017. */
  178018. switch (n) {
  178019. case 0:
  178020. lb = (b1->c0max + b1->c0min) / 2;
  178021. b1->c0max = lb;
  178022. b2->c0min = lb+1;
  178023. break;
  178024. case 1:
  178025. lb = (b1->c1max + b1->c1min) / 2;
  178026. b1->c1max = lb;
  178027. b2->c1min = lb+1;
  178028. break;
  178029. case 2:
  178030. lb = (b1->c2max + b1->c2min) / 2;
  178031. b1->c2max = lb;
  178032. b2->c2min = lb+1;
  178033. break;
  178034. }
  178035. /* Update stats for boxes */
  178036. update_box(cinfo, b1);
  178037. update_box(cinfo, b2);
  178038. numboxes++;
  178039. }
  178040. return numboxes;
  178041. }
  178042. LOCAL(void)
  178043. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178044. /* Compute representative color for a box, put it in colormap[icolor] */
  178045. {
  178046. /* Current algorithm: mean weighted by pixels (not colors) */
  178047. /* Note it is important to get the rounding correct! */
  178048. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178049. hist3d histogram = cquantize->histogram;
  178050. histptr histp;
  178051. int c0,c1,c2;
  178052. int c0min,c0max,c1min,c1max,c2min,c2max;
  178053. long count;
  178054. long total = 0;
  178055. long c0total = 0;
  178056. long c1total = 0;
  178057. long c2total = 0;
  178058. c0min = boxp->c0min; c0max = boxp->c0max;
  178059. c1min = boxp->c1min; c1max = boxp->c1max;
  178060. c2min = boxp->c2min; c2max = boxp->c2max;
  178061. for (c0 = c0min; c0 <= c0max; c0++)
  178062. for (c1 = c1min; c1 <= c1max; c1++) {
  178063. histp = & histogram[c0][c1][c2min];
  178064. for (c2 = c2min; c2 <= c2max; c2++) {
  178065. if ((count = *histp++) != 0) {
  178066. total += count;
  178067. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178068. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178069. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178070. }
  178071. }
  178072. }
  178073. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178074. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178075. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178076. }
  178077. LOCAL(void)
  178078. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178079. /* Master routine for color selection */
  178080. {
  178081. boxptr boxlist;
  178082. int numboxes;
  178083. int i;
  178084. /* Allocate workspace for box list */
  178085. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178086. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178087. /* Initialize one box containing whole space */
  178088. numboxes = 1;
  178089. boxlist[0].c0min = 0;
  178090. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178091. boxlist[0].c1min = 0;
  178092. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178093. boxlist[0].c2min = 0;
  178094. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178095. /* Shrink it to actually-used volume and set its statistics */
  178096. update_box(cinfo, & boxlist[0]);
  178097. /* Perform median-cut to produce final box list */
  178098. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178099. /* Compute the representative color for each box, fill colormap */
  178100. for (i = 0; i < numboxes; i++)
  178101. compute_color(cinfo, & boxlist[i], i);
  178102. cinfo->actual_number_of_colors = numboxes;
  178103. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178104. }
  178105. /*
  178106. * These routines are concerned with the time-critical task of mapping input
  178107. * colors to the nearest color in the selected colormap.
  178108. *
  178109. * We re-use the histogram space as an "inverse color map", essentially a
  178110. * cache for the results of nearest-color searches. All colors within a
  178111. * histogram cell will be mapped to the same colormap entry, namely the one
  178112. * closest to the cell's center. This may not be quite the closest entry to
  178113. * the actual input color, but it's almost as good. A zero in the cache
  178114. * indicates we haven't found the nearest color for that cell yet; the array
  178115. * is cleared to zeroes before starting the mapping pass. When we find the
  178116. * nearest color for a cell, its colormap index plus one is recorded in the
  178117. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178118. * when they need to use an unfilled entry in the cache.
  178119. *
  178120. * Our method of efficiently finding nearest colors is based on the "locally
  178121. * sorted search" idea described by Heckbert and on the incremental distance
  178122. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178123. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178124. * the distances from a given colormap entry to each cell of the histogram can
  178125. * be computed quickly using an incremental method: the differences between
  178126. * distances to adjacent cells themselves differ by a constant. This allows a
  178127. * fairly fast implementation of the "brute force" approach of computing the
  178128. * distance from every colormap entry to every histogram cell. Unfortunately,
  178129. * it needs a work array to hold the best-distance-so-far for each histogram
  178130. * cell (because the inner loop has to be over cells, not colormap entries).
  178131. * The work array elements have to be INT32s, so the work array would need
  178132. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178133. *
  178134. * To get around these problems, we apply Thomas' method to compute the
  178135. * nearest colors for only the cells within a small subbox of the histogram.
  178136. * The work array need be only as big as the subbox, so the memory usage
  178137. * problem is solved. Furthermore, we need not fill subboxes that are never
  178138. * referenced in pass2; many images use only part of the color gamut, so a
  178139. * fair amount of work is saved. An additional advantage of this
  178140. * approach is that we can apply Heckbert's locality criterion to quickly
  178141. * eliminate colormap entries that are far away from the subbox; typically
  178142. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178143. * and we need not compute their distances to individual cells in the subbox.
  178144. * The speed of this approach is heavily influenced by the subbox size: too
  178145. * small means too much overhead, too big loses because Heckbert's criterion
  178146. * can't eliminate as many colormap entries. Empirically the best subbox
  178147. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178148. *
  178149. * Thomas' article also describes a refined method which is asymptotically
  178150. * faster than the brute-force method, but it is also far more complex and
  178151. * cannot efficiently be applied to small subboxes. It is therefore not
  178152. * useful for programs intended to be portable to DOS machines. On machines
  178153. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178154. * refined method might be faster than the present code --- but then again,
  178155. * it might not be any faster, and it's certainly more complicated.
  178156. */
  178157. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178158. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178159. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178160. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178161. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178162. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178163. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178164. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178165. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178166. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178167. /*
  178168. * The next three routines implement inverse colormap filling. They could
  178169. * all be folded into one big routine, but splitting them up this way saves
  178170. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178171. * and may allow some compilers to produce better code by registerizing more
  178172. * inner-loop variables.
  178173. */
  178174. LOCAL(int)
  178175. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178176. JSAMPLE colorlist[])
  178177. /* Locate the colormap entries close enough to an update box to be candidates
  178178. * for the nearest entry to some cell(s) in the update box. The update box
  178179. * is specified by the center coordinates of its first cell. The number of
  178180. * candidate colormap entries is returned, and their colormap indexes are
  178181. * placed in colorlist[].
  178182. * This routine uses Heckbert's "locally sorted search" criterion to select
  178183. * the colors that need further consideration.
  178184. */
  178185. {
  178186. int numcolors = cinfo->actual_number_of_colors;
  178187. int maxc0, maxc1, maxc2;
  178188. int centerc0, centerc1, centerc2;
  178189. int i, x, ncolors;
  178190. INT32 minmaxdist, min_dist, max_dist, tdist;
  178191. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178192. /* Compute true coordinates of update box's upper corner and center.
  178193. * Actually we compute the coordinates of the center of the upper-corner
  178194. * histogram cell, which are the upper bounds of the volume we care about.
  178195. * Note that since ">>" rounds down, the "center" values may be closer to
  178196. * min than to max; hence comparisons to them must be "<=", not "<".
  178197. */
  178198. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178199. centerc0 = (minc0 + maxc0) >> 1;
  178200. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178201. centerc1 = (minc1 + maxc1) >> 1;
  178202. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178203. centerc2 = (minc2 + maxc2) >> 1;
  178204. /* For each color in colormap, find:
  178205. * 1. its minimum squared-distance to any point in the update box
  178206. * (zero if color is within update box);
  178207. * 2. its maximum squared-distance to any point in the update box.
  178208. * Both of these can be found by considering only the corners of the box.
  178209. * We save the minimum distance for each color in mindist[];
  178210. * only the smallest maximum distance is of interest.
  178211. */
  178212. minmaxdist = 0x7FFFFFFFL;
  178213. for (i = 0; i < numcolors; i++) {
  178214. /* We compute the squared-c0-distance term, then add in the other two. */
  178215. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178216. if (x < minc0) {
  178217. tdist = (x - minc0) * C0_SCALE;
  178218. min_dist = tdist*tdist;
  178219. tdist = (x - maxc0) * C0_SCALE;
  178220. max_dist = tdist*tdist;
  178221. } else if (x > maxc0) {
  178222. tdist = (x - maxc0) * C0_SCALE;
  178223. min_dist = tdist*tdist;
  178224. tdist = (x - minc0) * C0_SCALE;
  178225. max_dist = tdist*tdist;
  178226. } else {
  178227. /* within cell range so no contribution to min_dist */
  178228. min_dist = 0;
  178229. if (x <= centerc0) {
  178230. tdist = (x - maxc0) * C0_SCALE;
  178231. max_dist = tdist*tdist;
  178232. } else {
  178233. tdist = (x - minc0) * C0_SCALE;
  178234. max_dist = tdist*tdist;
  178235. }
  178236. }
  178237. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178238. if (x < minc1) {
  178239. tdist = (x - minc1) * C1_SCALE;
  178240. min_dist += tdist*tdist;
  178241. tdist = (x - maxc1) * C1_SCALE;
  178242. max_dist += tdist*tdist;
  178243. } else if (x > maxc1) {
  178244. tdist = (x - maxc1) * C1_SCALE;
  178245. min_dist += tdist*tdist;
  178246. tdist = (x - minc1) * C1_SCALE;
  178247. max_dist += tdist*tdist;
  178248. } else {
  178249. /* within cell range so no contribution to min_dist */
  178250. if (x <= centerc1) {
  178251. tdist = (x - maxc1) * C1_SCALE;
  178252. max_dist += tdist*tdist;
  178253. } else {
  178254. tdist = (x - minc1) * C1_SCALE;
  178255. max_dist += tdist*tdist;
  178256. }
  178257. }
  178258. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178259. if (x < minc2) {
  178260. tdist = (x - minc2) * C2_SCALE;
  178261. min_dist += tdist*tdist;
  178262. tdist = (x - maxc2) * C2_SCALE;
  178263. max_dist += tdist*tdist;
  178264. } else if (x > maxc2) {
  178265. tdist = (x - maxc2) * C2_SCALE;
  178266. min_dist += tdist*tdist;
  178267. tdist = (x - minc2) * C2_SCALE;
  178268. max_dist += tdist*tdist;
  178269. } else {
  178270. /* within cell range so no contribution to min_dist */
  178271. if (x <= centerc2) {
  178272. tdist = (x - maxc2) * C2_SCALE;
  178273. max_dist += tdist*tdist;
  178274. } else {
  178275. tdist = (x - minc2) * C2_SCALE;
  178276. max_dist += tdist*tdist;
  178277. }
  178278. }
  178279. mindist[i] = min_dist; /* save away the results */
  178280. if (max_dist < minmaxdist)
  178281. minmaxdist = max_dist;
  178282. }
  178283. /* Now we know that no cell in the update box is more than minmaxdist
  178284. * away from some colormap entry. Therefore, only colors that are
  178285. * within minmaxdist of some part of the box need be considered.
  178286. */
  178287. ncolors = 0;
  178288. for (i = 0; i < numcolors; i++) {
  178289. if (mindist[i] <= minmaxdist)
  178290. colorlist[ncolors++] = (JSAMPLE) i;
  178291. }
  178292. return ncolors;
  178293. }
  178294. LOCAL(void)
  178295. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178296. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178297. /* Find the closest colormap entry for each cell in the update box,
  178298. * given the list of candidate colors prepared by find_nearby_colors.
  178299. * Return the indexes of the closest entries in the bestcolor[] array.
  178300. * This routine uses Thomas' incremental distance calculation method to
  178301. * find the distance from a colormap entry to successive cells in the box.
  178302. */
  178303. {
  178304. int ic0, ic1, ic2;
  178305. int i, icolor;
  178306. register INT32 * bptr; /* pointer into bestdist[] array */
  178307. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178308. INT32 dist0, dist1; /* initial distance values */
  178309. register INT32 dist2; /* current distance in inner loop */
  178310. INT32 xx0, xx1; /* distance increments */
  178311. register INT32 xx2;
  178312. INT32 inc0, inc1, inc2; /* initial values for increments */
  178313. /* This array holds the distance to the nearest-so-far color for each cell */
  178314. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178315. /* Initialize best-distance for each cell of the update box */
  178316. bptr = bestdist;
  178317. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178318. *bptr++ = 0x7FFFFFFFL;
  178319. /* For each color selected by find_nearby_colors,
  178320. * compute its distance to the center of each cell in the box.
  178321. * If that's less than best-so-far, update best distance and color number.
  178322. */
  178323. /* Nominal steps between cell centers ("x" in Thomas article) */
  178324. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178325. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178326. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178327. for (i = 0; i < numcolors; i++) {
  178328. icolor = GETJSAMPLE(colorlist[i]);
  178329. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178330. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178331. dist0 = inc0*inc0;
  178332. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178333. dist0 += inc1*inc1;
  178334. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178335. dist0 += inc2*inc2;
  178336. /* Form the initial difference increments */
  178337. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178338. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178339. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178340. /* Now loop over all cells in box, updating distance per Thomas method */
  178341. bptr = bestdist;
  178342. cptr = bestcolor;
  178343. xx0 = inc0;
  178344. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178345. dist1 = dist0;
  178346. xx1 = inc1;
  178347. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178348. dist2 = dist1;
  178349. xx2 = inc2;
  178350. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178351. if (dist2 < *bptr) {
  178352. *bptr = dist2;
  178353. *cptr = (JSAMPLE) icolor;
  178354. }
  178355. dist2 += xx2;
  178356. xx2 += 2 * STEP_C2 * STEP_C2;
  178357. bptr++;
  178358. cptr++;
  178359. }
  178360. dist1 += xx1;
  178361. xx1 += 2 * STEP_C1 * STEP_C1;
  178362. }
  178363. dist0 += xx0;
  178364. xx0 += 2 * STEP_C0 * STEP_C0;
  178365. }
  178366. }
  178367. }
  178368. LOCAL(void)
  178369. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178370. /* Fill the inverse-colormap entries in the update box that contains */
  178371. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178372. /* we can fill as many others as we wish.) */
  178373. {
  178374. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178375. hist3d histogram = cquantize->histogram;
  178376. int minc0, minc1, minc2; /* lower left corner of update box */
  178377. int ic0, ic1, ic2;
  178378. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178379. register histptr cachep; /* pointer into main cache array */
  178380. /* This array lists the candidate colormap indexes. */
  178381. JSAMPLE colorlist[MAXNUMCOLORS];
  178382. int numcolors; /* number of candidate colors */
  178383. /* This array holds the actually closest colormap index for each cell. */
  178384. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178385. /* Convert cell coordinates to update box ID */
  178386. c0 >>= BOX_C0_LOG;
  178387. c1 >>= BOX_C1_LOG;
  178388. c2 >>= BOX_C2_LOG;
  178389. /* Compute true coordinates of update box's origin corner.
  178390. * Actually we compute the coordinates of the center of the corner
  178391. * histogram cell, which are the lower bounds of the volume we care about.
  178392. */
  178393. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178394. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178395. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178396. /* Determine which colormap entries are close enough to be candidates
  178397. * for the nearest entry to some cell in the update box.
  178398. */
  178399. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178400. /* Determine the actually nearest colors. */
  178401. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178402. bestcolor);
  178403. /* Save the best color numbers (plus 1) in the main cache array */
  178404. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178405. c1 <<= BOX_C1_LOG;
  178406. c2 <<= BOX_C2_LOG;
  178407. cptr = bestcolor;
  178408. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178409. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178410. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178411. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178412. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178413. }
  178414. }
  178415. }
  178416. }
  178417. /*
  178418. * Map some rows of pixels to the output colormapped representation.
  178419. */
  178420. METHODDEF(void)
  178421. pass2_no_dither (j_decompress_ptr cinfo,
  178422. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178423. /* This version performs no dithering */
  178424. {
  178425. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178426. hist3d histogram = cquantize->histogram;
  178427. register JSAMPROW inptr, outptr;
  178428. register histptr cachep;
  178429. register int c0, c1, c2;
  178430. int row;
  178431. JDIMENSION col;
  178432. JDIMENSION width = cinfo->output_width;
  178433. for (row = 0; row < num_rows; row++) {
  178434. inptr = input_buf[row];
  178435. outptr = output_buf[row];
  178436. for (col = width; col > 0; col--) {
  178437. /* get pixel value and index into the cache */
  178438. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178439. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178440. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178441. cachep = & histogram[c0][c1][c2];
  178442. /* If we have not seen this color before, find nearest colormap entry */
  178443. /* and update the cache */
  178444. if (*cachep == 0)
  178445. fill_inverse_cmap(cinfo, c0,c1,c2);
  178446. /* Now emit the colormap index for this cell */
  178447. *outptr++ = (JSAMPLE) (*cachep - 1);
  178448. }
  178449. }
  178450. }
  178451. METHODDEF(void)
  178452. pass2_fs_dither (j_decompress_ptr cinfo,
  178453. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178454. /* This version performs Floyd-Steinberg dithering */
  178455. {
  178456. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178457. hist3d histogram = cquantize->histogram;
  178458. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178459. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178460. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178461. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178462. JSAMPROW inptr; /* => current input pixel */
  178463. JSAMPROW outptr; /* => current output pixel */
  178464. histptr cachep;
  178465. int dir; /* +1 or -1 depending on direction */
  178466. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178467. int row;
  178468. JDIMENSION col;
  178469. JDIMENSION width = cinfo->output_width;
  178470. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178471. int *error_limit = cquantize->error_limiter;
  178472. JSAMPROW colormap0 = cinfo->colormap[0];
  178473. JSAMPROW colormap1 = cinfo->colormap[1];
  178474. JSAMPROW colormap2 = cinfo->colormap[2];
  178475. SHIFT_TEMPS
  178476. for (row = 0; row < num_rows; row++) {
  178477. inptr = input_buf[row];
  178478. outptr = output_buf[row];
  178479. if (cquantize->on_odd_row) {
  178480. /* work right to left in this row */
  178481. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178482. outptr += width-1;
  178483. dir = -1;
  178484. dir3 = -3;
  178485. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178486. cquantize->on_odd_row = FALSE; /* flip for next time */
  178487. } else {
  178488. /* work left to right in this row */
  178489. dir = 1;
  178490. dir3 = 3;
  178491. errorptr = cquantize->fserrors; /* => entry before first real column */
  178492. cquantize->on_odd_row = TRUE; /* flip for next time */
  178493. }
  178494. /* Preset error values: no error propagated to first pixel from left */
  178495. cur0 = cur1 = cur2 = 0;
  178496. /* and no error propagated to row below yet */
  178497. belowerr0 = belowerr1 = belowerr2 = 0;
  178498. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178499. for (col = width; col > 0; col--) {
  178500. /* curN holds the error propagated from the previous pixel on the
  178501. * current line. Add the error propagated from the previous line
  178502. * to form the complete error correction term for this pixel, and
  178503. * round the error term (which is expressed * 16) to an integer.
  178504. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178505. * for either sign of the error value.
  178506. * Note: errorptr points to *previous* column's array entry.
  178507. */
  178508. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178509. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178510. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178511. /* Limit the error using transfer function set by init_error_limit.
  178512. * See comments with init_error_limit for rationale.
  178513. */
  178514. cur0 = error_limit[cur0];
  178515. cur1 = error_limit[cur1];
  178516. cur2 = error_limit[cur2];
  178517. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178518. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178519. * this sets the required size of the range_limit array.
  178520. */
  178521. cur0 += GETJSAMPLE(inptr[0]);
  178522. cur1 += GETJSAMPLE(inptr[1]);
  178523. cur2 += GETJSAMPLE(inptr[2]);
  178524. cur0 = GETJSAMPLE(range_limit[cur0]);
  178525. cur1 = GETJSAMPLE(range_limit[cur1]);
  178526. cur2 = GETJSAMPLE(range_limit[cur2]);
  178527. /* Index into the cache with adjusted pixel value */
  178528. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178529. /* If we have not seen this color before, find nearest colormap */
  178530. /* entry and update the cache */
  178531. if (*cachep == 0)
  178532. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178533. /* Now emit the colormap index for this cell */
  178534. { register int pixcode = *cachep - 1;
  178535. *outptr = (JSAMPLE) pixcode;
  178536. /* Compute representation error for this pixel */
  178537. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178538. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178539. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178540. }
  178541. /* Compute error fractions to be propagated to adjacent pixels.
  178542. * Add these into the running sums, and simultaneously shift the
  178543. * next-line error sums left by 1 column.
  178544. */
  178545. { register LOCFSERROR bnexterr, delta;
  178546. bnexterr = cur0; /* Process component 0 */
  178547. delta = cur0 * 2;
  178548. cur0 += delta; /* form error * 3 */
  178549. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178550. cur0 += delta; /* form error * 5 */
  178551. bpreverr0 = belowerr0 + cur0;
  178552. belowerr0 = bnexterr;
  178553. cur0 += delta; /* form error * 7 */
  178554. bnexterr = cur1; /* Process component 1 */
  178555. delta = cur1 * 2;
  178556. cur1 += delta; /* form error * 3 */
  178557. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178558. cur1 += delta; /* form error * 5 */
  178559. bpreverr1 = belowerr1 + cur1;
  178560. belowerr1 = bnexterr;
  178561. cur1 += delta; /* form error * 7 */
  178562. bnexterr = cur2; /* Process component 2 */
  178563. delta = cur2 * 2;
  178564. cur2 += delta; /* form error * 3 */
  178565. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178566. cur2 += delta; /* form error * 5 */
  178567. bpreverr2 = belowerr2 + cur2;
  178568. belowerr2 = bnexterr;
  178569. cur2 += delta; /* form error * 7 */
  178570. }
  178571. /* At this point curN contains the 7/16 error value to be propagated
  178572. * to the next pixel on the current line, and all the errors for the
  178573. * next line have been shifted over. We are therefore ready to move on.
  178574. */
  178575. inptr += dir3; /* Advance pixel pointers to next column */
  178576. outptr += dir;
  178577. errorptr += dir3; /* advance errorptr to current column */
  178578. }
  178579. /* Post-loop cleanup: we must unload the final error values into the
  178580. * final fserrors[] entry. Note we need not unload belowerrN because
  178581. * it is for the dummy column before or after the actual array.
  178582. */
  178583. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178584. errorptr[1] = (FSERROR) bpreverr1;
  178585. errorptr[2] = (FSERROR) bpreverr2;
  178586. }
  178587. }
  178588. /*
  178589. * Initialize the error-limiting transfer function (lookup table).
  178590. * The raw F-S error computation can potentially compute error values of up to
  178591. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178592. * much less, otherwise obviously wrong pixels will be created. (Typical
  178593. * effects include weird fringes at color-area boundaries, isolated bright
  178594. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178595. * is to ensure that the "corners" of the color cube are allocated as output
  178596. * colors; then repeated errors in the same direction cannot cause cascading
  178597. * error buildup. However, that only prevents the error from getting
  178598. * completely out of hand; Aaron Giles reports that error limiting improves
  178599. * the results even with corner colors allocated.
  178600. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178601. * well, but the smoother transfer function used below is even better. Thanks
  178602. * to Aaron Giles for this idea.
  178603. */
  178604. LOCAL(void)
  178605. init_error_limit (j_decompress_ptr cinfo)
  178606. /* Allocate and fill in the error_limiter table */
  178607. {
  178608. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178609. int * table;
  178610. int in, out;
  178611. table = (int *) (*cinfo->mem->alloc_small)
  178612. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178613. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178614. cquantize->error_limiter = table;
  178615. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178616. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178617. out = 0;
  178618. for (in = 0; in < STEPSIZE; in++, out++) {
  178619. table[in] = out; table[-in] = -out;
  178620. }
  178621. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178622. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178623. table[in] = out; table[-in] = -out;
  178624. }
  178625. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178626. for (; in <= MAXJSAMPLE; in++) {
  178627. table[in] = out; table[-in] = -out;
  178628. }
  178629. #undef STEPSIZE
  178630. }
  178631. /*
  178632. * Finish up at the end of each pass.
  178633. */
  178634. METHODDEF(void)
  178635. finish_pass1 (j_decompress_ptr cinfo)
  178636. {
  178637. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178638. /* Select the representative colors and fill in cinfo->colormap */
  178639. cinfo->colormap = cquantize->sv_colormap;
  178640. select_colors(cinfo, cquantize->desired);
  178641. /* Force next pass to zero the color index table */
  178642. cquantize->needs_zeroed = TRUE;
  178643. }
  178644. METHODDEF(void)
  178645. finish_pass2 (j_decompress_ptr)
  178646. {
  178647. /* no work */
  178648. }
  178649. /*
  178650. * Initialize for each processing pass.
  178651. */
  178652. METHODDEF(void)
  178653. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178654. {
  178655. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178656. hist3d histogram = cquantize->histogram;
  178657. int i;
  178658. /* Only F-S dithering or no dithering is supported. */
  178659. /* If user asks for ordered dither, give him F-S. */
  178660. if (cinfo->dither_mode != JDITHER_NONE)
  178661. cinfo->dither_mode = JDITHER_FS;
  178662. if (is_pre_scan) {
  178663. /* Set up method pointers */
  178664. cquantize->pub.color_quantize = prescan_quantize;
  178665. cquantize->pub.finish_pass = finish_pass1;
  178666. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178667. } else {
  178668. /* Set up method pointers */
  178669. if (cinfo->dither_mode == JDITHER_FS)
  178670. cquantize->pub.color_quantize = pass2_fs_dither;
  178671. else
  178672. cquantize->pub.color_quantize = pass2_no_dither;
  178673. cquantize->pub.finish_pass = finish_pass2;
  178674. /* Make sure color count is acceptable */
  178675. i = cinfo->actual_number_of_colors;
  178676. if (i < 1)
  178677. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178678. if (i > MAXNUMCOLORS)
  178679. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178680. if (cinfo->dither_mode == JDITHER_FS) {
  178681. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178682. (3 * SIZEOF(FSERROR)));
  178683. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178684. if (cquantize->fserrors == NULL)
  178685. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178686. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178687. /* Initialize the propagated errors to zero. */
  178688. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178689. /* Make the error-limit table if we didn't already. */
  178690. if (cquantize->error_limiter == NULL)
  178691. init_error_limit(cinfo);
  178692. cquantize->on_odd_row = FALSE;
  178693. }
  178694. }
  178695. /* Zero the histogram or inverse color map, if necessary */
  178696. if (cquantize->needs_zeroed) {
  178697. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178698. jzero_far((void FAR *) histogram[i],
  178699. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178700. }
  178701. cquantize->needs_zeroed = FALSE;
  178702. }
  178703. }
  178704. /*
  178705. * Switch to a new external colormap between output passes.
  178706. */
  178707. METHODDEF(void)
  178708. new_color_map_2_quant (j_decompress_ptr cinfo)
  178709. {
  178710. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178711. /* Reset the inverse color map */
  178712. cquantize->needs_zeroed = TRUE;
  178713. }
  178714. /*
  178715. * Module initialization routine for 2-pass color quantization.
  178716. */
  178717. GLOBAL(void)
  178718. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178719. {
  178720. my_cquantize_ptr2 cquantize;
  178721. int i;
  178722. cquantize = (my_cquantize_ptr2)
  178723. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178724. SIZEOF(my_cquantizer2));
  178725. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178726. cquantize->pub.start_pass = start_pass_2_quant;
  178727. cquantize->pub.new_color_map = new_color_map_2_quant;
  178728. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178729. cquantize->error_limiter = NULL;
  178730. /* Make sure jdmaster didn't give me a case I can't handle */
  178731. if (cinfo->out_color_components != 3)
  178732. ERREXIT(cinfo, JERR_NOTIMPL);
  178733. /* Allocate the histogram/inverse colormap storage */
  178734. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178735. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178736. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178737. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178738. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178739. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178740. }
  178741. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178742. /* Allocate storage for the completed colormap, if required.
  178743. * We do this now since it is FAR storage and may affect
  178744. * the memory manager's space calculations.
  178745. */
  178746. if (cinfo->enable_2pass_quant) {
  178747. /* Make sure color count is acceptable */
  178748. int desired = cinfo->desired_number_of_colors;
  178749. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178750. if (desired < 8)
  178751. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178752. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178753. if (desired > MAXNUMCOLORS)
  178754. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178755. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178756. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178757. cquantize->desired = desired;
  178758. } else
  178759. cquantize->sv_colormap = NULL;
  178760. /* Only F-S dithering or no dithering is supported. */
  178761. /* If user asks for ordered dither, give him F-S. */
  178762. if (cinfo->dither_mode != JDITHER_NONE)
  178763. cinfo->dither_mode = JDITHER_FS;
  178764. /* Allocate Floyd-Steinberg workspace if necessary.
  178765. * This isn't really needed until pass 2, but again it is FAR storage.
  178766. * Although we will cope with a later change in dither_mode,
  178767. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178768. */
  178769. if (cinfo->dither_mode == JDITHER_FS) {
  178770. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178771. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178772. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178773. /* Might as well create the error-limiting table too. */
  178774. init_error_limit(cinfo);
  178775. }
  178776. }
  178777. #endif /* QUANT_2PASS_SUPPORTED */
  178778. /*** End of inlined file: jquant2.c ***/
  178779. /*** Start of inlined file: jutils.c ***/
  178780. #define JPEG_INTERNALS
  178781. /*
  178782. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178783. * of a DCT block read in natural order (left to right, top to bottom).
  178784. */
  178785. #if 0 /* This table is not actually needed in v6a */
  178786. const int jpeg_zigzag_order[DCTSIZE2] = {
  178787. 0, 1, 5, 6, 14, 15, 27, 28,
  178788. 2, 4, 7, 13, 16, 26, 29, 42,
  178789. 3, 8, 12, 17, 25, 30, 41, 43,
  178790. 9, 11, 18, 24, 31, 40, 44, 53,
  178791. 10, 19, 23, 32, 39, 45, 52, 54,
  178792. 20, 22, 33, 38, 46, 51, 55, 60,
  178793. 21, 34, 37, 47, 50, 56, 59, 61,
  178794. 35, 36, 48, 49, 57, 58, 62, 63
  178795. };
  178796. #endif
  178797. /*
  178798. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178799. * of zigzag order.
  178800. *
  178801. * When reading corrupted data, the Huffman decoders could attempt
  178802. * to reference an entry beyond the end of this array (if the decoded
  178803. * zero run length reaches past the end of the block). To prevent
  178804. * wild stores without adding an inner-loop test, we put some extra
  178805. * "63"s after the real entries. This will cause the extra coefficient
  178806. * to be stored in location 63 of the block, not somewhere random.
  178807. * The worst case would be a run-length of 15, which means we need 16
  178808. * fake entries.
  178809. */
  178810. const int jpeg_natural_order[DCTSIZE2+16] = {
  178811. 0, 1, 8, 16, 9, 2, 3, 10,
  178812. 17, 24, 32, 25, 18, 11, 4, 5,
  178813. 12, 19, 26, 33, 40, 48, 41, 34,
  178814. 27, 20, 13, 6, 7, 14, 21, 28,
  178815. 35, 42, 49, 56, 57, 50, 43, 36,
  178816. 29, 22, 15, 23, 30, 37, 44, 51,
  178817. 58, 59, 52, 45, 38, 31, 39, 46,
  178818. 53, 60, 61, 54, 47, 55, 62, 63,
  178819. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178820. 63, 63, 63, 63, 63, 63, 63, 63
  178821. };
  178822. /*
  178823. * Arithmetic utilities
  178824. */
  178825. GLOBAL(long)
  178826. jdiv_round_up (long a, long b)
  178827. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178828. /* Assumes a >= 0, b > 0 */
  178829. {
  178830. return (a + b - 1L) / b;
  178831. }
  178832. GLOBAL(long)
  178833. jround_up (long a, long b)
  178834. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178835. /* Assumes a >= 0, b > 0 */
  178836. {
  178837. a += b - 1L;
  178838. return a - (a % b);
  178839. }
  178840. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178841. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178842. * are FAR and we're assuming a small-pointer memory model. However, some
  178843. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178844. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178845. * Otherwise, the routines below do it the hard way. (The performance cost
  178846. * is not all that great, because these routines aren't very heavily used.)
  178847. */
  178848. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178849. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178850. #define FMEMZERO(target,size) MEMZERO(target,size)
  178851. #else /* 80x86 case, define if we can */
  178852. #ifdef USE_FMEM
  178853. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178854. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178855. #endif
  178856. #endif
  178857. GLOBAL(void)
  178858. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178859. JSAMPARRAY output_array, int dest_row,
  178860. int num_rows, JDIMENSION num_cols)
  178861. /* Copy some rows of samples from one place to another.
  178862. * num_rows rows are copied from input_array[source_row++]
  178863. * to output_array[dest_row++]; these areas may overlap for duplication.
  178864. * The source and destination arrays must be at least as wide as num_cols.
  178865. */
  178866. {
  178867. register JSAMPROW inptr, outptr;
  178868. #ifdef FMEMCOPY
  178869. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178870. #else
  178871. register JDIMENSION count;
  178872. #endif
  178873. register int row;
  178874. input_array += source_row;
  178875. output_array += dest_row;
  178876. for (row = num_rows; row > 0; row--) {
  178877. inptr = *input_array++;
  178878. outptr = *output_array++;
  178879. #ifdef FMEMCOPY
  178880. FMEMCOPY(outptr, inptr, count);
  178881. #else
  178882. for (count = num_cols; count > 0; count--)
  178883. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178884. #endif
  178885. }
  178886. }
  178887. GLOBAL(void)
  178888. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178889. JDIMENSION num_blocks)
  178890. /* Copy a row of coefficient blocks from one place to another. */
  178891. {
  178892. #ifdef FMEMCOPY
  178893. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178894. #else
  178895. register JCOEFPTR inptr, outptr;
  178896. register long count;
  178897. inptr = (JCOEFPTR) input_row;
  178898. outptr = (JCOEFPTR) output_row;
  178899. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178900. *outptr++ = *inptr++;
  178901. }
  178902. #endif
  178903. }
  178904. GLOBAL(void)
  178905. jzero_far (void FAR * target, size_t bytestozero)
  178906. /* Zero out a chunk of FAR memory. */
  178907. /* This might be sample-array data, block-array data, or alloc_large data. */
  178908. {
  178909. #ifdef FMEMZERO
  178910. FMEMZERO(target, bytestozero);
  178911. #else
  178912. register char FAR * ptr = (char FAR *) target;
  178913. register size_t count;
  178914. for (count = bytestozero; count > 0; count--) {
  178915. *ptr++ = 0;
  178916. }
  178917. #endif
  178918. }
  178919. /*** End of inlined file: jutils.c ***/
  178920. /*** Start of inlined file: transupp.c ***/
  178921. /* Although this file really shouldn't have access to the library internals,
  178922. * it's helpful to let it call jround_up() and jcopy_block_row().
  178923. */
  178924. #define JPEG_INTERNALS
  178925. /*** Start of inlined file: transupp.h ***/
  178926. /* If you happen not to want the image transform support, disable it here */
  178927. #ifndef TRANSFORMS_SUPPORTED
  178928. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178929. #endif
  178930. /* Short forms of external names for systems with brain-damaged linkers. */
  178931. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178932. #define jtransform_request_workspace jTrRequest
  178933. #define jtransform_adjust_parameters jTrAdjust
  178934. #define jtransform_execute_transformation jTrExec
  178935. #define jcopy_markers_setup jCMrkSetup
  178936. #define jcopy_markers_execute jCMrkExec
  178937. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178938. /*
  178939. * Codes for supported types of image transformations.
  178940. */
  178941. typedef enum {
  178942. JXFORM_NONE, /* no transformation */
  178943. JXFORM_FLIP_H, /* horizontal flip */
  178944. JXFORM_FLIP_V, /* vertical flip */
  178945. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178946. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178947. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178948. JXFORM_ROT_180, /* 180-degree rotation */
  178949. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178950. } JXFORM_CODE;
  178951. /*
  178952. * Although rotating and flipping data expressed as DCT coefficients is not
  178953. * hard, there is an asymmetry in the JPEG format specification for images
  178954. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178955. * image edges are padded out to the next iMCU boundary with junk data; but
  178956. * no padding is possible at the top and left edges. If we were to flip
  178957. * the whole image including the pad data, then pad garbage would become
  178958. * visible at the top and/or left, and real pixels would disappear into the
  178959. * pad margins --- perhaps permanently, since encoders & decoders may not
  178960. * bother to preserve DCT blocks that appear to be completely outside the
  178961. * nominal image area. So, we have to exclude any partial iMCUs from the
  178962. * basic transformation.
  178963. *
  178964. * Transpose is the only transformation that can handle partial iMCUs at the
  178965. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178966. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178967. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178968. * The other transforms are defined as combinations of these basic transforms
  178969. * and process edge blocks in a way that preserves the equivalence.
  178970. *
  178971. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178972. * this is not strictly lossless, but it usually gives the best-looking
  178973. * result for odd-size images. Note that when this option is active,
  178974. * the expected mathematical equivalences between the transforms may not hold.
  178975. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178976. * followed by -rot 180 -trim trims both edges.)
  178977. *
  178978. * We also offer a "force to grayscale" option, which simply discards the
  178979. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178980. * the luminance channel is preserved exactly. It's not the same kind of
  178981. * thing as the rotate/flip transformations, but it's convenient to handle it
  178982. * as part of this package, mainly because the transformation routines have to
  178983. * be aware of the option to know how many components to work on.
  178984. */
  178985. typedef struct {
  178986. /* Options: set by caller */
  178987. JXFORM_CODE transform; /* image transform operator */
  178988. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178989. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178990. /* Internal workspace: caller should not touch these */
  178991. int num_components; /* # of components in workspace */
  178992. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178993. } jpeg_transform_info;
  178994. #if TRANSFORMS_SUPPORTED
  178995. /* Request any required workspace */
  178996. EXTERN(void) jtransform_request_workspace
  178997. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178998. /* Adjust output image parameters */
  178999. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179000. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179001. jvirt_barray_ptr *src_coef_arrays,
  179002. jpeg_transform_info *info));
  179003. /* Execute the actual transformation, if any */
  179004. EXTERN(void) jtransform_execute_transformation
  179005. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179006. jvirt_barray_ptr *src_coef_arrays,
  179007. jpeg_transform_info *info));
  179008. #endif /* TRANSFORMS_SUPPORTED */
  179009. /*
  179010. * Support for copying optional markers from source to destination file.
  179011. */
  179012. typedef enum {
  179013. JCOPYOPT_NONE, /* copy no optional markers */
  179014. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179015. JCOPYOPT_ALL /* copy all optional markers */
  179016. } JCOPY_OPTION;
  179017. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179018. /* Setup decompression object to save desired markers in memory */
  179019. EXTERN(void) jcopy_markers_setup
  179020. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179021. /* Copy markers saved in the given source object to the destination object */
  179022. EXTERN(void) jcopy_markers_execute
  179023. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179024. JCOPY_OPTION option));
  179025. /*** End of inlined file: transupp.h ***/
  179026. /* My own external interface */
  179027. #if TRANSFORMS_SUPPORTED
  179028. /*
  179029. * Lossless image transformation routines. These routines work on DCT
  179030. * coefficient arrays and thus do not require any lossy decompression
  179031. * or recompression of the image.
  179032. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179033. *
  179034. * Horizontal flipping is done in-place, using a single top-to-bottom
  179035. * pass through the virtual source array. It will thus be much the
  179036. * fastest option for images larger than main memory.
  179037. *
  179038. * The other routines require a set of destination virtual arrays, so they
  179039. * need twice as much memory as jpegtran normally does. The destination
  179040. * arrays are always written in normal scan order (top to bottom) because
  179041. * the virtual array manager expects this. The source arrays will be scanned
  179042. * in the corresponding order, which means multiple passes through the source
  179043. * arrays for most of the transforms. That could result in much thrashing
  179044. * if the image is larger than main memory.
  179045. *
  179046. * Some notes about the operating environment of the individual transform
  179047. * routines:
  179048. * 1. Both the source and destination virtual arrays are allocated from the
  179049. * source JPEG object, and therefore should be manipulated by calling the
  179050. * source's memory manager.
  179051. * 2. The destination's component count should be used. It may be smaller
  179052. * than the source's when forcing to grayscale.
  179053. * 3. Likewise the destination's sampling factors should be used. When
  179054. * forcing to grayscale the destination's sampling factors will be all 1,
  179055. * and we may as well take that as the effective iMCU size.
  179056. * 4. When "trim" is in effect, the destination's dimensions will be the
  179057. * trimmed values but the source's will be untrimmed.
  179058. * 5. All the routines assume that the source and destination buffers are
  179059. * padded out to a full iMCU boundary. This is true, although for the
  179060. * source buffer it is an undocumented property of jdcoefct.c.
  179061. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179062. * dimensions and ignore the source's.
  179063. */
  179064. LOCAL(void)
  179065. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179066. jvirt_barray_ptr *src_coef_arrays)
  179067. /* Horizontal flip; done in-place, so no separate dest array is required */
  179068. {
  179069. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179070. int ci, k, offset_y;
  179071. JBLOCKARRAY buffer;
  179072. JCOEFPTR ptr1, ptr2;
  179073. JCOEF temp1, temp2;
  179074. jpeg_component_info *compptr;
  179075. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179076. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179077. * mirroring by changing the signs of odd-numbered columns.
  179078. * Partial iMCUs at the right edge are left untouched.
  179079. */
  179080. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179081. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179082. compptr = dstinfo->comp_info + ci;
  179083. comp_width = MCU_cols * compptr->h_samp_factor;
  179084. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179085. blk_y += compptr->v_samp_factor) {
  179086. buffer = (*srcinfo->mem->access_virt_barray)
  179087. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179088. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179089. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179090. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179091. ptr1 = buffer[offset_y][blk_x];
  179092. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179093. /* this unrolled loop doesn't need to know which row it's on... */
  179094. for (k = 0; k < DCTSIZE2; k += 2) {
  179095. temp1 = *ptr1; /* swap even column */
  179096. temp2 = *ptr2;
  179097. *ptr1++ = temp2;
  179098. *ptr2++ = temp1;
  179099. temp1 = *ptr1; /* swap odd column with sign change */
  179100. temp2 = *ptr2;
  179101. *ptr1++ = -temp2;
  179102. *ptr2++ = -temp1;
  179103. }
  179104. }
  179105. }
  179106. }
  179107. }
  179108. }
  179109. LOCAL(void)
  179110. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179111. jvirt_barray_ptr *src_coef_arrays,
  179112. jvirt_barray_ptr *dst_coef_arrays)
  179113. /* Vertical flip */
  179114. {
  179115. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179116. int ci, i, j, offset_y;
  179117. JBLOCKARRAY src_buffer, dst_buffer;
  179118. JBLOCKROW src_row_ptr, dst_row_ptr;
  179119. JCOEFPTR src_ptr, dst_ptr;
  179120. jpeg_component_info *compptr;
  179121. /* We output into a separate array because we can't touch different
  179122. * rows of the source virtual array simultaneously. Otherwise, this
  179123. * is a pretty straightforward analog of horizontal flip.
  179124. * Within a DCT block, vertical mirroring is done by changing the signs
  179125. * of odd-numbered rows.
  179126. * Partial iMCUs at the bottom edge are copied verbatim.
  179127. */
  179128. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179129. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179130. compptr = dstinfo->comp_info + ci;
  179131. comp_height = MCU_rows * compptr->v_samp_factor;
  179132. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179133. dst_blk_y += compptr->v_samp_factor) {
  179134. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179135. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179136. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179137. if (dst_blk_y < comp_height) {
  179138. /* Row is within the mirrorable area. */
  179139. src_buffer = (*srcinfo->mem->access_virt_barray)
  179140. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179141. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179142. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179143. } else {
  179144. /* Bottom-edge blocks will be copied verbatim. */
  179145. src_buffer = (*srcinfo->mem->access_virt_barray)
  179146. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179147. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179148. }
  179149. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179150. if (dst_blk_y < comp_height) {
  179151. /* Row is within the mirrorable area. */
  179152. dst_row_ptr = dst_buffer[offset_y];
  179153. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179154. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179155. dst_blk_x++) {
  179156. dst_ptr = dst_row_ptr[dst_blk_x];
  179157. src_ptr = src_row_ptr[dst_blk_x];
  179158. for (i = 0; i < DCTSIZE; i += 2) {
  179159. /* copy even row */
  179160. for (j = 0; j < DCTSIZE; j++)
  179161. *dst_ptr++ = *src_ptr++;
  179162. /* copy odd row with sign change */
  179163. for (j = 0; j < DCTSIZE; j++)
  179164. *dst_ptr++ = - *src_ptr++;
  179165. }
  179166. }
  179167. } else {
  179168. /* Just copy row verbatim. */
  179169. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179170. compptr->width_in_blocks);
  179171. }
  179172. }
  179173. }
  179174. }
  179175. }
  179176. LOCAL(void)
  179177. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179178. jvirt_barray_ptr *src_coef_arrays,
  179179. jvirt_barray_ptr *dst_coef_arrays)
  179180. /* Transpose source into destination */
  179181. {
  179182. JDIMENSION dst_blk_x, dst_blk_y;
  179183. int ci, i, j, offset_x, offset_y;
  179184. JBLOCKARRAY src_buffer, dst_buffer;
  179185. JCOEFPTR src_ptr, dst_ptr;
  179186. jpeg_component_info *compptr;
  179187. /* Transposing pixels within a block just requires transposing the
  179188. * DCT coefficients.
  179189. * Partial iMCUs at the edges require no special treatment; we simply
  179190. * process all the available DCT blocks for every component.
  179191. */
  179192. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179193. compptr = dstinfo->comp_info + ci;
  179194. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179195. dst_blk_y += compptr->v_samp_factor) {
  179196. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179197. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179198. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179199. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179200. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179201. dst_blk_x += compptr->h_samp_factor) {
  179202. src_buffer = (*srcinfo->mem->access_virt_barray)
  179203. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179204. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179205. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179206. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179207. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179208. for (i = 0; i < DCTSIZE; i++)
  179209. for (j = 0; j < DCTSIZE; j++)
  179210. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179211. }
  179212. }
  179213. }
  179214. }
  179215. }
  179216. }
  179217. LOCAL(void)
  179218. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179219. jvirt_barray_ptr *src_coef_arrays,
  179220. jvirt_barray_ptr *dst_coef_arrays)
  179221. /* 90 degree rotation is equivalent to
  179222. * 1. Transposing the image;
  179223. * 2. Horizontal mirroring.
  179224. * These two steps are merged into a single processing routine.
  179225. */
  179226. {
  179227. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179228. int ci, i, j, offset_x, offset_y;
  179229. JBLOCKARRAY src_buffer, dst_buffer;
  179230. JCOEFPTR src_ptr, dst_ptr;
  179231. jpeg_component_info *compptr;
  179232. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179233. * at the (output) right edge properly. They just get transposed and
  179234. * not mirrored.
  179235. */
  179236. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179237. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179238. compptr = dstinfo->comp_info + ci;
  179239. comp_width = MCU_cols * compptr->h_samp_factor;
  179240. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179241. dst_blk_y += compptr->v_samp_factor) {
  179242. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179243. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179244. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179245. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179246. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179247. dst_blk_x += compptr->h_samp_factor) {
  179248. src_buffer = (*srcinfo->mem->access_virt_barray)
  179249. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179250. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179251. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179252. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179253. if (dst_blk_x < comp_width) {
  179254. /* Block is within the mirrorable area. */
  179255. dst_ptr = dst_buffer[offset_y]
  179256. [comp_width - dst_blk_x - offset_x - 1];
  179257. for (i = 0; i < DCTSIZE; i++) {
  179258. for (j = 0; j < DCTSIZE; j++)
  179259. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179260. i++;
  179261. for (j = 0; j < DCTSIZE; j++)
  179262. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179263. }
  179264. } else {
  179265. /* Edge blocks are transposed but not mirrored. */
  179266. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179267. for (i = 0; i < DCTSIZE; i++)
  179268. for (j = 0; j < DCTSIZE; j++)
  179269. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179270. }
  179271. }
  179272. }
  179273. }
  179274. }
  179275. }
  179276. }
  179277. LOCAL(void)
  179278. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179279. jvirt_barray_ptr *src_coef_arrays,
  179280. jvirt_barray_ptr *dst_coef_arrays)
  179281. /* 270 degree rotation is equivalent to
  179282. * 1. Horizontal mirroring;
  179283. * 2. Transposing the image.
  179284. * These two steps are merged into a single processing routine.
  179285. */
  179286. {
  179287. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179288. int ci, i, j, offset_x, offset_y;
  179289. JBLOCKARRAY src_buffer, dst_buffer;
  179290. JCOEFPTR src_ptr, dst_ptr;
  179291. jpeg_component_info *compptr;
  179292. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179293. * at the (output) bottom edge properly. They just get transposed and
  179294. * not mirrored.
  179295. */
  179296. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179297. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179298. compptr = dstinfo->comp_info + ci;
  179299. comp_height = MCU_rows * compptr->v_samp_factor;
  179300. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179301. dst_blk_y += compptr->v_samp_factor) {
  179302. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179303. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179304. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179305. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179306. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179307. dst_blk_x += compptr->h_samp_factor) {
  179308. src_buffer = (*srcinfo->mem->access_virt_barray)
  179309. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179310. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179311. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179312. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179313. if (dst_blk_y < comp_height) {
  179314. /* Block is within the mirrorable area. */
  179315. src_ptr = src_buffer[offset_x]
  179316. [comp_height - dst_blk_y - offset_y - 1];
  179317. for (i = 0; i < DCTSIZE; i++) {
  179318. for (j = 0; j < DCTSIZE; j++) {
  179319. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179320. j++;
  179321. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179322. }
  179323. }
  179324. } else {
  179325. /* Edge blocks are transposed but not mirrored. */
  179326. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179327. for (i = 0; i < DCTSIZE; i++)
  179328. for (j = 0; j < DCTSIZE; j++)
  179329. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179330. }
  179331. }
  179332. }
  179333. }
  179334. }
  179335. }
  179336. }
  179337. LOCAL(void)
  179338. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179339. jvirt_barray_ptr *src_coef_arrays,
  179340. jvirt_barray_ptr *dst_coef_arrays)
  179341. /* 180 degree rotation is equivalent to
  179342. * 1. Vertical mirroring;
  179343. * 2. Horizontal mirroring.
  179344. * These two steps are merged into a single processing routine.
  179345. */
  179346. {
  179347. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179348. int ci, i, j, offset_y;
  179349. JBLOCKARRAY src_buffer, dst_buffer;
  179350. JBLOCKROW src_row_ptr, dst_row_ptr;
  179351. JCOEFPTR src_ptr, dst_ptr;
  179352. jpeg_component_info *compptr;
  179353. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179354. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179355. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179356. compptr = dstinfo->comp_info + ci;
  179357. comp_width = MCU_cols * compptr->h_samp_factor;
  179358. comp_height = MCU_rows * compptr->v_samp_factor;
  179359. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179360. dst_blk_y += compptr->v_samp_factor) {
  179361. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179362. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179363. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179364. if (dst_blk_y < comp_height) {
  179365. /* Row is within the vertically mirrorable area. */
  179366. src_buffer = (*srcinfo->mem->access_virt_barray)
  179367. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179368. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179369. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179370. } else {
  179371. /* Bottom-edge rows are only mirrored horizontally. */
  179372. src_buffer = (*srcinfo->mem->access_virt_barray)
  179373. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179374. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179375. }
  179376. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179377. if (dst_blk_y < comp_height) {
  179378. /* Row is within the mirrorable area. */
  179379. dst_row_ptr = dst_buffer[offset_y];
  179380. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179381. /* Process the blocks that can be mirrored both ways. */
  179382. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179383. dst_ptr = dst_row_ptr[dst_blk_x];
  179384. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179385. for (i = 0; i < DCTSIZE; i += 2) {
  179386. /* For even row, negate every odd column. */
  179387. for (j = 0; j < DCTSIZE; j += 2) {
  179388. *dst_ptr++ = *src_ptr++;
  179389. *dst_ptr++ = - *src_ptr++;
  179390. }
  179391. /* For odd row, negate every even column. */
  179392. for (j = 0; j < DCTSIZE; j += 2) {
  179393. *dst_ptr++ = - *src_ptr++;
  179394. *dst_ptr++ = *src_ptr++;
  179395. }
  179396. }
  179397. }
  179398. /* Any remaining right-edge blocks are only mirrored vertically. */
  179399. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179400. dst_ptr = dst_row_ptr[dst_blk_x];
  179401. src_ptr = src_row_ptr[dst_blk_x];
  179402. for (i = 0; i < DCTSIZE; i += 2) {
  179403. for (j = 0; j < DCTSIZE; j++)
  179404. *dst_ptr++ = *src_ptr++;
  179405. for (j = 0; j < DCTSIZE; j++)
  179406. *dst_ptr++ = - *src_ptr++;
  179407. }
  179408. }
  179409. } else {
  179410. /* Remaining rows are just mirrored horizontally. */
  179411. dst_row_ptr = dst_buffer[offset_y];
  179412. src_row_ptr = src_buffer[offset_y];
  179413. /* Process the blocks that can be mirrored. */
  179414. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179415. dst_ptr = dst_row_ptr[dst_blk_x];
  179416. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179417. for (i = 0; i < DCTSIZE2; i += 2) {
  179418. *dst_ptr++ = *src_ptr++;
  179419. *dst_ptr++ = - *src_ptr++;
  179420. }
  179421. }
  179422. /* Any remaining right-edge blocks are only copied. */
  179423. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179424. dst_ptr = dst_row_ptr[dst_blk_x];
  179425. src_ptr = src_row_ptr[dst_blk_x];
  179426. for (i = 0; i < DCTSIZE2; i++)
  179427. *dst_ptr++ = *src_ptr++;
  179428. }
  179429. }
  179430. }
  179431. }
  179432. }
  179433. }
  179434. LOCAL(void)
  179435. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179436. jvirt_barray_ptr *src_coef_arrays,
  179437. jvirt_barray_ptr *dst_coef_arrays)
  179438. /* Transverse transpose is equivalent to
  179439. * 1. 180 degree rotation;
  179440. * 2. Transposition;
  179441. * or
  179442. * 1. Horizontal mirroring;
  179443. * 2. Transposition;
  179444. * 3. Horizontal mirroring.
  179445. * These steps are merged into a single processing routine.
  179446. */
  179447. {
  179448. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179449. int ci, i, j, offset_x, offset_y;
  179450. JBLOCKARRAY src_buffer, dst_buffer;
  179451. JCOEFPTR src_ptr, dst_ptr;
  179452. jpeg_component_info *compptr;
  179453. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179454. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179455. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179456. compptr = dstinfo->comp_info + ci;
  179457. comp_width = MCU_cols * compptr->h_samp_factor;
  179458. comp_height = MCU_rows * compptr->v_samp_factor;
  179459. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179460. dst_blk_y += compptr->v_samp_factor) {
  179461. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179462. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179463. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179464. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179465. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179466. dst_blk_x += compptr->h_samp_factor) {
  179467. src_buffer = (*srcinfo->mem->access_virt_barray)
  179468. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179469. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179470. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179471. if (dst_blk_y < comp_height) {
  179472. src_ptr = src_buffer[offset_x]
  179473. [comp_height - dst_blk_y - offset_y - 1];
  179474. if (dst_blk_x < comp_width) {
  179475. /* Block is within the mirrorable area. */
  179476. dst_ptr = dst_buffer[offset_y]
  179477. [comp_width - dst_blk_x - offset_x - 1];
  179478. for (i = 0; i < DCTSIZE; i++) {
  179479. for (j = 0; j < DCTSIZE; j++) {
  179480. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179481. j++;
  179482. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179483. }
  179484. i++;
  179485. for (j = 0; j < DCTSIZE; j++) {
  179486. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179487. j++;
  179488. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179489. }
  179490. }
  179491. } else {
  179492. /* Right-edge blocks are mirrored in y only */
  179493. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179494. for (i = 0; i < DCTSIZE; i++) {
  179495. for (j = 0; j < DCTSIZE; j++) {
  179496. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179497. j++;
  179498. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179499. }
  179500. }
  179501. }
  179502. } else {
  179503. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179504. if (dst_blk_x < comp_width) {
  179505. /* Bottom-edge blocks are mirrored in x only */
  179506. dst_ptr = dst_buffer[offset_y]
  179507. [comp_width - dst_blk_x - offset_x - 1];
  179508. for (i = 0; i < DCTSIZE; i++) {
  179509. for (j = 0; j < DCTSIZE; j++)
  179510. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179511. i++;
  179512. for (j = 0; j < DCTSIZE; j++)
  179513. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179514. }
  179515. } else {
  179516. /* At lower right corner, just transpose, no mirroring */
  179517. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179518. for (i = 0; i < DCTSIZE; i++)
  179519. for (j = 0; j < DCTSIZE; j++)
  179520. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179521. }
  179522. }
  179523. }
  179524. }
  179525. }
  179526. }
  179527. }
  179528. }
  179529. /* Request any required workspace.
  179530. *
  179531. * We allocate the workspace virtual arrays from the source decompression
  179532. * object, so that all the arrays (both the original data and the workspace)
  179533. * will be taken into account while making memory management decisions.
  179534. * Hence, this routine must be called after jpeg_read_header (which reads
  179535. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179536. * the source's virtual arrays).
  179537. */
  179538. GLOBAL(void)
  179539. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179540. jpeg_transform_info *info)
  179541. {
  179542. jvirt_barray_ptr *coef_arrays = NULL;
  179543. jpeg_component_info *compptr;
  179544. int ci;
  179545. if (info->force_grayscale &&
  179546. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179547. srcinfo->num_components == 3) {
  179548. /* We'll only process the first component */
  179549. info->num_components = 1;
  179550. } else {
  179551. /* Process all the components */
  179552. info->num_components = srcinfo->num_components;
  179553. }
  179554. switch (info->transform) {
  179555. case JXFORM_NONE:
  179556. case JXFORM_FLIP_H:
  179557. /* Don't need a workspace array */
  179558. break;
  179559. case JXFORM_FLIP_V:
  179560. case JXFORM_ROT_180:
  179561. /* Need workspace arrays having same dimensions as source image.
  179562. * Note that we allocate arrays padded out to the next iMCU boundary,
  179563. * so that transform routines need not worry about missing edge blocks.
  179564. */
  179565. coef_arrays = (jvirt_barray_ptr *)
  179566. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179567. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179568. for (ci = 0; ci < info->num_components; ci++) {
  179569. compptr = srcinfo->comp_info + ci;
  179570. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179571. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179572. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179573. (long) compptr->h_samp_factor),
  179574. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179575. (long) compptr->v_samp_factor),
  179576. (JDIMENSION) compptr->v_samp_factor);
  179577. }
  179578. break;
  179579. case JXFORM_TRANSPOSE:
  179580. case JXFORM_TRANSVERSE:
  179581. case JXFORM_ROT_90:
  179582. case JXFORM_ROT_270:
  179583. /* Need workspace arrays having transposed dimensions.
  179584. * Note that we allocate arrays padded out to the next iMCU boundary,
  179585. * so that transform routines need not worry about missing edge blocks.
  179586. */
  179587. coef_arrays = (jvirt_barray_ptr *)
  179588. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179589. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179590. for (ci = 0; ci < info->num_components; ci++) {
  179591. compptr = srcinfo->comp_info + ci;
  179592. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179593. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179594. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179595. (long) compptr->v_samp_factor),
  179596. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179597. (long) compptr->h_samp_factor),
  179598. (JDIMENSION) compptr->h_samp_factor);
  179599. }
  179600. break;
  179601. }
  179602. info->workspace_coef_arrays = coef_arrays;
  179603. }
  179604. /* Transpose destination image parameters */
  179605. LOCAL(void)
  179606. transpose_critical_parameters (j_compress_ptr dstinfo)
  179607. {
  179608. int tblno, i, j, ci, itemp;
  179609. jpeg_component_info *compptr;
  179610. JQUANT_TBL *qtblptr;
  179611. JDIMENSION dtemp;
  179612. UINT16 qtemp;
  179613. /* Transpose basic image dimensions */
  179614. dtemp = dstinfo->image_width;
  179615. dstinfo->image_width = dstinfo->image_height;
  179616. dstinfo->image_height = dtemp;
  179617. /* Transpose sampling factors */
  179618. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179619. compptr = dstinfo->comp_info + ci;
  179620. itemp = compptr->h_samp_factor;
  179621. compptr->h_samp_factor = compptr->v_samp_factor;
  179622. compptr->v_samp_factor = itemp;
  179623. }
  179624. /* Transpose quantization tables */
  179625. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179626. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179627. if (qtblptr != NULL) {
  179628. for (i = 0; i < DCTSIZE; i++) {
  179629. for (j = 0; j < i; j++) {
  179630. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179631. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179632. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179633. }
  179634. }
  179635. }
  179636. }
  179637. }
  179638. /* Trim off any partial iMCUs on the indicated destination edge */
  179639. LOCAL(void)
  179640. trim_right_edge (j_compress_ptr dstinfo)
  179641. {
  179642. int ci, max_h_samp_factor;
  179643. JDIMENSION MCU_cols;
  179644. /* We have to compute max_h_samp_factor ourselves,
  179645. * because it hasn't been set yet in the destination
  179646. * (and we don't want to use the source's value).
  179647. */
  179648. max_h_samp_factor = 1;
  179649. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179650. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179651. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179652. }
  179653. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179654. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179655. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179656. }
  179657. LOCAL(void)
  179658. trim_bottom_edge (j_compress_ptr dstinfo)
  179659. {
  179660. int ci, max_v_samp_factor;
  179661. JDIMENSION MCU_rows;
  179662. /* We have to compute max_v_samp_factor ourselves,
  179663. * because it hasn't been set yet in the destination
  179664. * (and we don't want to use the source's value).
  179665. */
  179666. max_v_samp_factor = 1;
  179667. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179668. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179669. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179670. }
  179671. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179672. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179673. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179674. }
  179675. /* Adjust output image parameters as needed.
  179676. *
  179677. * This must be called after jpeg_copy_critical_parameters()
  179678. * and before jpeg_write_coefficients().
  179679. *
  179680. * The return value is the set of virtual coefficient arrays to be written
  179681. * (either the ones allocated by jtransform_request_workspace, or the
  179682. * original source data arrays). The caller will need to pass this value
  179683. * to jpeg_write_coefficients().
  179684. */
  179685. GLOBAL(jvirt_barray_ptr *)
  179686. jtransform_adjust_parameters (j_decompress_ptr,
  179687. j_compress_ptr dstinfo,
  179688. jvirt_barray_ptr *src_coef_arrays,
  179689. jpeg_transform_info *info)
  179690. {
  179691. /* If force-to-grayscale is requested, adjust destination parameters */
  179692. if (info->force_grayscale) {
  179693. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179694. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179695. * will get set to 1, which typically won't match the source.
  179696. * In fact we do this even if the source is already grayscale; that
  179697. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179698. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179699. */
  179700. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179701. dstinfo->num_components == 3) ||
  179702. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179703. dstinfo->num_components == 1)) {
  179704. /* We have to preserve the source's quantization table number. */
  179705. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179706. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179707. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179708. } else {
  179709. /* Sorry, can't do it */
  179710. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179711. }
  179712. }
  179713. /* Correct the destination's image dimensions etc if necessary */
  179714. switch (info->transform) {
  179715. case JXFORM_NONE:
  179716. /* Nothing to do */
  179717. break;
  179718. case JXFORM_FLIP_H:
  179719. if (info->trim)
  179720. trim_right_edge(dstinfo);
  179721. break;
  179722. case JXFORM_FLIP_V:
  179723. if (info->trim)
  179724. trim_bottom_edge(dstinfo);
  179725. break;
  179726. case JXFORM_TRANSPOSE:
  179727. transpose_critical_parameters(dstinfo);
  179728. /* transpose does NOT have to trim anything */
  179729. break;
  179730. case JXFORM_TRANSVERSE:
  179731. transpose_critical_parameters(dstinfo);
  179732. if (info->trim) {
  179733. trim_right_edge(dstinfo);
  179734. trim_bottom_edge(dstinfo);
  179735. }
  179736. break;
  179737. case JXFORM_ROT_90:
  179738. transpose_critical_parameters(dstinfo);
  179739. if (info->trim)
  179740. trim_right_edge(dstinfo);
  179741. break;
  179742. case JXFORM_ROT_180:
  179743. if (info->trim) {
  179744. trim_right_edge(dstinfo);
  179745. trim_bottom_edge(dstinfo);
  179746. }
  179747. break;
  179748. case JXFORM_ROT_270:
  179749. transpose_critical_parameters(dstinfo);
  179750. if (info->trim)
  179751. trim_bottom_edge(dstinfo);
  179752. break;
  179753. }
  179754. /* Return the appropriate output data set */
  179755. if (info->workspace_coef_arrays != NULL)
  179756. return info->workspace_coef_arrays;
  179757. return src_coef_arrays;
  179758. }
  179759. /* Execute the actual transformation, if any.
  179760. *
  179761. * This must be called *after* jpeg_write_coefficients, because it depends
  179762. * on jpeg_write_coefficients to have computed subsidiary values such as
  179763. * the per-component width and height fields in the destination object.
  179764. *
  179765. * Note that some transformations will modify the source data arrays!
  179766. */
  179767. GLOBAL(void)
  179768. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179769. j_compress_ptr dstinfo,
  179770. jvirt_barray_ptr *src_coef_arrays,
  179771. jpeg_transform_info *info)
  179772. {
  179773. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179774. switch (info->transform) {
  179775. case JXFORM_NONE:
  179776. break;
  179777. case JXFORM_FLIP_H:
  179778. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179779. break;
  179780. case JXFORM_FLIP_V:
  179781. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179782. break;
  179783. case JXFORM_TRANSPOSE:
  179784. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179785. break;
  179786. case JXFORM_TRANSVERSE:
  179787. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179788. break;
  179789. case JXFORM_ROT_90:
  179790. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179791. break;
  179792. case JXFORM_ROT_180:
  179793. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179794. break;
  179795. case JXFORM_ROT_270:
  179796. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179797. break;
  179798. }
  179799. }
  179800. #endif /* TRANSFORMS_SUPPORTED */
  179801. /* Setup decompression object to save desired markers in memory.
  179802. * This must be called before jpeg_read_header() to have the desired effect.
  179803. */
  179804. GLOBAL(void)
  179805. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179806. {
  179807. #ifdef SAVE_MARKERS_SUPPORTED
  179808. int m;
  179809. /* Save comments except under NONE option */
  179810. if (option != JCOPYOPT_NONE) {
  179811. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179812. }
  179813. /* Save all types of APPn markers iff ALL option */
  179814. if (option == JCOPYOPT_ALL) {
  179815. for (m = 0; m < 16; m++)
  179816. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179817. }
  179818. #endif /* SAVE_MARKERS_SUPPORTED */
  179819. }
  179820. /* Copy markers saved in the given source object to the destination object.
  179821. * This should be called just after jpeg_start_compress() or
  179822. * jpeg_write_coefficients().
  179823. * Note that those routines will have written the SOI, and also the
  179824. * JFIF APP0 or Adobe APP14 markers if selected.
  179825. */
  179826. GLOBAL(void)
  179827. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179828. JCOPY_OPTION)
  179829. {
  179830. jpeg_saved_marker_ptr marker;
  179831. /* In the current implementation, we don't actually need to examine the
  179832. * option flag here; we just copy everything that got saved.
  179833. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179834. * if the encoder library already wrote one.
  179835. */
  179836. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179837. if (dstinfo->write_JFIF_header &&
  179838. marker->marker == JPEG_APP0 &&
  179839. marker->data_length >= 5 &&
  179840. GETJOCTET(marker->data[0]) == 0x4A &&
  179841. GETJOCTET(marker->data[1]) == 0x46 &&
  179842. GETJOCTET(marker->data[2]) == 0x49 &&
  179843. GETJOCTET(marker->data[3]) == 0x46 &&
  179844. GETJOCTET(marker->data[4]) == 0)
  179845. continue; /* reject duplicate JFIF */
  179846. if (dstinfo->write_Adobe_marker &&
  179847. marker->marker == JPEG_APP0+14 &&
  179848. marker->data_length >= 5 &&
  179849. GETJOCTET(marker->data[0]) == 0x41 &&
  179850. GETJOCTET(marker->data[1]) == 0x64 &&
  179851. GETJOCTET(marker->data[2]) == 0x6F &&
  179852. GETJOCTET(marker->data[3]) == 0x62 &&
  179853. GETJOCTET(marker->data[4]) == 0x65)
  179854. continue; /* reject duplicate Adobe */
  179855. #ifdef NEED_FAR_POINTERS
  179856. /* We could use jpeg_write_marker if the data weren't FAR... */
  179857. {
  179858. unsigned int i;
  179859. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179860. for (i = 0; i < marker->data_length; i++)
  179861. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179862. }
  179863. #else
  179864. jpeg_write_marker(dstinfo, marker->marker,
  179865. marker->data, marker->data_length);
  179866. #endif
  179867. }
  179868. }
  179869. /*** End of inlined file: transupp.c ***/
  179870. #else
  179871. #define JPEG_INTERNALS
  179872. #undef FAR
  179873. #include <jpeglib.h>
  179874. #endif
  179875. }
  179876. #undef max
  179877. #undef min
  179878. #if JUCE_MSVC
  179879. #pragma warning (pop)
  179880. #endif
  179881. BEGIN_JUCE_NAMESPACE
  179882. namespace JPEGHelpers
  179883. {
  179884. using namespace jpeglibNamespace;
  179885. #if ! JUCE_MSVC
  179886. using jpeglibNamespace::boolean;
  179887. #endif
  179888. struct JPEGDecodingFailure {};
  179889. static void fatalErrorHandler (j_common_ptr)
  179890. {
  179891. throw JPEGDecodingFailure();
  179892. }
  179893. static void silentErrorCallback1 (j_common_ptr) {}
  179894. static void silentErrorCallback2 (j_common_ptr, int) {}
  179895. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179896. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179897. {
  179898. zerostruct (err);
  179899. err.error_exit = fatalErrorHandler;
  179900. err.emit_message = silentErrorCallback2;
  179901. err.output_message = silentErrorCallback1;
  179902. err.format_message = silentErrorCallback3;
  179903. err.reset_error_mgr = silentErrorCallback1;
  179904. }
  179905. static void dummyCallback1 (j_decompress_ptr)
  179906. {
  179907. }
  179908. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179909. {
  179910. decompStruct->src->next_input_byte += num;
  179911. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179912. decompStruct->src->bytes_in_buffer -= num;
  179913. }
  179914. static boolean jpegFill (j_decompress_ptr)
  179915. {
  179916. return 0;
  179917. }
  179918. static const int jpegBufferSize = 512;
  179919. struct JuceJpegDest : public jpeg_destination_mgr
  179920. {
  179921. OutputStream* output;
  179922. char* buffer;
  179923. };
  179924. static void jpegWriteInit (j_compress_ptr)
  179925. {
  179926. }
  179927. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179928. {
  179929. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179930. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179931. dest->output->write (dest->buffer, (int) numToWrite);
  179932. }
  179933. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179934. {
  179935. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179936. const int numToWrite = jpegBufferSize;
  179937. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179938. dest->free_in_buffer = jpegBufferSize;
  179939. return dest->output->write (dest->buffer, numToWrite);
  179940. }
  179941. }
  179942. JPEGImageFormat::JPEGImageFormat()
  179943. : quality (-1.0f)
  179944. {
  179945. }
  179946. JPEGImageFormat::~JPEGImageFormat() {}
  179947. void JPEGImageFormat::setQuality (const float newQuality)
  179948. {
  179949. quality = newQuality;
  179950. }
  179951. const String JPEGImageFormat::getFormatName()
  179952. {
  179953. return "JPEG";
  179954. }
  179955. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179956. {
  179957. const int bytesNeeded = 10;
  179958. uint8 header [bytesNeeded];
  179959. if (in.read (header, bytesNeeded) == bytesNeeded)
  179960. {
  179961. return header[0] == 0xff
  179962. && header[1] == 0xd8
  179963. && header[2] == 0xff
  179964. && (header[3] == 0xe0 || header[3] == 0xe1);
  179965. }
  179966. return false;
  179967. }
  179968. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179969. const Image juce_loadWithCoreImage (InputStream& input);
  179970. #endif
  179971. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179972. {
  179973. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179974. return juce_loadWithCoreImage (in);
  179975. #else
  179976. using namespace jpeglibNamespace;
  179977. using namespace JPEGHelpers;
  179978. MemoryOutputStream mb;
  179979. mb.writeFromInputStream (in, -1);
  179980. Image image;
  179981. if (mb.getDataSize() > 16)
  179982. {
  179983. struct jpeg_decompress_struct jpegDecompStruct;
  179984. struct jpeg_error_mgr jerr;
  179985. setupSilentErrorHandler (jerr);
  179986. jpegDecompStruct.err = &jerr;
  179987. jpeg_create_decompress (&jpegDecompStruct);
  179988. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179989. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179990. jpegDecompStruct.src->init_source = dummyCallback1;
  179991. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179992. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179993. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179994. jpegDecompStruct.src->term_source = dummyCallback1;
  179995. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179996. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179997. try
  179998. {
  179999. jpeg_read_header (&jpegDecompStruct, TRUE);
  180000. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180001. const int width = jpegDecompStruct.output_width;
  180002. const int height = jpegDecompStruct.output_height;
  180003. jpegDecompStruct.out_color_space = JCS_RGB;
  180004. JSAMPARRAY buffer
  180005. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180006. JPOOL_IMAGE,
  180007. width * 3, 1);
  180008. if (jpeg_start_decompress (&jpegDecompStruct))
  180009. {
  180010. image = Image (Image::RGB, width, height, false);
  180011. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180012. const Image::BitmapData destData (image, true);
  180013. for (int y = 0; y < height; ++y)
  180014. {
  180015. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180016. const uint8* src = *buffer;
  180017. uint8* dest = destData.getLinePointer (y);
  180018. if (hasAlphaChan)
  180019. {
  180020. for (int i = width; --i >= 0;)
  180021. {
  180022. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180023. ((PixelARGB*) dest)->premultiply();
  180024. dest += destData.pixelStride;
  180025. src += 3;
  180026. }
  180027. }
  180028. else
  180029. {
  180030. for (int i = width; --i >= 0;)
  180031. {
  180032. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180033. dest += destData.pixelStride;
  180034. src += 3;
  180035. }
  180036. }
  180037. }
  180038. jpeg_finish_decompress (&jpegDecompStruct);
  180039. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180040. }
  180041. jpeg_destroy_decompress (&jpegDecompStruct);
  180042. }
  180043. catch (...)
  180044. {}
  180045. }
  180046. return image;
  180047. #endif
  180048. }
  180049. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180050. {
  180051. using namespace jpeglibNamespace;
  180052. using namespace JPEGHelpers;
  180053. if (image.hasAlphaChannel())
  180054. {
  180055. // this method could fill the background in white and still save the image..
  180056. jassertfalse;
  180057. return true;
  180058. }
  180059. struct jpeg_compress_struct jpegCompStruct;
  180060. struct jpeg_error_mgr jerr;
  180061. setupSilentErrorHandler (jerr);
  180062. jpegCompStruct.err = &jerr;
  180063. jpeg_create_compress (&jpegCompStruct);
  180064. JuceJpegDest dest;
  180065. jpegCompStruct.dest = &dest;
  180066. dest.output = &out;
  180067. HeapBlock <char> tempBuffer (jpegBufferSize);
  180068. dest.buffer = tempBuffer;
  180069. dest.next_output_byte = (JOCTET*) dest.buffer;
  180070. dest.free_in_buffer = jpegBufferSize;
  180071. dest.init_destination = jpegWriteInit;
  180072. dest.empty_output_buffer = jpegWriteFlush;
  180073. dest.term_destination = jpegWriteTerminate;
  180074. jpegCompStruct.image_width = image.getWidth();
  180075. jpegCompStruct.image_height = image.getHeight();
  180076. jpegCompStruct.input_components = 3;
  180077. jpegCompStruct.in_color_space = JCS_RGB;
  180078. jpegCompStruct.write_JFIF_header = 1;
  180079. jpegCompStruct.X_density = 72;
  180080. jpegCompStruct.Y_density = 72;
  180081. jpeg_set_defaults (&jpegCompStruct);
  180082. jpegCompStruct.dct_method = JDCT_FLOAT;
  180083. jpegCompStruct.optimize_coding = 1;
  180084. //jpegCompStruct.smoothing_factor = 10;
  180085. if (quality < 0.0f)
  180086. quality = 0.85f;
  180087. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180088. jpeg_start_compress (&jpegCompStruct, TRUE);
  180089. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180090. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180091. JPOOL_IMAGE, strideBytes, 1);
  180092. const Image::BitmapData srcData (image, false);
  180093. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180094. {
  180095. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180096. uint8* dst = *buffer;
  180097. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180098. {
  180099. *dst++ = ((const PixelRGB*) src)->getRed();
  180100. *dst++ = ((const PixelRGB*) src)->getGreen();
  180101. *dst++ = ((const PixelRGB*) src)->getBlue();
  180102. src += srcData.pixelStride;
  180103. }
  180104. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180105. }
  180106. jpeg_finish_compress (&jpegCompStruct);
  180107. jpeg_destroy_compress (&jpegCompStruct);
  180108. out.flush();
  180109. return true;
  180110. }
  180111. END_JUCE_NAMESPACE
  180112. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180113. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180114. #if JUCE_MSVC
  180115. #pragma warning (push)
  180116. #pragma warning (disable: 4390 4611)
  180117. #endif
  180118. namespace zlibNamespace
  180119. {
  180120. #if JUCE_INCLUDE_ZLIB_CODE
  180121. #undef OS_CODE
  180122. #undef fdopen
  180123. #undef OS_CODE
  180124. #else
  180125. #include <zlib.h>
  180126. #endif
  180127. }
  180128. namespace pnglibNamespace
  180129. {
  180130. using namespace zlibNamespace;
  180131. #if JUCE_INCLUDE_PNGLIB_CODE
  180132. #if _MSC_VER != 1310
  180133. using ::calloc; // (causes conflict in VS.NET 2003)
  180134. using ::malloc;
  180135. using ::free;
  180136. #endif
  180137. using ::abs;
  180138. #define PNG_INTERNAL
  180139. #define NO_DUMMY_DECL
  180140. #define PNG_SETJMP_NOT_SUPPORTED
  180141. /*** Start of inlined file: png.h ***/
  180142. /* png.h - header file for PNG reference library
  180143. *
  180144. * libpng version 1.2.21 - October 4, 2007
  180145. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180146. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180147. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180148. *
  180149. * Authors and maintainers:
  180150. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180151. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180152. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180153. * See also "Contributing Authors", below.
  180154. *
  180155. * Note about libpng version numbers:
  180156. *
  180157. * Due to various miscommunications, unforeseen code incompatibilities
  180158. * and occasional factors outside the authors' control, version numbering
  180159. * on the library has not always been consistent and straightforward.
  180160. * The following table summarizes matters since version 0.89c, which was
  180161. * the first widely used release:
  180162. *
  180163. * source png.h png.h shared-lib
  180164. * version string int version
  180165. * ------- ------ ----- ----------
  180166. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180167. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180168. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180169. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180170. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180171. * 0.97c 0.97 97 2.0.97
  180172. * 0.98 0.98 98 2.0.98
  180173. * 0.99 0.99 98 2.0.99
  180174. * 0.99a-m 0.99 99 2.0.99
  180175. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180176. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180177. * 1.0.1 png.h string is 10001 2.1.0
  180178. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180179. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180180. * 1.0.2a-b 10003 version, except as noted.
  180181. * 1.0.3 10003
  180182. * 1.0.3a-d 10004
  180183. * 1.0.4 10004
  180184. * 1.0.4a-f 10005
  180185. * 1.0.5 (+ 2 patches) 10005
  180186. * 1.0.5a-d 10006
  180187. * 1.0.5e-r 10100 (not source compatible)
  180188. * 1.0.5s-v 10006 (not binary compatible)
  180189. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180190. * 1.0.6d-f 10007 (still binary incompatible)
  180191. * 1.0.6g 10007
  180192. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180193. * 1.0.6i 10007 10.6i
  180194. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180195. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180196. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180197. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180198. * 1.0.7 1 10007 (still compatible)
  180199. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180200. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180201. * 1.0.8 1 10008 2.1.0.8
  180202. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180203. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180204. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180205. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180206. * 1.0.9 1 10009 2.1.0.9
  180207. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180208. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180209. * 1.0.10 1 10010 2.1.0.10
  180210. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180211. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180212. * 1.0.11 1 10011 2.1.0.11
  180213. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180214. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180215. * 1.0.12 2 10012 2.1.0.12
  180216. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180217. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180218. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180219. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180220. * 1.2.0 3 10200 3.1.2.0
  180221. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180222. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180223. * 1.2.1 3 10201 3.1.2.1
  180224. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180225. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180226. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180227. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180228. * 1.0.13 10 10013 10.so.0.1.0.13
  180229. * 1.2.2 12 10202 12.so.0.1.2.2
  180230. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180231. * 1.2.3 12 10203 12.so.0.1.2.3
  180232. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180233. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180234. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180235. * 1.0.14 10 10014 10.so.0.1.0.14
  180236. * 1.2.4 13 10204 12.so.0.1.2.4
  180237. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180238. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180239. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180240. * 1.0.15 10 10015 10.so.0.1.0.15
  180241. * 1.2.5 13 10205 12.so.0.1.2.5
  180242. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180243. * 1.0.16 10 10016 10.so.0.1.0.16
  180244. * 1.2.6 13 10206 12.so.0.1.2.6
  180245. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180246. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180247. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180248. * 1.0.17 10 10017 10.so.0.1.0.17
  180249. * 1.2.7 13 10207 12.so.0.1.2.7
  180250. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180251. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180252. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180253. * 1.0.18 10 10018 10.so.0.1.0.18
  180254. * 1.2.8 13 10208 12.so.0.1.2.8
  180255. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180256. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180257. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180258. * 1.2.9 13 10209 12.so.0.9[.0]
  180259. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180260. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180261. * 1.2.10 13 10210 12.so.0.10[.0]
  180262. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180263. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180264. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180265. * 1.0.19 10 10019 10.so.0.19[.0]
  180266. * 1.2.11 13 10211 12.so.0.11[.0]
  180267. * 1.0.20 10 10020 10.so.0.20[.0]
  180268. * 1.2.12 13 10212 12.so.0.12[.0]
  180269. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180270. * 1.0.21 10 10021 10.so.0.21[.0]
  180271. * 1.2.13 13 10213 12.so.0.13[.0]
  180272. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180273. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180274. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180275. * 1.0.22 10 10022 10.so.0.22[.0]
  180276. * 1.2.14 13 10214 12.so.0.14[.0]
  180277. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180278. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180279. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180280. * 1.0.23 10 10023 10.so.0.23[.0]
  180281. * 1.2.15 13 10215 12.so.0.15[.0]
  180282. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180283. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180284. * 1.0.24 10 10024 10.so.0.24[.0]
  180285. * 1.2.16 13 10216 12.so.0.16[.0]
  180286. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180287. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180288. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180289. * 1.0.25 10 10025 10.so.0.25[.0]
  180290. * 1.2.17 13 10217 12.so.0.17[.0]
  180291. * 1.0.26 10 10026 10.so.0.26[.0]
  180292. * 1.2.18 13 10218 12.so.0.18[.0]
  180293. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180294. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180295. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180296. * 1.0.27 10 10027 10.so.0.27[.0]
  180297. * 1.2.19 13 10219 12.so.0.19[.0]
  180298. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180299. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180300. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180301. * 1.0.28 10 10028 10.so.0.28[.0]
  180302. * 1.2.20 13 10220 12.so.0.20[.0]
  180303. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180304. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180305. * 1.0.29 10 10029 10.so.0.29[.0]
  180306. * 1.2.21 13 10221 12.so.0.21[.0]
  180307. *
  180308. * Henceforth the source version will match the shared-library major
  180309. * and minor numbers; the shared-library major version number will be
  180310. * used for changes in backward compatibility, as it is intended. The
  180311. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180312. * for applications, is an unsigned integer of the form xyyzz corresponding
  180313. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180314. * were given the previous public release number plus a letter, until
  180315. * version 1.0.6j; from then on they were given the upcoming public
  180316. * release number plus "betaNN" or "rcN".
  180317. *
  180318. * Binary incompatibility exists only when applications make direct access
  180319. * to the info_ptr or png_ptr members through png.h, and the compiled
  180320. * application is loaded with a different version of the library.
  180321. *
  180322. * DLLNUM will change each time there are forward or backward changes
  180323. * in binary compatibility (e.g., when a new feature is added).
  180324. *
  180325. * See libpng.txt or libpng.3 for more information. The PNG specification
  180326. * is available as a W3C Recommendation and as an ISO Specification,
  180327. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180328. */
  180329. /*
  180330. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180331. *
  180332. * If you modify libpng you may insert additional notices immediately following
  180333. * this sentence.
  180334. *
  180335. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180336. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180337. * distributed according to the same disclaimer and license as libpng-1.2.5
  180338. * with the following individual added to the list of Contributing Authors:
  180339. *
  180340. * Cosmin Truta
  180341. *
  180342. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180343. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180344. * distributed according to the same disclaimer and license as libpng-1.0.6
  180345. * with the following individuals added to the list of Contributing Authors:
  180346. *
  180347. * Simon-Pierre Cadieux
  180348. * Eric S. Raymond
  180349. * Gilles Vollant
  180350. *
  180351. * and with the following additions to the disclaimer:
  180352. *
  180353. * There is no warranty against interference with your enjoyment of the
  180354. * library or against infringement. There is no warranty that our
  180355. * efforts or the library will fulfill any of your particular purposes
  180356. * or needs. This library is provided with all faults, and the entire
  180357. * risk of satisfactory quality, performance, accuracy, and effort is with
  180358. * the user.
  180359. *
  180360. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180361. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180362. * distributed according to the same disclaimer and license as libpng-0.96,
  180363. * with the following individuals added to the list of Contributing Authors:
  180364. *
  180365. * Tom Lane
  180366. * Glenn Randers-Pehrson
  180367. * Willem van Schaik
  180368. *
  180369. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180370. * Copyright (c) 1996, 1997 Andreas Dilger
  180371. * Distributed according to the same disclaimer and license as libpng-0.88,
  180372. * with the following individuals added to the list of Contributing Authors:
  180373. *
  180374. * John Bowler
  180375. * Kevin Bracey
  180376. * Sam Bushell
  180377. * Magnus Holmgren
  180378. * Greg Roelofs
  180379. * Tom Tanner
  180380. *
  180381. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180382. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180383. *
  180384. * For the purposes of this copyright and license, "Contributing Authors"
  180385. * is defined as the following set of individuals:
  180386. *
  180387. * Andreas Dilger
  180388. * Dave Martindale
  180389. * Guy Eric Schalnat
  180390. * Paul Schmidt
  180391. * Tim Wegner
  180392. *
  180393. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180394. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180395. * including, without limitation, the warranties of merchantability and of
  180396. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180397. * assume no liability for direct, indirect, incidental, special, exemplary,
  180398. * or consequential damages, which may result from the use of the PNG
  180399. * Reference Library, even if advised of the possibility of such damage.
  180400. *
  180401. * Permission is hereby granted to use, copy, modify, and distribute this
  180402. * source code, or portions hereof, for any purpose, without fee, subject
  180403. * to the following restrictions:
  180404. *
  180405. * 1. The origin of this source code must not be misrepresented.
  180406. *
  180407. * 2. Altered versions must be plainly marked as such and
  180408. * must not be misrepresented as being the original source.
  180409. *
  180410. * 3. This Copyright notice may not be removed or altered from
  180411. * any source or altered source distribution.
  180412. *
  180413. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180414. * fee, and encourage the use of this source code as a component to
  180415. * supporting the PNG file format in commercial products. If you use this
  180416. * source code in a product, acknowledgment is not required but would be
  180417. * appreciated.
  180418. */
  180419. /*
  180420. * A "png_get_copyright" function is available, for convenient use in "about"
  180421. * boxes and the like:
  180422. *
  180423. * printf("%s",png_get_copyright(NULL));
  180424. *
  180425. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180426. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180427. */
  180428. /*
  180429. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180430. * certification mark of the Open Source Initiative.
  180431. */
  180432. /*
  180433. * The contributing authors would like to thank all those who helped
  180434. * with testing, bug fixes, and patience. This wouldn't have been
  180435. * possible without all of you.
  180436. *
  180437. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180438. */
  180439. /*
  180440. * Y2K compliance in libpng:
  180441. * =========================
  180442. *
  180443. * October 4, 2007
  180444. *
  180445. * Since the PNG Development group is an ad-hoc body, we can't make
  180446. * an official declaration.
  180447. *
  180448. * This is your unofficial assurance that libpng from version 0.71 and
  180449. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180450. * versions were also Y2K compliant.
  180451. *
  180452. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180453. * that will hold years up to 65535. The other two hold the date in text
  180454. * format, and will hold years up to 9999.
  180455. *
  180456. * The integer is
  180457. * "png_uint_16 year" in png_time_struct.
  180458. *
  180459. * The strings are
  180460. * "png_charp time_buffer" in png_struct and
  180461. * "near_time_buffer", which is a local character string in png.c.
  180462. *
  180463. * There are seven time-related functions:
  180464. * png.c: png_convert_to_rfc_1123() in png.c
  180465. * (formerly png_convert_to_rfc_1152() in error)
  180466. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180467. * png_convert_from_time_t() in pngwrite.c
  180468. * png_get_tIME() in pngget.c
  180469. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180470. * png_set_tIME() in pngset.c
  180471. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180472. *
  180473. * All handle dates properly in a Y2K environment. The
  180474. * png_convert_from_time_t() function calls gmtime() to convert from system
  180475. * clock time, which returns (year - 1900), which we properly convert to
  180476. * the full 4-digit year. There is a possibility that applications using
  180477. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180478. * function, or that they are incorrectly passing only a 2-digit year
  180479. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180480. * but this is not under our control. The libpng documentation has always
  180481. * stated that it works with 4-digit years, and the APIs have been
  180482. * documented as such.
  180483. *
  180484. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180485. * integer to hold the year, and can hold years as large as 65535.
  180486. *
  180487. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180488. * no date-related code.
  180489. *
  180490. * Glenn Randers-Pehrson
  180491. * libpng maintainer
  180492. * PNG Development Group
  180493. */
  180494. #ifndef PNG_H
  180495. #define PNG_H
  180496. /* This is not the place to learn how to use libpng. The file libpng.txt
  180497. * describes how to use libpng, and the file example.c summarizes it
  180498. * with some code on which to build. This file is useful for looking
  180499. * at the actual function definitions and structure components.
  180500. */
  180501. /* Version information for png.h - this should match the version in png.c */
  180502. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180503. #define PNG_HEADER_VERSION_STRING \
  180504. " libpng version 1.2.21 - October 4, 2007\n"
  180505. #define PNG_LIBPNG_VER_SONUM 0
  180506. #define PNG_LIBPNG_VER_DLLNUM 13
  180507. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180508. #define PNG_LIBPNG_VER_MAJOR 1
  180509. #define PNG_LIBPNG_VER_MINOR 2
  180510. #define PNG_LIBPNG_VER_RELEASE 21
  180511. /* This should match the numeric part of the final component of
  180512. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180513. #define PNG_LIBPNG_VER_BUILD 0
  180514. /* Release Status */
  180515. #define PNG_LIBPNG_BUILD_ALPHA 1
  180516. #define PNG_LIBPNG_BUILD_BETA 2
  180517. #define PNG_LIBPNG_BUILD_RC 3
  180518. #define PNG_LIBPNG_BUILD_STABLE 4
  180519. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180520. /* Release-Specific Flags */
  180521. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180522. PNG_LIBPNG_BUILD_STABLE only */
  180523. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180524. PNG_LIBPNG_BUILD_SPECIAL */
  180525. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180526. PNG_LIBPNG_BUILD_PRIVATE */
  180527. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180528. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180529. * We must not include leading zeros.
  180530. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180531. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180532. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180533. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180534. #ifndef PNG_VERSION_INFO_ONLY
  180535. /* include the compression library's header */
  180536. #endif
  180537. /* include all user configurable info, including optional assembler routines */
  180538. /*** Start of inlined file: pngconf.h ***/
  180539. /* pngconf.h - machine configurable file for libpng
  180540. *
  180541. * libpng version 1.2.21 - October 4, 2007
  180542. * For conditions of distribution and use, see copyright notice in png.h
  180543. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180544. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180545. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180546. */
  180547. /* Any machine specific code is near the front of this file, so if you
  180548. * are configuring libpng for a machine, you may want to read the section
  180549. * starting here down to where it starts to typedef png_color, png_text,
  180550. * and png_info.
  180551. */
  180552. #ifndef PNGCONF_H
  180553. #define PNGCONF_H
  180554. #define PNG_1_2_X
  180555. // These are some Juce config settings that should remove any unnecessary code bloat..
  180556. #define PNG_NO_STDIO 1
  180557. #define PNG_DEBUG 0
  180558. #define PNG_NO_WARNINGS 1
  180559. #define PNG_NO_ERROR_TEXT 1
  180560. #define PNG_NO_ERROR_NUMBERS 1
  180561. #define PNG_NO_USER_MEM 1
  180562. #define PNG_NO_READ_iCCP 1
  180563. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180564. #define PNG_NO_READ_USER_CHUNKS 1
  180565. #define PNG_NO_READ_iTXt 1
  180566. #define PNG_NO_READ_sCAL 1
  180567. #define PNG_NO_READ_sPLT 1
  180568. #define png_error(a, b) png_err(a)
  180569. #define png_warning(a, b)
  180570. #define png_chunk_error(a, b) png_err(a)
  180571. #define png_chunk_warning(a, b)
  180572. /*
  180573. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180574. * includes the resource compiler for Windows DLL configurations.
  180575. */
  180576. #ifdef PNG_USER_CONFIG
  180577. # ifndef PNG_USER_PRIVATEBUILD
  180578. # define PNG_USER_PRIVATEBUILD
  180579. # endif
  180580. #include "pngusr.h"
  180581. #endif
  180582. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180583. #ifdef PNG_CONFIGURE_LIBPNG
  180584. #ifdef HAVE_CONFIG_H
  180585. #include "config.h"
  180586. #endif
  180587. #endif
  180588. /*
  180589. * Added at libpng-1.2.8
  180590. *
  180591. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180592. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180593. * the DLL was built>
  180594. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180595. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180596. * distinguish your DLL from those of the official release. These
  180597. * correspond to the trailing letters that come after the version
  180598. * number and must match your private DLL name>
  180599. * e.g. // private DLL "libpng13gx.dll"
  180600. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180601. *
  180602. * The following macros are also at your disposal if you want to complete the
  180603. * DLL VERSIONINFO structure.
  180604. * - PNG_USER_VERSIONINFO_COMMENTS
  180605. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180606. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180607. */
  180608. #ifdef __STDC__
  180609. #ifdef SPECIALBUILD
  180610. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180611. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180612. #endif
  180613. #ifdef PRIVATEBUILD
  180614. # pragma message("PRIVATEBUILD is deprecated.\
  180615. Use PNG_USER_PRIVATEBUILD instead.")
  180616. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180617. #endif
  180618. #endif /* __STDC__ */
  180619. #ifndef PNG_VERSION_INFO_ONLY
  180620. /* End of material added to libpng-1.2.8 */
  180621. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180622. Restored at libpng-1.2.21 */
  180623. # define PNG_WARN_UNINITIALIZED_ROW 1
  180624. /* End of material added at libpng-1.2.19/1.2.21 */
  180625. /* This is the size of the compression buffer, and thus the size of
  180626. * an IDAT chunk. Make this whatever size you feel is best for your
  180627. * machine. One of these will be allocated per png_struct. When this
  180628. * is full, it writes the data to the disk, and does some other
  180629. * calculations. Making this an extremely small size will slow
  180630. * the library down, but you may want to experiment to determine
  180631. * where it becomes significant, if you are concerned with memory
  180632. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180633. * this describes the size of the buffer available to read the data in.
  180634. * Unless this gets smaller than the size of a row (compressed),
  180635. * it should not make much difference how big this is.
  180636. */
  180637. #ifndef PNG_ZBUF_SIZE
  180638. # define PNG_ZBUF_SIZE 8192
  180639. #endif
  180640. /* Enable if you want a write-only libpng */
  180641. #ifndef PNG_NO_READ_SUPPORTED
  180642. # define PNG_READ_SUPPORTED
  180643. #endif
  180644. /* Enable if you want a read-only libpng */
  180645. #ifndef PNG_NO_WRITE_SUPPORTED
  180646. # define PNG_WRITE_SUPPORTED
  180647. #endif
  180648. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180649. support PNGs that are embedded in MNG datastreams */
  180650. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180651. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180652. # define PNG_MNG_FEATURES_SUPPORTED
  180653. # endif
  180654. #endif
  180655. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180656. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180657. # define PNG_FLOATING_POINT_SUPPORTED
  180658. # endif
  180659. #endif
  180660. /* If you are running on a machine where you cannot allocate more
  180661. * than 64K of memory at once, uncomment this. While libpng will not
  180662. * normally need that much memory in a chunk (unless you load up a very
  180663. * large file), zlib needs to know how big of a chunk it can use, and
  180664. * libpng thus makes sure to check any memory allocation to verify it
  180665. * will fit into memory.
  180666. #define PNG_MAX_MALLOC_64K
  180667. */
  180668. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180669. # define PNG_MAX_MALLOC_64K
  180670. #endif
  180671. /* Special munging to support doing things the 'cygwin' way:
  180672. * 'Normal' png-on-win32 defines/defaults:
  180673. * PNG_BUILD_DLL -- building dll
  180674. * PNG_USE_DLL -- building an application, linking to dll
  180675. * (no define) -- building static library, or building an
  180676. * application and linking to the static lib
  180677. * 'Cygwin' defines/defaults:
  180678. * PNG_BUILD_DLL -- (ignored) building the dll
  180679. * (no define) -- (ignored) building an application, linking to the dll
  180680. * PNG_STATIC -- (ignored) building the static lib, or building an
  180681. * application that links to the static lib.
  180682. * ALL_STATIC -- (ignored) building various static libs, or building an
  180683. * application that links to the static libs.
  180684. * Thus,
  180685. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180686. * this bit of #ifdefs will define the 'correct' config variables based on
  180687. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180688. * unnecessary.
  180689. *
  180690. * Also, the precedence order is:
  180691. * ALL_STATIC (since we can't #undef something outside our namespace)
  180692. * PNG_BUILD_DLL
  180693. * PNG_STATIC
  180694. * (nothing) == PNG_USE_DLL
  180695. *
  180696. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180697. * of auto-import in binutils, we no longer need to worry about
  180698. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180699. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180700. * to __declspec() stuff. However, we DO need to worry about
  180701. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180702. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180703. */
  180704. #if defined(__CYGWIN__)
  180705. # if defined(ALL_STATIC)
  180706. # if defined(PNG_BUILD_DLL)
  180707. # undef PNG_BUILD_DLL
  180708. # endif
  180709. # if defined(PNG_USE_DLL)
  180710. # undef PNG_USE_DLL
  180711. # endif
  180712. # if defined(PNG_DLL)
  180713. # undef PNG_DLL
  180714. # endif
  180715. # if !defined(PNG_STATIC)
  180716. # define PNG_STATIC
  180717. # endif
  180718. # else
  180719. # if defined (PNG_BUILD_DLL)
  180720. # if defined(PNG_STATIC)
  180721. # undef PNG_STATIC
  180722. # endif
  180723. # if defined(PNG_USE_DLL)
  180724. # undef PNG_USE_DLL
  180725. # endif
  180726. # if !defined(PNG_DLL)
  180727. # define PNG_DLL
  180728. # endif
  180729. # else
  180730. # if defined(PNG_STATIC)
  180731. # if defined(PNG_USE_DLL)
  180732. # undef PNG_USE_DLL
  180733. # endif
  180734. # if defined(PNG_DLL)
  180735. # undef PNG_DLL
  180736. # endif
  180737. # else
  180738. # if !defined(PNG_USE_DLL)
  180739. # define PNG_USE_DLL
  180740. # endif
  180741. # if !defined(PNG_DLL)
  180742. # define PNG_DLL
  180743. # endif
  180744. # endif
  180745. # endif
  180746. # endif
  180747. #endif
  180748. /* This protects us against compilers that run on a windowing system
  180749. * and thus don't have or would rather us not use the stdio types:
  180750. * stdin, stdout, and stderr. The only one currently used is stderr
  180751. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180752. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180753. * will also prevent these, plus will prevent the entire set of stdio
  180754. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180755. * unless (PNG_DEBUG > 0) has been #defined.
  180756. *
  180757. * #define PNG_NO_CONSOLE_IO
  180758. * #define PNG_NO_STDIO
  180759. */
  180760. #if defined(_WIN32_WCE)
  180761. # include <windows.h>
  180762. /* Console I/O functions are not supported on WindowsCE */
  180763. # define PNG_NO_CONSOLE_IO
  180764. # ifdef PNG_DEBUG
  180765. # undef PNG_DEBUG
  180766. # endif
  180767. #endif
  180768. #ifdef PNG_BUILD_DLL
  180769. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180770. # ifndef PNG_NO_CONSOLE_IO
  180771. # define PNG_NO_CONSOLE_IO
  180772. # endif
  180773. # endif
  180774. #endif
  180775. # ifdef PNG_NO_STDIO
  180776. # ifndef PNG_NO_CONSOLE_IO
  180777. # define PNG_NO_CONSOLE_IO
  180778. # endif
  180779. # ifdef PNG_DEBUG
  180780. # if (PNG_DEBUG > 0)
  180781. # include <stdio.h>
  180782. # endif
  180783. # endif
  180784. # else
  180785. # if !defined(_WIN32_WCE)
  180786. /* "stdio.h" functions are not supported on WindowsCE */
  180787. # include <stdio.h>
  180788. # endif
  180789. # endif
  180790. /* This macro protects us against machines that don't have function
  180791. * prototypes (ie K&R style headers). If your compiler does not handle
  180792. * function prototypes, define this macro and use the included ansi2knr.
  180793. * I've always been able to use _NO_PROTO as the indicator, but you may
  180794. * need to drag the empty declaration out in front of here, or change the
  180795. * ifdef to suit your own needs.
  180796. */
  180797. #ifndef PNGARG
  180798. #ifdef OF /* zlib prototype munger */
  180799. # define PNGARG(arglist) OF(arglist)
  180800. #else
  180801. #ifdef _NO_PROTO
  180802. # define PNGARG(arglist) ()
  180803. # ifndef PNG_TYPECAST_NULL
  180804. # define PNG_TYPECAST_NULL
  180805. # endif
  180806. #else
  180807. # define PNGARG(arglist) arglist
  180808. #endif /* _NO_PROTO */
  180809. #endif /* OF */
  180810. #endif /* PNGARG */
  180811. /* Try to determine if we are compiling on a Mac. Note that testing for
  180812. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180813. * on non-Mac platforms.
  180814. */
  180815. #ifndef MACOS
  180816. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180817. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180818. # define MACOS
  180819. # endif
  180820. #endif
  180821. /* enough people need this for various reasons to include it here */
  180822. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180823. # include <sys/types.h>
  180824. #endif
  180825. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180826. # define PNG_SETJMP_SUPPORTED
  180827. #endif
  180828. #ifdef PNG_SETJMP_SUPPORTED
  180829. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180830. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180831. */
  180832. # ifdef __linux__
  180833. # ifdef _BSD_SOURCE
  180834. # define PNG_SAVE_BSD_SOURCE
  180835. # undef _BSD_SOURCE
  180836. # endif
  180837. # ifdef _SETJMP_H
  180838. /* If you encounter a compiler error here, see the explanation
  180839. * near the end of INSTALL.
  180840. */
  180841. __png.h__ already includes setjmp.h;
  180842. __dont__ include it again.;
  180843. # endif
  180844. # endif /* __linux__ */
  180845. /* include setjmp.h for error handling */
  180846. # include <setjmp.h>
  180847. # ifdef __linux__
  180848. # ifdef PNG_SAVE_BSD_SOURCE
  180849. # define _BSD_SOURCE
  180850. # undef PNG_SAVE_BSD_SOURCE
  180851. # endif
  180852. # endif /* __linux__ */
  180853. #endif /* PNG_SETJMP_SUPPORTED */
  180854. #ifdef BSD
  180855. #if ! JUCE_MAC
  180856. # include <strings.h>
  180857. #endif
  180858. #else
  180859. # include <string.h>
  180860. #endif
  180861. /* Other defines for things like memory and the like can go here. */
  180862. #ifdef PNG_INTERNAL
  180863. #include <stdlib.h>
  180864. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180865. * aren't usually used outside the library (as far as I know), so it is
  180866. * debatable if they should be exported at all. In the future, when it is
  180867. * possible to have run-time registry of chunk-handling functions, some of
  180868. * these will be made available again.
  180869. #define PNG_EXTERN extern
  180870. */
  180871. #define PNG_EXTERN
  180872. /* Other defines specific to compilers can go here. Try to keep
  180873. * them inside an appropriate ifdef/endif pair for portability.
  180874. */
  180875. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180876. # if defined(MACOS)
  180877. /* We need to check that <math.h> hasn't already been included earlier
  180878. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180879. * <fp.h> if possible.
  180880. */
  180881. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180882. # include <fp.h>
  180883. # endif
  180884. # else
  180885. # include <math.h>
  180886. # endif
  180887. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180888. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180889. * MATH=68881
  180890. */
  180891. # include <m68881.h>
  180892. # endif
  180893. #endif
  180894. /* Codewarrior on NT has linking problems without this. */
  180895. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180896. # define PNG_ALWAYS_EXTERN
  180897. #endif
  180898. /* This provides the non-ANSI (far) memory allocation routines. */
  180899. #if defined(__TURBOC__) && defined(__MSDOS__)
  180900. # include <mem.h>
  180901. # include <alloc.h>
  180902. #endif
  180903. /* I have no idea why is this necessary... */
  180904. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180905. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180906. # include <malloc.h>
  180907. #endif
  180908. /* This controls how fine the dithering gets. As this allocates
  180909. * a largish chunk of memory (32K), those who are not as concerned
  180910. * with dithering quality can decrease some or all of these.
  180911. */
  180912. #ifndef PNG_DITHER_RED_BITS
  180913. # define PNG_DITHER_RED_BITS 5
  180914. #endif
  180915. #ifndef PNG_DITHER_GREEN_BITS
  180916. # define PNG_DITHER_GREEN_BITS 5
  180917. #endif
  180918. #ifndef PNG_DITHER_BLUE_BITS
  180919. # define PNG_DITHER_BLUE_BITS 5
  180920. #endif
  180921. /* This controls how fine the gamma correction becomes when you
  180922. * are only interested in 8 bits anyway. Increasing this value
  180923. * results in more memory being used, and more pow() functions
  180924. * being called to fill in the gamma tables. Don't set this value
  180925. * less then 8, and even that may not work (I haven't tested it).
  180926. */
  180927. #ifndef PNG_MAX_GAMMA_8
  180928. # define PNG_MAX_GAMMA_8 11
  180929. #endif
  180930. /* This controls how much a difference in gamma we can tolerate before
  180931. * we actually start doing gamma conversion.
  180932. */
  180933. #ifndef PNG_GAMMA_THRESHOLD
  180934. # define PNG_GAMMA_THRESHOLD 0.05
  180935. #endif
  180936. #endif /* PNG_INTERNAL */
  180937. /* The following uses const char * instead of char * for error
  180938. * and warning message functions, so some compilers won't complain.
  180939. * If you do not want to use const, define PNG_NO_CONST here.
  180940. */
  180941. #ifndef PNG_NO_CONST
  180942. # define PNG_CONST const
  180943. #else
  180944. # define PNG_CONST
  180945. #endif
  180946. /* The following defines give you the ability to remove code from the
  180947. * library that you will not be using. I wish I could figure out how to
  180948. * automate this, but I can't do that without making it seriously hard
  180949. * on the users. So if you are not using an ability, change the #define
  180950. * to and #undef, and that part of the library will not be compiled. If
  180951. * your linker can't find a function, you may want to make sure the
  180952. * ability is defined here. Some of these depend upon some others being
  180953. * defined. I haven't figured out all the interactions here, so you may
  180954. * have to experiment awhile to get everything to compile. If you are
  180955. * creating or using a shared library, you probably shouldn't touch this,
  180956. * as it will affect the size of the structures, and this will cause bad
  180957. * things to happen if the library and/or application ever change.
  180958. */
  180959. /* Any features you will not be using can be undef'ed here */
  180960. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180961. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180962. * on the compile line, then pick and choose which ones to define without
  180963. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180964. * if you only want to have a png-compliant reader/writer but don't need
  180965. * any of the extra transformations. This saves about 80 kbytes in a
  180966. * typical installation of the library. (PNG_NO_* form added in version
  180967. * 1.0.1c, for consistency)
  180968. */
  180969. /* The size of the png_text structure changed in libpng-1.0.6 when
  180970. * iTXt support was added. iTXt support was turned off by default through
  180971. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180972. * instead of calling png_set_text() and letting libpng malloc it. It
  180973. * was turned on by default in libpng-1.3.0.
  180974. */
  180975. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180976. # ifndef PNG_NO_iTXt_SUPPORTED
  180977. # define PNG_NO_iTXt_SUPPORTED
  180978. # endif
  180979. # ifndef PNG_NO_READ_iTXt
  180980. # define PNG_NO_READ_iTXt
  180981. # endif
  180982. # ifndef PNG_NO_WRITE_iTXt
  180983. # define PNG_NO_WRITE_iTXt
  180984. # endif
  180985. #endif
  180986. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180987. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180988. # define PNG_READ_iTXt
  180989. # endif
  180990. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180991. # define PNG_WRITE_iTXt
  180992. # endif
  180993. #endif
  180994. /* The following support, added after version 1.0.0, can be turned off here en
  180995. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180996. * with old applications that require the length of png_struct and png_info
  180997. * to remain unchanged.
  180998. */
  180999. #ifdef PNG_LEGACY_SUPPORTED
  181000. # define PNG_NO_FREE_ME
  181001. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181002. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181003. # define PNG_NO_READ_USER_CHUNKS
  181004. # define PNG_NO_READ_iCCP
  181005. # define PNG_NO_WRITE_iCCP
  181006. # define PNG_NO_READ_iTXt
  181007. # define PNG_NO_WRITE_iTXt
  181008. # define PNG_NO_READ_sCAL
  181009. # define PNG_NO_WRITE_sCAL
  181010. # define PNG_NO_READ_sPLT
  181011. # define PNG_NO_WRITE_sPLT
  181012. # define PNG_NO_INFO_IMAGE
  181013. # define PNG_NO_READ_RGB_TO_GRAY
  181014. # define PNG_NO_READ_USER_TRANSFORM
  181015. # define PNG_NO_WRITE_USER_TRANSFORM
  181016. # define PNG_NO_USER_MEM
  181017. # define PNG_NO_READ_EMPTY_PLTE
  181018. # define PNG_NO_MNG_FEATURES
  181019. # define PNG_NO_FIXED_POINT_SUPPORTED
  181020. #endif
  181021. /* Ignore attempt to turn off both floating and fixed point support */
  181022. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181023. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181024. # define PNG_FIXED_POINT_SUPPORTED
  181025. #endif
  181026. #ifndef PNG_NO_FREE_ME
  181027. # define PNG_FREE_ME_SUPPORTED
  181028. #endif
  181029. #if defined(PNG_READ_SUPPORTED)
  181030. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181031. !defined(PNG_NO_READ_TRANSFORMS)
  181032. # define PNG_READ_TRANSFORMS_SUPPORTED
  181033. #endif
  181034. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181035. # ifndef PNG_NO_READ_EXPAND
  181036. # define PNG_READ_EXPAND_SUPPORTED
  181037. # endif
  181038. # ifndef PNG_NO_READ_SHIFT
  181039. # define PNG_READ_SHIFT_SUPPORTED
  181040. # endif
  181041. # ifndef PNG_NO_READ_PACK
  181042. # define PNG_READ_PACK_SUPPORTED
  181043. # endif
  181044. # ifndef PNG_NO_READ_BGR
  181045. # define PNG_READ_BGR_SUPPORTED
  181046. # endif
  181047. # ifndef PNG_NO_READ_SWAP
  181048. # define PNG_READ_SWAP_SUPPORTED
  181049. # endif
  181050. # ifndef PNG_NO_READ_PACKSWAP
  181051. # define PNG_READ_PACKSWAP_SUPPORTED
  181052. # endif
  181053. # ifndef PNG_NO_READ_INVERT
  181054. # define PNG_READ_INVERT_SUPPORTED
  181055. # endif
  181056. # ifndef PNG_NO_READ_DITHER
  181057. # define PNG_READ_DITHER_SUPPORTED
  181058. # endif
  181059. # ifndef PNG_NO_READ_BACKGROUND
  181060. # define PNG_READ_BACKGROUND_SUPPORTED
  181061. # endif
  181062. # ifndef PNG_NO_READ_16_TO_8
  181063. # define PNG_READ_16_TO_8_SUPPORTED
  181064. # endif
  181065. # ifndef PNG_NO_READ_FILLER
  181066. # define PNG_READ_FILLER_SUPPORTED
  181067. # endif
  181068. # ifndef PNG_NO_READ_GAMMA
  181069. # define PNG_READ_GAMMA_SUPPORTED
  181070. # endif
  181071. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181072. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181073. # endif
  181074. # ifndef PNG_NO_READ_SWAP_ALPHA
  181075. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181076. # endif
  181077. # ifndef PNG_NO_READ_INVERT_ALPHA
  181078. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181079. # endif
  181080. # ifndef PNG_NO_READ_STRIP_ALPHA
  181081. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181082. # endif
  181083. # ifndef PNG_NO_READ_USER_TRANSFORM
  181084. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181085. # endif
  181086. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181087. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181088. # endif
  181089. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181090. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181091. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181092. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181093. #endif /* about interlacing capability! You'll */
  181094. /* still have interlacing unless you change the following line: */
  181095. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181096. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181097. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181098. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181099. # endif
  181100. #endif
  181101. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181102. /* Deprecated, will be removed from version 2.0.0.
  181103. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181104. #ifndef PNG_NO_READ_EMPTY_PLTE
  181105. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181106. #endif
  181107. #endif
  181108. #endif /* PNG_READ_SUPPORTED */
  181109. #if defined(PNG_WRITE_SUPPORTED)
  181110. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181111. !defined(PNG_NO_WRITE_TRANSFORMS)
  181112. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181113. #endif
  181114. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181115. # ifndef PNG_NO_WRITE_SHIFT
  181116. # define PNG_WRITE_SHIFT_SUPPORTED
  181117. # endif
  181118. # ifndef PNG_NO_WRITE_PACK
  181119. # define PNG_WRITE_PACK_SUPPORTED
  181120. # endif
  181121. # ifndef PNG_NO_WRITE_BGR
  181122. # define PNG_WRITE_BGR_SUPPORTED
  181123. # endif
  181124. # ifndef PNG_NO_WRITE_SWAP
  181125. # define PNG_WRITE_SWAP_SUPPORTED
  181126. # endif
  181127. # ifndef PNG_NO_WRITE_PACKSWAP
  181128. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181129. # endif
  181130. # ifndef PNG_NO_WRITE_INVERT
  181131. # define PNG_WRITE_INVERT_SUPPORTED
  181132. # endif
  181133. # ifndef PNG_NO_WRITE_FILLER
  181134. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181135. # endif
  181136. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181137. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181138. # endif
  181139. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181140. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181141. # endif
  181142. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181143. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181144. # endif
  181145. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181146. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181147. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181148. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181149. encoders, but can cause trouble
  181150. if left undefined */
  181151. #endif
  181152. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181153. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181154. defined(PNG_FLOATING_POINT_SUPPORTED)
  181155. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181156. #endif
  181157. #ifndef PNG_NO_WRITE_FLUSH
  181158. # define PNG_WRITE_FLUSH_SUPPORTED
  181159. #endif
  181160. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181161. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181162. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181163. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181164. #endif
  181165. #endif
  181166. #endif /* PNG_WRITE_SUPPORTED */
  181167. #ifndef PNG_1_0_X
  181168. # ifndef PNG_NO_ERROR_NUMBERS
  181169. # define PNG_ERROR_NUMBERS_SUPPORTED
  181170. # endif
  181171. #endif /* PNG_1_0_X */
  181172. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181173. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181174. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181175. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181176. # endif
  181177. #endif
  181178. #ifndef PNG_NO_STDIO
  181179. # define PNG_TIME_RFC1123_SUPPORTED
  181180. #endif
  181181. /* This adds extra functions in pngget.c for accessing data from the
  181182. * info pointer (added in version 0.99)
  181183. * png_get_image_width()
  181184. * png_get_image_height()
  181185. * png_get_bit_depth()
  181186. * png_get_color_type()
  181187. * png_get_compression_type()
  181188. * png_get_filter_type()
  181189. * png_get_interlace_type()
  181190. * png_get_pixel_aspect_ratio()
  181191. * png_get_pixels_per_meter()
  181192. * png_get_x_offset_pixels()
  181193. * png_get_y_offset_pixels()
  181194. * png_get_x_offset_microns()
  181195. * png_get_y_offset_microns()
  181196. */
  181197. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181198. # define PNG_EASY_ACCESS_SUPPORTED
  181199. #endif
  181200. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181201. * and removed from version 1.2.20. The following will be removed
  181202. * from libpng-1.4.0
  181203. */
  181204. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181205. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181206. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181207. # endif
  181208. #endif
  181209. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181210. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181211. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181212. # endif
  181213. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181214. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181215. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181216. # define PNG_NO_MMX_CODE
  181217. # endif
  181218. # endif
  181219. # if defined(__APPLE__)
  181220. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181221. # define PNG_NO_MMX_CODE
  181222. # endif
  181223. # endif
  181224. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181225. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181226. # define PNG_NO_MMX_CODE
  181227. # endif
  181228. # endif
  181229. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181230. # define PNG_MMX_CODE_SUPPORTED
  181231. # endif
  181232. #endif
  181233. /* end of obsolete code to be removed from libpng-1.4.0 */
  181234. #if !defined(PNG_1_0_X)
  181235. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181236. # define PNG_USER_MEM_SUPPORTED
  181237. #endif
  181238. #endif /* PNG_1_0_X */
  181239. /* Added at libpng-1.2.6 */
  181240. #if !defined(PNG_1_0_X)
  181241. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181242. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181243. # define PNG_SET_USER_LIMITS_SUPPORTED
  181244. #endif
  181245. #endif
  181246. #endif /* PNG_1_0_X */
  181247. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181248. * how large, set these limits to 0x7fffffffL
  181249. */
  181250. #ifndef PNG_USER_WIDTH_MAX
  181251. # define PNG_USER_WIDTH_MAX 1000000L
  181252. #endif
  181253. #ifndef PNG_USER_HEIGHT_MAX
  181254. # define PNG_USER_HEIGHT_MAX 1000000L
  181255. #endif
  181256. /* These are currently experimental features, define them if you want */
  181257. /* very little testing */
  181258. /*
  181259. #ifdef PNG_READ_SUPPORTED
  181260. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181261. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181262. # endif
  181263. #endif
  181264. */
  181265. /* This is only for PowerPC big-endian and 680x0 systems */
  181266. /* some testing */
  181267. /*
  181268. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181269. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181270. #endif
  181271. */
  181272. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181273. /*
  181274. #define PNG_NO_POINTER_INDEXING
  181275. */
  181276. /* These functions are turned off by default, as they will be phased out. */
  181277. /*
  181278. #define PNG_USELESS_TESTS_SUPPORTED
  181279. #define PNG_CORRECT_PALETTE_SUPPORTED
  181280. */
  181281. /* Any chunks you are not interested in, you can undef here. The
  181282. * ones that allocate memory may be expecially important (hIST,
  181283. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181284. * a bit smaller.
  181285. */
  181286. #if defined(PNG_READ_SUPPORTED) && \
  181287. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181288. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181289. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181290. #endif
  181291. #if defined(PNG_WRITE_SUPPORTED) && \
  181292. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181293. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181294. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181295. #endif
  181296. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181297. #ifdef PNG_NO_READ_TEXT
  181298. # define PNG_NO_READ_iTXt
  181299. # define PNG_NO_READ_tEXt
  181300. # define PNG_NO_READ_zTXt
  181301. #endif
  181302. #ifndef PNG_NO_READ_bKGD
  181303. # define PNG_READ_bKGD_SUPPORTED
  181304. # define PNG_bKGD_SUPPORTED
  181305. #endif
  181306. #ifndef PNG_NO_READ_cHRM
  181307. # define PNG_READ_cHRM_SUPPORTED
  181308. # define PNG_cHRM_SUPPORTED
  181309. #endif
  181310. #ifndef PNG_NO_READ_gAMA
  181311. # define PNG_READ_gAMA_SUPPORTED
  181312. # define PNG_gAMA_SUPPORTED
  181313. #endif
  181314. #ifndef PNG_NO_READ_hIST
  181315. # define PNG_READ_hIST_SUPPORTED
  181316. # define PNG_hIST_SUPPORTED
  181317. #endif
  181318. #ifndef PNG_NO_READ_iCCP
  181319. # define PNG_READ_iCCP_SUPPORTED
  181320. # define PNG_iCCP_SUPPORTED
  181321. #endif
  181322. #ifndef PNG_NO_READ_iTXt
  181323. # ifndef PNG_READ_iTXt_SUPPORTED
  181324. # define PNG_READ_iTXt_SUPPORTED
  181325. # endif
  181326. # ifndef PNG_iTXt_SUPPORTED
  181327. # define PNG_iTXt_SUPPORTED
  181328. # endif
  181329. #endif
  181330. #ifndef PNG_NO_READ_oFFs
  181331. # define PNG_READ_oFFs_SUPPORTED
  181332. # define PNG_oFFs_SUPPORTED
  181333. #endif
  181334. #ifndef PNG_NO_READ_pCAL
  181335. # define PNG_READ_pCAL_SUPPORTED
  181336. # define PNG_pCAL_SUPPORTED
  181337. #endif
  181338. #ifndef PNG_NO_READ_sCAL
  181339. # define PNG_READ_sCAL_SUPPORTED
  181340. # define PNG_sCAL_SUPPORTED
  181341. #endif
  181342. #ifndef PNG_NO_READ_pHYs
  181343. # define PNG_READ_pHYs_SUPPORTED
  181344. # define PNG_pHYs_SUPPORTED
  181345. #endif
  181346. #ifndef PNG_NO_READ_sBIT
  181347. # define PNG_READ_sBIT_SUPPORTED
  181348. # define PNG_sBIT_SUPPORTED
  181349. #endif
  181350. #ifndef PNG_NO_READ_sPLT
  181351. # define PNG_READ_sPLT_SUPPORTED
  181352. # define PNG_sPLT_SUPPORTED
  181353. #endif
  181354. #ifndef PNG_NO_READ_sRGB
  181355. # define PNG_READ_sRGB_SUPPORTED
  181356. # define PNG_sRGB_SUPPORTED
  181357. #endif
  181358. #ifndef PNG_NO_READ_tEXt
  181359. # define PNG_READ_tEXt_SUPPORTED
  181360. # define PNG_tEXt_SUPPORTED
  181361. #endif
  181362. #ifndef PNG_NO_READ_tIME
  181363. # define PNG_READ_tIME_SUPPORTED
  181364. # define PNG_tIME_SUPPORTED
  181365. #endif
  181366. #ifndef PNG_NO_READ_tRNS
  181367. # define PNG_READ_tRNS_SUPPORTED
  181368. # define PNG_tRNS_SUPPORTED
  181369. #endif
  181370. #ifndef PNG_NO_READ_zTXt
  181371. # define PNG_READ_zTXt_SUPPORTED
  181372. # define PNG_zTXt_SUPPORTED
  181373. #endif
  181374. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181375. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181376. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181377. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181378. # endif
  181379. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181380. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181381. # endif
  181382. #endif
  181383. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181384. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181385. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181386. # define PNG_USER_CHUNKS_SUPPORTED
  181387. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181388. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181389. # endif
  181390. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181391. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181392. # endif
  181393. #endif
  181394. #ifndef PNG_NO_READ_OPT_PLTE
  181395. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181396. #endif /* optional PLTE chunk in RGB and RGBA images */
  181397. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181398. defined(PNG_READ_zTXt_SUPPORTED)
  181399. # define PNG_READ_TEXT_SUPPORTED
  181400. # define PNG_TEXT_SUPPORTED
  181401. #endif
  181402. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181403. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181404. #ifdef PNG_NO_WRITE_TEXT
  181405. # define PNG_NO_WRITE_iTXt
  181406. # define PNG_NO_WRITE_tEXt
  181407. # define PNG_NO_WRITE_zTXt
  181408. #endif
  181409. #ifndef PNG_NO_WRITE_bKGD
  181410. # define PNG_WRITE_bKGD_SUPPORTED
  181411. # ifndef PNG_bKGD_SUPPORTED
  181412. # define PNG_bKGD_SUPPORTED
  181413. # endif
  181414. #endif
  181415. #ifndef PNG_NO_WRITE_cHRM
  181416. # define PNG_WRITE_cHRM_SUPPORTED
  181417. # ifndef PNG_cHRM_SUPPORTED
  181418. # define PNG_cHRM_SUPPORTED
  181419. # endif
  181420. #endif
  181421. #ifndef PNG_NO_WRITE_gAMA
  181422. # define PNG_WRITE_gAMA_SUPPORTED
  181423. # ifndef PNG_gAMA_SUPPORTED
  181424. # define PNG_gAMA_SUPPORTED
  181425. # endif
  181426. #endif
  181427. #ifndef PNG_NO_WRITE_hIST
  181428. # define PNG_WRITE_hIST_SUPPORTED
  181429. # ifndef PNG_hIST_SUPPORTED
  181430. # define PNG_hIST_SUPPORTED
  181431. # endif
  181432. #endif
  181433. #ifndef PNG_NO_WRITE_iCCP
  181434. # define PNG_WRITE_iCCP_SUPPORTED
  181435. # ifndef PNG_iCCP_SUPPORTED
  181436. # define PNG_iCCP_SUPPORTED
  181437. # endif
  181438. #endif
  181439. #ifndef PNG_NO_WRITE_iTXt
  181440. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181441. # define PNG_WRITE_iTXt_SUPPORTED
  181442. # endif
  181443. # ifndef PNG_iTXt_SUPPORTED
  181444. # define PNG_iTXt_SUPPORTED
  181445. # endif
  181446. #endif
  181447. #ifndef PNG_NO_WRITE_oFFs
  181448. # define PNG_WRITE_oFFs_SUPPORTED
  181449. # ifndef PNG_oFFs_SUPPORTED
  181450. # define PNG_oFFs_SUPPORTED
  181451. # endif
  181452. #endif
  181453. #ifndef PNG_NO_WRITE_pCAL
  181454. # define PNG_WRITE_pCAL_SUPPORTED
  181455. # ifndef PNG_pCAL_SUPPORTED
  181456. # define PNG_pCAL_SUPPORTED
  181457. # endif
  181458. #endif
  181459. #ifndef PNG_NO_WRITE_sCAL
  181460. # define PNG_WRITE_sCAL_SUPPORTED
  181461. # ifndef PNG_sCAL_SUPPORTED
  181462. # define PNG_sCAL_SUPPORTED
  181463. # endif
  181464. #endif
  181465. #ifndef PNG_NO_WRITE_pHYs
  181466. # define PNG_WRITE_pHYs_SUPPORTED
  181467. # ifndef PNG_pHYs_SUPPORTED
  181468. # define PNG_pHYs_SUPPORTED
  181469. # endif
  181470. #endif
  181471. #ifndef PNG_NO_WRITE_sBIT
  181472. # define PNG_WRITE_sBIT_SUPPORTED
  181473. # ifndef PNG_sBIT_SUPPORTED
  181474. # define PNG_sBIT_SUPPORTED
  181475. # endif
  181476. #endif
  181477. #ifndef PNG_NO_WRITE_sPLT
  181478. # define PNG_WRITE_sPLT_SUPPORTED
  181479. # ifndef PNG_sPLT_SUPPORTED
  181480. # define PNG_sPLT_SUPPORTED
  181481. # endif
  181482. #endif
  181483. #ifndef PNG_NO_WRITE_sRGB
  181484. # define PNG_WRITE_sRGB_SUPPORTED
  181485. # ifndef PNG_sRGB_SUPPORTED
  181486. # define PNG_sRGB_SUPPORTED
  181487. # endif
  181488. #endif
  181489. #ifndef PNG_NO_WRITE_tEXt
  181490. # define PNG_WRITE_tEXt_SUPPORTED
  181491. # ifndef PNG_tEXt_SUPPORTED
  181492. # define PNG_tEXt_SUPPORTED
  181493. # endif
  181494. #endif
  181495. #ifndef PNG_NO_WRITE_tIME
  181496. # define PNG_WRITE_tIME_SUPPORTED
  181497. # ifndef PNG_tIME_SUPPORTED
  181498. # define PNG_tIME_SUPPORTED
  181499. # endif
  181500. #endif
  181501. #ifndef PNG_NO_WRITE_tRNS
  181502. # define PNG_WRITE_tRNS_SUPPORTED
  181503. # ifndef PNG_tRNS_SUPPORTED
  181504. # define PNG_tRNS_SUPPORTED
  181505. # endif
  181506. #endif
  181507. #ifndef PNG_NO_WRITE_zTXt
  181508. # define PNG_WRITE_zTXt_SUPPORTED
  181509. # ifndef PNG_zTXt_SUPPORTED
  181510. # define PNG_zTXt_SUPPORTED
  181511. # endif
  181512. #endif
  181513. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181514. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181515. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181516. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181517. # endif
  181518. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181519. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181520. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181521. # endif
  181522. # endif
  181523. #endif
  181524. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181525. defined(PNG_WRITE_zTXt_SUPPORTED)
  181526. # define PNG_WRITE_TEXT_SUPPORTED
  181527. # ifndef PNG_TEXT_SUPPORTED
  181528. # define PNG_TEXT_SUPPORTED
  181529. # endif
  181530. #endif
  181531. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181532. /* Turn this off to disable png_read_png() and
  181533. * png_write_png() and leave the row_pointers member
  181534. * out of the info structure.
  181535. */
  181536. #ifndef PNG_NO_INFO_IMAGE
  181537. # define PNG_INFO_IMAGE_SUPPORTED
  181538. #endif
  181539. /* need the time information for reading tIME chunks */
  181540. #if defined(PNG_tIME_SUPPORTED)
  181541. # if !defined(_WIN32_WCE)
  181542. /* "time.h" functions are not supported on WindowsCE */
  181543. # include <time.h>
  181544. # endif
  181545. #endif
  181546. /* Some typedefs to get us started. These should be safe on most of the
  181547. * common platforms. The typedefs should be at least as large as the
  181548. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181549. * don't have to be exactly that size. Some compilers dislike passing
  181550. * unsigned shorts as function parameters, so you may be better off using
  181551. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181552. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181553. */
  181554. typedef unsigned long png_uint_32;
  181555. typedef long png_int_32;
  181556. typedef unsigned short png_uint_16;
  181557. typedef short png_int_16;
  181558. typedef unsigned char png_byte;
  181559. /* This is usually size_t. It is typedef'ed just in case you need it to
  181560. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181561. #ifdef PNG_SIZE_T
  181562. typedef PNG_SIZE_T png_size_t;
  181563. # define png_sizeof(x) png_convert_size(sizeof (x))
  181564. #else
  181565. typedef size_t png_size_t;
  181566. # define png_sizeof(x) sizeof (x)
  181567. #endif
  181568. /* The following is needed for medium model support. It cannot be in the
  181569. * PNG_INTERNAL section. Needs modification for other compilers besides
  181570. * MSC. Model independent support declares all arrays and pointers to be
  181571. * large using the far keyword. The zlib version used must also support
  181572. * model independent data. As of version zlib 1.0.4, the necessary changes
  181573. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181574. * changes that are needed. (Tim Wegner)
  181575. */
  181576. /* Separate compiler dependencies (problem here is that zlib.h always
  181577. defines FAR. (SJT) */
  181578. #ifdef __BORLANDC__
  181579. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181580. # define LDATA 1
  181581. # else
  181582. # define LDATA 0
  181583. # endif
  181584. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181585. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181586. # define PNG_MAX_MALLOC_64K
  181587. # if (LDATA != 1)
  181588. # ifndef FAR
  181589. # define FAR __far
  181590. # endif
  181591. # define USE_FAR_KEYWORD
  181592. # endif /* LDATA != 1 */
  181593. /* Possibly useful for moving data out of default segment.
  181594. * Uncomment it if you want. Could also define FARDATA as
  181595. * const if your compiler supports it. (SJT)
  181596. # define FARDATA FAR
  181597. */
  181598. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181599. #endif /* __BORLANDC__ */
  181600. /* Suggest testing for specific compiler first before testing for
  181601. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181602. * making reliance oncertain keywords suspect. (SJT)
  181603. */
  181604. /* MSC Medium model */
  181605. #if defined(FAR)
  181606. # if defined(M_I86MM)
  181607. # define USE_FAR_KEYWORD
  181608. # define FARDATA FAR
  181609. # include <dos.h>
  181610. # endif
  181611. #endif
  181612. /* SJT: default case */
  181613. #ifndef FAR
  181614. # define FAR
  181615. #endif
  181616. /* At this point FAR is always defined */
  181617. #ifndef FARDATA
  181618. # define FARDATA
  181619. #endif
  181620. /* Typedef for floating-point numbers that are converted
  181621. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181622. typedef png_int_32 png_fixed_point;
  181623. /* Add typedefs for pointers */
  181624. typedef void FAR * png_voidp;
  181625. typedef png_byte FAR * png_bytep;
  181626. typedef png_uint_32 FAR * png_uint_32p;
  181627. typedef png_int_32 FAR * png_int_32p;
  181628. typedef png_uint_16 FAR * png_uint_16p;
  181629. typedef png_int_16 FAR * png_int_16p;
  181630. typedef PNG_CONST char FAR * png_const_charp;
  181631. typedef char FAR * png_charp;
  181632. typedef png_fixed_point FAR * png_fixed_point_p;
  181633. #ifndef PNG_NO_STDIO
  181634. #if defined(_WIN32_WCE)
  181635. typedef HANDLE png_FILE_p;
  181636. #else
  181637. typedef FILE * png_FILE_p;
  181638. #endif
  181639. #endif
  181640. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181641. typedef double FAR * png_doublep;
  181642. #endif
  181643. /* Pointers to pointers; i.e. arrays */
  181644. typedef png_byte FAR * FAR * png_bytepp;
  181645. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181646. typedef png_int_32 FAR * FAR * png_int_32pp;
  181647. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181648. typedef png_int_16 FAR * FAR * png_int_16pp;
  181649. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181650. typedef char FAR * FAR * png_charpp;
  181651. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181652. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181653. typedef double FAR * FAR * png_doublepp;
  181654. #endif
  181655. /* Pointers to pointers to pointers; i.e., pointer to array */
  181656. typedef char FAR * FAR * FAR * png_charppp;
  181657. #if 0
  181658. /* SPC - Is this stuff deprecated? */
  181659. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181660. /* libpng typedefs for types in zlib. If zlib changes
  181661. * or another compression library is used, then change these.
  181662. * Eliminates need to change all the source files.
  181663. */
  181664. typedef charf * png_zcharp;
  181665. typedef charf * FAR * png_zcharpp;
  181666. typedef z_stream FAR * png_zstreamp;
  181667. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181668. /*
  181669. * Define PNG_BUILD_DLL if the module being built is a Windows
  181670. * LIBPNG DLL.
  181671. *
  181672. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181673. * It is equivalent to Microsoft predefined macro _DLL that is
  181674. * automatically defined when you compile using the share
  181675. * version of the CRT (C Run-Time library)
  181676. *
  181677. * The cygwin mods make this behavior a little different:
  181678. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181679. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181680. * -or- if you are building an application that you want to link to the
  181681. * static library.
  181682. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181683. * the other flags is defined.
  181684. */
  181685. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181686. # define PNG_DLL
  181687. #endif
  181688. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181689. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181690. * command-line override
  181691. */
  181692. #if defined(__CYGWIN__)
  181693. # if !defined(PNG_STATIC)
  181694. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181695. # undef PNG_USE_GLOBAL_ARRAYS
  181696. # endif
  181697. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181698. # define PNG_USE_LOCAL_ARRAYS
  181699. # endif
  181700. # else
  181701. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181702. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181703. # undef PNG_USE_GLOBAL_ARRAYS
  181704. # endif
  181705. # endif
  181706. # endif
  181707. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181708. # define PNG_USE_LOCAL_ARRAYS
  181709. # endif
  181710. #endif
  181711. /* Do not use global arrays (helps with building DLL's)
  181712. * They are no longer used in libpng itself, since version 1.0.5c,
  181713. * but might be required for some pre-1.0.5c applications.
  181714. */
  181715. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181716. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181717. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181718. # define PNG_USE_LOCAL_ARRAYS
  181719. # else
  181720. # define PNG_USE_GLOBAL_ARRAYS
  181721. # endif
  181722. #endif
  181723. #if defined(__CYGWIN__)
  181724. # undef PNGAPI
  181725. # define PNGAPI __cdecl
  181726. # undef PNG_IMPEXP
  181727. # define PNG_IMPEXP
  181728. #endif
  181729. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181730. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181731. * Don't ignore those warnings; you must also reset the default calling
  181732. * convention in your compiler to match your PNGAPI, and you must build
  181733. * zlib and your applications the same way you build libpng.
  181734. */
  181735. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181736. # ifndef PNG_NO_MODULEDEF
  181737. # define PNG_NO_MODULEDEF
  181738. # endif
  181739. #endif
  181740. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181741. # define PNG_IMPEXP
  181742. #endif
  181743. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181744. (( defined(_Windows) || defined(_WINDOWS) || \
  181745. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181746. # ifndef PNGAPI
  181747. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181748. # define PNGAPI __cdecl
  181749. # else
  181750. # define PNGAPI _cdecl
  181751. # endif
  181752. # endif
  181753. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181754. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181755. # define PNG_IMPEXP
  181756. # endif
  181757. # if !defined(PNG_IMPEXP)
  181758. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181759. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181760. /* Borland/Microsoft */
  181761. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181762. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181763. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181764. # else
  181765. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181766. # if defined(PNG_BUILD_DLL)
  181767. # define PNG_IMPEXP __export
  181768. # else
  181769. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181770. VC++ */
  181771. # endif /* Exists in Borland C++ for
  181772. C++ classes (== huge) */
  181773. # endif
  181774. # endif
  181775. # if !defined(PNG_IMPEXP)
  181776. # if defined(PNG_BUILD_DLL)
  181777. # define PNG_IMPEXP __declspec(dllexport)
  181778. # else
  181779. # define PNG_IMPEXP __declspec(dllimport)
  181780. # endif
  181781. # endif
  181782. # endif /* PNG_IMPEXP */
  181783. #else /* !(DLL || non-cygwin WINDOWS) */
  181784. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181785. # ifndef PNGAPI
  181786. # define PNGAPI _System
  181787. # endif
  181788. # else
  181789. # if 0 /* ... other platforms, with other meanings */
  181790. # endif
  181791. # endif
  181792. #endif
  181793. #ifndef PNGAPI
  181794. # define PNGAPI
  181795. #endif
  181796. #ifndef PNG_IMPEXP
  181797. # define PNG_IMPEXP
  181798. #endif
  181799. #ifdef PNG_BUILDSYMS
  181800. # ifndef PNG_EXPORT
  181801. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181802. # endif
  181803. # ifdef PNG_USE_GLOBAL_ARRAYS
  181804. # ifndef PNG_EXPORT_VAR
  181805. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181806. # endif
  181807. # endif
  181808. #endif
  181809. #ifndef PNG_EXPORT
  181810. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181811. #endif
  181812. #ifdef PNG_USE_GLOBAL_ARRAYS
  181813. # ifndef PNG_EXPORT_VAR
  181814. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181815. # endif
  181816. #endif
  181817. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181818. * functions that are passed far data must be model independent.
  181819. */
  181820. #ifndef PNG_ABORT
  181821. # define PNG_ABORT() abort()
  181822. #endif
  181823. #ifdef PNG_SETJMP_SUPPORTED
  181824. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181825. #else
  181826. # define png_jmpbuf(png_ptr) \
  181827. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181828. #endif
  181829. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181830. /* use this to make far-to-near assignments */
  181831. # define CHECK 1
  181832. # define NOCHECK 0
  181833. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181834. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181835. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181836. # define png_strcpy _fstrcpy
  181837. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181838. # define png_strlen _fstrlen
  181839. # define png_memcmp _fmemcmp /* SJT: added */
  181840. # define png_memcpy _fmemcpy
  181841. # define png_memset _fmemset
  181842. #else /* use the usual functions */
  181843. # define CVT_PTR(ptr) (ptr)
  181844. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181845. # ifndef PNG_NO_SNPRINTF
  181846. # ifdef _MSC_VER
  181847. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181848. # define png_snprintf2 _snprintf
  181849. # define png_snprintf6 _snprintf
  181850. # else
  181851. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181852. # define png_snprintf2 snprintf
  181853. # define png_snprintf6 snprintf
  181854. # endif
  181855. # else
  181856. /* You don't have or don't want to use snprintf(). Caution: Using
  181857. * sprintf instead of snprintf exposes your application to accidental
  181858. * or malevolent buffer overflows. If you don't have snprintf()
  181859. * as a general rule you should provide one (you can get one from
  181860. * Portable OpenSSH). */
  181861. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181862. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181863. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181864. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181865. # endif
  181866. # define png_strcpy strcpy
  181867. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181868. # define png_strlen strlen
  181869. # define png_memcmp memcmp /* SJT: added */
  181870. # define png_memcpy memcpy
  181871. # define png_memset memset
  181872. #endif
  181873. /* End of memory model independent support */
  181874. /* Just a little check that someone hasn't tried to define something
  181875. * contradictory.
  181876. */
  181877. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181878. # undef PNG_ZBUF_SIZE
  181879. # define PNG_ZBUF_SIZE 65536L
  181880. #endif
  181881. /* Added at libpng-1.2.8 */
  181882. #endif /* PNG_VERSION_INFO_ONLY */
  181883. #endif /* PNGCONF_H */
  181884. /*** End of inlined file: pngconf.h ***/
  181885. #ifdef _MSC_VER
  181886. #pragma warning (disable: 4996 4100)
  181887. #endif
  181888. /*
  181889. * Added at libpng-1.2.8 */
  181890. /* Ref MSDN: Private as priority over Special
  181891. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181892. * procedures. If this value is given, the StringFileInfo block must
  181893. * contain a PrivateBuild string.
  181894. *
  181895. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181896. * standard release procedures but is a variation of the standard
  181897. * file of the same version number. If this value is given, the
  181898. * StringFileInfo block must contain a SpecialBuild string.
  181899. */
  181900. #if defined(PNG_USER_PRIVATEBUILD)
  181901. # define PNG_LIBPNG_BUILD_TYPE \
  181902. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181903. #else
  181904. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181905. # define PNG_LIBPNG_BUILD_TYPE \
  181906. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181907. # else
  181908. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181909. # endif
  181910. #endif
  181911. #ifndef PNG_VERSION_INFO_ONLY
  181912. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181913. #ifdef __cplusplus
  181914. //extern "C" {
  181915. #endif /* __cplusplus */
  181916. /* This file is arranged in several sections. The first section contains
  181917. * structure and type definitions. The second section contains the external
  181918. * library functions, while the third has the internal library functions,
  181919. * which applications aren't expected to use directly.
  181920. */
  181921. #ifndef PNG_NO_TYPECAST_NULL
  181922. #define int_p_NULL (int *)NULL
  181923. #define png_bytep_NULL (png_bytep)NULL
  181924. #define png_bytepp_NULL (png_bytepp)NULL
  181925. #define png_doublep_NULL (png_doublep)NULL
  181926. #define png_error_ptr_NULL (png_error_ptr)NULL
  181927. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181928. #define png_free_ptr_NULL (png_free_ptr)NULL
  181929. #define png_infopp_NULL (png_infopp)NULL
  181930. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181931. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181932. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181933. #define png_structp_NULL (png_structp)NULL
  181934. #define png_uint_16p_NULL (png_uint_16p)NULL
  181935. #define png_voidp_NULL (png_voidp)NULL
  181936. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181937. #else
  181938. #define int_p_NULL NULL
  181939. #define png_bytep_NULL NULL
  181940. #define png_bytepp_NULL NULL
  181941. #define png_doublep_NULL NULL
  181942. #define png_error_ptr_NULL NULL
  181943. #define png_flush_ptr_NULL NULL
  181944. #define png_free_ptr_NULL NULL
  181945. #define png_infopp_NULL NULL
  181946. #define png_malloc_ptr_NULL NULL
  181947. #define png_read_status_ptr_NULL NULL
  181948. #define png_rw_ptr_NULL NULL
  181949. #define png_structp_NULL NULL
  181950. #define png_uint_16p_NULL NULL
  181951. #define png_voidp_NULL NULL
  181952. #define png_write_status_ptr_NULL NULL
  181953. #endif
  181954. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181955. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181956. /* Version information for C files, stored in png.c. This had better match
  181957. * the version above.
  181958. */
  181959. #ifdef PNG_USE_GLOBAL_ARRAYS
  181960. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181961. /* need room for 99.99.99beta99z */
  181962. #else
  181963. #define png_libpng_ver png_get_header_ver(NULL)
  181964. #endif
  181965. #ifdef PNG_USE_GLOBAL_ARRAYS
  181966. /* This was removed in version 1.0.5c */
  181967. /* Structures to facilitate easy interlacing. See png.c for more details */
  181968. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181969. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181970. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181971. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181972. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181973. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181974. /* This isn't currently used. If you need it, see png.c for more details.
  181975. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181976. */
  181977. #endif
  181978. #endif /* PNG_NO_EXTERN */
  181979. /* Three color definitions. The order of the red, green, and blue, (and the
  181980. * exact size) is not important, although the size of the fields need to
  181981. * be png_byte or png_uint_16 (as defined below).
  181982. */
  181983. typedef struct png_color_struct
  181984. {
  181985. png_byte red;
  181986. png_byte green;
  181987. png_byte blue;
  181988. } png_color;
  181989. typedef png_color FAR * png_colorp;
  181990. typedef png_color FAR * FAR * png_colorpp;
  181991. typedef struct png_color_16_struct
  181992. {
  181993. png_byte index; /* used for palette files */
  181994. png_uint_16 red; /* for use in red green blue files */
  181995. png_uint_16 green;
  181996. png_uint_16 blue;
  181997. png_uint_16 gray; /* for use in grayscale files */
  181998. } png_color_16;
  181999. typedef png_color_16 FAR * png_color_16p;
  182000. typedef png_color_16 FAR * FAR * png_color_16pp;
  182001. typedef struct png_color_8_struct
  182002. {
  182003. png_byte red; /* for use in red green blue files */
  182004. png_byte green;
  182005. png_byte blue;
  182006. png_byte gray; /* for use in grayscale files */
  182007. png_byte alpha; /* for alpha channel files */
  182008. } png_color_8;
  182009. typedef png_color_8 FAR * png_color_8p;
  182010. typedef png_color_8 FAR * FAR * png_color_8pp;
  182011. /*
  182012. * The following two structures are used for the in-core representation
  182013. * of sPLT chunks.
  182014. */
  182015. typedef struct png_sPLT_entry_struct
  182016. {
  182017. png_uint_16 red;
  182018. png_uint_16 green;
  182019. png_uint_16 blue;
  182020. png_uint_16 alpha;
  182021. png_uint_16 frequency;
  182022. } png_sPLT_entry;
  182023. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182024. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182025. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182026. * occupy the LSB of their respective members, and the MSB of each member
  182027. * is zero-filled. The frequency member always occupies the full 16 bits.
  182028. */
  182029. typedef struct png_sPLT_struct
  182030. {
  182031. png_charp name; /* palette name */
  182032. png_byte depth; /* depth of palette samples */
  182033. png_sPLT_entryp entries; /* palette entries */
  182034. png_int_32 nentries; /* number of palette entries */
  182035. } png_sPLT_t;
  182036. typedef png_sPLT_t FAR * png_sPLT_tp;
  182037. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182038. #ifdef PNG_TEXT_SUPPORTED
  182039. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182040. * and whether that contents is compressed or not. The "key" field
  182041. * points to a regular zero-terminated C string. The "text", "lang", and
  182042. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182043. * However, the * structure returned by png_get_text() will always contain
  182044. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182045. * so they can be safely used in printf() and other string-handling functions.
  182046. */
  182047. typedef struct png_text_struct
  182048. {
  182049. int compression; /* compression value:
  182050. -1: tEXt, none
  182051. 0: zTXt, deflate
  182052. 1: iTXt, none
  182053. 2: iTXt, deflate */
  182054. png_charp key; /* keyword, 1-79 character description of "text" */
  182055. png_charp text; /* comment, may be an empty string (ie "")
  182056. or a NULL pointer */
  182057. png_size_t text_length; /* length of the text string */
  182058. #ifdef PNG_iTXt_SUPPORTED
  182059. png_size_t itxt_length; /* length of the itxt string */
  182060. png_charp lang; /* language code, 0-79 characters
  182061. or a NULL pointer */
  182062. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182063. chars or a NULL pointer */
  182064. #endif
  182065. } png_text;
  182066. typedef png_text FAR * png_textp;
  182067. typedef png_text FAR * FAR * png_textpp;
  182068. #endif
  182069. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182070. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182071. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182072. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182073. #define PNG_TEXT_COMPRESSION_NONE -1
  182074. #define PNG_TEXT_COMPRESSION_zTXt 0
  182075. #define PNG_ITXT_COMPRESSION_NONE 1
  182076. #define PNG_ITXT_COMPRESSION_zTXt 2
  182077. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182078. /* png_time is a way to hold the time in an machine independent way.
  182079. * Two conversions are provided, both from time_t and struct tm. There
  182080. * is no portable way to convert to either of these structures, as far
  182081. * as I know. If you know of a portable way, send it to me. As a side
  182082. * note - PNG has always been Year 2000 compliant!
  182083. */
  182084. typedef struct png_time_struct
  182085. {
  182086. png_uint_16 year; /* full year, as in, 1995 */
  182087. png_byte month; /* month of year, 1 - 12 */
  182088. png_byte day; /* day of month, 1 - 31 */
  182089. png_byte hour; /* hour of day, 0 - 23 */
  182090. png_byte minute; /* minute of hour, 0 - 59 */
  182091. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182092. } png_time;
  182093. typedef png_time FAR * png_timep;
  182094. typedef png_time FAR * FAR * png_timepp;
  182095. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182096. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182097. * no specific support. The idea is that we can use this to queue
  182098. * up private chunks for output even though the library doesn't actually
  182099. * know about their semantics.
  182100. */
  182101. typedef struct png_unknown_chunk_t
  182102. {
  182103. png_byte name[5];
  182104. png_byte *data;
  182105. png_size_t size;
  182106. /* libpng-using applications should NOT directly modify this byte. */
  182107. png_byte location; /* mode of operation at read time */
  182108. }
  182109. png_unknown_chunk;
  182110. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182111. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182112. #endif
  182113. /* png_info is a structure that holds the information in a PNG file so
  182114. * that the application can find out the characteristics of the image.
  182115. * If you are reading the file, this structure will tell you what is
  182116. * in the PNG file. If you are writing the file, fill in the information
  182117. * you want to put into the PNG file, then call png_write_info().
  182118. * The names chosen should be very close to the PNG specification, so
  182119. * consult that document for information about the meaning of each field.
  182120. *
  182121. * With libpng < 0.95, it was only possible to directly set and read the
  182122. * the values in the png_info_struct, which meant that the contents and
  182123. * order of the values had to remain fixed. With libpng 0.95 and later,
  182124. * however, there are now functions that abstract the contents of
  182125. * png_info_struct from the application, so this makes it easier to use
  182126. * libpng with dynamic libraries, and even makes it possible to use
  182127. * libraries that don't have all of the libpng ancillary chunk-handing
  182128. * functionality.
  182129. *
  182130. * In any case, the order of the parameters in png_info_struct should NOT
  182131. * be changed for as long as possible to keep compatibility with applications
  182132. * that use the old direct-access method with png_info_struct.
  182133. *
  182134. * The following members may have allocated storage attached that should be
  182135. * cleaned up before the structure is discarded: palette, trans, text,
  182136. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182137. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182138. * are automatically freed when the info structure is deallocated, if they were
  182139. * allocated internally by libpng. This behavior can be changed by means
  182140. * of the png_data_freer() function.
  182141. *
  182142. * More allocation details: all the chunk-reading functions that
  182143. * change these members go through the corresponding png_set_*
  182144. * functions. A function to clear these members is available: see
  182145. * png_free_data(). The png_set_* functions do not depend on being
  182146. * able to point info structure members to any of the storage they are
  182147. * passed (they make their own copies), EXCEPT that the png_set_text
  182148. * functions use the same storage passed to them in the text_ptr or
  182149. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182150. * functions do not make their own copies.
  182151. */
  182152. typedef struct png_info_struct
  182153. {
  182154. /* the following are necessary for every PNG file */
  182155. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182156. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182157. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182158. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182159. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182160. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182161. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182162. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182163. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182164. /* The following three should have been named *_method not *_type */
  182165. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182166. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182167. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182168. /* The following is informational only on read, and not used on writes. */
  182169. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182170. png_byte pixel_depth; /* number of bits per pixel */
  182171. png_byte spare_byte; /* to align the data, and for future use */
  182172. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182173. /* The rest of the data is optional. If you are reading, check the
  182174. * valid field to see if the information in these are valid. If you
  182175. * are writing, set the valid field to those chunks you want written,
  182176. * and initialize the appropriate fields below.
  182177. */
  182178. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182179. /* The gAMA chunk describes the gamma characteristics of the system
  182180. * on which the image was created, normally in the range [1.0, 2.5].
  182181. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182182. */
  182183. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182184. #endif
  182185. #if defined(PNG_sRGB_SUPPORTED)
  182186. /* GR-P, 0.96a */
  182187. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182188. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182189. #endif
  182190. #if defined(PNG_TEXT_SUPPORTED)
  182191. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182192. * uncompressed, compressed, and optionally compressed forms, respectively.
  182193. * The data in "text" is an array of pointers to uncompressed,
  182194. * null-terminated C strings. Each chunk has a keyword that describes the
  182195. * textual data contained in that chunk. Keywords are not required to be
  182196. * unique, and the text string may be empty. Any number of text chunks may
  182197. * be in an image.
  182198. */
  182199. int num_text; /* number of comments read/to write */
  182200. int max_text; /* current size of text array */
  182201. png_textp text; /* array of comments read/to write */
  182202. #endif /* PNG_TEXT_SUPPORTED */
  182203. #if defined(PNG_tIME_SUPPORTED)
  182204. /* The tIME chunk holds the last time the displayed image data was
  182205. * modified. See the png_time struct for the contents of this struct.
  182206. */
  182207. png_time mod_time;
  182208. #endif
  182209. #if defined(PNG_sBIT_SUPPORTED)
  182210. /* The sBIT chunk specifies the number of significant high-order bits
  182211. * in the pixel data. Values are in the range [1, bit_depth], and are
  182212. * only specified for the channels in the pixel data. The contents of
  182213. * the low-order bits is not specified. Data is valid if
  182214. * (valid & PNG_INFO_sBIT) is non-zero.
  182215. */
  182216. png_color_8 sig_bit; /* significant bits in color channels */
  182217. #endif
  182218. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182219. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182220. /* The tRNS chunk supplies transparency data for paletted images and
  182221. * other image types that don't need a full alpha channel. There are
  182222. * "num_trans" transparency values for a paletted image, stored in the
  182223. * same order as the palette colors, starting from index 0. Values
  182224. * for the data are in the range [0, 255], ranging from fully transparent
  182225. * to fully opaque, respectively. For non-paletted images, there is a
  182226. * single color specified that should be treated as fully transparent.
  182227. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182228. */
  182229. png_bytep trans; /* transparent values for paletted image */
  182230. png_color_16 trans_values; /* transparent color for non-palette image */
  182231. #endif
  182232. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182233. /* The bKGD chunk gives the suggested image background color if the
  182234. * display program does not have its own background color and the image
  182235. * is needs to composited onto a background before display. The colors
  182236. * in "background" are normally in the same color space/depth as the
  182237. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182238. */
  182239. png_color_16 background;
  182240. #endif
  182241. #if defined(PNG_oFFs_SUPPORTED)
  182242. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182243. * and downwards from the top-left corner of the display, page, or other
  182244. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182245. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182246. */
  182247. png_int_32 x_offset; /* x offset on page */
  182248. png_int_32 y_offset; /* y offset on page */
  182249. png_byte offset_unit_type; /* offset units type */
  182250. #endif
  182251. #if defined(PNG_pHYs_SUPPORTED)
  182252. /* The pHYs chunk gives the physical pixel density of the image for
  182253. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182254. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182255. */
  182256. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182257. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182258. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182259. #endif
  182260. #if defined(PNG_hIST_SUPPORTED)
  182261. /* The hIST chunk contains the relative frequency or importance of the
  182262. * various palette entries, so that a viewer can intelligently select a
  182263. * reduced-color palette, if required. Data is an array of "num_palette"
  182264. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182265. * is non-zero.
  182266. */
  182267. png_uint_16p hist;
  182268. #endif
  182269. #ifdef PNG_cHRM_SUPPORTED
  182270. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182271. * on which the PNG was created. This data allows the viewer to do gamut
  182272. * mapping of the input image to ensure that the viewer sees the same
  182273. * colors in the image as the creator. Values are in the range
  182274. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182275. */
  182276. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182277. float x_white;
  182278. float y_white;
  182279. float x_red;
  182280. float y_red;
  182281. float x_green;
  182282. float y_green;
  182283. float x_blue;
  182284. float y_blue;
  182285. #endif
  182286. #endif
  182287. #if defined(PNG_pCAL_SUPPORTED)
  182288. /* The pCAL chunk describes a transformation between the stored pixel
  182289. * values and original physical data values used to create the image.
  182290. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182291. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182292. * (possibly non-linear) transformation function given by "pcal_type"
  182293. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182294. * defines below, and the PNG-Group's PNG extensions document for a
  182295. * complete description of the transformations and how they should be
  182296. * implemented, and for a description of the ASCII parameter strings.
  182297. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182298. */
  182299. png_charp pcal_purpose; /* pCAL chunk description string */
  182300. png_int_32 pcal_X0; /* minimum value */
  182301. png_int_32 pcal_X1; /* maximum value */
  182302. png_charp pcal_units; /* Latin-1 string giving physical units */
  182303. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182304. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182305. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182306. #endif
  182307. /* New members added in libpng-1.0.6 */
  182308. #ifdef PNG_FREE_ME_SUPPORTED
  182309. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182310. #endif
  182311. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182312. /* storage for unknown chunks that the library doesn't recognize. */
  182313. png_unknown_chunkp unknown_chunks;
  182314. png_size_t unknown_chunks_num;
  182315. #endif
  182316. #if defined(PNG_iCCP_SUPPORTED)
  182317. /* iCCP chunk data. */
  182318. png_charp iccp_name; /* profile name */
  182319. png_charp iccp_profile; /* International Color Consortium profile data */
  182320. /* Note to maintainer: should be png_bytep */
  182321. png_uint_32 iccp_proflen; /* ICC profile data length */
  182322. png_byte iccp_compression; /* Always zero */
  182323. #endif
  182324. #if defined(PNG_sPLT_SUPPORTED)
  182325. /* data on sPLT chunks (there may be more than one). */
  182326. png_sPLT_tp splt_palettes;
  182327. png_uint_32 splt_palettes_num;
  182328. #endif
  182329. #if defined(PNG_sCAL_SUPPORTED)
  182330. /* The sCAL chunk describes the actual physical dimensions of the
  182331. * subject matter of the graphic. The chunk contains a unit specification
  182332. * a byte value, and two ASCII strings representing floating-point
  182333. * values. The values are width and height corresponsing to one pixel
  182334. * in the image. This external representation is converted to double
  182335. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182336. */
  182337. png_byte scal_unit; /* unit of physical scale */
  182338. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182339. double scal_pixel_width; /* width of one pixel */
  182340. double scal_pixel_height; /* height of one pixel */
  182341. #endif
  182342. #ifdef PNG_FIXED_POINT_SUPPORTED
  182343. png_charp scal_s_width; /* string containing height */
  182344. png_charp scal_s_height; /* string containing width */
  182345. #endif
  182346. #endif
  182347. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182348. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182349. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182350. png_bytepp row_pointers; /* the image bits */
  182351. #endif
  182352. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182353. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182354. #endif
  182355. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182356. png_fixed_point int_x_white;
  182357. png_fixed_point int_y_white;
  182358. png_fixed_point int_x_red;
  182359. png_fixed_point int_y_red;
  182360. png_fixed_point int_x_green;
  182361. png_fixed_point int_y_green;
  182362. png_fixed_point int_x_blue;
  182363. png_fixed_point int_y_blue;
  182364. #endif
  182365. } png_info;
  182366. typedef png_info FAR * png_infop;
  182367. typedef png_info FAR * FAR * png_infopp;
  182368. /* Maximum positive integer used in PNG is (2^31)-1 */
  182369. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182370. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182371. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182372. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182373. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182374. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182375. #endif
  182376. /* These describe the color_type field in png_info. */
  182377. /* color type masks */
  182378. #define PNG_COLOR_MASK_PALETTE 1
  182379. #define PNG_COLOR_MASK_COLOR 2
  182380. #define PNG_COLOR_MASK_ALPHA 4
  182381. /* color types. Note that not all combinations are legal */
  182382. #define PNG_COLOR_TYPE_GRAY 0
  182383. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182384. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182385. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182386. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182387. /* aliases */
  182388. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182389. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182390. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182391. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182392. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182393. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182394. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182395. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182396. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182397. /* These are for the interlacing type. These values should NOT be changed. */
  182398. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182399. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182400. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182401. /* These are for the oFFs chunk. These values should NOT be changed. */
  182402. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182403. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182404. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182405. /* These are for the pCAL chunk. These values should NOT be changed. */
  182406. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182407. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182408. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182409. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182410. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182411. /* These are for the sCAL chunk. These values should NOT be changed. */
  182412. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182413. #define PNG_SCALE_METER 1 /* meters per pixel */
  182414. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182415. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182416. /* These are for the pHYs chunk. These values should NOT be changed. */
  182417. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182418. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182419. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182420. /* These are for the sRGB chunk. These values should NOT be changed. */
  182421. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182422. #define PNG_sRGB_INTENT_RELATIVE 1
  182423. #define PNG_sRGB_INTENT_SATURATION 2
  182424. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182425. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182426. /* This is for text chunks */
  182427. #define PNG_KEYWORD_MAX_LENGTH 79
  182428. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182429. #define PNG_MAX_PALETTE_LENGTH 256
  182430. /* These determine if an ancillary chunk's data has been successfully read
  182431. * from the PNG header, or if the application has filled in the corresponding
  182432. * data in the info_struct to be written into the output file. The values
  182433. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182434. */
  182435. #define PNG_INFO_gAMA 0x0001
  182436. #define PNG_INFO_sBIT 0x0002
  182437. #define PNG_INFO_cHRM 0x0004
  182438. #define PNG_INFO_PLTE 0x0008
  182439. #define PNG_INFO_tRNS 0x0010
  182440. #define PNG_INFO_bKGD 0x0020
  182441. #define PNG_INFO_hIST 0x0040
  182442. #define PNG_INFO_pHYs 0x0080
  182443. #define PNG_INFO_oFFs 0x0100
  182444. #define PNG_INFO_tIME 0x0200
  182445. #define PNG_INFO_pCAL 0x0400
  182446. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182447. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182448. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182449. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182450. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182451. /* This is used for the transformation routines, as some of them
  182452. * change these values for the row. It also should enable using
  182453. * the routines for other purposes.
  182454. */
  182455. typedef struct png_row_info_struct
  182456. {
  182457. png_uint_32 width; /* width of row */
  182458. png_uint_32 rowbytes; /* number of bytes in row */
  182459. png_byte color_type; /* color type of row */
  182460. png_byte bit_depth; /* bit depth of row */
  182461. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182462. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182463. } png_row_info;
  182464. typedef png_row_info FAR * png_row_infop;
  182465. typedef png_row_info FAR * FAR * png_row_infopp;
  182466. /* These are the function types for the I/O functions and for the functions
  182467. * that allow the user to override the default I/O functions with his or her
  182468. * own. The png_error_ptr type should match that of user-supplied warning
  182469. * and error functions, while the png_rw_ptr type should match that of the
  182470. * user read/write data functions.
  182471. */
  182472. typedef struct png_struct_def png_struct;
  182473. typedef png_struct FAR * png_structp;
  182474. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182475. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182476. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182477. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182478. int));
  182479. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182480. int));
  182481. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182482. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182483. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182484. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182485. png_uint_32, int));
  182486. #endif
  182487. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182488. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182489. defined(PNG_LEGACY_SUPPORTED)
  182490. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182491. png_row_infop, png_bytep));
  182492. #endif
  182493. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182494. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182495. #endif
  182496. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182497. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182498. #endif
  182499. /* Transform masks for the high-level interface */
  182500. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182501. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182502. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182503. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182504. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182505. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182506. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182507. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182508. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182509. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182510. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182511. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182512. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182513. /* Flags for MNG supported features */
  182514. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182515. #define PNG_FLAG_MNG_FILTER_64 0x04
  182516. #define PNG_ALL_MNG_FEATURES 0x05
  182517. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182518. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182519. /* The structure that holds the information to read and write PNG files.
  182520. * The only people who need to care about what is inside of this are the
  182521. * people who will be modifying the library for their own special needs.
  182522. * It should NOT be accessed directly by an application, except to store
  182523. * the jmp_buf.
  182524. */
  182525. struct png_struct_def
  182526. {
  182527. #ifdef PNG_SETJMP_SUPPORTED
  182528. jmp_buf jmpbuf; /* used in png_error */
  182529. #endif
  182530. png_error_ptr error_fn; /* function for printing errors and aborting */
  182531. png_error_ptr warning_fn; /* function for printing warnings */
  182532. png_voidp error_ptr; /* user supplied struct for error functions */
  182533. png_rw_ptr write_data_fn; /* function for writing output data */
  182534. png_rw_ptr read_data_fn; /* function for reading input data */
  182535. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182536. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182537. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182538. #endif
  182539. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182540. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182541. #endif
  182542. /* These were added in libpng-1.0.2 */
  182543. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182544. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182545. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182546. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182547. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182548. png_byte user_transform_channels; /* channels in user transformed pixels */
  182549. #endif
  182550. #endif
  182551. png_uint_32 mode; /* tells us where we are in the PNG file */
  182552. png_uint_32 flags; /* flags indicating various things to libpng */
  182553. png_uint_32 transformations; /* which transformations to perform */
  182554. z_stream zstream; /* pointer to decompression structure (below) */
  182555. png_bytep zbuf; /* buffer for zlib */
  182556. png_size_t zbuf_size; /* size of zbuf */
  182557. int zlib_level; /* holds zlib compression level */
  182558. int zlib_method; /* holds zlib compression method */
  182559. int zlib_window_bits; /* holds zlib compression window bits */
  182560. int zlib_mem_level; /* holds zlib compression memory level */
  182561. int zlib_strategy; /* holds zlib compression strategy */
  182562. png_uint_32 width; /* width of image in pixels */
  182563. png_uint_32 height; /* height of image in pixels */
  182564. png_uint_32 num_rows; /* number of rows in current pass */
  182565. png_uint_32 usr_width; /* width of row at start of write */
  182566. png_uint_32 rowbytes; /* size of row in bytes */
  182567. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182568. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182569. png_uint_32 row_number; /* current row in interlace pass */
  182570. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182571. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182572. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182573. png_bytep up_row; /* buffer to save "up" row when filtering */
  182574. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182575. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182576. png_row_info row_info; /* used for transformation routines */
  182577. png_uint_32 idat_size; /* current IDAT size for read */
  182578. png_uint_32 crc; /* current chunk CRC value */
  182579. png_colorp palette; /* palette from the input file */
  182580. png_uint_16 num_palette; /* number of color entries in palette */
  182581. png_uint_16 num_trans; /* number of transparency values */
  182582. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182583. png_byte compression; /* file compression type (always 0) */
  182584. png_byte filter; /* file filter type (always 0) */
  182585. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182586. png_byte pass; /* current interlace pass (0 - 6) */
  182587. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182588. png_byte color_type; /* color type of file */
  182589. png_byte bit_depth; /* bit depth of file */
  182590. png_byte usr_bit_depth; /* bit depth of users row */
  182591. png_byte pixel_depth; /* number of bits per pixel */
  182592. png_byte channels; /* number of channels in file */
  182593. png_byte usr_channels; /* channels at start of write */
  182594. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182595. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182596. #ifdef PNG_LEGACY_SUPPORTED
  182597. png_byte filler; /* filler byte for pixel expansion */
  182598. #else
  182599. png_uint_16 filler; /* filler bytes for pixel expansion */
  182600. #endif
  182601. #endif
  182602. #if defined(PNG_bKGD_SUPPORTED)
  182603. png_byte background_gamma_type;
  182604. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182605. float background_gamma;
  182606. # endif
  182607. png_color_16 background; /* background color in screen gamma space */
  182608. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182609. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182610. #endif
  182611. #endif /* PNG_bKGD_SUPPORTED */
  182612. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182613. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182614. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182615. png_uint_32 flush_rows; /* number of rows written since last flush */
  182616. #endif
  182617. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182618. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182619. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182620. float gamma; /* file gamma value */
  182621. float screen_gamma; /* screen gamma value (display_exponent) */
  182622. #endif
  182623. #endif
  182624. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182625. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182626. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182627. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182628. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182629. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182630. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182631. #endif
  182632. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182633. png_color_8 sig_bit; /* significant bits in each available channel */
  182634. #endif
  182635. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182636. png_color_8 shift; /* shift for significant bit tranformation */
  182637. #endif
  182638. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182639. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182640. png_bytep trans; /* transparency values for paletted files */
  182641. png_color_16 trans_values; /* transparency values for non-paletted files */
  182642. #endif
  182643. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182644. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182645. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182646. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182647. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182648. png_progressive_end_ptr end_fn; /* called after image is complete */
  182649. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182650. png_bytep save_buffer; /* buffer for previously read data */
  182651. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182652. png_bytep current_buffer; /* buffer for recently used data */
  182653. png_uint_32 push_length; /* size of current input chunk */
  182654. png_uint_32 skip_length; /* bytes to skip in input data */
  182655. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182656. png_size_t save_buffer_max; /* total size of save_buffer */
  182657. png_size_t buffer_size; /* total amount of available input data */
  182658. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182659. int process_mode; /* what push library is currently doing */
  182660. int cur_palette; /* current push library palette index */
  182661. # if defined(PNG_TEXT_SUPPORTED)
  182662. png_size_t current_text_size; /* current size of text input data */
  182663. png_size_t current_text_left; /* how much text left to read in input */
  182664. png_charp current_text; /* current text chunk buffer */
  182665. png_charp current_text_ptr; /* current location in current_text */
  182666. # endif /* PNG_TEXT_SUPPORTED */
  182667. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182668. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182669. /* for the Borland special 64K segment handler */
  182670. png_bytepp offset_table_ptr;
  182671. png_bytep offset_table;
  182672. png_uint_16 offset_table_number;
  182673. png_uint_16 offset_table_count;
  182674. png_uint_16 offset_table_count_free;
  182675. #endif
  182676. #if defined(PNG_READ_DITHER_SUPPORTED)
  182677. png_bytep palette_lookup; /* lookup table for dithering */
  182678. png_bytep dither_index; /* index translation for palette files */
  182679. #endif
  182680. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182681. png_uint_16p hist; /* histogram */
  182682. #endif
  182683. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182684. png_byte heuristic_method; /* heuristic for row filter selection */
  182685. png_byte num_prev_filters; /* number of weights for previous rows */
  182686. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182687. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182688. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182689. png_uint_16p filter_costs; /* relative filter calculation cost */
  182690. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182691. #endif
  182692. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182693. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182694. #endif
  182695. /* New members added in libpng-1.0.6 */
  182696. #ifdef PNG_FREE_ME_SUPPORTED
  182697. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182698. #endif
  182699. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182700. png_voidp user_chunk_ptr;
  182701. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182702. #endif
  182703. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182704. int num_chunk_list;
  182705. png_bytep chunk_list;
  182706. #endif
  182707. /* New members added in libpng-1.0.3 */
  182708. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182709. png_byte rgb_to_gray_status;
  182710. /* These were changed from png_byte in libpng-1.0.6 */
  182711. png_uint_16 rgb_to_gray_red_coeff;
  182712. png_uint_16 rgb_to_gray_green_coeff;
  182713. png_uint_16 rgb_to_gray_blue_coeff;
  182714. #endif
  182715. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182716. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182717. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182718. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182719. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182720. #ifdef PNG_1_0_X
  182721. png_byte mng_features_permitted;
  182722. #else
  182723. png_uint_32 mng_features_permitted;
  182724. #endif /* PNG_1_0_X */
  182725. #endif
  182726. /* New member added in libpng-1.0.7 */
  182727. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182728. png_fixed_point int_gamma;
  182729. #endif
  182730. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182731. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182732. png_byte filter_type;
  182733. #endif
  182734. #if defined(PNG_1_0_X)
  182735. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182736. png_uint_32 row_buf_size;
  182737. #endif
  182738. /* New members added in libpng-1.2.0 */
  182739. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182740. # if !defined(PNG_1_0_X)
  182741. # if defined(PNG_MMX_CODE_SUPPORTED)
  182742. png_byte mmx_bitdepth_threshold;
  182743. png_uint_32 mmx_rowbytes_threshold;
  182744. # endif
  182745. png_uint_32 asm_flags;
  182746. # endif
  182747. #endif
  182748. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182749. #ifdef PNG_USER_MEM_SUPPORTED
  182750. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182751. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182752. png_free_ptr free_fn; /* function for freeing memory */
  182753. #endif
  182754. /* New member added in libpng-1.0.13 and 1.2.0 */
  182755. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182756. #if defined(PNG_READ_DITHER_SUPPORTED)
  182757. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182758. png_bytep dither_sort; /* working sort array */
  182759. png_bytep index_to_palette; /* where the original index currently is */
  182760. /* in the palette */
  182761. png_bytep palette_to_index; /* which original index points to this */
  182762. /* palette color */
  182763. #endif
  182764. /* New members added in libpng-1.0.16 and 1.2.6 */
  182765. png_byte compression_type;
  182766. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182767. png_uint_32 user_width_max;
  182768. png_uint_32 user_height_max;
  182769. #endif
  182770. /* New member added in libpng-1.0.25 and 1.2.17 */
  182771. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182772. /* storage for unknown chunk that the library doesn't recognize. */
  182773. png_unknown_chunk unknown_chunk;
  182774. #endif
  182775. };
  182776. /* This triggers a compiler error in png.c, if png.c and png.h
  182777. * do not agree upon the version number.
  182778. */
  182779. typedef png_structp version_1_2_21;
  182780. typedef png_struct FAR * FAR * png_structpp;
  182781. /* Here are the function definitions most commonly used. This is not
  182782. * the place to find out how to use libpng. See libpng.txt for the
  182783. * full explanation, see example.c for the summary. This just provides
  182784. * a simple one line description of the use of each function.
  182785. */
  182786. /* Returns the version number of the library */
  182787. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182788. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182789. * Handling more than 8 bytes from the beginning of the file is an error.
  182790. */
  182791. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182792. int num_bytes));
  182793. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182794. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182795. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182796. * start > 7 will always fail (ie return non-zero).
  182797. */
  182798. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182799. png_size_t num_to_check));
  182800. /* Simple signature checking function. This is the same as calling
  182801. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182802. */
  182803. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182804. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182805. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182806. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182807. png_error_ptr error_fn, png_error_ptr warn_fn));
  182808. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182809. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182810. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182811. png_error_ptr error_fn, png_error_ptr warn_fn));
  182812. #ifdef PNG_WRITE_SUPPORTED
  182813. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182814. PNGARG((png_structp png_ptr));
  182815. #endif
  182816. #ifdef PNG_WRITE_SUPPORTED
  182817. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182818. PNGARG((png_structp png_ptr, png_uint_32 size));
  182819. #endif
  182820. /* Reset the compression stream */
  182821. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182822. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182823. #ifdef PNG_USER_MEM_SUPPORTED
  182824. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182825. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182826. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182827. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182828. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182829. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182830. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182831. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182832. #endif
  182833. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182834. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182835. png_bytep chunk_name, png_bytep data, png_size_t length));
  182836. /* Write the start of a PNG chunk - length and chunk name. */
  182837. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182838. png_bytep chunk_name, png_uint_32 length));
  182839. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182840. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182841. png_bytep data, png_size_t length));
  182842. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182843. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182844. /* Allocate and initialize the info structure */
  182845. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182846. PNGARG((png_structp png_ptr));
  182847. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182848. /* Initialize the info structure (old interface - DEPRECATED) */
  182849. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182850. #undef png_info_init
  182851. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182852. png_sizeof(png_info));
  182853. #endif
  182854. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182855. png_size_t png_info_struct_size));
  182856. /* Writes all the PNG information before the image. */
  182857. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182858. png_infop info_ptr));
  182859. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182860. png_infop info_ptr));
  182861. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182862. /* read the information before the actual image data. */
  182863. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182864. png_infop info_ptr));
  182865. #endif
  182866. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182867. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182868. PNGARG((png_structp png_ptr, png_timep ptime));
  182869. #endif
  182870. #if !defined(_WIN32_WCE)
  182871. /* "time.h" functions are not supported on WindowsCE */
  182872. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182873. /* convert from a struct tm to png_time */
  182874. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182875. struct tm FAR * ttime));
  182876. /* convert from time_t to png_time. Uses gmtime() */
  182877. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182878. time_t ttime));
  182879. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182880. #endif /* _WIN32_WCE */
  182881. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182882. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182883. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182884. #if !defined(PNG_1_0_X)
  182885. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182886. png_ptr));
  182887. #endif
  182888. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182889. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182890. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182891. /* Deprecated */
  182892. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182893. #endif
  182894. #endif
  182895. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182896. /* Use blue, green, red order for pixels. */
  182897. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182898. #endif
  182899. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182900. /* Expand the grayscale to 24-bit RGB if necessary. */
  182901. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182902. #endif
  182903. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182904. /* Reduce RGB to grayscale. */
  182905. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182906. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182907. int error_action, double red, double green ));
  182908. #endif
  182909. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182910. int error_action, png_fixed_point red, png_fixed_point green ));
  182911. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182912. png_ptr));
  182913. #endif
  182914. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182915. png_colorp palette));
  182916. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182917. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182918. #endif
  182919. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182920. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182921. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182922. #endif
  182923. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182924. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182925. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182926. #endif
  182927. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182928. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182929. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182930. png_uint_32 filler, int flags));
  182931. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182932. #define PNG_FILLER_BEFORE 0
  182933. #define PNG_FILLER_AFTER 1
  182934. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182935. #if !defined(PNG_1_0_X)
  182936. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182937. png_uint_32 filler, int flags));
  182938. #endif
  182939. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182940. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182941. /* Swap bytes in 16-bit depth files. */
  182942. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182943. #endif
  182944. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182945. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182946. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182947. #endif
  182948. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182949. /* Swap packing order of pixels in bytes. */
  182950. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182951. #endif
  182952. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182953. /* Converts files to legal bit depths. */
  182954. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182955. png_color_8p true_bits));
  182956. #endif
  182957. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182958. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182959. /* Have the code handle the interlacing. Returns the number of passes. */
  182960. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182961. #endif
  182962. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182963. /* Invert monochrome files */
  182964. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182965. #endif
  182966. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182967. /* Handle alpha and tRNS by replacing with a background color. */
  182968. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182969. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182970. png_color_16p background_color, int background_gamma_code,
  182971. int need_expand, double background_gamma));
  182972. #endif
  182973. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182974. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182975. #define PNG_BACKGROUND_GAMMA_FILE 2
  182976. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182977. #endif
  182978. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182979. /* strip the second byte of information from a 16-bit depth file. */
  182980. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182981. #endif
  182982. #if defined(PNG_READ_DITHER_SUPPORTED)
  182983. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182984. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182985. png_colorp palette, int num_palette, int maximum_colors,
  182986. png_uint_16p histogram, int full_dither));
  182987. #endif
  182988. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182989. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182990. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182991. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182992. double screen_gamma, double default_file_gamma));
  182993. #endif
  182994. #endif
  182995. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182996. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182997. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182998. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182999. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183000. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183001. int empty_plte_permitted));
  183002. #endif
  183003. #endif
  183004. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183005. /* Set how many lines between output flushes - 0 for no flushing */
  183006. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183007. /* Flush the current PNG output buffer */
  183008. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183009. #endif
  183010. /* optional update palette with requested transformations */
  183011. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183012. /* optional call to update the users info structure */
  183013. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183014. png_infop info_ptr));
  183015. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183016. /* read one or more rows of image data. */
  183017. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183018. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183019. #endif
  183020. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183021. /* read a row of data. */
  183022. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183023. png_bytep row,
  183024. png_bytep display_row));
  183025. #endif
  183026. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183027. /* read the whole image into memory at once. */
  183028. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183029. png_bytepp image));
  183030. #endif
  183031. /* write a row of image data */
  183032. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183033. png_bytep row));
  183034. /* write a few rows of image data */
  183035. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183036. png_bytepp row, png_uint_32 num_rows));
  183037. /* write the image data */
  183038. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183039. png_bytepp image));
  183040. /* writes the end of the PNG file. */
  183041. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183042. png_infop info_ptr));
  183043. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183044. /* read the end of the PNG file. */
  183045. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183046. png_infop info_ptr));
  183047. #endif
  183048. /* free any memory associated with the png_info_struct */
  183049. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183050. png_infopp info_ptr_ptr));
  183051. /* free any memory associated with the png_struct and the png_info_structs */
  183052. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183053. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183054. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183055. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183056. png_infop end_info_ptr));
  183057. /* free any memory associated with the png_struct and the png_info_structs */
  183058. extern PNG_EXPORT(void,png_destroy_write_struct)
  183059. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183060. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183061. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183062. /* set the libpng method of handling chunk CRC errors */
  183063. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183064. int crit_action, int ancil_action));
  183065. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183066. * ancillary and critical chunks, and whether to use the data contained
  183067. * therein. Note that it is impossible to "discard" data in a critical
  183068. * chunk. For versions prior to 0.90, the action was always error/quit,
  183069. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183070. * chunks is warn/discard. These values should NOT be changed.
  183071. *
  183072. * value action:critical action:ancillary
  183073. */
  183074. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183075. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183076. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183077. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183078. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183079. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183080. /* These functions give the user control over the scan-line filtering in
  183081. * libpng and the compression methods used by zlib. These functions are
  183082. * mainly useful for testing, as the defaults should work with most users.
  183083. * Those users who are tight on memory or want faster performance at the
  183084. * expense of compression can modify them. See the compression library
  183085. * header file (zlib.h) for an explination of the compression functions.
  183086. */
  183087. /* set the filtering method(s) used by libpng. Currently, the only valid
  183088. * value for "method" is 0.
  183089. */
  183090. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183091. int filters));
  183092. /* Flags for png_set_filter() to say which filters to use. The flags
  183093. * are chosen so that they don't conflict with real filter types
  183094. * below, in case they are supplied instead of the #defined constants.
  183095. * These values should NOT be changed.
  183096. */
  183097. #define PNG_NO_FILTERS 0x00
  183098. #define PNG_FILTER_NONE 0x08
  183099. #define PNG_FILTER_SUB 0x10
  183100. #define PNG_FILTER_UP 0x20
  183101. #define PNG_FILTER_AVG 0x40
  183102. #define PNG_FILTER_PAETH 0x80
  183103. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183104. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183105. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183106. * These defines should NOT be changed.
  183107. */
  183108. #define PNG_FILTER_VALUE_NONE 0
  183109. #define PNG_FILTER_VALUE_SUB 1
  183110. #define PNG_FILTER_VALUE_UP 2
  183111. #define PNG_FILTER_VALUE_AVG 3
  183112. #define PNG_FILTER_VALUE_PAETH 4
  183113. #define PNG_FILTER_VALUE_LAST 5
  183114. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183115. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183116. * defines, either the default (minimum-sum-of-absolute-differences), or
  183117. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183118. *
  183119. * Weights are factors >= 1.0, indicating how important it is to keep the
  183120. * filter type consistent between rows. Larger numbers mean the current
  183121. * filter is that many times as likely to be the same as the "num_weights"
  183122. * previous filters. This is cumulative for each previous row with a weight.
  183123. * There needs to be "num_weights" values in "filter_weights", or it can be
  183124. * NULL if the weights aren't being specified. Weights have no influence on
  183125. * the selection of the first row filter. Well chosen weights can (in theory)
  183126. * improve the compression for a given image.
  183127. *
  183128. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183129. * filter type. Higher costs indicate more decoding expense, and are
  183130. * therefore less likely to be selected over a filter with lower computational
  183131. * costs. There needs to be a value in "filter_costs" for each valid filter
  183132. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183133. * setting the costs. Costs try to improve the speed of decompression without
  183134. * unduly increasing the compressed image size.
  183135. *
  183136. * A negative weight or cost indicates the default value is to be used, and
  183137. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183138. * The default values for both weights and costs are currently 1.0, but may
  183139. * change if good general weighting/cost heuristics can be found. If both
  183140. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183141. * to the UNWEIGHTED method, but with added encoding time/computation.
  183142. */
  183143. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183144. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183145. int heuristic_method, int num_weights, png_doublep filter_weights,
  183146. png_doublep filter_costs));
  183147. #endif
  183148. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183149. /* Heuristic used for row filter selection. These defines should NOT be
  183150. * changed.
  183151. */
  183152. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183153. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183154. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183155. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183156. /* Set the library compression level. Currently, valid values range from
  183157. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183158. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183159. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183160. * for PNG images, and do considerably fewer caclulations. In the future,
  183161. * these values may not correspond directly to the zlib compression levels.
  183162. */
  183163. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183164. int level));
  183165. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183166. PNGARG((png_structp png_ptr, int mem_level));
  183167. extern PNG_EXPORT(void,png_set_compression_strategy)
  183168. PNGARG((png_structp png_ptr, int strategy));
  183169. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183170. PNGARG((png_structp png_ptr, int window_bits));
  183171. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183172. int method));
  183173. /* These next functions are called for input/output, memory, and error
  183174. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183175. * and call standard C I/O routines such as fread(), fwrite(), and
  183176. * fprintf(). These functions can be made to use other I/O routines
  183177. * at run time for those applications that need to handle I/O in a
  183178. * different manner by calling png_set_???_fn(). See libpng.txt for
  183179. * more information.
  183180. */
  183181. #if !defined(PNG_NO_STDIO)
  183182. /* Initialize the input/output for the PNG file to the default functions. */
  183183. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183184. #endif
  183185. /* Replace the (error and abort), and warning functions with user
  183186. * supplied functions. If no messages are to be printed you must still
  183187. * write and use replacement functions. The replacement error_fn should
  183188. * still do a longjmp to the last setjmp location if you are using this
  183189. * method of error handling. If error_fn or warning_fn is NULL, the
  183190. * default function will be used.
  183191. */
  183192. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183193. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183194. /* Return the user pointer associated with the error functions */
  183195. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183196. /* Replace the default data output functions with a user supplied one(s).
  183197. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183198. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183199. * output_flush_fn will be ignored (and thus can be NULL).
  183200. */
  183201. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183202. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183203. /* Replace the default data input function with a user supplied one. */
  183204. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183205. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183206. /* Return the user pointer associated with the I/O functions */
  183207. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183208. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183209. png_read_status_ptr read_row_fn));
  183210. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183211. png_write_status_ptr write_row_fn));
  183212. #ifdef PNG_USER_MEM_SUPPORTED
  183213. /* Replace the default memory allocation functions with user supplied one(s). */
  183214. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183215. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183216. /* Return the user pointer associated with the memory functions */
  183217. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183218. #endif
  183219. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183220. defined(PNG_LEGACY_SUPPORTED)
  183221. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183222. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183223. #endif
  183224. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183225. defined(PNG_LEGACY_SUPPORTED)
  183226. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183227. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183228. #endif
  183229. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183230. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183231. defined(PNG_LEGACY_SUPPORTED)
  183232. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183233. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183234. int user_transform_channels));
  183235. /* Return the user pointer associated with the user transform functions */
  183236. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183237. PNGARG((png_structp png_ptr));
  183238. #endif
  183239. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183240. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183241. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183242. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183243. png_ptr));
  183244. #endif
  183245. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183246. /* Sets the function callbacks for the push reader, and a pointer to a
  183247. * user-defined structure available to the callback functions.
  183248. */
  183249. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183250. png_voidp progressive_ptr,
  183251. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183252. png_progressive_end_ptr end_fn));
  183253. /* returns the user pointer associated with the push read functions */
  183254. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183255. PNGARG((png_structp png_ptr));
  183256. /* function to be called when data becomes available */
  183257. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183258. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183259. /* function that combines rows. Not very much different than the
  183260. * png_combine_row() call. Is this even used?????
  183261. */
  183262. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183263. png_bytep old_row, png_bytep new_row));
  183264. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183265. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183266. png_uint_32 size));
  183267. #if defined(PNG_1_0_X)
  183268. # define png_malloc_warn png_malloc
  183269. #else
  183270. /* Added at libpng version 1.2.4 */
  183271. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183272. png_uint_32 size));
  183273. #endif
  183274. /* frees a pointer allocated by png_malloc() */
  183275. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183276. #if defined(PNG_1_0_X)
  183277. /* Function to allocate memory for zlib. */
  183278. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183279. uInt size));
  183280. /* Function to free memory for zlib */
  183281. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183282. #endif
  183283. /* Free data that was allocated internally */
  183284. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183285. png_infop info_ptr, png_uint_32 free_me, int num));
  183286. #ifdef PNG_FREE_ME_SUPPORTED
  183287. /* Reassign responsibility for freeing existing data, whether allocated
  183288. * by libpng or by the application */
  183289. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183290. png_infop info_ptr, int freer, png_uint_32 mask));
  183291. #endif
  183292. /* assignments for png_data_freer */
  183293. #define PNG_DESTROY_WILL_FREE_DATA 1
  183294. #define PNG_SET_WILL_FREE_DATA 1
  183295. #define PNG_USER_WILL_FREE_DATA 2
  183296. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183297. #define PNG_FREE_HIST 0x0008
  183298. #define PNG_FREE_ICCP 0x0010
  183299. #define PNG_FREE_SPLT 0x0020
  183300. #define PNG_FREE_ROWS 0x0040
  183301. #define PNG_FREE_PCAL 0x0080
  183302. #define PNG_FREE_SCAL 0x0100
  183303. #define PNG_FREE_UNKN 0x0200
  183304. #define PNG_FREE_LIST 0x0400
  183305. #define PNG_FREE_PLTE 0x1000
  183306. #define PNG_FREE_TRNS 0x2000
  183307. #define PNG_FREE_TEXT 0x4000
  183308. #define PNG_FREE_ALL 0x7fff
  183309. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183310. #ifdef PNG_USER_MEM_SUPPORTED
  183311. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183312. png_uint_32 size));
  183313. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183314. png_voidp ptr));
  183315. #endif
  183316. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183317. png_voidp s1, png_voidp s2, png_uint_32 size));
  183318. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183319. png_voidp s1, int value, png_uint_32 size));
  183320. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183321. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183322. int check));
  183323. #endif /* USE_FAR_KEYWORD */
  183324. #ifndef PNG_NO_ERROR_TEXT
  183325. /* Fatal error in PNG image of libpng - can't continue */
  183326. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183327. png_const_charp error_message));
  183328. /* The same, but the chunk name is prepended to the error string. */
  183329. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183330. png_const_charp error_message));
  183331. #else
  183332. /* Fatal error in PNG image of libpng - can't continue */
  183333. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183334. #endif
  183335. #ifndef PNG_NO_WARNINGS
  183336. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183337. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183338. png_const_charp warning_message));
  183339. #ifdef PNG_READ_SUPPORTED
  183340. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183341. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183342. png_const_charp warning_message));
  183343. #endif /* PNG_READ_SUPPORTED */
  183344. #endif /* PNG_NO_WARNINGS */
  183345. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183346. * Similarly, the png_get_<chunk> calls are used to read values from the
  183347. * png_info_struct, either storing the parameters in the passed variables, or
  183348. * setting pointers into the png_info_struct where the data is stored. The
  183349. * png_get_<chunk> functions return a non-zero value if the data was available
  183350. * in info_ptr, or return zero and do not change any of the parameters if the
  183351. * data was not available.
  183352. *
  183353. * These functions should be used instead of directly accessing png_info
  183354. * to avoid problems with future changes in the size and internal layout of
  183355. * png_info_struct.
  183356. */
  183357. /* Returns "flag" if chunk data is valid in info_ptr. */
  183358. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183359. png_infop info_ptr, png_uint_32 flag));
  183360. /* Returns number of bytes needed to hold a transformed row. */
  183361. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183362. png_infop info_ptr));
  183363. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183364. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183365. returned from png_read_png(). */
  183366. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183367. png_infop info_ptr));
  183368. /* Set row_pointers, which is an array of pointers to scanlines for use
  183369. by png_write_png(). */
  183370. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183371. png_infop info_ptr, png_bytepp row_pointers));
  183372. #endif
  183373. /* Returns number of color channels in image. */
  183374. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183375. png_infop info_ptr));
  183376. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183377. /* Returns image width in pixels. */
  183378. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183379. png_ptr, png_infop info_ptr));
  183380. /* Returns image height in pixels. */
  183381. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183382. png_ptr, png_infop info_ptr));
  183383. /* Returns image bit_depth. */
  183384. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183385. png_ptr, png_infop info_ptr));
  183386. /* Returns image color_type. */
  183387. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183388. png_ptr, png_infop info_ptr));
  183389. /* Returns image filter_type. */
  183390. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183391. png_ptr, png_infop info_ptr));
  183392. /* Returns image interlace_type. */
  183393. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183394. png_ptr, png_infop info_ptr));
  183395. /* Returns image compression_type. */
  183396. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183397. png_ptr, png_infop info_ptr));
  183398. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183399. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183400. png_ptr, png_infop info_ptr));
  183401. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183402. png_ptr, png_infop info_ptr));
  183403. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183404. png_ptr, png_infop info_ptr));
  183405. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183406. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183407. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183408. png_ptr, png_infop info_ptr));
  183409. #endif
  183410. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183411. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183412. png_ptr, png_infop info_ptr));
  183413. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183414. png_ptr, png_infop info_ptr));
  183415. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183416. png_ptr, png_infop info_ptr));
  183417. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183418. png_ptr, png_infop info_ptr));
  183419. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183420. /* Returns pointer to signature string read from PNG header */
  183421. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183422. png_infop info_ptr));
  183423. #if defined(PNG_bKGD_SUPPORTED)
  183424. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183425. png_infop info_ptr, png_color_16p *background));
  183426. #endif
  183427. #if defined(PNG_bKGD_SUPPORTED)
  183428. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183429. png_infop info_ptr, png_color_16p background));
  183430. #endif
  183431. #if defined(PNG_cHRM_SUPPORTED)
  183432. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183433. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183434. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183435. double *red_y, double *green_x, double *green_y, double *blue_x,
  183436. double *blue_y));
  183437. #endif
  183438. #ifdef PNG_FIXED_POINT_SUPPORTED
  183439. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183440. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183441. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183442. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183443. *int_blue_x, png_fixed_point *int_blue_y));
  183444. #endif
  183445. #endif
  183446. #if defined(PNG_cHRM_SUPPORTED)
  183447. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183448. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183449. png_infop info_ptr, double white_x, double white_y, double red_x,
  183450. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183451. #endif
  183452. #ifdef PNG_FIXED_POINT_SUPPORTED
  183453. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183454. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183455. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183456. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183457. png_fixed_point int_blue_y));
  183458. #endif
  183459. #endif
  183460. #if defined(PNG_gAMA_SUPPORTED)
  183461. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183462. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183463. png_infop info_ptr, double *file_gamma));
  183464. #endif
  183465. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183466. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183467. #endif
  183468. #if defined(PNG_gAMA_SUPPORTED)
  183469. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183470. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183471. png_infop info_ptr, double file_gamma));
  183472. #endif
  183473. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183474. png_infop info_ptr, png_fixed_point int_file_gamma));
  183475. #endif
  183476. #if defined(PNG_hIST_SUPPORTED)
  183477. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183478. png_infop info_ptr, png_uint_16p *hist));
  183479. #endif
  183480. #if defined(PNG_hIST_SUPPORTED)
  183481. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183482. png_infop info_ptr, png_uint_16p hist));
  183483. #endif
  183484. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183485. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183486. int *bit_depth, int *color_type, int *interlace_method,
  183487. int *compression_method, int *filter_method));
  183488. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183489. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183490. int color_type, int interlace_method, int compression_method,
  183491. int filter_method));
  183492. #if defined(PNG_oFFs_SUPPORTED)
  183493. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183494. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183495. int *unit_type));
  183496. #endif
  183497. #if defined(PNG_oFFs_SUPPORTED)
  183498. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183499. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183500. int unit_type));
  183501. #endif
  183502. #if defined(PNG_pCAL_SUPPORTED)
  183503. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183504. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183505. int *type, int *nparams, png_charp *units, png_charpp *params));
  183506. #endif
  183507. #if defined(PNG_pCAL_SUPPORTED)
  183508. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183509. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183510. int type, int nparams, png_charp units, png_charpp params));
  183511. #endif
  183512. #if defined(PNG_pHYs_SUPPORTED)
  183513. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183514. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183515. #endif
  183516. #if defined(PNG_pHYs_SUPPORTED)
  183517. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183518. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183519. #endif
  183520. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183521. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183522. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183523. png_infop info_ptr, png_colorp palette, int num_palette));
  183524. #if defined(PNG_sBIT_SUPPORTED)
  183525. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183526. png_infop info_ptr, png_color_8p *sig_bit));
  183527. #endif
  183528. #if defined(PNG_sBIT_SUPPORTED)
  183529. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183530. png_infop info_ptr, png_color_8p sig_bit));
  183531. #endif
  183532. #if defined(PNG_sRGB_SUPPORTED)
  183533. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183534. png_infop info_ptr, int *intent));
  183535. #endif
  183536. #if defined(PNG_sRGB_SUPPORTED)
  183537. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183538. png_infop info_ptr, int intent));
  183539. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183540. png_infop info_ptr, int intent));
  183541. #endif
  183542. #if defined(PNG_iCCP_SUPPORTED)
  183543. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183544. png_infop info_ptr, png_charpp name, int *compression_type,
  183545. png_charpp profile, png_uint_32 *proflen));
  183546. /* Note to maintainer: profile should be png_bytepp */
  183547. #endif
  183548. #if defined(PNG_iCCP_SUPPORTED)
  183549. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183550. png_infop info_ptr, png_charp name, int compression_type,
  183551. png_charp profile, png_uint_32 proflen));
  183552. /* Note to maintainer: profile should be png_bytep */
  183553. #endif
  183554. #if defined(PNG_sPLT_SUPPORTED)
  183555. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183556. png_infop info_ptr, png_sPLT_tpp entries));
  183557. #endif
  183558. #if defined(PNG_sPLT_SUPPORTED)
  183559. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183560. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183561. #endif
  183562. #if defined(PNG_TEXT_SUPPORTED)
  183563. /* png_get_text also returns the number of text chunks in *num_text */
  183564. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183565. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183566. #endif
  183567. /*
  183568. * Note while png_set_text() will accept a structure whose text,
  183569. * language, and translated keywords are NULL pointers, the structure
  183570. * returned by png_get_text will always contain regular
  183571. * zero-terminated C strings. They might be empty strings but
  183572. * they will never be NULL pointers.
  183573. */
  183574. #if defined(PNG_TEXT_SUPPORTED)
  183575. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr, png_textp text_ptr, int num_text));
  183577. #endif
  183578. #if defined(PNG_tIME_SUPPORTED)
  183579. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183580. png_infop info_ptr, png_timep *mod_time));
  183581. #endif
  183582. #if defined(PNG_tIME_SUPPORTED)
  183583. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183584. png_infop info_ptr, png_timep mod_time));
  183585. #endif
  183586. #if defined(PNG_tRNS_SUPPORTED)
  183587. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183588. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183589. png_color_16p *trans_values));
  183590. #endif
  183591. #if defined(PNG_tRNS_SUPPORTED)
  183592. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183593. png_infop info_ptr, png_bytep trans, int num_trans,
  183594. png_color_16p trans_values));
  183595. #endif
  183596. #if defined(PNG_tRNS_SUPPORTED)
  183597. #endif
  183598. #if defined(PNG_sCAL_SUPPORTED)
  183599. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183600. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183601. png_infop info_ptr, int *unit, double *width, double *height));
  183602. #else
  183603. #ifdef PNG_FIXED_POINT_SUPPORTED
  183604. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183605. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183606. #endif
  183607. #endif
  183608. #endif /* PNG_sCAL_SUPPORTED */
  183609. #if defined(PNG_sCAL_SUPPORTED)
  183610. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183611. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183612. png_infop info_ptr, int unit, double width, double height));
  183613. #else
  183614. #ifdef PNG_FIXED_POINT_SUPPORTED
  183615. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183616. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183617. #endif
  183618. #endif
  183619. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183620. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183621. /* provide a list of chunks and how they are to be handled, if the built-in
  183622. handling or default unknown chunk handling is not desired. Any chunks not
  183623. listed will be handled in the default manner. The IHDR and IEND chunks
  183624. must not be listed.
  183625. keep = 0: follow default behaviour
  183626. = 1: do not keep
  183627. = 2: keep only if safe-to-copy
  183628. = 3: keep even if unsafe-to-copy
  183629. */
  183630. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183631. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183632. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183633. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183634. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183635. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183636. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183637. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183638. #endif
  183639. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183640. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183641. chunk_name));
  183642. #endif
  183643. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183644. If you need to turn it off for a chunk that your application has freed,
  183645. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183646. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183647. png_infop info_ptr, int mask));
  183648. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183649. /* The "params" pointer is currently not used and is for future expansion. */
  183650. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183651. png_infop info_ptr,
  183652. int transforms,
  183653. png_voidp params));
  183654. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183655. png_infop info_ptr,
  183656. int transforms,
  183657. png_voidp params));
  183658. #endif
  183659. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183660. * numbers for PNG_DEBUG mean more debugging information. This has
  183661. * only been added since version 0.95 so it is not implemented throughout
  183662. * libpng yet, but more support will be added as needed.
  183663. */
  183664. #ifdef PNG_DEBUG
  183665. #if (PNG_DEBUG > 0)
  183666. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183667. #include <crtdbg.h>
  183668. #if (PNG_DEBUG > 1)
  183669. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183670. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183671. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183672. #endif
  183673. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183674. #ifndef PNG_DEBUG_FILE
  183675. #define PNG_DEBUG_FILE stderr
  183676. #endif /* PNG_DEBUG_FILE */
  183677. #if (PNG_DEBUG > 1)
  183678. #define png_debug(l,m) \
  183679. { \
  183680. int num_tabs=l; \
  183681. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183682. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183683. }
  183684. #define png_debug1(l,m,p1) \
  183685. { \
  183686. int num_tabs=l; \
  183687. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183688. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183689. }
  183690. #define png_debug2(l,m,p1,p2) \
  183691. { \
  183692. int num_tabs=l; \
  183693. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183694. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183695. }
  183696. #endif /* (PNG_DEBUG > 1) */
  183697. #endif /* _MSC_VER */
  183698. #endif /* (PNG_DEBUG > 0) */
  183699. #endif /* PNG_DEBUG */
  183700. #ifndef png_debug
  183701. #define png_debug(l, m)
  183702. #endif
  183703. #ifndef png_debug1
  183704. #define png_debug1(l, m, p1)
  183705. #endif
  183706. #ifndef png_debug2
  183707. #define png_debug2(l, m, p1, p2)
  183708. #endif
  183709. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183710. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183711. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183712. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183713. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183714. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183715. png_ptr, png_uint_32 mng_features_permitted));
  183716. #endif
  183717. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183718. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183719. #define PNG_HANDLE_CHUNK_NEVER 1
  183720. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183721. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183722. /* Added to version 1.2.0 */
  183723. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183724. #if defined(PNG_MMX_CODE_SUPPORTED)
  183725. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183726. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183727. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183728. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183729. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183730. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183731. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183732. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183733. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183734. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183735. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183736. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183737. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183738. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183739. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183740. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183741. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183742. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183743. | PNG_MMX_READ_FLAGS \
  183744. | PNG_MMX_WRITE_FLAGS )
  183745. #define PNG_SELECT_READ 1
  183746. #define PNG_SELECT_WRITE 2
  183747. #endif /* PNG_MMX_CODE_SUPPORTED */
  183748. #if !defined(PNG_1_0_X)
  183749. /* pngget.c */
  183750. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183751. PNGARG((int flag_select, int *compilerID));
  183752. /* pngget.c */
  183753. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183754. PNGARG((int flag_select));
  183755. /* pngget.c */
  183756. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183757. PNGARG((png_structp png_ptr));
  183758. /* pngget.c */
  183759. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183760. PNGARG((png_structp png_ptr));
  183761. /* pngget.c */
  183762. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183763. PNGARG((png_structp png_ptr));
  183764. /* pngset.c */
  183765. extern PNG_EXPORT(void,png_set_asm_flags)
  183766. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183767. /* pngset.c */
  183768. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183769. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183770. png_uint_32 mmx_rowbytes_threshold));
  183771. #endif /* PNG_1_0_X */
  183772. #if !defined(PNG_1_0_X)
  183773. /* png.c, pnggccrd.c, or pngvcrd.c */
  183774. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183775. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183776. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183777. * messages before passing them to the error or warning handler. */
  183778. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183779. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183780. png_ptr, png_uint_32 strip_mode));
  183781. #endif
  183782. #endif /* PNG_1_0_X */
  183783. /* Added at libpng-1.2.6 */
  183784. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183785. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183786. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183787. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183788. png_ptr));
  183789. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183790. png_ptr));
  183791. #endif
  183792. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183793. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183794. /* With these routines we avoid an integer divide, which will be slower on
  183795. * most machines. However, it does take more operations than the corresponding
  183796. * divide method, so it may be slower on a few RISC systems. There are two
  183797. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183798. *
  183799. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183800. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183801. * standard method.
  183802. *
  183803. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183804. */
  183805. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183806. # define png_composite(composite, fg, alpha, bg) \
  183807. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183808. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183809. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183810. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183811. # define png_composite_16(composite, fg, alpha, bg) \
  183812. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183813. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183814. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183815. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183816. #else /* standard method using integer division */
  183817. # define png_composite(composite, fg, alpha, bg) \
  183818. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183819. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183820. (png_uint_16)127) / 255)
  183821. # define png_composite_16(composite, fg, alpha, bg) \
  183822. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183823. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183824. (png_uint_32)32767) / (png_uint_32)65535L)
  183825. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183826. /* Inline macros to do direct reads of bytes from the input buffer. These
  183827. * require that you are using an architecture that uses PNG byte ordering
  183828. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183829. * in big-endian mode and 680x0 are the only ones that will support this.
  183830. * The x86 line of processors definitely do not. The png_get_int_32()
  183831. * routine also assumes we are using two's complement format for negative
  183832. * values, which is almost certainly true.
  183833. */
  183834. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183835. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183836. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183837. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183838. #else
  183839. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183840. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183841. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183842. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183843. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183844. PNGARG((png_structp png_ptr, png_bytep buf));
  183845. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183846. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183847. */
  183848. extern PNG_EXPORT(void,png_save_uint_32)
  183849. PNGARG((png_bytep buf, png_uint_32 i));
  183850. extern PNG_EXPORT(void,png_save_int_32)
  183851. PNGARG((png_bytep buf, png_int_32 i));
  183852. /* Place a 16-bit number into a buffer in PNG byte order.
  183853. * The parameter is declared unsigned int, not png_uint_16,
  183854. * just to avoid potential problems on pre-ANSI C compilers.
  183855. */
  183856. extern PNG_EXPORT(void,png_save_uint_16)
  183857. PNGARG((png_bytep buf, unsigned int i));
  183858. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183859. /* ************************************************************************* */
  183860. /* These next functions are used internally in the code. They generally
  183861. * shouldn't be used unless you are writing code to add or replace some
  183862. * functionality in libpng. More information about most functions can
  183863. * be found in the files where the functions are located.
  183864. */
  183865. /* Various modes of operation, that are visible to applications because
  183866. * they are used for unknown chunk location.
  183867. */
  183868. #define PNG_HAVE_IHDR 0x01
  183869. #define PNG_HAVE_PLTE 0x02
  183870. #define PNG_HAVE_IDAT 0x04
  183871. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183872. #define PNG_HAVE_IEND 0x10
  183873. #if defined(PNG_INTERNAL)
  183874. /* More modes of operation. Note that after an init, mode is set to
  183875. * zero automatically when the structure is created.
  183876. */
  183877. #define PNG_HAVE_gAMA 0x20
  183878. #define PNG_HAVE_cHRM 0x40
  183879. #define PNG_HAVE_sRGB 0x80
  183880. #define PNG_HAVE_CHUNK_HEADER 0x100
  183881. #define PNG_WROTE_tIME 0x200
  183882. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183883. #define PNG_BACKGROUND_IS_GRAY 0x800
  183884. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183885. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183886. /* flags for the transformations the PNG library does on the image data */
  183887. #define PNG_BGR 0x0001
  183888. #define PNG_INTERLACE 0x0002
  183889. #define PNG_PACK 0x0004
  183890. #define PNG_SHIFT 0x0008
  183891. #define PNG_SWAP_BYTES 0x0010
  183892. #define PNG_INVERT_MONO 0x0020
  183893. #define PNG_DITHER 0x0040
  183894. #define PNG_BACKGROUND 0x0080
  183895. #define PNG_BACKGROUND_EXPAND 0x0100
  183896. /* 0x0200 unused */
  183897. #define PNG_16_TO_8 0x0400
  183898. #define PNG_RGBA 0x0800
  183899. #define PNG_EXPAND 0x1000
  183900. #define PNG_GAMMA 0x2000
  183901. #define PNG_GRAY_TO_RGB 0x4000
  183902. #define PNG_FILLER 0x8000L
  183903. #define PNG_PACKSWAP 0x10000L
  183904. #define PNG_SWAP_ALPHA 0x20000L
  183905. #define PNG_STRIP_ALPHA 0x40000L
  183906. #define PNG_INVERT_ALPHA 0x80000L
  183907. #define PNG_USER_TRANSFORM 0x100000L
  183908. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183909. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183910. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183911. /* 0x800000L Unused */
  183912. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183913. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183914. /* 0x4000000L unused */
  183915. /* 0x8000000L unused */
  183916. /* 0x10000000L unused */
  183917. /* 0x20000000L unused */
  183918. /* 0x40000000L unused */
  183919. /* flags for png_create_struct */
  183920. #define PNG_STRUCT_PNG 0x0001
  183921. #define PNG_STRUCT_INFO 0x0002
  183922. /* Scaling factor for filter heuristic weighting calculations */
  183923. #define PNG_WEIGHT_SHIFT 8
  183924. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183925. #define PNG_COST_SHIFT 3
  183926. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183927. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183928. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183929. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183930. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183931. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183932. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183933. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183934. #define PNG_FLAG_ROW_INIT 0x0040
  183935. #define PNG_FLAG_FILLER_AFTER 0x0080
  183936. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183937. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183938. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183939. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183940. #define PNG_FLAG_FREE_PLTE 0x1000
  183941. #define PNG_FLAG_FREE_TRNS 0x2000
  183942. #define PNG_FLAG_FREE_HIST 0x4000
  183943. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183944. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183945. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183946. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183947. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183948. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183949. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183950. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183951. /* 0x800000L unused */
  183952. /* 0x1000000L unused */
  183953. /* 0x2000000L unused */
  183954. /* 0x4000000L unused */
  183955. /* 0x8000000L unused */
  183956. /* 0x10000000L unused */
  183957. /* 0x20000000L unused */
  183958. /* 0x40000000L unused */
  183959. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183960. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183961. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183962. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183963. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183964. PNG_FLAG_CRC_CRITICAL_MASK)
  183965. /* save typing and make code easier to understand */
  183966. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183967. abs((int)((c1).green) - (int)((c2).green)) + \
  183968. abs((int)((c1).blue) - (int)((c2).blue)))
  183969. /* Added to libpng-1.2.6 JB */
  183970. #define PNG_ROWBYTES(pixel_bits, width) \
  183971. ((pixel_bits) >= 8 ? \
  183972. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183973. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183974. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183975. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183976. "ideal" and "delta" should be constants, normally simple
  183977. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183978. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183979. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183980. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183981. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183982. /* place to hold the signature string for a PNG file. */
  183983. #ifdef PNG_USE_GLOBAL_ARRAYS
  183984. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183985. #else
  183986. #endif
  183987. #endif /* PNG_NO_EXTERN */
  183988. /* Constant strings for known chunk types. If you need to add a chunk,
  183989. * define the name here, and add an invocation of the macro in png.c and
  183990. * wherever it's needed.
  183991. */
  183992. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183993. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183994. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183995. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183996. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183997. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183998. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183999. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184000. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184001. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184002. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184003. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184004. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184005. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184006. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184007. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184008. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184009. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184010. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184011. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184012. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184013. #ifdef PNG_USE_GLOBAL_ARRAYS
  184014. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184015. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184016. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184017. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184018. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184019. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184020. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184021. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184022. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184023. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184024. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184025. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184026. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184027. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184028. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184029. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184030. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184031. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184032. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184033. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184034. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184035. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184036. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184037. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184038. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184039. */
  184040. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184041. #undef png_read_init
  184042. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184043. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184044. #endif
  184045. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184046. png_const_charp user_png_ver, png_size_t png_struct_size));
  184047. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184048. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184049. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184050. png_info_size));
  184051. #endif
  184052. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184053. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184054. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184055. */
  184056. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184057. #undef png_write_init
  184058. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184059. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184060. #endif
  184061. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184062. png_const_charp user_png_ver, png_size_t png_struct_size));
  184063. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184064. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184065. png_info_size));
  184066. /* Allocate memory for an internal libpng struct */
  184067. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184068. /* Free memory from internal libpng struct */
  184069. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184070. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184071. malloc_fn, png_voidp mem_ptr));
  184072. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184073. png_free_ptr free_fn, png_voidp mem_ptr));
  184074. /* Free any memory that info_ptr points to and reset struct. */
  184075. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184076. png_infop info_ptr));
  184077. #ifndef PNG_1_0_X
  184078. /* Function to allocate memory for zlib. */
  184079. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184080. /* Function to free memory for zlib */
  184081. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184082. #ifdef PNG_SIZE_T
  184083. /* Function to convert a sizeof an item to png_sizeof item */
  184084. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184085. #endif
  184086. /* Next four functions are used internally as callbacks. PNGAPI is required
  184087. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184088. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184089. png_bytep data, png_size_t length));
  184090. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184091. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184092. png_bytep buffer, png_size_t length));
  184093. #endif
  184094. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184095. png_bytep data, png_size_t length));
  184096. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184097. #if !defined(PNG_NO_STDIO)
  184098. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184099. #endif
  184100. #endif
  184101. #else /* PNG_1_0_X */
  184102. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184103. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184104. png_bytep buffer, png_size_t length));
  184105. #endif
  184106. #endif /* PNG_1_0_X */
  184107. /* Reset the CRC variable */
  184108. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184109. /* Write the "data" buffer to whatever output you are using. */
  184110. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184111. png_size_t length));
  184112. /* Read data from whatever input you are using into the "data" buffer */
  184113. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184114. png_size_t length));
  184115. /* Read bytes into buf, and update png_ptr->crc */
  184116. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184117. png_size_t length));
  184118. /* Decompress data in a chunk that uses compression */
  184119. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184120. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184121. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184122. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184123. png_size_t prefix_length, png_size_t *data_length));
  184124. #endif
  184125. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184126. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184127. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184128. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184129. /* Calculate the CRC over a section of data. Note that we are only
  184130. * passing a maximum of 64K on systems that have this as a memory limit,
  184131. * since this is the maximum buffer size we can specify.
  184132. */
  184133. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184134. png_size_t length));
  184135. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184136. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184137. #endif
  184138. /* simple function to write the signature */
  184139. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184140. /* write various chunks */
  184141. /* Write the IHDR chunk, and update the png_struct with the necessary
  184142. * information.
  184143. */
  184144. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184145. png_uint_32 height,
  184146. int bit_depth, int color_type, int compression_method, int filter_method,
  184147. int interlace_method));
  184148. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184149. png_uint_32 num_pal));
  184150. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184151. png_size_t length));
  184152. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184153. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184154. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184155. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184156. #endif
  184157. #ifdef PNG_FIXED_POINT_SUPPORTED
  184158. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184159. file_gamma));
  184160. #endif
  184161. #endif
  184162. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184163. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184164. int color_type));
  184165. #endif
  184166. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184167. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184168. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184169. double white_x, double white_y,
  184170. double red_x, double red_y, double green_x, double green_y,
  184171. double blue_x, double blue_y));
  184172. #endif
  184173. #ifdef PNG_FIXED_POINT_SUPPORTED
  184174. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184175. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184176. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184177. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184178. png_fixed_point int_blue_y));
  184179. #endif
  184180. #endif
  184181. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184182. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184183. int intent));
  184184. #endif
  184185. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184186. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184187. png_charp name, int compression_type,
  184188. png_charp profile, int proflen));
  184189. /* Note to maintainer: profile should be png_bytep */
  184190. #endif
  184191. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184192. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184193. png_sPLT_tp palette));
  184194. #endif
  184195. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184196. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184197. png_color_16p values, int number, int color_type));
  184198. #endif
  184199. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184200. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184201. png_color_16p values, int color_type));
  184202. #endif
  184203. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184204. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184205. int num_hist));
  184206. #endif
  184207. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184208. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184209. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184210. png_charp key, png_charpp new_key));
  184211. #endif
  184212. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184213. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184214. png_charp text, png_size_t text_len));
  184215. #endif
  184216. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184217. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184218. png_charp text, png_size_t text_len, int compression));
  184219. #endif
  184220. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184221. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184222. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184223. png_charp text));
  184224. #endif
  184225. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184226. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184227. png_infop info_ptr, png_textp text_ptr, int num_text));
  184228. #endif
  184229. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184230. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184231. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184232. #endif
  184233. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184234. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184235. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184236. png_charp units, png_charpp params));
  184237. #endif
  184238. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184239. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184240. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184241. int unit_type));
  184242. #endif
  184243. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184244. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184245. png_timep mod_time));
  184246. #endif
  184247. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184248. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184249. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184250. int unit, double width, double height));
  184251. #else
  184252. #ifdef PNG_FIXED_POINT_SUPPORTED
  184253. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184254. int unit, png_charp width, png_charp height));
  184255. #endif
  184256. #endif
  184257. #endif
  184258. /* Called when finished processing a row of data */
  184259. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184260. /* Internal use only. Called before first row of data */
  184261. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184262. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184263. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184264. #endif
  184265. /* combine a row of data, dealing with alpha, etc. if requested */
  184266. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184267. int mask));
  184268. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184269. /* expand an interlaced row */
  184270. /* OLD pre-1.0.9 interface:
  184271. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184272. png_bytep row, int pass, png_uint_32 transformations));
  184273. */
  184274. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184275. #endif
  184276. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184277. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184278. /* grab pixels out of a row for an interlaced pass */
  184279. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184280. png_bytep row, int pass));
  184281. #endif
  184282. /* unfilter a row */
  184283. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184284. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184285. /* Choose the best filter to use and filter the row data */
  184286. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184287. png_row_infop row_info));
  184288. /* Write out the filtered row. */
  184289. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184290. png_bytep filtered_row));
  184291. /* finish a row while reading, dealing with interlacing passes, etc. */
  184292. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184293. /* initialize the row buffers, etc. */
  184294. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184295. /* optional call to update the users info structure */
  184296. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184297. png_infop info_ptr));
  184298. /* these are the functions that do the transformations */
  184299. #if defined(PNG_READ_FILLER_SUPPORTED)
  184300. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184301. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184302. #endif
  184303. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184304. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184305. png_bytep row));
  184306. #endif
  184307. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184308. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184309. png_bytep row));
  184310. #endif
  184311. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184312. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184313. png_bytep row));
  184314. #endif
  184315. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184316. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184317. png_bytep row));
  184318. #endif
  184319. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184320. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184321. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184322. png_bytep row, png_uint_32 flags));
  184323. #endif
  184324. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184325. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184326. #endif
  184327. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184328. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184329. #endif
  184330. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184331. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184332. row_info, png_bytep row));
  184333. #endif
  184334. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184335. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184336. png_bytep row));
  184337. #endif
  184338. #if defined(PNG_READ_PACK_SUPPORTED)
  184339. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184340. #endif
  184341. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184342. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184343. png_color_8p sig_bits));
  184344. #endif
  184345. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184346. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184347. #endif
  184348. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184349. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184350. #endif
  184351. #if defined(PNG_READ_DITHER_SUPPORTED)
  184352. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184353. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184354. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184355. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184356. png_colorp palette, int num_palette));
  184357. # endif
  184358. #endif
  184359. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184360. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184361. #endif
  184362. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184363. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184364. png_bytep row, png_uint_32 bit_depth));
  184365. #endif
  184366. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184367. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184368. png_color_8p bit_depth));
  184369. #endif
  184370. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184371. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184372. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184373. png_color_16p trans_values, png_color_16p background,
  184374. png_color_16p background_1,
  184375. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184376. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184377. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184378. #else
  184379. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184380. png_color_16p trans_values, png_color_16p background));
  184381. #endif
  184382. #endif
  184383. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184384. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184385. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184386. int gamma_shift));
  184387. #endif
  184388. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184389. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184390. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184391. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184392. png_bytep row, png_color_16p trans_value));
  184393. #endif
  184394. /* The following decodes the appropriate chunks, and does error correction,
  184395. * then calls the appropriate callback for the chunk if it is valid.
  184396. */
  184397. /* decode the IHDR chunk */
  184398. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184399. png_uint_32 length));
  184400. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184401. png_uint_32 length));
  184402. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184403. png_uint_32 length));
  184404. #if defined(PNG_READ_bKGD_SUPPORTED)
  184405. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184406. png_uint_32 length));
  184407. #endif
  184408. #if defined(PNG_READ_cHRM_SUPPORTED)
  184409. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184410. png_uint_32 length));
  184411. #endif
  184412. #if defined(PNG_READ_gAMA_SUPPORTED)
  184413. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184414. png_uint_32 length));
  184415. #endif
  184416. #if defined(PNG_READ_hIST_SUPPORTED)
  184417. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184418. png_uint_32 length));
  184419. #endif
  184420. #if defined(PNG_READ_iCCP_SUPPORTED)
  184421. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184422. png_uint_32 length));
  184423. #endif /* PNG_READ_iCCP_SUPPORTED */
  184424. #if defined(PNG_READ_iTXt_SUPPORTED)
  184425. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184426. png_uint_32 length));
  184427. #endif
  184428. #if defined(PNG_READ_oFFs_SUPPORTED)
  184429. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184430. png_uint_32 length));
  184431. #endif
  184432. #if defined(PNG_READ_pCAL_SUPPORTED)
  184433. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184434. png_uint_32 length));
  184435. #endif
  184436. #if defined(PNG_READ_pHYs_SUPPORTED)
  184437. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184438. png_uint_32 length));
  184439. #endif
  184440. #if defined(PNG_READ_sBIT_SUPPORTED)
  184441. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184442. png_uint_32 length));
  184443. #endif
  184444. #if defined(PNG_READ_sCAL_SUPPORTED)
  184445. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184446. png_uint_32 length));
  184447. #endif
  184448. #if defined(PNG_READ_sPLT_SUPPORTED)
  184449. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184450. png_uint_32 length));
  184451. #endif /* PNG_READ_sPLT_SUPPORTED */
  184452. #if defined(PNG_READ_sRGB_SUPPORTED)
  184453. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184454. png_uint_32 length));
  184455. #endif
  184456. #if defined(PNG_READ_tEXt_SUPPORTED)
  184457. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184458. png_uint_32 length));
  184459. #endif
  184460. #if defined(PNG_READ_tIME_SUPPORTED)
  184461. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184462. png_uint_32 length));
  184463. #endif
  184464. #if defined(PNG_READ_tRNS_SUPPORTED)
  184465. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184466. png_uint_32 length));
  184467. #endif
  184468. #if defined(PNG_READ_zTXt_SUPPORTED)
  184469. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184470. png_uint_32 length));
  184471. #endif
  184472. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184473. png_infop info_ptr, png_uint_32 length));
  184474. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184475. png_bytep chunk_name));
  184476. /* handle the transformations for reading and writing */
  184477. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184478. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184479. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184480. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184481. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184482. png_infop info_ptr));
  184483. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184484. png_infop info_ptr));
  184485. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184486. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184487. png_uint_32 length));
  184488. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184489. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184490. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184491. png_bytep buffer, png_size_t buffer_length));
  184492. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184493. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184494. png_bytep buffer, png_size_t buffer_length));
  184495. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184496. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184497. png_infop info_ptr, png_uint_32 length));
  184498. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184499. png_infop info_ptr));
  184500. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184501. png_infop info_ptr));
  184502. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184503. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184504. png_infop info_ptr));
  184505. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184506. png_infop info_ptr));
  184507. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184508. #if defined(PNG_READ_tEXt_SUPPORTED)
  184509. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184510. png_infop info_ptr, png_uint_32 length));
  184511. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184512. png_infop info_ptr));
  184513. #endif
  184514. #if defined(PNG_READ_zTXt_SUPPORTED)
  184515. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184516. png_infop info_ptr, png_uint_32 length));
  184517. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184518. png_infop info_ptr));
  184519. #endif
  184520. #if defined(PNG_READ_iTXt_SUPPORTED)
  184521. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184522. png_infop info_ptr, png_uint_32 length));
  184523. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184524. png_infop info_ptr));
  184525. #endif
  184526. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184527. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184528. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184529. png_bytep row));
  184530. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184531. png_bytep row));
  184532. #endif
  184533. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184534. #if defined(PNG_MMX_CODE_SUPPORTED)
  184535. /* png.c */ /* PRIVATE */
  184536. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184537. #endif
  184538. #endif
  184539. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184540. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184541. png_infop info_ptr));
  184542. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184543. png_infop info_ptr));
  184544. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184545. png_infop info_ptr));
  184546. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184547. png_infop info_ptr));
  184548. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184549. png_infop info_ptr));
  184550. #if defined(PNG_pHYs_SUPPORTED)
  184551. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184552. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184553. #endif /* PNG_pHYs_SUPPORTED */
  184554. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184555. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184556. #endif /* PNG_INTERNAL */
  184557. #ifdef __cplusplus
  184558. //}
  184559. #endif
  184560. #endif /* PNG_VERSION_INFO_ONLY */
  184561. /* do not put anything past this line */
  184562. #endif /* PNG_H */
  184563. /*** End of inlined file: png.h ***/
  184564. #define PNG_NO_EXTERN
  184565. /*** Start of inlined file: png.c ***/
  184566. /* png.c - location for general purpose libpng functions
  184567. *
  184568. * Last changed in libpng 1.2.21 [October 4, 2007]
  184569. * For conditions of distribution and use, see copyright notice in png.h
  184570. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184571. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184572. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184573. */
  184574. #define PNG_INTERNAL
  184575. #define PNG_NO_EXTERN
  184576. /* Generate a compiler error if there is an old png.h in the search path. */
  184577. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184578. /* Version information for C files. This had better match the version
  184579. * string defined in png.h. */
  184580. #ifdef PNG_USE_GLOBAL_ARRAYS
  184581. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184582. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184583. #ifdef PNG_READ_SUPPORTED
  184584. /* png_sig was changed to a function in version 1.0.5c */
  184585. /* Place to hold the signature string for a PNG file. */
  184586. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184587. #endif /* PNG_READ_SUPPORTED */
  184588. /* Invoke global declarations for constant strings for known chunk types */
  184589. PNG_IHDR;
  184590. PNG_IDAT;
  184591. PNG_IEND;
  184592. PNG_PLTE;
  184593. PNG_bKGD;
  184594. PNG_cHRM;
  184595. PNG_gAMA;
  184596. PNG_hIST;
  184597. PNG_iCCP;
  184598. PNG_iTXt;
  184599. PNG_oFFs;
  184600. PNG_pCAL;
  184601. PNG_sCAL;
  184602. PNG_pHYs;
  184603. PNG_sBIT;
  184604. PNG_sPLT;
  184605. PNG_sRGB;
  184606. PNG_tEXt;
  184607. PNG_tIME;
  184608. PNG_tRNS;
  184609. PNG_zTXt;
  184610. #ifdef PNG_READ_SUPPORTED
  184611. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184612. /* start of interlace block */
  184613. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184614. /* offset to next interlace block */
  184615. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184616. /* start of interlace block in the y direction */
  184617. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184618. /* offset to next interlace block in the y direction */
  184619. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184620. /* Height of interlace block. This is not currently used - if you need
  184621. * it, uncomment it here and in png.h
  184622. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184623. */
  184624. /* Mask to determine which pixels are valid in a pass */
  184625. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184626. /* Mask to determine which pixels to overwrite while displaying */
  184627. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184628. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184629. #endif /* PNG_READ_SUPPORTED */
  184630. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184631. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184632. * of the PNG file signature. If the PNG data is embedded into another
  184633. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184634. * or write any of the magic bytes before it starts on the IHDR.
  184635. */
  184636. #ifdef PNG_READ_SUPPORTED
  184637. void PNGAPI
  184638. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184639. {
  184640. if(png_ptr == NULL) return;
  184641. png_debug(1, "in png_set_sig_bytes\n");
  184642. if (num_bytes > 8)
  184643. png_error(png_ptr, "Too many bytes for PNG signature.");
  184644. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184645. }
  184646. /* Checks whether the supplied bytes match the PNG signature. We allow
  184647. * checking less than the full 8-byte signature so that those apps that
  184648. * already read the first few bytes of a file to determine the file type
  184649. * can simply check the remaining bytes for extra assurance. Returns
  184650. * an integer less than, equal to, or greater than zero if sig is found,
  184651. * respectively, to be less than, to match, or be greater than the correct
  184652. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184653. */
  184654. int PNGAPI
  184655. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184656. {
  184657. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184658. if (num_to_check > 8)
  184659. num_to_check = 8;
  184660. else if (num_to_check < 1)
  184661. return (-1);
  184662. if (start > 7)
  184663. return (-1);
  184664. if (start + num_to_check > 8)
  184665. num_to_check = 8 - start;
  184666. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184667. }
  184668. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184669. /* (Obsolete) function to check signature bytes. It does not allow one
  184670. * to check a partial signature. This function might be removed in the
  184671. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184672. */
  184673. int PNGAPI
  184674. png_check_sig(png_bytep sig, int num)
  184675. {
  184676. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184677. }
  184678. #endif
  184679. #endif /* PNG_READ_SUPPORTED */
  184680. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184681. /* Function to allocate memory for zlib and clear it to 0. */
  184682. #ifdef PNG_1_0_X
  184683. voidpf PNGAPI
  184684. #else
  184685. voidpf /* private */
  184686. #endif
  184687. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184688. {
  184689. png_voidp ptr;
  184690. png_structp p=(png_structp)png_ptr;
  184691. png_uint_32 save_flags=p->flags;
  184692. png_uint_32 num_bytes;
  184693. if(png_ptr == NULL) return (NULL);
  184694. if (items > PNG_UINT_32_MAX/size)
  184695. {
  184696. png_warning (p, "Potential overflow in png_zalloc()");
  184697. return (NULL);
  184698. }
  184699. num_bytes = (png_uint_32)items * size;
  184700. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184701. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184702. p->flags=save_flags;
  184703. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184704. if (ptr == NULL)
  184705. return ((voidpf)ptr);
  184706. if (num_bytes > (png_uint_32)0x8000L)
  184707. {
  184708. png_memset(ptr, 0, (png_size_t)0x8000L);
  184709. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184710. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184711. }
  184712. else
  184713. {
  184714. png_memset(ptr, 0, (png_size_t)num_bytes);
  184715. }
  184716. #endif
  184717. return ((voidpf)ptr);
  184718. }
  184719. /* function to free memory for zlib */
  184720. #ifdef PNG_1_0_X
  184721. void PNGAPI
  184722. #else
  184723. void /* private */
  184724. #endif
  184725. png_zfree(voidpf png_ptr, voidpf ptr)
  184726. {
  184727. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184728. }
  184729. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184730. * in case CRC is > 32 bits to leave the top bits 0.
  184731. */
  184732. void /* PRIVATE */
  184733. png_reset_crc(png_structp png_ptr)
  184734. {
  184735. png_ptr->crc = crc32(0, Z_NULL, 0);
  184736. }
  184737. /* Calculate the CRC over a section of data. We can only pass as
  184738. * much data to this routine as the largest single buffer size. We
  184739. * also check that this data will actually be used before going to the
  184740. * trouble of calculating it.
  184741. */
  184742. void /* PRIVATE */
  184743. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184744. {
  184745. int need_crc = 1;
  184746. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184747. {
  184748. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184749. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184750. need_crc = 0;
  184751. }
  184752. else /* critical */
  184753. {
  184754. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184755. need_crc = 0;
  184756. }
  184757. if (need_crc)
  184758. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184759. }
  184760. /* Allocate the memory for an info_struct for the application. We don't
  184761. * really need the png_ptr, but it could potentially be useful in the
  184762. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184763. * and png_info_init() so that applications that want to use a shared
  184764. * libpng don't have to be recompiled if png_info changes size.
  184765. */
  184766. png_infop PNGAPI
  184767. png_create_info_struct(png_structp png_ptr)
  184768. {
  184769. png_infop info_ptr;
  184770. png_debug(1, "in png_create_info_struct\n");
  184771. if(png_ptr == NULL) return (NULL);
  184772. #ifdef PNG_USER_MEM_SUPPORTED
  184773. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184774. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184775. #else
  184776. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184777. #endif
  184778. if (info_ptr != NULL)
  184779. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184780. return (info_ptr);
  184781. }
  184782. /* This function frees the memory associated with a single info struct.
  184783. * Normally, one would use either png_destroy_read_struct() or
  184784. * png_destroy_write_struct() to free an info struct, but this may be
  184785. * useful for some applications.
  184786. */
  184787. void PNGAPI
  184788. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184789. {
  184790. png_infop info_ptr = NULL;
  184791. if(png_ptr == NULL) return;
  184792. png_debug(1, "in png_destroy_info_struct\n");
  184793. if (info_ptr_ptr != NULL)
  184794. info_ptr = *info_ptr_ptr;
  184795. if (info_ptr != NULL)
  184796. {
  184797. png_info_destroy(png_ptr, info_ptr);
  184798. #ifdef PNG_USER_MEM_SUPPORTED
  184799. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184800. png_ptr->mem_ptr);
  184801. #else
  184802. png_destroy_struct((png_voidp)info_ptr);
  184803. #endif
  184804. *info_ptr_ptr = NULL;
  184805. }
  184806. }
  184807. /* Initialize the info structure. This is now an internal function (0.89)
  184808. * and applications using it are urged to use png_create_info_struct()
  184809. * instead.
  184810. */
  184811. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184812. #undef png_info_init
  184813. void PNGAPI
  184814. png_info_init(png_infop info_ptr)
  184815. {
  184816. /* We only come here via pre-1.0.12-compiled applications */
  184817. png_info_init_3(&info_ptr, 0);
  184818. }
  184819. #endif
  184820. void PNGAPI
  184821. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184822. {
  184823. png_infop info_ptr = *ptr_ptr;
  184824. if(info_ptr == NULL) return;
  184825. png_debug(1, "in png_info_init_3\n");
  184826. if(png_sizeof(png_info) > png_info_struct_size)
  184827. {
  184828. png_destroy_struct(info_ptr);
  184829. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184830. *ptr_ptr = info_ptr;
  184831. }
  184832. /* set everything to 0 */
  184833. png_memset(info_ptr, 0, png_sizeof (png_info));
  184834. }
  184835. #ifdef PNG_FREE_ME_SUPPORTED
  184836. void PNGAPI
  184837. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184838. int freer, png_uint_32 mask)
  184839. {
  184840. png_debug(1, "in png_data_freer\n");
  184841. if (png_ptr == NULL || info_ptr == NULL)
  184842. return;
  184843. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184844. info_ptr->free_me |= mask;
  184845. else if(freer == PNG_USER_WILL_FREE_DATA)
  184846. info_ptr->free_me &= ~mask;
  184847. else
  184848. png_warning(png_ptr,
  184849. "Unknown freer parameter in png_data_freer.");
  184850. }
  184851. #endif
  184852. void PNGAPI
  184853. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184854. int num)
  184855. {
  184856. png_debug(1, "in png_free_data\n");
  184857. if (png_ptr == NULL || info_ptr == NULL)
  184858. return;
  184859. #if defined(PNG_TEXT_SUPPORTED)
  184860. /* free text item num or (if num == -1) all text items */
  184861. #ifdef PNG_FREE_ME_SUPPORTED
  184862. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184863. #else
  184864. if (mask & PNG_FREE_TEXT)
  184865. #endif
  184866. {
  184867. if (num != -1)
  184868. {
  184869. if (info_ptr->text && info_ptr->text[num].key)
  184870. {
  184871. png_free(png_ptr, info_ptr->text[num].key);
  184872. info_ptr->text[num].key = NULL;
  184873. }
  184874. }
  184875. else
  184876. {
  184877. int i;
  184878. for (i = 0; i < info_ptr->num_text; i++)
  184879. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184880. png_free(png_ptr, info_ptr->text);
  184881. info_ptr->text = NULL;
  184882. info_ptr->num_text=0;
  184883. }
  184884. }
  184885. #endif
  184886. #if defined(PNG_tRNS_SUPPORTED)
  184887. /* free any tRNS entry */
  184888. #ifdef PNG_FREE_ME_SUPPORTED
  184889. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184890. #else
  184891. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184892. #endif
  184893. {
  184894. png_free(png_ptr, info_ptr->trans);
  184895. info_ptr->valid &= ~PNG_INFO_tRNS;
  184896. #ifndef PNG_FREE_ME_SUPPORTED
  184897. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184898. #endif
  184899. info_ptr->trans = NULL;
  184900. }
  184901. #endif
  184902. #if defined(PNG_sCAL_SUPPORTED)
  184903. /* free any sCAL entry */
  184904. #ifdef PNG_FREE_ME_SUPPORTED
  184905. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184906. #else
  184907. if (mask & PNG_FREE_SCAL)
  184908. #endif
  184909. {
  184910. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184911. png_free(png_ptr, info_ptr->scal_s_width);
  184912. png_free(png_ptr, info_ptr->scal_s_height);
  184913. info_ptr->scal_s_width = NULL;
  184914. info_ptr->scal_s_height = NULL;
  184915. #endif
  184916. info_ptr->valid &= ~PNG_INFO_sCAL;
  184917. }
  184918. #endif
  184919. #if defined(PNG_pCAL_SUPPORTED)
  184920. /* free any pCAL entry */
  184921. #ifdef PNG_FREE_ME_SUPPORTED
  184922. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184923. #else
  184924. if (mask & PNG_FREE_PCAL)
  184925. #endif
  184926. {
  184927. png_free(png_ptr, info_ptr->pcal_purpose);
  184928. png_free(png_ptr, info_ptr->pcal_units);
  184929. info_ptr->pcal_purpose = NULL;
  184930. info_ptr->pcal_units = NULL;
  184931. if (info_ptr->pcal_params != NULL)
  184932. {
  184933. int i;
  184934. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184935. {
  184936. png_free(png_ptr, info_ptr->pcal_params[i]);
  184937. info_ptr->pcal_params[i]=NULL;
  184938. }
  184939. png_free(png_ptr, info_ptr->pcal_params);
  184940. info_ptr->pcal_params = NULL;
  184941. }
  184942. info_ptr->valid &= ~PNG_INFO_pCAL;
  184943. }
  184944. #endif
  184945. #if defined(PNG_iCCP_SUPPORTED)
  184946. /* free any iCCP entry */
  184947. #ifdef PNG_FREE_ME_SUPPORTED
  184948. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184949. #else
  184950. if (mask & PNG_FREE_ICCP)
  184951. #endif
  184952. {
  184953. png_free(png_ptr, info_ptr->iccp_name);
  184954. png_free(png_ptr, info_ptr->iccp_profile);
  184955. info_ptr->iccp_name = NULL;
  184956. info_ptr->iccp_profile = NULL;
  184957. info_ptr->valid &= ~PNG_INFO_iCCP;
  184958. }
  184959. #endif
  184960. #if defined(PNG_sPLT_SUPPORTED)
  184961. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184962. #ifdef PNG_FREE_ME_SUPPORTED
  184963. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184964. #else
  184965. if (mask & PNG_FREE_SPLT)
  184966. #endif
  184967. {
  184968. if (num != -1)
  184969. {
  184970. if(info_ptr->splt_palettes)
  184971. {
  184972. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184973. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184974. info_ptr->splt_palettes[num].name = NULL;
  184975. info_ptr->splt_palettes[num].entries = NULL;
  184976. }
  184977. }
  184978. else
  184979. {
  184980. if(info_ptr->splt_palettes_num)
  184981. {
  184982. int i;
  184983. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184984. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184985. png_free(png_ptr, info_ptr->splt_palettes);
  184986. info_ptr->splt_palettes = NULL;
  184987. info_ptr->splt_palettes_num = 0;
  184988. }
  184989. info_ptr->valid &= ~PNG_INFO_sPLT;
  184990. }
  184991. }
  184992. #endif
  184993. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184994. if(png_ptr->unknown_chunk.data)
  184995. {
  184996. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184997. png_ptr->unknown_chunk.data = NULL;
  184998. }
  184999. #ifdef PNG_FREE_ME_SUPPORTED
  185000. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185001. #else
  185002. if (mask & PNG_FREE_UNKN)
  185003. #endif
  185004. {
  185005. if (num != -1)
  185006. {
  185007. if(info_ptr->unknown_chunks)
  185008. {
  185009. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185010. info_ptr->unknown_chunks[num].data = NULL;
  185011. }
  185012. }
  185013. else
  185014. {
  185015. int i;
  185016. if(info_ptr->unknown_chunks_num)
  185017. {
  185018. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185019. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185020. png_free(png_ptr, info_ptr->unknown_chunks);
  185021. info_ptr->unknown_chunks = NULL;
  185022. info_ptr->unknown_chunks_num = 0;
  185023. }
  185024. }
  185025. }
  185026. #endif
  185027. #if defined(PNG_hIST_SUPPORTED)
  185028. /* free any hIST entry */
  185029. #ifdef PNG_FREE_ME_SUPPORTED
  185030. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185031. #else
  185032. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185033. #endif
  185034. {
  185035. png_free(png_ptr, info_ptr->hist);
  185036. info_ptr->hist = NULL;
  185037. info_ptr->valid &= ~PNG_INFO_hIST;
  185038. #ifndef PNG_FREE_ME_SUPPORTED
  185039. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185040. #endif
  185041. }
  185042. #endif
  185043. /* free any PLTE entry that was internally allocated */
  185044. #ifdef PNG_FREE_ME_SUPPORTED
  185045. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185046. #else
  185047. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185048. #endif
  185049. {
  185050. png_zfree(png_ptr, info_ptr->palette);
  185051. info_ptr->palette = NULL;
  185052. info_ptr->valid &= ~PNG_INFO_PLTE;
  185053. #ifndef PNG_FREE_ME_SUPPORTED
  185054. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185055. #endif
  185056. info_ptr->num_palette = 0;
  185057. }
  185058. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185059. /* free any image bits attached to the info structure */
  185060. #ifdef PNG_FREE_ME_SUPPORTED
  185061. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185062. #else
  185063. if (mask & PNG_FREE_ROWS)
  185064. #endif
  185065. {
  185066. if(info_ptr->row_pointers)
  185067. {
  185068. int row;
  185069. for (row = 0; row < (int)info_ptr->height; row++)
  185070. {
  185071. png_free(png_ptr, info_ptr->row_pointers[row]);
  185072. info_ptr->row_pointers[row]=NULL;
  185073. }
  185074. png_free(png_ptr, info_ptr->row_pointers);
  185075. info_ptr->row_pointers=NULL;
  185076. }
  185077. info_ptr->valid &= ~PNG_INFO_IDAT;
  185078. }
  185079. #endif
  185080. #ifdef PNG_FREE_ME_SUPPORTED
  185081. if(num == -1)
  185082. info_ptr->free_me &= ~mask;
  185083. else
  185084. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185085. #endif
  185086. }
  185087. /* This is an internal routine to free any memory that the info struct is
  185088. * pointing to before re-using it or freeing the struct itself. Recall
  185089. * that png_free() checks for NULL pointers for us.
  185090. */
  185091. void /* PRIVATE */
  185092. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185093. {
  185094. png_debug(1, "in png_info_destroy\n");
  185095. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185096. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185097. if (png_ptr->num_chunk_list)
  185098. {
  185099. png_free(png_ptr, png_ptr->chunk_list);
  185100. png_ptr->chunk_list=NULL;
  185101. png_ptr->num_chunk_list=0;
  185102. }
  185103. #endif
  185104. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185105. }
  185106. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185107. /* This function returns a pointer to the io_ptr associated with the user
  185108. * functions. The application should free any memory associated with this
  185109. * pointer before png_write_destroy() or png_read_destroy() are called.
  185110. */
  185111. png_voidp PNGAPI
  185112. png_get_io_ptr(png_structp png_ptr)
  185113. {
  185114. if(png_ptr == NULL) return (NULL);
  185115. return (png_ptr->io_ptr);
  185116. }
  185117. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185118. #if !defined(PNG_NO_STDIO)
  185119. /* Initialize the default input/output functions for the PNG file. If you
  185120. * use your own read or write routines, you can call either png_set_read_fn()
  185121. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185122. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185123. * necessarily available.
  185124. */
  185125. void PNGAPI
  185126. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185127. {
  185128. png_debug(1, "in png_init_io\n");
  185129. if(png_ptr == NULL) return;
  185130. png_ptr->io_ptr = (png_voidp)fp;
  185131. }
  185132. #endif
  185133. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185134. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185135. * a "Creation Time" or other text-based time string.
  185136. */
  185137. png_charp PNGAPI
  185138. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185139. {
  185140. static PNG_CONST char short_months[12][4] =
  185141. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185142. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185143. if(png_ptr == NULL) return (NULL);
  185144. if (png_ptr->time_buffer == NULL)
  185145. {
  185146. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185147. png_sizeof(char)));
  185148. }
  185149. #if defined(_WIN32_WCE)
  185150. {
  185151. wchar_t time_buf[29];
  185152. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185153. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185154. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185155. ptime->second % 61);
  185156. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185157. NULL, NULL);
  185158. }
  185159. #else
  185160. #ifdef USE_FAR_KEYWORD
  185161. {
  185162. char near_time_buf[29];
  185163. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185164. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185165. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185166. ptime->second % 61);
  185167. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185168. 29*png_sizeof(char));
  185169. }
  185170. #else
  185171. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185172. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185173. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185174. ptime->second % 61);
  185175. #endif
  185176. #endif /* _WIN32_WCE */
  185177. return ((png_charp)png_ptr->time_buffer);
  185178. }
  185179. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185180. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185181. png_charp PNGAPI
  185182. png_get_copyright(png_structp png_ptr)
  185183. {
  185184. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185185. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185186. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185187. Copyright (c) 1996-1997 Andreas Dilger\n\
  185188. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185189. }
  185190. /* The following return the library version as a short string in the
  185191. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185192. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185193. * is defined in png.h.
  185194. * Note: now there is no difference between png_get_libpng_ver() and
  185195. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185196. * it is guaranteed that png.c uses the correct version of png.h.
  185197. */
  185198. png_charp PNGAPI
  185199. png_get_libpng_ver(png_structp png_ptr)
  185200. {
  185201. /* Version of *.c files used when building libpng */
  185202. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185203. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185204. }
  185205. png_charp PNGAPI
  185206. png_get_header_ver(png_structp png_ptr)
  185207. {
  185208. /* Version of *.h files used when building libpng */
  185209. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185210. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185211. }
  185212. png_charp PNGAPI
  185213. png_get_header_version(png_structp png_ptr)
  185214. {
  185215. /* Returns longer string containing both version and date */
  185216. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185217. return ((png_charp) PNG_HEADER_VERSION_STRING
  185218. #ifndef PNG_READ_SUPPORTED
  185219. " (NO READ SUPPORT)"
  185220. #endif
  185221. "\n");
  185222. }
  185223. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185224. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185225. int PNGAPI
  185226. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185227. {
  185228. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185229. int i;
  185230. png_bytep p;
  185231. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185232. return 0;
  185233. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185234. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185235. if (!png_memcmp(chunk_name, p, 4))
  185236. return ((int)*(p+4));
  185237. return 0;
  185238. }
  185239. #endif
  185240. /* This function, added to libpng-1.0.6g, is untested. */
  185241. int PNGAPI
  185242. png_reset_zstream(png_structp png_ptr)
  185243. {
  185244. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185245. return (inflateReset(&png_ptr->zstream));
  185246. }
  185247. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185248. /* This function was added to libpng-1.0.7 */
  185249. png_uint_32 PNGAPI
  185250. png_access_version_number(void)
  185251. {
  185252. /* Version of *.c files used when building libpng */
  185253. return((png_uint_32) PNG_LIBPNG_VER);
  185254. }
  185255. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185256. #if !defined(PNG_1_0_X)
  185257. /* this function was added to libpng 1.2.0 */
  185258. int PNGAPI
  185259. png_mmx_support(void)
  185260. {
  185261. /* obsolete, to be removed from libpng-1.4.0 */
  185262. return -1;
  185263. }
  185264. #endif /* PNG_1_0_X */
  185265. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185266. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185267. #ifdef PNG_SIZE_T
  185268. /* Added at libpng version 1.2.6 */
  185269. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185270. png_size_t PNGAPI
  185271. png_convert_size(size_t size)
  185272. {
  185273. if (size > (png_size_t)-1)
  185274. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185275. return ((png_size_t)size);
  185276. }
  185277. #endif /* PNG_SIZE_T */
  185278. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185279. /*** End of inlined file: png.c ***/
  185280. /*** Start of inlined file: pngerror.c ***/
  185281. /* pngerror.c - stub functions for i/o and memory allocation
  185282. *
  185283. * Last changed in libpng 1.2.20 October 4, 2007
  185284. * For conditions of distribution and use, see copyright notice in png.h
  185285. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185286. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185287. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185288. *
  185289. * This file provides a location for all error handling. Users who
  185290. * need special error handling are expected to write replacement functions
  185291. * and use png_set_error_fn() to use those functions. See the instructions
  185292. * at each function.
  185293. */
  185294. #define PNG_INTERNAL
  185295. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185296. static void /* PRIVATE */
  185297. png_default_error PNGARG((png_structp png_ptr,
  185298. png_const_charp error_message));
  185299. #ifndef PNG_NO_WARNINGS
  185300. static void /* PRIVATE */
  185301. png_default_warning PNGARG((png_structp png_ptr,
  185302. png_const_charp warning_message));
  185303. #endif /* PNG_NO_WARNINGS */
  185304. /* This function is called whenever there is a fatal error. This function
  185305. * should not be changed. If there is a need to handle errors differently,
  185306. * you should supply a replacement error function and use png_set_error_fn()
  185307. * to replace the error function at run-time.
  185308. */
  185309. #ifndef PNG_NO_ERROR_TEXT
  185310. void PNGAPI
  185311. png_error(png_structp png_ptr, png_const_charp error_message)
  185312. {
  185313. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185314. char msg[16];
  185315. if (png_ptr != NULL)
  185316. {
  185317. if (png_ptr->flags&
  185318. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185319. {
  185320. if (*error_message == '#')
  185321. {
  185322. int offset;
  185323. for (offset=1; offset<15; offset++)
  185324. if (*(error_message+offset) == ' ')
  185325. break;
  185326. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185327. {
  185328. int i;
  185329. for (i=0; i<offset-1; i++)
  185330. msg[i]=error_message[i+1];
  185331. msg[i]='\0';
  185332. error_message=msg;
  185333. }
  185334. else
  185335. error_message+=offset;
  185336. }
  185337. else
  185338. {
  185339. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185340. {
  185341. msg[0]='0';
  185342. msg[1]='\0';
  185343. error_message=msg;
  185344. }
  185345. }
  185346. }
  185347. }
  185348. #endif
  185349. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185350. (*(png_ptr->error_fn))(png_ptr, error_message);
  185351. /* If the custom handler doesn't exist, or if it returns,
  185352. use the default handler, which will not return. */
  185353. png_default_error(png_ptr, error_message);
  185354. }
  185355. #else
  185356. void PNGAPI
  185357. png_err(png_structp png_ptr)
  185358. {
  185359. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185360. (*(png_ptr->error_fn))(png_ptr, '\0');
  185361. /* If the custom handler doesn't exist, or if it returns,
  185362. use the default handler, which will not return. */
  185363. png_default_error(png_ptr, '\0');
  185364. }
  185365. #endif /* PNG_NO_ERROR_TEXT */
  185366. #ifndef PNG_NO_WARNINGS
  185367. /* This function is called whenever there is a non-fatal error. This function
  185368. * should not be changed. If there is a need to handle warnings differently,
  185369. * you should supply a replacement warning function and use
  185370. * png_set_error_fn() to replace the warning function at run-time.
  185371. */
  185372. void PNGAPI
  185373. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185374. {
  185375. int offset = 0;
  185376. if (png_ptr != NULL)
  185377. {
  185378. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185379. if (png_ptr->flags&
  185380. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185381. #endif
  185382. {
  185383. if (*warning_message == '#')
  185384. {
  185385. for (offset=1; offset<15; offset++)
  185386. if (*(warning_message+offset) == ' ')
  185387. break;
  185388. }
  185389. }
  185390. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185391. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185392. }
  185393. else
  185394. png_default_warning(png_ptr, warning_message+offset);
  185395. }
  185396. #endif /* PNG_NO_WARNINGS */
  185397. /* These utilities are used internally to build an error message that relates
  185398. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185399. * this is used to prefix the message. The message is limited in length
  185400. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185401. * if the character is invalid.
  185402. */
  185403. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185404. /*static PNG_CONST char png_digit[16] = {
  185405. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185406. 'A', 'B', 'C', 'D', 'E', 'F'
  185407. };*/
  185408. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185409. static void /* PRIVATE */
  185410. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185411. error_message)
  185412. {
  185413. int iout = 0, iin = 0;
  185414. while (iin < 4)
  185415. {
  185416. int c = png_ptr->chunk_name[iin++];
  185417. if (isnonalpha(c))
  185418. {
  185419. buffer[iout++] = '[';
  185420. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185421. buffer[iout++] = png_digit[c & 0x0f];
  185422. buffer[iout++] = ']';
  185423. }
  185424. else
  185425. {
  185426. buffer[iout++] = (png_byte)c;
  185427. }
  185428. }
  185429. if (error_message == NULL)
  185430. buffer[iout] = 0;
  185431. else
  185432. {
  185433. buffer[iout++] = ':';
  185434. buffer[iout++] = ' ';
  185435. png_strncpy(buffer+iout, error_message, 63);
  185436. buffer[iout+63] = 0;
  185437. }
  185438. }
  185439. #ifdef PNG_READ_SUPPORTED
  185440. void PNGAPI
  185441. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185442. {
  185443. char msg[18+64];
  185444. if (png_ptr == NULL)
  185445. png_error(png_ptr, error_message);
  185446. else
  185447. {
  185448. png_format_buffer(png_ptr, msg, error_message);
  185449. png_error(png_ptr, msg);
  185450. }
  185451. }
  185452. #endif /* PNG_READ_SUPPORTED */
  185453. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185454. #ifndef PNG_NO_WARNINGS
  185455. void PNGAPI
  185456. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185457. {
  185458. char msg[18+64];
  185459. if (png_ptr == NULL)
  185460. png_warning(png_ptr, warning_message);
  185461. else
  185462. {
  185463. png_format_buffer(png_ptr, msg, warning_message);
  185464. png_warning(png_ptr, msg);
  185465. }
  185466. }
  185467. #endif /* PNG_NO_WARNINGS */
  185468. /* This is the default error handling function. Note that replacements for
  185469. * this function MUST NOT RETURN, or the program will likely crash. This
  185470. * function is used by default, or if the program supplies NULL for the
  185471. * error function pointer in png_set_error_fn().
  185472. */
  185473. static void /* PRIVATE */
  185474. png_default_error(png_structp, png_const_charp error_message)
  185475. {
  185476. #ifndef PNG_NO_CONSOLE_IO
  185477. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185478. if (*error_message == '#')
  185479. {
  185480. int offset;
  185481. char error_number[16];
  185482. for (offset=0; offset<15; offset++)
  185483. {
  185484. error_number[offset] = *(error_message+offset+1);
  185485. if (*(error_message+offset) == ' ')
  185486. break;
  185487. }
  185488. if((offset > 1) && (offset < 15))
  185489. {
  185490. error_number[offset-1]='\0';
  185491. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185492. error_message+offset);
  185493. }
  185494. else
  185495. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185496. }
  185497. else
  185498. #endif
  185499. fprintf(stderr, "libpng error: %s\n", error_message);
  185500. #endif
  185501. #ifdef PNG_SETJMP_SUPPORTED
  185502. if (png_ptr)
  185503. {
  185504. # ifdef USE_FAR_KEYWORD
  185505. {
  185506. jmp_buf jmpbuf;
  185507. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185508. longjmp(jmpbuf, 1);
  185509. }
  185510. # else
  185511. longjmp(png_ptr->jmpbuf, 1);
  185512. # endif
  185513. }
  185514. #else
  185515. PNG_ABORT();
  185516. #endif
  185517. #ifdef PNG_NO_CONSOLE_IO
  185518. error_message = error_message; /* make compiler happy */
  185519. #endif
  185520. }
  185521. #ifndef PNG_NO_WARNINGS
  185522. /* This function is called when there is a warning, but the library thinks
  185523. * it can continue anyway. Replacement functions don't have to do anything
  185524. * here if you don't want them to. In the default configuration, png_ptr is
  185525. * not used, but it is passed in case it may be useful.
  185526. */
  185527. static void /* PRIVATE */
  185528. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185529. {
  185530. #ifndef PNG_NO_CONSOLE_IO
  185531. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185532. if (*warning_message == '#')
  185533. {
  185534. int offset;
  185535. char warning_number[16];
  185536. for (offset=0; offset<15; offset++)
  185537. {
  185538. warning_number[offset]=*(warning_message+offset+1);
  185539. if (*(warning_message+offset) == ' ')
  185540. break;
  185541. }
  185542. if((offset > 1) && (offset < 15))
  185543. {
  185544. warning_number[offset-1]='\0';
  185545. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185546. warning_message+offset);
  185547. }
  185548. else
  185549. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185550. }
  185551. else
  185552. # endif
  185553. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185554. #else
  185555. warning_message = warning_message; /* make compiler happy */
  185556. #endif
  185557. png_ptr = png_ptr; /* make compiler happy */
  185558. }
  185559. #endif /* PNG_NO_WARNINGS */
  185560. /* This function is called when the application wants to use another method
  185561. * of handling errors and warnings. Note that the error function MUST NOT
  185562. * return to the calling routine or serious problems will occur. The return
  185563. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185564. */
  185565. void PNGAPI
  185566. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185567. png_error_ptr error_fn, png_error_ptr warning_fn)
  185568. {
  185569. if (png_ptr == NULL)
  185570. return;
  185571. png_ptr->error_ptr = error_ptr;
  185572. png_ptr->error_fn = error_fn;
  185573. png_ptr->warning_fn = warning_fn;
  185574. }
  185575. /* This function returns a pointer to the error_ptr associated with the user
  185576. * functions. The application should free any memory associated with this
  185577. * pointer before png_write_destroy and png_read_destroy are called.
  185578. */
  185579. png_voidp PNGAPI
  185580. png_get_error_ptr(png_structp png_ptr)
  185581. {
  185582. if (png_ptr == NULL)
  185583. return NULL;
  185584. return ((png_voidp)png_ptr->error_ptr);
  185585. }
  185586. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185587. void PNGAPI
  185588. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185589. {
  185590. if(png_ptr != NULL)
  185591. {
  185592. png_ptr->flags &=
  185593. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185594. }
  185595. }
  185596. #endif
  185597. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185598. /*** End of inlined file: pngerror.c ***/
  185599. /*** Start of inlined file: pngget.c ***/
  185600. /* pngget.c - retrieval of values from info struct
  185601. *
  185602. * Last changed in libpng 1.2.15 January 5, 2007
  185603. * For conditions of distribution and use, see copyright notice in png.h
  185604. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185605. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185606. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185607. */
  185608. #define PNG_INTERNAL
  185609. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185610. png_uint_32 PNGAPI
  185611. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185612. {
  185613. if (png_ptr != NULL && info_ptr != NULL)
  185614. return(info_ptr->valid & flag);
  185615. else
  185616. return(0);
  185617. }
  185618. png_uint_32 PNGAPI
  185619. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185620. {
  185621. if (png_ptr != NULL && info_ptr != NULL)
  185622. return(info_ptr->rowbytes);
  185623. else
  185624. return(0);
  185625. }
  185626. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185627. png_bytepp PNGAPI
  185628. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185629. {
  185630. if (png_ptr != NULL && info_ptr != NULL)
  185631. return(info_ptr->row_pointers);
  185632. else
  185633. return(0);
  185634. }
  185635. #endif
  185636. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185637. /* easy access to info, added in libpng-0.99 */
  185638. png_uint_32 PNGAPI
  185639. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185640. {
  185641. if (png_ptr != NULL && info_ptr != NULL)
  185642. {
  185643. return info_ptr->width;
  185644. }
  185645. return (0);
  185646. }
  185647. png_uint_32 PNGAPI
  185648. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185649. {
  185650. if (png_ptr != NULL && info_ptr != NULL)
  185651. {
  185652. return info_ptr->height;
  185653. }
  185654. return (0);
  185655. }
  185656. png_byte PNGAPI
  185657. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185658. {
  185659. if (png_ptr != NULL && info_ptr != NULL)
  185660. {
  185661. return info_ptr->bit_depth;
  185662. }
  185663. return (0);
  185664. }
  185665. png_byte PNGAPI
  185666. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185667. {
  185668. if (png_ptr != NULL && info_ptr != NULL)
  185669. {
  185670. return info_ptr->color_type;
  185671. }
  185672. return (0);
  185673. }
  185674. png_byte PNGAPI
  185675. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185676. {
  185677. if (png_ptr != NULL && info_ptr != NULL)
  185678. {
  185679. return info_ptr->filter_type;
  185680. }
  185681. return (0);
  185682. }
  185683. png_byte PNGAPI
  185684. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185685. {
  185686. if (png_ptr != NULL && info_ptr != NULL)
  185687. {
  185688. return info_ptr->interlace_type;
  185689. }
  185690. return (0);
  185691. }
  185692. png_byte PNGAPI
  185693. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185694. {
  185695. if (png_ptr != NULL && info_ptr != NULL)
  185696. {
  185697. return info_ptr->compression_type;
  185698. }
  185699. return (0);
  185700. }
  185701. png_uint_32 PNGAPI
  185702. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185703. {
  185704. if (png_ptr != NULL && info_ptr != NULL)
  185705. #if defined(PNG_pHYs_SUPPORTED)
  185706. if (info_ptr->valid & PNG_INFO_pHYs)
  185707. {
  185708. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185709. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185710. return (0);
  185711. else return (info_ptr->x_pixels_per_unit);
  185712. }
  185713. #else
  185714. return (0);
  185715. #endif
  185716. return (0);
  185717. }
  185718. png_uint_32 PNGAPI
  185719. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185720. {
  185721. if (png_ptr != NULL && info_ptr != NULL)
  185722. #if defined(PNG_pHYs_SUPPORTED)
  185723. if (info_ptr->valid & PNG_INFO_pHYs)
  185724. {
  185725. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185726. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185727. return (0);
  185728. else return (info_ptr->y_pixels_per_unit);
  185729. }
  185730. #else
  185731. return (0);
  185732. #endif
  185733. return (0);
  185734. }
  185735. png_uint_32 PNGAPI
  185736. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185737. {
  185738. if (png_ptr != NULL && info_ptr != NULL)
  185739. #if defined(PNG_pHYs_SUPPORTED)
  185740. if (info_ptr->valid & PNG_INFO_pHYs)
  185741. {
  185742. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185743. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185744. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185745. return (0);
  185746. else return (info_ptr->x_pixels_per_unit);
  185747. }
  185748. #else
  185749. return (0);
  185750. #endif
  185751. return (0);
  185752. }
  185753. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185754. float PNGAPI
  185755. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185756. {
  185757. if (png_ptr != NULL && info_ptr != NULL)
  185758. #if defined(PNG_pHYs_SUPPORTED)
  185759. if (info_ptr->valid & PNG_INFO_pHYs)
  185760. {
  185761. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185762. if (info_ptr->x_pixels_per_unit == 0)
  185763. return ((float)0.0);
  185764. else
  185765. return ((float)((float)info_ptr->y_pixels_per_unit
  185766. /(float)info_ptr->x_pixels_per_unit));
  185767. }
  185768. #else
  185769. return (0.0);
  185770. #endif
  185771. return ((float)0.0);
  185772. }
  185773. #endif
  185774. png_int_32 PNGAPI
  185775. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185776. {
  185777. if (png_ptr != NULL && info_ptr != NULL)
  185778. #if defined(PNG_oFFs_SUPPORTED)
  185779. if (info_ptr->valid & PNG_INFO_oFFs)
  185780. {
  185781. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185782. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185783. return (0);
  185784. else return (info_ptr->x_offset);
  185785. }
  185786. #else
  185787. return (0);
  185788. #endif
  185789. return (0);
  185790. }
  185791. png_int_32 PNGAPI
  185792. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185793. {
  185794. if (png_ptr != NULL && info_ptr != NULL)
  185795. #if defined(PNG_oFFs_SUPPORTED)
  185796. if (info_ptr->valid & PNG_INFO_oFFs)
  185797. {
  185798. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185799. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185800. return (0);
  185801. else return (info_ptr->y_offset);
  185802. }
  185803. #else
  185804. return (0);
  185805. #endif
  185806. return (0);
  185807. }
  185808. png_int_32 PNGAPI
  185809. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185810. {
  185811. if (png_ptr != NULL && info_ptr != NULL)
  185812. #if defined(PNG_oFFs_SUPPORTED)
  185813. if (info_ptr->valid & PNG_INFO_oFFs)
  185814. {
  185815. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185816. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185817. return (0);
  185818. else return (info_ptr->x_offset);
  185819. }
  185820. #else
  185821. return (0);
  185822. #endif
  185823. return (0);
  185824. }
  185825. png_int_32 PNGAPI
  185826. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185827. {
  185828. if (png_ptr != NULL && info_ptr != NULL)
  185829. #if defined(PNG_oFFs_SUPPORTED)
  185830. if (info_ptr->valid & PNG_INFO_oFFs)
  185831. {
  185832. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185833. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185834. return (0);
  185835. else return (info_ptr->y_offset);
  185836. }
  185837. #else
  185838. return (0);
  185839. #endif
  185840. return (0);
  185841. }
  185842. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185843. png_uint_32 PNGAPI
  185844. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185845. {
  185846. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185847. *.0254 +.5));
  185848. }
  185849. png_uint_32 PNGAPI
  185850. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185851. {
  185852. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185853. *.0254 +.5));
  185854. }
  185855. png_uint_32 PNGAPI
  185856. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185857. {
  185858. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185859. *.0254 +.5));
  185860. }
  185861. float PNGAPI
  185862. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185863. {
  185864. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185865. *.00003937);
  185866. }
  185867. float PNGAPI
  185868. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185869. {
  185870. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185871. *.00003937);
  185872. }
  185873. #if defined(PNG_pHYs_SUPPORTED)
  185874. png_uint_32 PNGAPI
  185875. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185876. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185877. {
  185878. png_uint_32 retval = 0;
  185879. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185880. {
  185881. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185882. if (res_x != NULL)
  185883. {
  185884. *res_x = info_ptr->x_pixels_per_unit;
  185885. retval |= PNG_INFO_pHYs;
  185886. }
  185887. if (res_y != NULL)
  185888. {
  185889. *res_y = info_ptr->y_pixels_per_unit;
  185890. retval |= PNG_INFO_pHYs;
  185891. }
  185892. if (unit_type != NULL)
  185893. {
  185894. *unit_type = (int)info_ptr->phys_unit_type;
  185895. retval |= PNG_INFO_pHYs;
  185896. if(*unit_type == 1)
  185897. {
  185898. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185899. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185900. }
  185901. }
  185902. }
  185903. return (retval);
  185904. }
  185905. #endif /* PNG_pHYs_SUPPORTED */
  185906. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185907. /* png_get_channels really belongs in here, too, but it's been around longer */
  185908. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185909. png_byte PNGAPI
  185910. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185911. {
  185912. if (png_ptr != NULL && info_ptr != NULL)
  185913. return(info_ptr->channels);
  185914. else
  185915. return (0);
  185916. }
  185917. png_bytep PNGAPI
  185918. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185919. {
  185920. if (png_ptr != NULL && info_ptr != NULL)
  185921. return(info_ptr->signature);
  185922. else
  185923. return (NULL);
  185924. }
  185925. #if defined(PNG_bKGD_SUPPORTED)
  185926. png_uint_32 PNGAPI
  185927. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185928. png_color_16p *background)
  185929. {
  185930. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185931. && background != NULL)
  185932. {
  185933. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185934. *background = &(info_ptr->background);
  185935. return (PNG_INFO_bKGD);
  185936. }
  185937. return (0);
  185938. }
  185939. #endif
  185940. #if defined(PNG_cHRM_SUPPORTED)
  185941. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185942. png_uint_32 PNGAPI
  185943. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185944. double *white_x, double *white_y, double *red_x, double *red_y,
  185945. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185946. {
  185947. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185948. {
  185949. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185950. if (white_x != NULL)
  185951. *white_x = (double)info_ptr->x_white;
  185952. if (white_y != NULL)
  185953. *white_y = (double)info_ptr->y_white;
  185954. if (red_x != NULL)
  185955. *red_x = (double)info_ptr->x_red;
  185956. if (red_y != NULL)
  185957. *red_y = (double)info_ptr->y_red;
  185958. if (green_x != NULL)
  185959. *green_x = (double)info_ptr->x_green;
  185960. if (green_y != NULL)
  185961. *green_y = (double)info_ptr->y_green;
  185962. if (blue_x != NULL)
  185963. *blue_x = (double)info_ptr->x_blue;
  185964. if (blue_y != NULL)
  185965. *blue_y = (double)info_ptr->y_blue;
  185966. return (PNG_INFO_cHRM);
  185967. }
  185968. return (0);
  185969. }
  185970. #endif
  185971. #ifdef PNG_FIXED_POINT_SUPPORTED
  185972. png_uint_32 PNGAPI
  185973. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185974. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185975. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185976. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185977. {
  185978. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185979. {
  185980. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185981. if (white_x != NULL)
  185982. *white_x = info_ptr->int_x_white;
  185983. if (white_y != NULL)
  185984. *white_y = info_ptr->int_y_white;
  185985. if (red_x != NULL)
  185986. *red_x = info_ptr->int_x_red;
  185987. if (red_y != NULL)
  185988. *red_y = info_ptr->int_y_red;
  185989. if (green_x != NULL)
  185990. *green_x = info_ptr->int_x_green;
  185991. if (green_y != NULL)
  185992. *green_y = info_ptr->int_y_green;
  185993. if (blue_x != NULL)
  185994. *blue_x = info_ptr->int_x_blue;
  185995. if (blue_y != NULL)
  185996. *blue_y = info_ptr->int_y_blue;
  185997. return (PNG_INFO_cHRM);
  185998. }
  185999. return (0);
  186000. }
  186001. #endif
  186002. #endif
  186003. #if defined(PNG_gAMA_SUPPORTED)
  186004. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186005. png_uint_32 PNGAPI
  186006. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186007. {
  186008. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186009. && file_gamma != NULL)
  186010. {
  186011. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186012. *file_gamma = (double)info_ptr->gamma;
  186013. return (PNG_INFO_gAMA);
  186014. }
  186015. return (0);
  186016. }
  186017. #endif
  186018. #ifdef PNG_FIXED_POINT_SUPPORTED
  186019. png_uint_32 PNGAPI
  186020. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186021. png_fixed_point *int_file_gamma)
  186022. {
  186023. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186024. && int_file_gamma != NULL)
  186025. {
  186026. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186027. *int_file_gamma = info_ptr->int_gamma;
  186028. return (PNG_INFO_gAMA);
  186029. }
  186030. return (0);
  186031. }
  186032. #endif
  186033. #endif
  186034. #if defined(PNG_sRGB_SUPPORTED)
  186035. png_uint_32 PNGAPI
  186036. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186037. {
  186038. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186039. && file_srgb_intent != NULL)
  186040. {
  186041. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186042. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186043. return (PNG_INFO_sRGB);
  186044. }
  186045. return (0);
  186046. }
  186047. #endif
  186048. #if defined(PNG_iCCP_SUPPORTED)
  186049. png_uint_32 PNGAPI
  186050. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186051. png_charpp name, int *compression_type,
  186052. png_charpp profile, png_uint_32 *proflen)
  186053. {
  186054. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186055. && name != NULL && profile != NULL && proflen != NULL)
  186056. {
  186057. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186058. *name = info_ptr->iccp_name;
  186059. *profile = info_ptr->iccp_profile;
  186060. /* compression_type is a dummy so the API won't have to change
  186061. if we introduce multiple compression types later. */
  186062. *proflen = (int)info_ptr->iccp_proflen;
  186063. *compression_type = (int)info_ptr->iccp_compression;
  186064. return (PNG_INFO_iCCP);
  186065. }
  186066. return (0);
  186067. }
  186068. #endif
  186069. #if defined(PNG_sPLT_SUPPORTED)
  186070. png_uint_32 PNGAPI
  186071. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186072. png_sPLT_tpp spalettes)
  186073. {
  186074. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186075. {
  186076. *spalettes = info_ptr->splt_palettes;
  186077. return ((png_uint_32)info_ptr->splt_palettes_num);
  186078. }
  186079. return (0);
  186080. }
  186081. #endif
  186082. #if defined(PNG_hIST_SUPPORTED)
  186083. png_uint_32 PNGAPI
  186084. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186085. {
  186086. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186087. && hist != NULL)
  186088. {
  186089. png_debug1(1, "in %s retrieval function\n", "hIST");
  186090. *hist = info_ptr->hist;
  186091. return (PNG_INFO_hIST);
  186092. }
  186093. return (0);
  186094. }
  186095. #endif
  186096. png_uint_32 PNGAPI
  186097. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186098. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186099. int *color_type, int *interlace_type, int *compression_type,
  186100. int *filter_type)
  186101. {
  186102. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186103. bit_depth != NULL && color_type != NULL)
  186104. {
  186105. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186106. *width = info_ptr->width;
  186107. *height = info_ptr->height;
  186108. *bit_depth = info_ptr->bit_depth;
  186109. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186110. png_error(png_ptr, "Invalid bit depth");
  186111. *color_type = info_ptr->color_type;
  186112. if (info_ptr->color_type > 6)
  186113. png_error(png_ptr, "Invalid color type");
  186114. if (compression_type != NULL)
  186115. *compression_type = info_ptr->compression_type;
  186116. if (filter_type != NULL)
  186117. *filter_type = info_ptr->filter_type;
  186118. if (interlace_type != NULL)
  186119. *interlace_type = info_ptr->interlace_type;
  186120. /* check for potential overflow of rowbytes */
  186121. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186122. png_error(png_ptr, "Invalid image width");
  186123. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186124. png_error(png_ptr, "Invalid image height");
  186125. if (info_ptr->width > (PNG_UINT_32_MAX
  186126. >> 3) /* 8-byte RGBA pixels */
  186127. - 64 /* bigrowbuf hack */
  186128. - 1 /* filter byte */
  186129. - 7*8 /* rounding of width to multiple of 8 pixels */
  186130. - 8) /* extra max_pixel_depth pad */
  186131. {
  186132. png_warning(png_ptr,
  186133. "Width too large for libpng to process image data.");
  186134. }
  186135. return (1);
  186136. }
  186137. return (0);
  186138. }
  186139. #if defined(PNG_oFFs_SUPPORTED)
  186140. png_uint_32 PNGAPI
  186141. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186142. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186143. {
  186144. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186145. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186146. {
  186147. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186148. *offset_x = info_ptr->x_offset;
  186149. *offset_y = info_ptr->y_offset;
  186150. *unit_type = (int)info_ptr->offset_unit_type;
  186151. return (PNG_INFO_oFFs);
  186152. }
  186153. return (0);
  186154. }
  186155. #endif
  186156. #if defined(PNG_pCAL_SUPPORTED)
  186157. png_uint_32 PNGAPI
  186158. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186159. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186160. png_charp *units, png_charpp *params)
  186161. {
  186162. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186163. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186164. nparams != NULL && units != NULL && params != NULL)
  186165. {
  186166. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186167. *purpose = info_ptr->pcal_purpose;
  186168. *X0 = info_ptr->pcal_X0;
  186169. *X1 = info_ptr->pcal_X1;
  186170. *type = (int)info_ptr->pcal_type;
  186171. *nparams = (int)info_ptr->pcal_nparams;
  186172. *units = info_ptr->pcal_units;
  186173. *params = info_ptr->pcal_params;
  186174. return (PNG_INFO_pCAL);
  186175. }
  186176. return (0);
  186177. }
  186178. #endif
  186179. #if defined(PNG_sCAL_SUPPORTED)
  186180. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186181. png_uint_32 PNGAPI
  186182. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186183. int *unit, double *width, double *height)
  186184. {
  186185. if (png_ptr != NULL && info_ptr != NULL &&
  186186. (info_ptr->valid & PNG_INFO_sCAL))
  186187. {
  186188. *unit = info_ptr->scal_unit;
  186189. *width = info_ptr->scal_pixel_width;
  186190. *height = info_ptr->scal_pixel_height;
  186191. return (PNG_INFO_sCAL);
  186192. }
  186193. return(0);
  186194. }
  186195. #else
  186196. #ifdef PNG_FIXED_POINT_SUPPORTED
  186197. png_uint_32 PNGAPI
  186198. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186199. int *unit, png_charpp width, png_charpp height)
  186200. {
  186201. if (png_ptr != NULL && info_ptr != NULL &&
  186202. (info_ptr->valid & PNG_INFO_sCAL))
  186203. {
  186204. *unit = info_ptr->scal_unit;
  186205. *width = info_ptr->scal_s_width;
  186206. *height = info_ptr->scal_s_height;
  186207. return (PNG_INFO_sCAL);
  186208. }
  186209. return(0);
  186210. }
  186211. #endif
  186212. #endif
  186213. #endif
  186214. #if defined(PNG_pHYs_SUPPORTED)
  186215. png_uint_32 PNGAPI
  186216. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186217. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186218. {
  186219. png_uint_32 retval = 0;
  186220. if (png_ptr != NULL && info_ptr != NULL &&
  186221. (info_ptr->valid & PNG_INFO_pHYs))
  186222. {
  186223. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186224. if (res_x != NULL)
  186225. {
  186226. *res_x = info_ptr->x_pixels_per_unit;
  186227. retval |= PNG_INFO_pHYs;
  186228. }
  186229. if (res_y != NULL)
  186230. {
  186231. *res_y = info_ptr->y_pixels_per_unit;
  186232. retval |= PNG_INFO_pHYs;
  186233. }
  186234. if (unit_type != NULL)
  186235. {
  186236. *unit_type = (int)info_ptr->phys_unit_type;
  186237. retval |= PNG_INFO_pHYs;
  186238. }
  186239. }
  186240. return (retval);
  186241. }
  186242. #endif
  186243. png_uint_32 PNGAPI
  186244. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186245. int *num_palette)
  186246. {
  186247. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186248. && palette != NULL)
  186249. {
  186250. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186251. *palette = info_ptr->palette;
  186252. *num_palette = info_ptr->num_palette;
  186253. png_debug1(3, "num_palette = %d\n", *num_palette);
  186254. return (PNG_INFO_PLTE);
  186255. }
  186256. return (0);
  186257. }
  186258. #if defined(PNG_sBIT_SUPPORTED)
  186259. png_uint_32 PNGAPI
  186260. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186261. {
  186262. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186263. && sig_bit != NULL)
  186264. {
  186265. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186266. *sig_bit = &(info_ptr->sig_bit);
  186267. return (PNG_INFO_sBIT);
  186268. }
  186269. return (0);
  186270. }
  186271. #endif
  186272. #if defined(PNG_TEXT_SUPPORTED)
  186273. png_uint_32 PNGAPI
  186274. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186275. int *num_text)
  186276. {
  186277. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186278. {
  186279. png_debug1(1, "in %s retrieval function\n",
  186280. (png_ptr->chunk_name[0] == '\0' ? "text"
  186281. : (png_const_charp)png_ptr->chunk_name));
  186282. if (text_ptr != NULL)
  186283. *text_ptr = info_ptr->text;
  186284. if (num_text != NULL)
  186285. *num_text = info_ptr->num_text;
  186286. return ((png_uint_32)info_ptr->num_text);
  186287. }
  186288. if (num_text != NULL)
  186289. *num_text = 0;
  186290. return(0);
  186291. }
  186292. #endif
  186293. #if defined(PNG_tIME_SUPPORTED)
  186294. png_uint_32 PNGAPI
  186295. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186296. {
  186297. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186298. && mod_time != NULL)
  186299. {
  186300. png_debug1(1, "in %s retrieval function\n", "tIME");
  186301. *mod_time = &(info_ptr->mod_time);
  186302. return (PNG_INFO_tIME);
  186303. }
  186304. return (0);
  186305. }
  186306. #endif
  186307. #if defined(PNG_tRNS_SUPPORTED)
  186308. png_uint_32 PNGAPI
  186309. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186310. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186311. {
  186312. png_uint_32 retval = 0;
  186313. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186314. {
  186315. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186316. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186317. {
  186318. if (trans != NULL)
  186319. {
  186320. *trans = info_ptr->trans;
  186321. retval |= PNG_INFO_tRNS;
  186322. }
  186323. if (trans_values != NULL)
  186324. *trans_values = &(info_ptr->trans_values);
  186325. }
  186326. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186327. {
  186328. if (trans_values != NULL)
  186329. {
  186330. *trans_values = &(info_ptr->trans_values);
  186331. retval |= PNG_INFO_tRNS;
  186332. }
  186333. if(trans != NULL)
  186334. *trans = NULL;
  186335. }
  186336. if(num_trans != NULL)
  186337. {
  186338. *num_trans = info_ptr->num_trans;
  186339. retval |= PNG_INFO_tRNS;
  186340. }
  186341. }
  186342. return (retval);
  186343. }
  186344. #endif
  186345. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186346. png_uint_32 PNGAPI
  186347. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186348. png_unknown_chunkpp unknowns)
  186349. {
  186350. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186351. {
  186352. *unknowns = info_ptr->unknown_chunks;
  186353. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186354. }
  186355. return (0);
  186356. }
  186357. #endif
  186358. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186359. png_byte PNGAPI
  186360. png_get_rgb_to_gray_status (png_structp png_ptr)
  186361. {
  186362. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186363. }
  186364. #endif
  186365. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186366. png_voidp PNGAPI
  186367. png_get_user_chunk_ptr(png_structp png_ptr)
  186368. {
  186369. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186370. }
  186371. #endif
  186372. #ifdef PNG_WRITE_SUPPORTED
  186373. png_uint_32 PNGAPI
  186374. png_get_compression_buffer_size(png_structp png_ptr)
  186375. {
  186376. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186377. }
  186378. #endif
  186379. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186380. #ifndef PNG_1_0_X
  186381. /* this function was added to libpng 1.2.0 and should exist by default */
  186382. png_uint_32 PNGAPI
  186383. png_get_asm_flags (png_structp png_ptr)
  186384. {
  186385. /* obsolete, to be removed from libpng-1.4.0 */
  186386. return (png_ptr? 0L: 0L);
  186387. }
  186388. /* this function was added to libpng 1.2.0 and should exist by default */
  186389. png_uint_32 PNGAPI
  186390. png_get_asm_flagmask (int flag_select)
  186391. {
  186392. /* obsolete, to be removed from libpng-1.4.0 */
  186393. flag_select=flag_select;
  186394. return 0L;
  186395. }
  186396. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186397. /* this function was added to libpng 1.2.0 */
  186398. png_uint_32 PNGAPI
  186399. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186400. {
  186401. /* obsolete, to be removed from libpng-1.4.0 */
  186402. flag_select=flag_select;
  186403. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186404. return 0L;
  186405. }
  186406. /* this function was added to libpng 1.2.0 */
  186407. png_byte PNGAPI
  186408. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186409. {
  186410. /* obsolete, to be removed from libpng-1.4.0 */
  186411. return (png_ptr? 0: 0);
  186412. }
  186413. /* this function was added to libpng 1.2.0 */
  186414. png_uint_32 PNGAPI
  186415. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186416. {
  186417. /* obsolete, to be removed from libpng-1.4.0 */
  186418. return (png_ptr? 0L: 0L);
  186419. }
  186420. #endif /* ?PNG_1_0_X */
  186421. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186422. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186423. /* these functions were added to libpng 1.2.6 */
  186424. png_uint_32 PNGAPI
  186425. png_get_user_width_max (png_structp png_ptr)
  186426. {
  186427. return (png_ptr? png_ptr->user_width_max : 0);
  186428. }
  186429. png_uint_32 PNGAPI
  186430. png_get_user_height_max (png_structp png_ptr)
  186431. {
  186432. return (png_ptr? png_ptr->user_height_max : 0);
  186433. }
  186434. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186435. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186436. /*** End of inlined file: pngget.c ***/
  186437. /*** Start of inlined file: pngmem.c ***/
  186438. /* pngmem.c - stub functions for memory allocation
  186439. *
  186440. * Last changed in libpng 1.2.13 November 13, 2006
  186441. * For conditions of distribution and use, see copyright notice in png.h
  186442. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186443. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186444. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186445. *
  186446. * This file provides a location for all memory allocation. Users who
  186447. * need special memory handling are expected to supply replacement
  186448. * functions for png_malloc() and png_free(), and to use
  186449. * png_create_read_struct_2() and png_create_write_struct_2() to
  186450. * identify the replacement functions.
  186451. */
  186452. #define PNG_INTERNAL
  186453. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186454. /* Borland DOS special memory handler */
  186455. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186456. /* if you change this, be sure to change the one in png.h also */
  186457. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186458. by a single call to calloc() if this is thought to improve performance. */
  186459. png_voidp /* PRIVATE */
  186460. png_create_struct(int type)
  186461. {
  186462. #ifdef PNG_USER_MEM_SUPPORTED
  186463. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186464. }
  186465. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186466. png_voidp /* PRIVATE */
  186467. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186468. {
  186469. #endif /* PNG_USER_MEM_SUPPORTED */
  186470. png_size_t size;
  186471. png_voidp struct_ptr;
  186472. if (type == PNG_STRUCT_INFO)
  186473. size = png_sizeof(png_info);
  186474. else if (type == PNG_STRUCT_PNG)
  186475. size = png_sizeof(png_struct);
  186476. else
  186477. return (png_get_copyright(NULL));
  186478. #ifdef PNG_USER_MEM_SUPPORTED
  186479. if(malloc_fn != NULL)
  186480. {
  186481. png_struct dummy_struct;
  186482. png_structp png_ptr = &dummy_struct;
  186483. png_ptr->mem_ptr=mem_ptr;
  186484. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186485. }
  186486. else
  186487. #endif /* PNG_USER_MEM_SUPPORTED */
  186488. struct_ptr = (png_voidp)farmalloc(size);
  186489. if (struct_ptr != NULL)
  186490. png_memset(struct_ptr, 0, size);
  186491. return (struct_ptr);
  186492. }
  186493. /* Free memory allocated by a png_create_struct() call */
  186494. void /* PRIVATE */
  186495. png_destroy_struct(png_voidp struct_ptr)
  186496. {
  186497. #ifdef PNG_USER_MEM_SUPPORTED
  186498. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186499. }
  186500. /* Free memory allocated by a png_create_struct() call */
  186501. void /* PRIVATE */
  186502. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186503. png_voidp mem_ptr)
  186504. {
  186505. #endif
  186506. if (struct_ptr != NULL)
  186507. {
  186508. #ifdef PNG_USER_MEM_SUPPORTED
  186509. if(free_fn != NULL)
  186510. {
  186511. png_struct dummy_struct;
  186512. png_structp png_ptr = &dummy_struct;
  186513. png_ptr->mem_ptr=mem_ptr;
  186514. (*(free_fn))(png_ptr, struct_ptr);
  186515. return;
  186516. }
  186517. #endif /* PNG_USER_MEM_SUPPORTED */
  186518. farfree (struct_ptr);
  186519. }
  186520. }
  186521. /* Allocate memory. For reasonable files, size should never exceed
  186522. * 64K. However, zlib may allocate more then 64K if you don't tell
  186523. * it not to. See zconf.h and png.h for more information. zlib does
  186524. * need to allocate exactly 64K, so whatever you call here must
  186525. * have the ability to do that.
  186526. *
  186527. * Borland seems to have a problem in DOS mode for exactly 64K.
  186528. * It gives you a segment with an offset of 8 (perhaps to store its
  186529. * memory stuff). zlib doesn't like this at all, so we have to
  186530. * detect and deal with it. This code should not be needed in
  186531. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186532. * been updated by Alexander Lehmann for version 0.89 to waste less
  186533. * memory.
  186534. *
  186535. * Note that we can't use png_size_t for the "size" declaration,
  186536. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186537. * result, we would be truncating potentially larger memory requests
  186538. * (which should cause a fatal error) and introducing major problems.
  186539. */
  186540. png_voidp PNGAPI
  186541. png_malloc(png_structp png_ptr, png_uint_32 size)
  186542. {
  186543. png_voidp ret;
  186544. if (png_ptr == NULL || size == 0)
  186545. return (NULL);
  186546. #ifdef PNG_USER_MEM_SUPPORTED
  186547. if(png_ptr->malloc_fn != NULL)
  186548. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186549. else
  186550. ret = (png_malloc_default(png_ptr, size));
  186551. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186552. png_error(png_ptr, "Out of memory!");
  186553. return (ret);
  186554. }
  186555. png_voidp PNGAPI
  186556. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186557. {
  186558. png_voidp ret;
  186559. #endif /* PNG_USER_MEM_SUPPORTED */
  186560. if (png_ptr == NULL || size == 0)
  186561. return (NULL);
  186562. #ifdef PNG_MAX_MALLOC_64K
  186563. if (size > (png_uint_32)65536L)
  186564. {
  186565. png_warning(png_ptr, "Cannot Allocate > 64K");
  186566. ret = NULL;
  186567. }
  186568. else
  186569. #endif
  186570. if (size != (size_t)size)
  186571. ret = NULL;
  186572. else if (size == (png_uint_32)65536L)
  186573. {
  186574. if (png_ptr->offset_table == NULL)
  186575. {
  186576. /* try to see if we need to do any of this fancy stuff */
  186577. ret = farmalloc(size);
  186578. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186579. {
  186580. int num_blocks;
  186581. png_uint_32 total_size;
  186582. png_bytep table;
  186583. int i;
  186584. png_byte huge * hptr;
  186585. if (ret != NULL)
  186586. {
  186587. farfree(ret);
  186588. ret = NULL;
  186589. }
  186590. if(png_ptr->zlib_window_bits > 14)
  186591. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186592. else
  186593. num_blocks = 1;
  186594. if (png_ptr->zlib_mem_level >= 7)
  186595. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186596. else
  186597. num_blocks++;
  186598. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186599. table = farmalloc(total_size);
  186600. if (table == NULL)
  186601. {
  186602. #ifndef PNG_USER_MEM_SUPPORTED
  186603. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186604. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186605. else
  186606. png_warning(png_ptr, "Out Of Memory.");
  186607. #endif
  186608. return (NULL);
  186609. }
  186610. if ((png_size_t)table & 0xfff0)
  186611. {
  186612. #ifndef PNG_USER_MEM_SUPPORTED
  186613. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186614. png_error(png_ptr,
  186615. "Farmalloc didn't return normalized pointer");
  186616. else
  186617. png_warning(png_ptr,
  186618. "Farmalloc didn't return normalized pointer");
  186619. #endif
  186620. return (NULL);
  186621. }
  186622. png_ptr->offset_table = table;
  186623. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186624. png_sizeof (png_bytep));
  186625. if (png_ptr->offset_table_ptr == NULL)
  186626. {
  186627. #ifndef PNG_USER_MEM_SUPPORTED
  186628. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186629. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186630. else
  186631. png_warning(png_ptr, "Out Of memory.");
  186632. #endif
  186633. return (NULL);
  186634. }
  186635. hptr = (png_byte huge *)table;
  186636. if ((png_size_t)hptr & 0xf)
  186637. {
  186638. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186639. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186640. }
  186641. for (i = 0; i < num_blocks; i++)
  186642. {
  186643. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186644. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186645. }
  186646. png_ptr->offset_table_number = num_blocks;
  186647. png_ptr->offset_table_count = 0;
  186648. png_ptr->offset_table_count_free = 0;
  186649. }
  186650. }
  186651. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186652. {
  186653. #ifndef PNG_USER_MEM_SUPPORTED
  186654. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186655. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186656. else
  186657. png_warning(png_ptr, "Out of Memory.");
  186658. #endif
  186659. return (NULL);
  186660. }
  186661. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186662. }
  186663. else
  186664. ret = farmalloc(size);
  186665. #ifndef PNG_USER_MEM_SUPPORTED
  186666. if (ret == NULL)
  186667. {
  186668. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186669. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186670. else
  186671. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186672. }
  186673. #endif
  186674. return (ret);
  186675. }
  186676. /* free a pointer allocated by png_malloc(). In the default
  186677. configuration, png_ptr is not used, but is passed in case it
  186678. is needed. If ptr is NULL, return without taking any action. */
  186679. void PNGAPI
  186680. png_free(png_structp png_ptr, png_voidp ptr)
  186681. {
  186682. if (png_ptr == NULL || ptr == NULL)
  186683. return;
  186684. #ifdef PNG_USER_MEM_SUPPORTED
  186685. if (png_ptr->free_fn != NULL)
  186686. {
  186687. (*(png_ptr->free_fn))(png_ptr, ptr);
  186688. return;
  186689. }
  186690. else png_free_default(png_ptr, ptr);
  186691. }
  186692. void PNGAPI
  186693. png_free_default(png_structp png_ptr, png_voidp ptr)
  186694. {
  186695. #endif /* PNG_USER_MEM_SUPPORTED */
  186696. if(png_ptr == NULL) return;
  186697. if (png_ptr->offset_table != NULL)
  186698. {
  186699. int i;
  186700. for (i = 0; i < png_ptr->offset_table_count; i++)
  186701. {
  186702. if (ptr == png_ptr->offset_table_ptr[i])
  186703. {
  186704. ptr = NULL;
  186705. png_ptr->offset_table_count_free++;
  186706. break;
  186707. }
  186708. }
  186709. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186710. {
  186711. farfree(png_ptr->offset_table);
  186712. farfree(png_ptr->offset_table_ptr);
  186713. png_ptr->offset_table = NULL;
  186714. png_ptr->offset_table_ptr = NULL;
  186715. }
  186716. }
  186717. if (ptr != NULL)
  186718. {
  186719. farfree(ptr);
  186720. }
  186721. }
  186722. #else /* Not the Borland DOS special memory handler */
  186723. /* Allocate memory for a png_struct or a png_info. The malloc and
  186724. memset can be replaced by a single call to calloc() if this is thought
  186725. to improve performance noticably. */
  186726. png_voidp /* PRIVATE */
  186727. png_create_struct(int type)
  186728. {
  186729. #ifdef PNG_USER_MEM_SUPPORTED
  186730. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186731. }
  186732. /* Allocate memory for a png_struct or a png_info. The malloc and
  186733. memset can be replaced by a single call to calloc() if this is thought
  186734. to improve performance noticably. */
  186735. png_voidp /* PRIVATE */
  186736. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186737. {
  186738. #endif /* PNG_USER_MEM_SUPPORTED */
  186739. png_size_t size;
  186740. png_voidp struct_ptr;
  186741. if (type == PNG_STRUCT_INFO)
  186742. size = png_sizeof(png_info);
  186743. else if (type == PNG_STRUCT_PNG)
  186744. size = png_sizeof(png_struct);
  186745. else
  186746. return (NULL);
  186747. #ifdef PNG_USER_MEM_SUPPORTED
  186748. if(malloc_fn != NULL)
  186749. {
  186750. png_struct dummy_struct;
  186751. png_structp png_ptr = &dummy_struct;
  186752. png_ptr->mem_ptr=mem_ptr;
  186753. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186754. if (struct_ptr != NULL)
  186755. png_memset(struct_ptr, 0, size);
  186756. return (struct_ptr);
  186757. }
  186758. #endif /* PNG_USER_MEM_SUPPORTED */
  186759. #if defined(__TURBOC__) && !defined(__FLAT__)
  186760. struct_ptr = (png_voidp)farmalloc(size);
  186761. #else
  186762. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186763. struct_ptr = (png_voidp)halloc(size,1);
  186764. # else
  186765. struct_ptr = (png_voidp)malloc(size);
  186766. # endif
  186767. #endif
  186768. if (struct_ptr != NULL)
  186769. png_memset(struct_ptr, 0, size);
  186770. return (struct_ptr);
  186771. }
  186772. /* Free memory allocated by a png_create_struct() call */
  186773. void /* PRIVATE */
  186774. png_destroy_struct(png_voidp struct_ptr)
  186775. {
  186776. #ifdef PNG_USER_MEM_SUPPORTED
  186777. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186778. }
  186779. /* Free memory allocated by a png_create_struct() call */
  186780. void /* PRIVATE */
  186781. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186782. png_voidp mem_ptr)
  186783. {
  186784. #endif /* PNG_USER_MEM_SUPPORTED */
  186785. if (struct_ptr != NULL)
  186786. {
  186787. #ifdef PNG_USER_MEM_SUPPORTED
  186788. if(free_fn != NULL)
  186789. {
  186790. png_struct dummy_struct;
  186791. png_structp png_ptr = &dummy_struct;
  186792. png_ptr->mem_ptr=mem_ptr;
  186793. (*(free_fn))(png_ptr, struct_ptr);
  186794. return;
  186795. }
  186796. #endif /* PNG_USER_MEM_SUPPORTED */
  186797. #if defined(__TURBOC__) && !defined(__FLAT__)
  186798. farfree(struct_ptr);
  186799. #else
  186800. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186801. hfree(struct_ptr);
  186802. # else
  186803. free(struct_ptr);
  186804. # endif
  186805. #endif
  186806. }
  186807. }
  186808. /* Allocate memory. For reasonable files, size should never exceed
  186809. 64K. However, zlib may allocate more then 64K if you don't tell
  186810. it not to. See zconf.h and png.h for more information. zlib does
  186811. need to allocate exactly 64K, so whatever you call here must
  186812. have the ability to do that. */
  186813. png_voidp PNGAPI
  186814. png_malloc(png_structp png_ptr, png_uint_32 size)
  186815. {
  186816. png_voidp ret;
  186817. #ifdef PNG_USER_MEM_SUPPORTED
  186818. if (png_ptr == NULL || size == 0)
  186819. return (NULL);
  186820. if(png_ptr->malloc_fn != NULL)
  186821. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186822. else
  186823. ret = (png_malloc_default(png_ptr, size));
  186824. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186825. png_error(png_ptr, "Out of Memory!");
  186826. return (ret);
  186827. }
  186828. png_voidp PNGAPI
  186829. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186830. {
  186831. png_voidp ret;
  186832. #endif /* PNG_USER_MEM_SUPPORTED */
  186833. if (png_ptr == NULL || size == 0)
  186834. return (NULL);
  186835. #ifdef PNG_MAX_MALLOC_64K
  186836. if (size > (png_uint_32)65536L)
  186837. {
  186838. #ifndef PNG_USER_MEM_SUPPORTED
  186839. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186840. png_error(png_ptr, "Cannot Allocate > 64K");
  186841. else
  186842. #endif
  186843. return NULL;
  186844. }
  186845. #endif
  186846. /* Check for overflow */
  186847. #if defined(__TURBOC__) && !defined(__FLAT__)
  186848. if (size != (unsigned long)size)
  186849. ret = NULL;
  186850. else
  186851. ret = farmalloc(size);
  186852. #else
  186853. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186854. if (size != (unsigned long)size)
  186855. ret = NULL;
  186856. else
  186857. ret = halloc(size, 1);
  186858. # else
  186859. if (size != (size_t)size)
  186860. ret = NULL;
  186861. else
  186862. ret = malloc((size_t)size);
  186863. # endif
  186864. #endif
  186865. #ifndef PNG_USER_MEM_SUPPORTED
  186866. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186867. png_error(png_ptr, "Out of Memory");
  186868. #endif
  186869. return (ret);
  186870. }
  186871. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186872. without taking any action. */
  186873. void PNGAPI
  186874. png_free(png_structp png_ptr, png_voidp ptr)
  186875. {
  186876. if (png_ptr == NULL || ptr == NULL)
  186877. return;
  186878. #ifdef PNG_USER_MEM_SUPPORTED
  186879. if (png_ptr->free_fn != NULL)
  186880. {
  186881. (*(png_ptr->free_fn))(png_ptr, ptr);
  186882. return;
  186883. }
  186884. else png_free_default(png_ptr, ptr);
  186885. }
  186886. void PNGAPI
  186887. png_free_default(png_structp png_ptr, png_voidp ptr)
  186888. {
  186889. if (png_ptr == NULL || ptr == NULL)
  186890. return;
  186891. #endif /* PNG_USER_MEM_SUPPORTED */
  186892. #if defined(__TURBOC__) && !defined(__FLAT__)
  186893. farfree(ptr);
  186894. #else
  186895. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186896. hfree(ptr);
  186897. # else
  186898. free(ptr);
  186899. # endif
  186900. #endif
  186901. }
  186902. #endif /* Not Borland DOS special memory handler */
  186903. #if defined(PNG_1_0_X)
  186904. # define png_malloc_warn png_malloc
  186905. #else
  186906. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186907. * function will set up png_malloc() to issue a png_warning and return NULL
  186908. * instead of issuing a png_error, if it fails to allocate the requested
  186909. * memory.
  186910. */
  186911. png_voidp PNGAPI
  186912. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186913. {
  186914. png_voidp ptr;
  186915. png_uint_32 save_flags;
  186916. if(png_ptr == NULL) return (NULL);
  186917. save_flags=png_ptr->flags;
  186918. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186919. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186920. png_ptr->flags=save_flags;
  186921. return(ptr);
  186922. }
  186923. #endif
  186924. png_voidp PNGAPI
  186925. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186926. png_uint_32 length)
  186927. {
  186928. png_size_t size;
  186929. size = (png_size_t)length;
  186930. if ((png_uint_32)size != length)
  186931. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186932. return(png_memcpy (s1, s2, size));
  186933. }
  186934. png_voidp PNGAPI
  186935. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186936. png_uint_32 length)
  186937. {
  186938. png_size_t size;
  186939. size = (png_size_t)length;
  186940. if ((png_uint_32)size != length)
  186941. png_error(png_ptr,"Overflow in png_memset_check.");
  186942. return (png_memset (s1, value, size));
  186943. }
  186944. #ifdef PNG_USER_MEM_SUPPORTED
  186945. /* This function is called when the application wants to use another method
  186946. * of allocating and freeing memory.
  186947. */
  186948. void PNGAPI
  186949. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186950. malloc_fn, png_free_ptr free_fn)
  186951. {
  186952. if(png_ptr != NULL) {
  186953. png_ptr->mem_ptr = mem_ptr;
  186954. png_ptr->malloc_fn = malloc_fn;
  186955. png_ptr->free_fn = free_fn;
  186956. }
  186957. }
  186958. /* This function returns a pointer to the mem_ptr associated with the user
  186959. * functions. The application should free any memory associated with this
  186960. * pointer before png_write_destroy and png_read_destroy are called.
  186961. */
  186962. png_voidp PNGAPI
  186963. png_get_mem_ptr(png_structp png_ptr)
  186964. {
  186965. if(png_ptr == NULL) return (NULL);
  186966. return ((png_voidp)png_ptr->mem_ptr);
  186967. }
  186968. #endif /* PNG_USER_MEM_SUPPORTED */
  186969. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186970. /*** End of inlined file: pngmem.c ***/
  186971. /*** Start of inlined file: pngread.c ***/
  186972. /* pngread.c - read a PNG file
  186973. *
  186974. * Last changed in libpng 1.2.20 September 7, 2007
  186975. * For conditions of distribution and use, see copyright notice in png.h
  186976. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186977. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186978. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186979. *
  186980. * This file contains routines that an application calls directly to
  186981. * read a PNG file or stream.
  186982. */
  186983. #define PNG_INTERNAL
  186984. #if defined(PNG_READ_SUPPORTED)
  186985. /* Create a PNG structure for reading, and allocate any memory needed. */
  186986. png_structp PNGAPI
  186987. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186988. png_error_ptr error_fn, png_error_ptr warn_fn)
  186989. {
  186990. #ifdef PNG_USER_MEM_SUPPORTED
  186991. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186992. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186993. }
  186994. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186995. png_structp PNGAPI
  186996. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186997. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186998. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186999. {
  187000. #endif /* PNG_USER_MEM_SUPPORTED */
  187001. png_structp png_ptr;
  187002. #ifdef PNG_SETJMP_SUPPORTED
  187003. #ifdef USE_FAR_KEYWORD
  187004. jmp_buf jmpbuf;
  187005. #endif
  187006. #endif
  187007. int i;
  187008. png_debug(1, "in png_create_read_struct\n");
  187009. #ifdef PNG_USER_MEM_SUPPORTED
  187010. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187011. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187012. #else
  187013. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187014. #endif
  187015. if (png_ptr == NULL)
  187016. return (NULL);
  187017. /* added at libpng-1.2.6 */
  187018. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187019. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187020. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187021. #endif
  187022. #ifdef PNG_SETJMP_SUPPORTED
  187023. #ifdef USE_FAR_KEYWORD
  187024. if (setjmp(jmpbuf))
  187025. #else
  187026. if (setjmp(png_ptr->jmpbuf))
  187027. #endif
  187028. {
  187029. png_free(png_ptr, png_ptr->zbuf);
  187030. png_ptr->zbuf=NULL;
  187031. #ifdef PNG_USER_MEM_SUPPORTED
  187032. png_destroy_struct_2((png_voidp)png_ptr,
  187033. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187034. #else
  187035. png_destroy_struct((png_voidp)png_ptr);
  187036. #endif
  187037. return (NULL);
  187038. }
  187039. #ifdef USE_FAR_KEYWORD
  187040. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187041. #endif
  187042. #endif
  187043. #ifdef PNG_USER_MEM_SUPPORTED
  187044. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187045. #endif
  187046. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187047. i=0;
  187048. do
  187049. {
  187050. if(user_png_ver[i] != png_libpng_ver[i])
  187051. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187052. } while (png_libpng_ver[i++]);
  187053. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187054. {
  187055. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187056. * we must recompile any applications that use any older library version.
  187057. * For versions after libpng 1.0, we will be compatible, so we need
  187058. * only check the first digit.
  187059. */
  187060. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187061. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187062. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187063. {
  187064. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187065. char msg[80];
  187066. if (user_png_ver)
  187067. {
  187068. png_snprintf(msg, 80,
  187069. "Application was compiled with png.h from libpng-%.20s",
  187070. user_png_ver);
  187071. png_warning(png_ptr, msg);
  187072. }
  187073. png_snprintf(msg, 80,
  187074. "Application is running with png.c from libpng-%.20s",
  187075. png_libpng_ver);
  187076. png_warning(png_ptr, msg);
  187077. #endif
  187078. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187079. png_ptr->flags=0;
  187080. #endif
  187081. png_error(png_ptr,
  187082. "Incompatible libpng version in application and library");
  187083. }
  187084. }
  187085. /* initialize zbuf - compression buffer */
  187086. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187087. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187088. (png_uint_32)png_ptr->zbuf_size);
  187089. png_ptr->zstream.zalloc = png_zalloc;
  187090. png_ptr->zstream.zfree = png_zfree;
  187091. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187092. switch (inflateInit(&png_ptr->zstream))
  187093. {
  187094. case Z_OK: /* Do nothing */ break;
  187095. case Z_MEM_ERROR:
  187096. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187097. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187098. default: png_error(png_ptr, "Unknown zlib error");
  187099. }
  187100. png_ptr->zstream.next_out = png_ptr->zbuf;
  187101. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187102. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187103. #ifdef PNG_SETJMP_SUPPORTED
  187104. /* Applications that neglect to set up their own setjmp() and then encounter
  187105. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187106. abort instead of returning. */
  187107. #ifdef USE_FAR_KEYWORD
  187108. if (setjmp(jmpbuf))
  187109. PNG_ABORT();
  187110. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187111. #else
  187112. if (setjmp(png_ptr->jmpbuf))
  187113. PNG_ABORT();
  187114. #endif
  187115. #endif
  187116. return (png_ptr);
  187117. }
  187118. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187119. /* Initialize PNG structure for reading, and allocate any memory needed.
  187120. This interface is deprecated in favour of the png_create_read_struct(),
  187121. and it will disappear as of libpng-1.3.0. */
  187122. #undef png_read_init
  187123. void PNGAPI
  187124. png_read_init(png_structp png_ptr)
  187125. {
  187126. /* We only come here via pre-1.0.7-compiled applications */
  187127. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187128. }
  187129. void PNGAPI
  187130. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187131. png_size_t png_struct_size, png_size_t png_info_size)
  187132. {
  187133. /* We only come here via pre-1.0.12-compiled applications */
  187134. if(png_ptr == NULL) return;
  187135. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187136. if(png_sizeof(png_struct) > png_struct_size ||
  187137. png_sizeof(png_info) > png_info_size)
  187138. {
  187139. char msg[80];
  187140. png_ptr->warning_fn=NULL;
  187141. if (user_png_ver)
  187142. {
  187143. png_snprintf(msg, 80,
  187144. "Application was compiled with png.h from libpng-%.20s",
  187145. user_png_ver);
  187146. png_warning(png_ptr, msg);
  187147. }
  187148. png_snprintf(msg, 80,
  187149. "Application is running with png.c from libpng-%.20s",
  187150. png_libpng_ver);
  187151. png_warning(png_ptr, msg);
  187152. }
  187153. #endif
  187154. if(png_sizeof(png_struct) > png_struct_size)
  187155. {
  187156. png_ptr->error_fn=NULL;
  187157. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187158. png_ptr->flags=0;
  187159. #endif
  187160. png_error(png_ptr,
  187161. "The png struct allocated by the application for reading is too small.");
  187162. }
  187163. if(png_sizeof(png_info) > png_info_size)
  187164. {
  187165. png_ptr->error_fn=NULL;
  187166. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187167. png_ptr->flags=0;
  187168. #endif
  187169. png_error(png_ptr,
  187170. "The info struct allocated by application for reading is too small.");
  187171. }
  187172. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187173. }
  187174. #endif /* PNG_1_0_X || PNG_1_2_X */
  187175. void PNGAPI
  187176. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187177. png_size_t png_struct_size)
  187178. {
  187179. #ifdef PNG_SETJMP_SUPPORTED
  187180. jmp_buf tmp_jmp; /* to save current jump buffer */
  187181. #endif
  187182. int i=0;
  187183. png_structp png_ptr=*ptr_ptr;
  187184. if(png_ptr == NULL) return;
  187185. do
  187186. {
  187187. if(user_png_ver[i] != png_libpng_ver[i])
  187188. {
  187189. #ifdef PNG_LEGACY_SUPPORTED
  187190. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187191. #else
  187192. png_ptr->warning_fn=NULL;
  187193. png_warning(png_ptr,
  187194. "Application uses deprecated png_read_init() and should be recompiled.");
  187195. break;
  187196. #endif
  187197. }
  187198. } while (png_libpng_ver[i++]);
  187199. png_debug(1, "in png_read_init_3\n");
  187200. #ifdef PNG_SETJMP_SUPPORTED
  187201. /* save jump buffer and error functions */
  187202. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187203. #endif
  187204. if(png_sizeof(png_struct) > png_struct_size)
  187205. {
  187206. png_destroy_struct(png_ptr);
  187207. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187208. png_ptr = *ptr_ptr;
  187209. }
  187210. /* reset all variables to 0 */
  187211. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187212. #ifdef PNG_SETJMP_SUPPORTED
  187213. /* restore jump buffer */
  187214. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187215. #endif
  187216. /* added at libpng-1.2.6 */
  187217. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187218. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187219. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187220. #endif
  187221. /* initialize zbuf - compression buffer */
  187222. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187223. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187224. (png_uint_32)png_ptr->zbuf_size);
  187225. png_ptr->zstream.zalloc = png_zalloc;
  187226. png_ptr->zstream.zfree = png_zfree;
  187227. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187228. switch (inflateInit(&png_ptr->zstream))
  187229. {
  187230. case Z_OK: /* Do nothing */ break;
  187231. case Z_MEM_ERROR:
  187232. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187233. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187234. default: png_error(png_ptr, "Unknown zlib error");
  187235. }
  187236. png_ptr->zstream.next_out = png_ptr->zbuf;
  187237. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187238. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187239. }
  187240. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187241. /* Read the information before the actual image data. This has been
  187242. * changed in v0.90 to allow reading a file that already has the magic
  187243. * bytes read from the stream. You can tell libpng how many bytes have
  187244. * been read from the beginning of the stream (up to the maximum of 8)
  187245. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187246. * here. The application can then have access to the signature bytes we
  187247. * read if it is determined that this isn't a valid PNG file.
  187248. */
  187249. void PNGAPI
  187250. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187251. {
  187252. if(png_ptr == NULL) return;
  187253. png_debug(1, "in png_read_info\n");
  187254. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187255. if (png_ptr->sig_bytes < 8)
  187256. {
  187257. png_size_t num_checked = png_ptr->sig_bytes,
  187258. num_to_check = 8 - num_checked;
  187259. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187260. png_ptr->sig_bytes = 8;
  187261. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187262. {
  187263. if (num_checked < 4 &&
  187264. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187265. png_error(png_ptr, "Not a PNG file");
  187266. else
  187267. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187268. }
  187269. if (num_checked < 3)
  187270. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187271. }
  187272. for(;;)
  187273. {
  187274. #ifdef PNG_USE_LOCAL_ARRAYS
  187275. PNG_CONST PNG_IHDR;
  187276. PNG_CONST PNG_IDAT;
  187277. PNG_CONST PNG_IEND;
  187278. PNG_CONST PNG_PLTE;
  187279. #if defined(PNG_READ_bKGD_SUPPORTED)
  187280. PNG_CONST PNG_bKGD;
  187281. #endif
  187282. #if defined(PNG_READ_cHRM_SUPPORTED)
  187283. PNG_CONST PNG_cHRM;
  187284. #endif
  187285. #if defined(PNG_READ_gAMA_SUPPORTED)
  187286. PNG_CONST PNG_gAMA;
  187287. #endif
  187288. #if defined(PNG_READ_hIST_SUPPORTED)
  187289. PNG_CONST PNG_hIST;
  187290. #endif
  187291. #if defined(PNG_READ_iCCP_SUPPORTED)
  187292. PNG_CONST PNG_iCCP;
  187293. #endif
  187294. #if defined(PNG_READ_iTXt_SUPPORTED)
  187295. PNG_CONST PNG_iTXt;
  187296. #endif
  187297. #if defined(PNG_READ_oFFs_SUPPORTED)
  187298. PNG_CONST PNG_oFFs;
  187299. #endif
  187300. #if defined(PNG_READ_pCAL_SUPPORTED)
  187301. PNG_CONST PNG_pCAL;
  187302. #endif
  187303. #if defined(PNG_READ_pHYs_SUPPORTED)
  187304. PNG_CONST PNG_pHYs;
  187305. #endif
  187306. #if defined(PNG_READ_sBIT_SUPPORTED)
  187307. PNG_CONST PNG_sBIT;
  187308. #endif
  187309. #if defined(PNG_READ_sCAL_SUPPORTED)
  187310. PNG_CONST PNG_sCAL;
  187311. #endif
  187312. #if defined(PNG_READ_sPLT_SUPPORTED)
  187313. PNG_CONST PNG_sPLT;
  187314. #endif
  187315. #if defined(PNG_READ_sRGB_SUPPORTED)
  187316. PNG_CONST PNG_sRGB;
  187317. #endif
  187318. #if defined(PNG_READ_tEXt_SUPPORTED)
  187319. PNG_CONST PNG_tEXt;
  187320. #endif
  187321. #if defined(PNG_READ_tIME_SUPPORTED)
  187322. PNG_CONST PNG_tIME;
  187323. #endif
  187324. #if defined(PNG_READ_tRNS_SUPPORTED)
  187325. PNG_CONST PNG_tRNS;
  187326. #endif
  187327. #if defined(PNG_READ_zTXt_SUPPORTED)
  187328. PNG_CONST PNG_zTXt;
  187329. #endif
  187330. #endif /* PNG_USE_LOCAL_ARRAYS */
  187331. png_byte chunk_length[4];
  187332. png_uint_32 length;
  187333. png_read_data(png_ptr, chunk_length, 4);
  187334. length = png_get_uint_31(png_ptr,chunk_length);
  187335. png_reset_crc(png_ptr);
  187336. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187337. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187338. length);
  187339. /* This should be a binary subdivision search or a hash for
  187340. * matching the chunk name rather than a linear search.
  187341. */
  187342. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187343. if(png_ptr->mode & PNG_AFTER_IDAT)
  187344. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187345. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187346. png_handle_IHDR(png_ptr, info_ptr, length);
  187347. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187348. png_handle_IEND(png_ptr, info_ptr, length);
  187349. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187350. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187351. {
  187352. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187353. png_ptr->mode |= PNG_HAVE_IDAT;
  187354. png_handle_unknown(png_ptr, info_ptr, length);
  187355. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187356. png_ptr->mode |= PNG_HAVE_PLTE;
  187357. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187358. {
  187359. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187360. png_error(png_ptr, "Missing IHDR before IDAT");
  187361. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187362. !(png_ptr->mode & PNG_HAVE_PLTE))
  187363. png_error(png_ptr, "Missing PLTE before IDAT");
  187364. break;
  187365. }
  187366. }
  187367. #endif
  187368. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187369. png_handle_PLTE(png_ptr, info_ptr, length);
  187370. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187371. {
  187372. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187373. png_error(png_ptr, "Missing IHDR before IDAT");
  187374. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187375. !(png_ptr->mode & PNG_HAVE_PLTE))
  187376. png_error(png_ptr, "Missing PLTE before IDAT");
  187377. png_ptr->idat_size = length;
  187378. png_ptr->mode |= PNG_HAVE_IDAT;
  187379. break;
  187380. }
  187381. #if defined(PNG_READ_bKGD_SUPPORTED)
  187382. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187383. png_handle_bKGD(png_ptr, info_ptr, length);
  187384. #endif
  187385. #if defined(PNG_READ_cHRM_SUPPORTED)
  187386. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187387. png_handle_cHRM(png_ptr, info_ptr, length);
  187388. #endif
  187389. #if defined(PNG_READ_gAMA_SUPPORTED)
  187390. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187391. png_handle_gAMA(png_ptr, info_ptr, length);
  187392. #endif
  187393. #if defined(PNG_READ_hIST_SUPPORTED)
  187394. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187395. png_handle_hIST(png_ptr, info_ptr, length);
  187396. #endif
  187397. #if defined(PNG_READ_oFFs_SUPPORTED)
  187398. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187399. png_handle_oFFs(png_ptr, info_ptr, length);
  187400. #endif
  187401. #if defined(PNG_READ_pCAL_SUPPORTED)
  187402. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187403. png_handle_pCAL(png_ptr, info_ptr, length);
  187404. #endif
  187405. #if defined(PNG_READ_sCAL_SUPPORTED)
  187406. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187407. png_handle_sCAL(png_ptr, info_ptr, length);
  187408. #endif
  187409. #if defined(PNG_READ_pHYs_SUPPORTED)
  187410. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187411. png_handle_pHYs(png_ptr, info_ptr, length);
  187412. #endif
  187413. #if defined(PNG_READ_sBIT_SUPPORTED)
  187414. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187415. png_handle_sBIT(png_ptr, info_ptr, length);
  187416. #endif
  187417. #if defined(PNG_READ_sRGB_SUPPORTED)
  187418. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187419. png_handle_sRGB(png_ptr, info_ptr, length);
  187420. #endif
  187421. #if defined(PNG_READ_iCCP_SUPPORTED)
  187422. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187423. png_handle_iCCP(png_ptr, info_ptr, length);
  187424. #endif
  187425. #if defined(PNG_READ_sPLT_SUPPORTED)
  187426. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187427. png_handle_sPLT(png_ptr, info_ptr, length);
  187428. #endif
  187429. #if defined(PNG_READ_tEXt_SUPPORTED)
  187430. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187431. png_handle_tEXt(png_ptr, info_ptr, length);
  187432. #endif
  187433. #if defined(PNG_READ_tIME_SUPPORTED)
  187434. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187435. png_handle_tIME(png_ptr, info_ptr, length);
  187436. #endif
  187437. #if defined(PNG_READ_tRNS_SUPPORTED)
  187438. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187439. png_handle_tRNS(png_ptr, info_ptr, length);
  187440. #endif
  187441. #if defined(PNG_READ_zTXt_SUPPORTED)
  187442. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187443. png_handle_zTXt(png_ptr, info_ptr, length);
  187444. #endif
  187445. #if defined(PNG_READ_iTXt_SUPPORTED)
  187446. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187447. png_handle_iTXt(png_ptr, info_ptr, length);
  187448. #endif
  187449. else
  187450. png_handle_unknown(png_ptr, info_ptr, length);
  187451. }
  187452. }
  187453. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187454. /* optional call to update the users info_ptr structure */
  187455. void PNGAPI
  187456. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187457. {
  187458. png_debug(1, "in png_read_update_info\n");
  187459. if(png_ptr == NULL) return;
  187460. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187461. png_read_start_row(png_ptr);
  187462. else
  187463. png_warning(png_ptr,
  187464. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187465. png_read_transform_info(png_ptr, info_ptr);
  187466. }
  187467. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187468. /* Initialize palette, background, etc, after transformations
  187469. * are set, but before any reading takes place. This allows
  187470. * the user to obtain a gamma-corrected palette, for example.
  187471. * If the user doesn't call this, we will do it ourselves.
  187472. */
  187473. void PNGAPI
  187474. png_start_read_image(png_structp png_ptr)
  187475. {
  187476. png_debug(1, "in png_start_read_image\n");
  187477. if(png_ptr == NULL) return;
  187478. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187479. png_read_start_row(png_ptr);
  187480. }
  187481. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187482. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187483. void PNGAPI
  187484. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187485. {
  187486. #ifdef PNG_USE_LOCAL_ARRAYS
  187487. PNG_CONST PNG_IDAT;
  187488. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187489. 0xff};
  187490. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187491. #endif
  187492. int ret;
  187493. if(png_ptr == NULL) return;
  187494. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187495. png_ptr->row_number, png_ptr->pass);
  187496. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187497. png_read_start_row(png_ptr);
  187498. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187499. {
  187500. /* check for transforms that have been set but were defined out */
  187501. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187502. if (png_ptr->transformations & PNG_INVERT_MONO)
  187503. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187504. #endif
  187505. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187506. if (png_ptr->transformations & PNG_FILLER)
  187507. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187508. #endif
  187509. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187510. if (png_ptr->transformations & PNG_PACKSWAP)
  187511. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187512. #endif
  187513. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187514. if (png_ptr->transformations & PNG_PACK)
  187515. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187516. #endif
  187517. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187518. if (png_ptr->transformations & PNG_SHIFT)
  187519. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187520. #endif
  187521. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187522. if (png_ptr->transformations & PNG_BGR)
  187523. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187524. #endif
  187525. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187526. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187527. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187528. #endif
  187529. }
  187530. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187531. /* if interlaced and we do not need a new row, combine row and return */
  187532. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187533. {
  187534. switch (png_ptr->pass)
  187535. {
  187536. case 0:
  187537. if (png_ptr->row_number & 0x07)
  187538. {
  187539. if (dsp_row != NULL)
  187540. png_combine_row(png_ptr, dsp_row,
  187541. png_pass_dsp_mask[png_ptr->pass]);
  187542. png_read_finish_row(png_ptr);
  187543. return;
  187544. }
  187545. break;
  187546. case 1:
  187547. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187548. {
  187549. if (dsp_row != NULL)
  187550. png_combine_row(png_ptr, dsp_row,
  187551. png_pass_dsp_mask[png_ptr->pass]);
  187552. png_read_finish_row(png_ptr);
  187553. return;
  187554. }
  187555. break;
  187556. case 2:
  187557. if ((png_ptr->row_number & 0x07) != 4)
  187558. {
  187559. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187560. png_combine_row(png_ptr, dsp_row,
  187561. png_pass_dsp_mask[png_ptr->pass]);
  187562. png_read_finish_row(png_ptr);
  187563. return;
  187564. }
  187565. break;
  187566. case 3:
  187567. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187568. {
  187569. if (dsp_row != NULL)
  187570. png_combine_row(png_ptr, dsp_row,
  187571. png_pass_dsp_mask[png_ptr->pass]);
  187572. png_read_finish_row(png_ptr);
  187573. return;
  187574. }
  187575. break;
  187576. case 4:
  187577. if ((png_ptr->row_number & 3) != 2)
  187578. {
  187579. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187580. png_combine_row(png_ptr, dsp_row,
  187581. png_pass_dsp_mask[png_ptr->pass]);
  187582. png_read_finish_row(png_ptr);
  187583. return;
  187584. }
  187585. break;
  187586. case 5:
  187587. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187588. {
  187589. if (dsp_row != NULL)
  187590. png_combine_row(png_ptr, dsp_row,
  187591. png_pass_dsp_mask[png_ptr->pass]);
  187592. png_read_finish_row(png_ptr);
  187593. return;
  187594. }
  187595. break;
  187596. case 6:
  187597. if (!(png_ptr->row_number & 1))
  187598. {
  187599. png_read_finish_row(png_ptr);
  187600. return;
  187601. }
  187602. break;
  187603. }
  187604. }
  187605. #endif
  187606. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187607. png_error(png_ptr, "Invalid attempt to read row data");
  187608. png_ptr->zstream.next_out = png_ptr->row_buf;
  187609. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187610. do
  187611. {
  187612. if (!(png_ptr->zstream.avail_in))
  187613. {
  187614. while (!png_ptr->idat_size)
  187615. {
  187616. png_byte chunk_length[4];
  187617. png_crc_finish(png_ptr, 0);
  187618. png_read_data(png_ptr, chunk_length, 4);
  187619. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187620. png_reset_crc(png_ptr);
  187621. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187622. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187623. png_error(png_ptr, "Not enough image data");
  187624. }
  187625. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187626. png_ptr->zstream.next_in = png_ptr->zbuf;
  187627. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187628. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187629. png_crc_read(png_ptr, png_ptr->zbuf,
  187630. (png_size_t)png_ptr->zstream.avail_in);
  187631. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187632. }
  187633. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187634. if (ret == Z_STREAM_END)
  187635. {
  187636. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187637. png_ptr->idat_size)
  187638. png_error(png_ptr, "Extra compressed data");
  187639. png_ptr->mode |= PNG_AFTER_IDAT;
  187640. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187641. break;
  187642. }
  187643. if (ret != Z_OK)
  187644. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187645. "Decompression error");
  187646. } while (png_ptr->zstream.avail_out);
  187647. png_ptr->row_info.color_type = png_ptr->color_type;
  187648. png_ptr->row_info.width = png_ptr->iwidth;
  187649. png_ptr->row_info.channels = png_ptr->channels;
  187650. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187651. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187652. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187653. png_ptr->row_info.width);
  187654. if(png_ptr->row_buf[0])
  187655. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187656. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187657. (int)(png_ptr->row_buf[0]));
  187658. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187659. png_ptr->rowbytes + 1);
  187660. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187661. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187662. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187663. {
  187664. /* Intrapixel differencing */
  187665. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187666. }
  187667. #endif
  187668. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187669. png_do_read_transformations(png_ptr);
  187670. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187671. /* blow up interlaced rows to full size */
  187672. if (png_ptr->interlaced &&
  187673. (png_ptr->transformations & PNG_INTERLACE))
  187674. {
  187675. if (png_ptr->pass < 6)
  187676. /* old interface (pre-1.0.9):
  187677. png_do_read_interlace(&(png_ptr->row_info),
  187678. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187679. */
  187680. png_do_read_interlace(png_ptr);
  187681. if (dsp_row != NULL)
  187682. png_combine_row(png_ptr, dsp_row,
  187683. png_pass_dsp_mask[png_ptr->pass]);
  187684. if (row != NULL)
  187685. png_combine_row(png_ptr, row,
  187686. png_pass_mask[png_ptr->pass]);
  187687. }
  187688. else
  187689. #endif
  187690. {
  187691. if (row != NULL)
  187692. png_combine_row(png_ptr, row, 0xff);
  187693. if (dsp_row != NULL)
  187694. png_combine_row(png_ptr, dsp_row, 0xff);
  187695. }
  187696. png_read_finish_row(png_ptr);
  187697. if (png_ptr->read_row_fn != NULL)
  187698. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187699. }
  187700. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187701. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187702. /* Read one or more rows of image data. If the image is interlaced,
  187703. * and png_set_interlace_handling() has been called, the rows need to
  187704. * contain the contents of the rows from the previous pass. If the
  187705. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187706. * called, the rows contents must be initialized to the contents of the
  187707. * screen.
  187708. *
  187709. * "row" holds the actual image, and pixels are placed in it
  187710. * as they arrive. If the image is displayed after each pass, it will
  187711. * appear to "sparkle" in. "display_row" can be used to display a
  187712. * "chunky" progressive image, with finer detail added as it becomes
  187713. * available. If you do not want this "chunky" display, you may pass
  187714. * NULL for display_row. If you do not want the sparkle display, and
  187715. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187716. * If you have called png_handle_alpha(), and the image has either an
  187717. * alpha channel or a transparency chunk, you must provide a buffer for
  187718. * rows. In this case, you do not have to provide a display_row buffer
  187719. * also, but you may. If the image is not interlaced, or if you have
  187720. * not called png_set_interlace_handling(), the display_row buffer will
  187721. * be ignored, so pass NULL to it.
  187722. *
  187723. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187724. */
  187725. void PNGAPI
  187726. png_read_rows(png_structp png_ptr, png_bytepp row,
  187727. png_bytepp display_row, png_uint_32 num_rows)
  187728. {
  187729. png_uint_32 i;
  187730. png_bytepp rp;
  187731. png_bytepp dp;
  187732. png_debug(1, "in png_read_rows\n");
  187733. if(png_ptr == NULL) return;
  187734. rp = row;
  187735. dp = display_row;
  187736. if (rp != NULL && dp != NULL)
  187737. for (i = 0; i < num_rows; i++)
  187738. {
  187739. png_bytep rptr = *rp++;
  187740. png_bytep dptr = *dp++;
  187741. png_read_row(png_ptr, rptr, dptr);
  187742. }
  187743. else if(rp != NULL)
  187744. for (i = 0; i < num_rows; i++)
  187745. {
  187746. png_bytep rptr = *rp;
  187747. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187748. rp++;
  187749. }
  187750. else if(dp != NULL)
  187751. for (i = 0; i < num_rows; i++)
  187752. {
  187753. png_bytep dptr = *dp;
  187754. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187755. dp++;
  187756. }
  187757. }
  187758. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187759. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187760. /* Read the entire image. If the image has an alpha channel or a tRNS
  187761. * chunk, and you have called png_handle_alpha()[*], you will need to
  187762. * initialize the image to the current image that PNG will be overlaying.
  187763. * We set the num_rows again here, in case it was incorrectly set in
  187764. * png_read_start_row() by a call to png_read_update_info() or
  187765. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187766. * prior to either of these functions like it should have been. You can
  187767. * only call this function once. If you desire to have an image for
  187768. * each pass of a interlaced image, use png_read_rows() instead.
  187769. *
  187770. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187771. */
  187772. void PNGAPI
  187773. png_read_image(png_structp png_ptr, png_bytepp image)
  187774. {
  187775. png_uint_32 i,image_height;
  187776. int pass, j;
  187777. png_bytepp rp;
  187778. png_debug(1, "in png_read_image\n");
  187779. if(png_ptr == NULL) return;
  187780. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187781. pass = png_set_interlace_handling(png_ptr);
  187782. #else
  187783. if (png_ptr->interlaced)
  187784. png_error(png_ptr,
  187785. "Cannot read interlaced image -- interlace handler disabled.");
  187786. pass = 1;
  187787. #endif
  187788. image_height=png_ptr->height;
  187789. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187790. for (j = 0; j < pass; j++)
  187791. {
  187792. rp = image;
  187793. for (i = 0; i < image_height; i++)
  187794. {
  187795. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187796. rp++;
  187797. }
  187798. }
  187799. }
  187800. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187801. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187802. /* Read the end of the PNG file. Will not read past the end of the
  187803. * file, will verify the end is accurate, and will read any comments
  187804. * or time information at the end of the file, if info is not NULL.
  187805. */
  187806. void PNGAPI
  187807. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187808. {
  187809. png_byte chunk_length[4];
  187810. png_uint_32 length;
  187811. png_debug(1, "in png_read_end\n");
  187812. if(png_ptr == NULL) return;
  187813. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187814. do
  187815. {
  187816. #ifdef PNG_USE_LOCAL_ARRAYS
  187817. PNG_CONST PNG_IHDR;
  187818. PNG_CONST PNG_IDAT;
  187819. PNG_CONST PNG_IEND;
  187820. PNG_CONST PNG_PLTE;
  187821. #if defined(PNG_READ_bKGD_SUPPORTED)
  187822. PNG_CONST PNG_bKGD;
  187823. #endif
  187824. #if defined(PNG_READ_cHRM_SUPPORTED)
  187825. PNG_CONST PNG_cHRM;
  187826. #endif
  187827. #if defined(PNG_READ_gAMA_SUPPORTED)
  187828. PNG_CONST PNG_gAMA;
  187829. #endif
  187830. #if defined(PNG_READ_hIST_SUPPORTED)
  187831. PNG_CONST PNG_hIST;
  187832. #endif
  187833. #if defined(PNG_READ_iCCP_SUPPORTED)
  187834. PNG_CONST PNG_iCCP;
  187835. #endif
  187836. #if defined(PNG_READ_iTXt_SUPPORTED)
  187837. PNG_CONST PNG_iTXt;
  187838. #endif
  187839. #if defined(PNG_READ_oFFs_SUPPORTED)
  187840. PNG_CONST PNG_oFFs;
  187841. #endif
  187842. #if defined(PNG_READ_pCAL_SUPPORTED)
  187843. PNG_CONST PNG_pCAL;
  187844. #endif
  187845. #if defined(PNG_READ_pHYs_SUPPORTED)
  187846. PNG_CONST PNG_pHYs;
  187847. #endif
  187848. #if defined(PNG_READ_sBIT_SUPPORTED)
  187849. PNG_CONST PNG_sBIT;
  187850. #endif
  187851. #if defined(PNG_READ_sCAL_SUPPORTED)
  187852. PNG_CONST PNG_sCAL;
  187853. #endif
  187854. #if defined(PNG_READ_sPLT_SUPPORTED)
  187855. PNG_CONST PNG_sPLT;
  187856. #endif
  187857. #if defined(PNG_READ_sRGB_SUPPORTED)
  187858. PNG_CONST PNG_sRGB;
  187859. #endif
  187860. #if defined(PNG_READ_tEXt_SUPPORTED)
  187861. PNG_CONST PNG_tEXt;
  187862. #endif
  187863. #if defined(PNG_READ_tIME_SUPPORTED)
  187864. PNG_CONST PNG_tIME;
  187865. #endif
  187866. #if defined(PNG_READ_tRNS_SUPPORTED)
  187867. PNG_CONST PNG_tRNS;
  187868. #endif
  187869. #if defined(PNG_READ_zTXt_SUPPORTED)
  187870. PNG_CONST PNG_zTXt;
  187871. #endif
  187872. #endif /* PNG_USE_LOCAL_ARRAYS */
  187873. png_read_data(png_ptr, chunk_length, 4);
  187874. length = png_get_uint_31(png_ptr,chunk_length);
  187875. png_reset_crc(png_ptr);
  187876. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187877. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187878. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187879. png_handle_IHDR(png_ptr, info_ptr, length);
  187880. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187881. png_handle_IEND(png_ptr, info_ptr, length);
  187882. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187883. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187884. {
  187885. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187886. {
  187887. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187888. png_error(png_ptr, "Too many IDAT's found");
  187889. }
  187890. png_handle_unknown(png_ptr, info_ptr, length);
  187891. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187892. png_ptr->mode |= PNG_HAVE_PLTE;
  187893. }
  187894. #endif
  187895. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187896. {
  187897. /* Zero length IDATs are legal after the last IDAT has been
  187898. * read, but not after other chunks have been read.
  187899. */
  187900. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187901. png_error(png_ptr, "Too many IDAT's found");
  187902. png_crc_finish(png_ptr, length);
  187903. }
  187904. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187905. png_handle_PLTE(png_ptr, info_ptr, length);
  187906. #if defined(PNG_READ_bKGD_SUPPORTED)
  187907. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187908. png_handle_bKGD(png_ptr, info_ptr, length);
  187909. #endif
  187910. #if defined(PNG_READ_cHRM_SUPPORTED)
  187911. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187912. png_handle_cHRM(png_ptr, info_ptr, length);
  187913. #endif
  187914. #if defined(PNG_READ_gAMA_SUPPORTED)
  187915. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187916. png_handle_gAMA(png_ptr, info_ptr, length);
  187917. #endif
  187918. #if defined(PNG_READ_hIST_SUPPORTED)
  187919. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187920. png_handle_hIST(png_ptr, info_ptr, length);
  187921. #endif
  187922. #if defined(PNG_READ_oFFs_SUPPORTED)
  187923. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187924. png_handle_oFFs(png_ptr, info_ptr, length);
  187925. #endif
  187926. #if defined(PNG_READ_pCAL_SUPPORTED)
  187927. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187928. png_handle_pCAL(png_ptr, info_ptr, length);
  187929. #endif
  187930. #if defined(PNG_READ_sCAL_SUPPORTED)
  187931. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187932. png_handle_sCAL(png_ptr, info_ptr, length);
  187933. #endif
  187934. #if defined(PNG_READ_pHYs_SUPPORTED)
  187935. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187936. png_handle_pHYs(png_ptr, info_ptr, length);
  187937. #endif
  187938. #if defined(PNG_READ_sBIT_SUPPORTED)
  187939. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187940. png_handle_sBIT(png_ptr, info_ptr, length);
  187941. #endif
  187942. #if defined(PNG_READ_sRGB_SUPPORTED)
  187943. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187944. png_handle_sRGB(png_ptr, info_ptr, length);
  187945. #endif
  187946. #if defined(PNG_READ_iCCP_SUPPORTED)
  187947. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187948. png_handle_iCCP(png_ptr, info_ptr, length);
  187949. #endif
  187950. #if defined(PNG_READ_sPLT_SUPPORTED)
  187951. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187952. png_handle_sPLT(png_ptr, info_ptr, length);
  187953. #endif
  187954. #if defined(PNG_READ_tEXt_SUPPORTED)
  187955. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187956. png_handle_tEXt(png_ptr, info_ptr, length);
  187957. #endif
  187958. #if defined(PNG_READ_tIME_SUPPORTED)
  187959. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187960. png_handle_tIME(png_ptr, info_ptr, length);
  187961. #endif
  187962. #if defined(PNG_READ_tRNS_SUPPORTED)
  187963. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187964. png_handle_tRNS(png_ptr, info_ptr, length);
  187965. #endif
  187966. #if defined(PNG_READ_zTXt_SUPPORTED)
  187967. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187968. png_handle_zTXt(png_ptr, info_ptr, length);
  187969. #endif
  187970. #if defined(PNG_READ_iTXt_SUPPORTED)
  187971. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187972. png_handle_iTXt(png_ptr, info_ptr, length);
  187973. #endif
  187974. else
  187975. png_handle_unknown(png_ptr, info_ptr, length);
  187976. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187977. }
  187978. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187979. /* free all memory used by the read */
  187980. void PNGAPI
  187981. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187982. png_infopp end_info_ptr_ptr)
  187983. {
  187984. png_structp png_ptr = NULL;
  187985. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187986. #ifdef PNG_USER_MEM_SUPPORTED
  187987. png_free_ptr free_fn;
  187988. png_voidp mem_ptr;
  187989. #endif
  187990. png_debug(1, "in png_destroy_read_struct\n");
  187991. if (png_ptr_ptr != NULL)
  187992. png_ptr = *png_ptr_ptr;
  187993. if (info_ptr_ptr != NULL)
  187994. info_ptr = *info_ptr_ptr;
  187995. if (end_info_ptr_ptr != NULL)
  187996. end_info_ptr = *end_info_ptr_ptr;
  187997. #ifdef PNG_USER_MEM_SUPPORTED
  187998. free_fn = png_ptr->free_fn;
  187999. mem_ptr = png_ptr->mem_ptr;
  188000. #endif
  188001. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188002. if (info_ptr != NULL)
  188003. {
  188004. #if defined(PNG_TEXT_SUPPORTED)
  188005. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188006. #endif
  188007. #ifdef PNG_USER_MEM_SUPPORTED
  188008. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188009. (png_voidp)mem_ptr);
  188010. #else
  188011. png_destroy_struct((png_voidp)info_ptr);
  188012. #endif
  188013. *info_ptr_ptr = NULL;
  188014. }
  188015. if (end_info_ptr != NULL)
  188016. {
  188017. #if defined(PNG_READ_TEXT_SUPPORTED)
  188018. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188019. #endif
  188020. #ifdef PNG_USER_MEM_SUPPORTED
  188021. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188022. (png_voidp)mem_ptr);
  188023. #else
  188024. png_destroy_struct((png_voidp)end_info_ptr);
  188025. #endif
  188026. *end_info_ptr_ptr = NULL;
  188027. }
  188028. if (png_ptr != NULL)
  188029. {
  188030. #ifdef PNG_USER_MEM_SUPPORTED
  188031. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188032. (png_voidp)mem_ptr);
  188033. #else
  188034. png_destroy_struct((png_voidp)png_ptr);
  188035. #endif
  188036. *png_ptr_ptr = NULL;
  188037. }
  188038. }
  188039. /* free all memory used by the read (old method) */
  188040. void /* PRIVATE */
  188041. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188042. {
  188043. #ifdef PNG_SETJMP_SUPPORTED
  188044. jmp_buf tmp_jmp;
  188045. #endif
  188046. png_error_ptr error_fn;
  188047. png_error_ptr warning_fn;
  188048. png_voidp error_ptr;
  188049. #ifdef PNG_USER_MEM_SUPPORTED
  188050. png_free_ptr free_fn;
  188051. #endif
  188052. png_debug(1, "in png_read_destroy\n");
  188053. if (info_ptr != NULL)
  188054. png_info_destroy(png_ptr, info_ptr);
  188055. if (end_info_ptr != NULL)
  188056. png_info_destroy(png_ptr, end_info_ptr);
  188057. png_free(png_ptr, png_ptr->zbuf);
  188058. png_free(png_ptr, png_ptr->big_row_buf);
  188059. png_free(png_ptr, png_ptr->prev_row);
  188060. #if defined(PNG_READ_DITHER_SUPPORTED)
  188061. png_free(png_ptr, png_ptr->palette_lookup);
  188062. png_free(png_ptr, png_ptr->dither_index);
  188063. #endif
  188064. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188065. png_free(png_ptr, png_ptr->gamma_table);
  188066. #endif
  188067. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188068. png_free(png_ptr, png_ptr->gamma_from_1);
  188069. png_free(png_ptr, png_ptr->gamma_to_1);
  188070. #endif
  188071. #ifdef PNG_FREE_ME_SUPPORTED
  188072. if (png_ptr->free_me & PNG_FREE_PLTE)
  188073. png_zfree(png_ptr, png_ptr->palette);
  188074. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188075. #else
  188076. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188077. png_zfree(png_ptr, png_ptr->palette);
  188078. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188079. #endif
  188080. #if defined(PNG_tRNS_SUPPORTED) || \
  188081. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188082. #ifdef PNG_FREE_ME_SUPPORTED
  188083. if (png_ptr->free_me & PNG_FREE_TRNS)
  188084. png_free(png_ptr, png_ptr->trans);
  188085. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188086. #else
  188087. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188088. png_free(png_ptr, png_ptr->trans);
  188089. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188090. #endif
  188091. #endif
  188092. #if defined(PNG_READ_hIST_SUPPORTED)
  188093. #ifdef PNG_FREE_ME_SUPPORTED
  188094. if (png_ptr->free_me & PNG_FREE_HIST)
  188095. png_free(png_ptr, png_ptr->hist);
  188096. png_ptr->free_me &= ~PNG_FREE_HIST;
  188097. #else
  188098. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188099. png_free(png_ptr, png_ptr->hist);
  188100. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188101. #endif
  188102. #endif
  188103. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188104. if (png_ptr->gamma_16_table != NULL)
  188105. {
  188106. int i;
  188107. int istop = (1 << (8 - png_ptr->gamma_shift));
  188108. for (i = 0; i < istop; i++)
  188109. {
  188110. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188111. }
  188112. png_free(png_ptr, png_ptr->gamma_16_table);
  188113. }
  188114. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188115. if (png_ptr->gamma_16_from_1 != NULL)
  188116. {
  188117. int i;
  188118. int istop = (1 << (8 - png_ptr->gamma_shift));
  188119. for (i = 0; i < istop; i++)
  188120. {
  188121. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188122. }
  188123. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188124. }
  188125. if (png_ptr->gamma_16_to_1 != NULL)
  188126. {
  188127. int i;
  188128. int istop = (1 << (8 - png_ptr->gamma_shift));
  188129. for (i = 0; i < istop; i++)
  188130. {
  188131. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188132. }
  188133. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188134. }
  188135. #endif
  188136. #endif
  188137. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188138. png_free(png_ptr, png_ptr->time_buffer);
  188139. #endif
  188140. inflateEnd(&png_ptr->zstream);
  188141. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188142. png_free(png_ptr, png_ptr->save_buffer);
  188143. #endif
  188144. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188145. #ifdef PNG_TEXT_SUPPORTED
  188146. png_free(png_ptr, png_ptr->current_text);
  188147. #endif /* PNG_TEXT_SUPPORTED */
  188148. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188149. /* Save the important info out of the png_struct, in case it is
  188150. * being used again.
  188151. */
  188152. #ifdef PNG_SETJMP_SUPPORTED
  188153. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188154. #endif
  188155. error_fn = png_ptr->error_fn;
  188156. warning_fn = png_ptr->warning_fn;
  188157. error_ptr = png_ptr->error_ptr;
  188158. #ifdef PNG_USER_MEM_SUPPORTED
  188159. free_fn = png_ptr->free_fn;
  188160. #endif
  188161. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188162. png_ptr->error_fn = error_fn;
  188163. png_ptr->warning_fn = warning_fn;
  188164. png_ptr->error_ptr = error_ptr;
  188165. #ifdef PNG_USER_MEM_SUPPORTED
  188166. png_ptr->free_fn = free_fn;
  188167. #endif
  188168. #ifdef PNG_SETJMP_SUPPORTED
  188169. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188170. #endif
  188171. }
  188172. void PNGAPI
  188173. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188174. {
  188175. if(png_ptr == NULL) return;
  188176. png_ptr->read_row_fn = read_row_fn;
  188177. }
  188178. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188179. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188180. void PNGAPI
  188181. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188182. int transforms,
  188183. voidp params)
  188184. {
  188185. int row;
  188186. if(png_ptr == NULL) return;
  188187. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188188. /* invert the alpha channel from opacity to transparency
  188189. */
  188190. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188191. png_set_invert_alpha(png_ptr);
  188192. #endif
  188193. /* png_read_info() gives us all of the information from the
  188194. * PNG file before the first IDAT (image data chunk).
  188195. */
  188196. png_read_info(png_ptr, info_ptr);
  188197. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188198. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188199. /* -------------- image transformations start here ------------------- */
  188200. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188201. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188202. */
  188203. if (transforms & PNG_TRANSFORM_STRIP_16)
  188204. png_set_strip_16(png_ptr);
  188205. #endif
  188206. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188207. /* Strip alpha bytes from the input data without combining with
  188208. * the background (not recommended).
  188209. */
  188210. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188211. png_set_strip_alpha(png_ptr);
  188212. #endif
  188213. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188214. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188215. * byte into separate bytes (useful for paletted and grayscale images).
  188216. */
  188217. if (transforms & PNG_TRANSFORM_PACKING)
  188218. png_set_packing(png_ptr);
  188219. #endif
  188220. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188221. /* Change the order of packed pixels to least significant bit first
  188222. * (not useful if you are using png_set_packing).
  188223. */
  188224. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188225. png_set_packswap(png_ptr);
  188226. #endif
  188227. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188228. /* Expand paletted colors into true RGB triplets
  188229. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188230. * Expand paletted or RGB images with transparency to full alpha
  188231. * channels so the data will be available as RGBA quartets.
  188232. */
  188233. if (transforms & PNG_TRANSFORM_EXPAND)
  188234. if ((png_ptr->bit_depth < 8) ||
  188235. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188236. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188237. png_set_expand(png_ptr);
  188238. #endif
  188239. /* We don't handle background color or gamma transformation or dithering.
  188240. */
  188241. #if defined(PNG_READ_INVERT_SUPPORTED)
  188242. /* invert monochrome files to have 0 as white and 1 as black
  188243. */
  188244. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188245. png_set_invert_mono(png_ptr);
  188246. #endif
  188247. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188248. /* If you want to shift the pixel values from the range [0,255] or
  188249. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188250. * colors were originally in:
  188251. */
  188252. if ((transforms & PNG_TRANSFORM_SHIFT)
  188253. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188254. {
  188255. png_color_8p sig_bit;
  188256. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188257. png_set_shift(png_ptr, sig_bit);
  188258. }
  188259. #endif
  188260. #if defined(PNG_READ_BGR_SUPPORTED)
  188261. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188262. */
  188263. if (transforms & PNG_TRANSFORM_BGR)
  188264. png_set_bgr(png_ptr);
  188265. #endif
  188266. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188267. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188268. */
  188269. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188270. png_set_swap_alpha(png_ptr);
  188271. #endif
  188272. #if defined(PNG_READ_SWAP_SUPPORTED)
  188273. /* swap bytes of 16 bit files to least significant byte first
  188274. */
  188275. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188276. png_set_swap(png_ptr);
  188277. #endif
  188278. /* We don't handle adding filler bytes */
  188279. /* Optional call to gamma correct and add the background to the palette
  188280. * and update info structure. REQUIRED if you are expecting libpng to
  188281. * update the palette for you (i.e., you selected such a transform above).
  188282. */
  188283. png_read_update_info(png_ptr, info_ptr);
  188284. /* -------------- image transformations end here ------------------- */
  188285. #ifdef PNG_FREE_ME_SUPPORTED
  188286. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188287. #endif
  188288. if(info_ptr->row_pointers == NULL)
  188289. {
  188290. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188291. info_ptr->height * png_sizeof(png_bytep));
  188292. #ifdef PNG_FREE_ME_SUPPORTED
  188293. info_ptr->free_me |= PNG_FREE_ROWS;
  188294. #endif
  188295. for (row = 0; row < (int)info_ptr->height; row++)
  188296. {
  188297. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188298. png_get_rowbytes(png_ptr, info_ptr));
  188299. }
  188300. }
  188301. png_read_image(png_ptr, info_ptr->row_pointers);
  188302. info_ptr->valid |= PNG_INFO_IDAT;
  188303. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188304. png_read_end(png_ptr, info_ptr);
  188305. transforms = transforms; /* quiet compiler warnings */
  188306. params = params;
  188307. }
  188308. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188309. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188310. #endif /* PNG_READ_SUPPORTED */
  188311. /*** End of inlined file: pngread.c ***/
  188312. /*** Start of inlined file: pngpread.c ***/
  188313. /* pngpread.c - read a png file in push mode
  188314. *
  188315. * Last changed in libpng 1.2.21 October 4, 2007
  188316. * For conditions of distribution and use, see copyright notice in png.h
  188317. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188318. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188319. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188320. */
  188321. #define PNG_INTERNAL
  188322. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188323. /* push model modes */
  188324. #define PNG_READ_SIG_MODE 0
  188325. #define PNG_READ_CHUNK_MODE 1
  188326. #define PNG_READ_IDAT_MODE 2
  188327. #define PNG_SKIP_MODE 3
  188328. #define PNG_READ_tEXt_MODE 4
  188329. #define PNG_READ_zTXt_MODE 5
  188330. #define PNG_READ_DONE_MODE 6
  188331. #define PNG_READ_iTXt_MODE 7
  188332. #define PNG_ERROR_MODE 8
  188333. void PNGAPI
  188334. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188335. png_bytep buffer, png_size_t buffer_size)
  188336. {
  188337. if(png_ptr == NULL) return;
  188338. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188339. while (png_ptr->buffer_size)
  188340. {
  188341. png_process_some_data(png_ptr, info_ptr);
  188342. }
  188343. }
  188344. /* What we do with the incoming data depends on what we were previously
  188345. * doing before we ran out of data...
  188346. */
  188347. void /* PRIVATE */
  188348. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188349. {
  188350. if(png_ptr == NULL) return;
  188351. switch (png_ptr->process_mode)
  188352. {
  188353. case PNG_READ_SIG_MODE:
  188354. {
  188355. png_push_read_sig(png_ptr, info_ptr);
  188356. break;
  188357. }
  188358. case PNG_READ_CHUNK_MODE:
  188359. {
  188360. png_push_read_chunk(png_ptr, info_ptr);
  188361. break;
  188362. }
  188363. case PNG_READ_IDAT_MODE:
  188364. {
  188365. png_push_read_IDAT(png_ptr);
  188366. break;
  188367. }
  188368. #if defined(PNG_READ_tEXt_SUPPORTED)
  188369. case PNG_READ_tEXt_MODE:
  188370. {
  188371. png_push_read_tEXt(png_ptr, info_ptr);
  188372. break;
  188373. }
  188374. #endif
  188375. #if defined(PNG_READ_zTXt_SUPPORTED)
  188376. case PNG_READ_zTXt_MODE:
  188377. {
  188378. png_push_read_zTXt(png_ptr, info_ptr);
  188379. break;
  188380. }
  188381. #endif
  188382. #if defined(PNG_READ_iTXt_SUPPORTED)
  188383. case PNG_READ_iTXt_MODE:
  188384. {
  188385. png_push_read_iTXt(png_ptr, info_ptr);
  188386. break;
  188387. }
  188388. #endif
  188389. case PNG_SKIP_MODE:
  188390. {
  188391. png_push_crc_finish(png_ptr);
  188392. break;
  188393. }
  188394. default:
  188395. {
  188396. png_ptr->buffer_size = 0;
  188397. break;
  188398. }
  188399. }
  188400. }
  188401. /* Read any remaining signature bytes from the stream and compare them with
  188402. * the correct PNG signature. It is possible that this routine is called
  188403. * with bytes already read from the signature, either because they have been
  188404. * checked by the calling application, or because of multiple calls to this
  188405. * routine.
  188406. */
  188407. void /* PRIVATE */
  188408. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188409. {
  188410. png_size_t num_checked = png_ptr->sig_bytes,
  188411. num_to_check = 8 - num_checked;
  188412. if (png_ptr->buffer_size < num_to_check)
  188413. {
  188414. num_to_check = png_ptr->buffer_size;
  188415. }
  188416. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188417. num_to_check);
  188418. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188419. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188420. {
  188421. if (num_checked < 4 &&
  188422. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188423. png_error(png_ptr, "Not a PNG file");
  188424. else
  188425. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188426. }
  188427. else
  188428. {
  188429. if (png_ptr->sig_bytes >= 8)
  188430. {
  188431. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188432. }
  188433. }
  188434. }
  188435. void /* PRIVATE */
  188436. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188437. {
  188438. #ifdef PNG_USE_LOCAL_ARRAYS
  188439. PNG_CONST PNG_IHDR;
  188440. PNG_CONST PNG_IDAT;
  188441. PNG_CONST PNG_IEND;
  188442. PNG_CONST PNG_PLTE;
  188443. #if defined(PNG_READ_bKGD_SUPPORTED)
  188444. PNG_CONST PNG_bKGD;
  188445. #endif
  188446. #if defined(PNG_READ_cHRM_SUPPORTED)
  188447. PNG_CONST PNG_cHRM;
  188448. #endif
  188449. #if defined(PNG_READ_gAMA_SUPPORTED)
  188450. PNG_CONST PNG_gAMA;
  188451. #endif
  188452. #if defined(PNG_READ_hIST_SUPPORTED)
  188453. PNG_CONST PNG_hIST;
  188454. #endif
  188455. #if defined(PNG_READ_iCCP_SUPPORTED)
  188456. PNG_CONST PNG_iCCP;
  188457. #endif
  188458. #if defined(PNG_READ_iTXt_SUPPORTED)
  188459. PNG_CONST PNG_iTXt;
  188460. #endif
  188461. #if defined(PNG_READ_oFFs_SUPPORTED)
  188462. PNG_CONST PNG_oFFs;
  188463. #endif
  188464. #if defined(PNG_READ_pCAL_SUPPORTED)
  188465. PNG_CONST PNG_pCAL;
  188466. #endif
  188467. #if defined(PNG_READ_pHYs_SUPPORTED)
  188468. PNG_CONST PNG_pHYs;
  188469. #endif
  188470. #if defined(PNG_READ_sBIT_SUPPORTED)
  188471. PNG_CONST PNG_sBIT;
  188472. #endif
  188473. #if defined(PNG_READ_sCAL_SUPPORTED)
  188474. PNG_CONST PNG_sCAL;
  188475. #endif
  188476. #if defined(PNG_READ_sRGB_SUPPORTED)
  188477. PNG_CONST PNG_sRGB;
  188478. #endif
  188479. #if defined(PNG_READ_sPLT_SUPPORTED)
  188480. PNG_CONST PNG_sPLT;
  188481. #endif
  188482. #if defined(PNG_READ_tEXt_SUPPORTED)
  188483. PNG_CONST PNG_tEXt;
  188484. #endif
  188485. #if defined(PNG_READ_tIME_SUPPORTED)
  188486. PNG_CONST PNG_tIME;
  188487. #endif
  188488. #if defined(PNG_READ_tRNS_SUPPORTED)
  188489. PNG_CONST PNG_tRNS;
  188490. #endif
  188491. #if defined(PNG_READ_zTXt_SUPPORTED)
  188492. PNG_CONST PNG_zTXt;
  188493. #endif
  188494. #endif /* PNG_USE_LOCAL_ARRAYS */
  188495. /* First we make sure we have enough data for the 4 byte chunk name
  188496. * and the 4 byte chunk length before proceeding with decoding the
  188497. * chunk data. To fully decode each of these chunks, we also make
  188498. * sure we have enough data in the buffer for the 4 byte CRC at the
  188499. * end of every chunk (except IDAT, which is handled separately).
  188500. */
  188501. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188502. {
  188503. png_byte chunk_length[4];
  188504. if (png_ptr->buffer_size < 8)
  188505. {
  188506. png_push_save_buffer(png_ptr);
  188507. return;
  188508. }
  188509. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188510. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188511. png_reset_crc(png_ptr);
  188512. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188513. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188514. }
  188515. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188516. if(png_ptr->mode & PNG_AFTER_IDAT)
  188517. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188518. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188519. {
  188520. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188521. {
  188522. png_push_save_buffer(png_ptr);
  188523. return;
  188524. }
  188525. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188526. }
  188527. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188528. {
  188529. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188530. {
  188531. png_push_save_buffer(png_ptr);
  188532. return;
  188533. }
  188534. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188535. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188536. png_push_have_end(png_ptr, info_ptr);
  188537. }
  188538. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188539. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188540. {
  188541. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188542. {
  188543. png_push_save_buffer(png_ptr);
  188544. return;
  188545. }
  188546. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188547. png_ptr->mode |= PNG_HAVE_IDAT;
  188548. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188549. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188550. png_ptr->mode |= PNG_HAVE_PLTE;
  188551. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188552. {
  188553. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188554. png_error(png_ptr, "Missing IHDR before IDAT");
  188555. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188556. !(png_ptr->mode & PNG_HAVE_PLTE))
  188557. png_error(png_ptr, "Missing PLTE before IDAT");
  188558. }
  188559. }
  188560. #endif
  188561. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188562. {
  188563. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188564. {
  188565. png_push_save_buffer(png_ptr);
  188566. return;
  188567. }
  188568. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188569. }
  188570. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188571. {
  188572. /* If we reach an IDAT chunk, this means we have read all of the
  188573. * header chunks, and we can start reading the image (or if this
  188574. * is called after the image has been read - we have an error).
  188575. */
  188576. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188577. png_error(png_ptr, "Missing IHDR before IDAT");
  188578. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188579. !(png_ptr->mode & PNG_HAVE_PLTE))
  188580. png_error(png_ptr, "Missing PLTE before IDAT");
  188581. if (png_ptr->mode & PNG_HAVE_IDAT)
  188582. {
  188583. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188584. if (png_ptr->push_length == 0)
  188585. return;
  188586. if (png_ptr->mode & PNG_AFTER_IDAT)
  188587. png_error(png_ptr, "Too many IDAT's found");
  188588. }
  188589. png_ptr->idat_size = png_ptr->push_length;
  188590. png_ptr->mode |= PNG_HAVE_IDAT;
  188591. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188592. png_push_have_info(png_ptr, info_ptr);
  188593. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188594. png_ptr->zstream.next_out = png_ptr->row_buf;
  188595. return;
  188596. }
  188597. #if defined(PNG_READ_gAMA_SUPPORTED)
  188598. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188599. {
  188600. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188601. {
  188602. png_push_save_buffer(png_ptr);
  188603. return;
  188604. }
  188605. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188606. }
  188607. #endif
  188608. #if defined(PNG_READ_sBIT_SUPPORTED)
  188609. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188610. {
  188611. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188612. {
  188613. png_push_save_buffer(png_ptr);
  188614. return;
  188615. }
  188616. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188617. }
  188618. #endif
  188619. #if defined(PNG_READ_cHRM_SUPPORTED)
  188620. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188621. {
  188622. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188623. {
  188624. png_push_save_buffer(png_ptr);
  188625. return;
  188626. }
  188627. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188628. }
  188629. #endif
  188630. #if defined(PNG_READ_sRGB_SUPPORTED)
  188631. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188632. {
  188633. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188634. {
  188635. png_push_save_buffer(png_ptr);
  188636. return;
  188637. }
  188638. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188639. }
  188640. #endif
  188641. #if defined(PNG_READ_iCCP_SUPPORTED)
  188642. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188643. {
  188644. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188645. {
  188646. png_push_save_buffer(png_ptr);
  188647. return;
  188648. }
  188649. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188650. }
  188651. #endif
  188652. #if defined(PNG_READ_sPLT_SUPPORTED)
  188653. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188654. {
  188655. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188656. {
  188657. png_push_save_buffer(png_ptr);
  188658. return;
  188659. }
  188660. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188661. }
  188662. #endif
  188663. #if defined(PNG_READ_tRNS_SUPPORTED)
  188664. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188665. {
  188666. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188667. {
  188668. png_push_save_buffer(png_ptr);
  188669. return;
  188670. }
  188671. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188672. }
  188673. #endif
  188674. #if defined(PNG_READ_bKGD_SUPPORTED)
  188675. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188676. {
  188677. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188678. {
  188679. png_push_save_buffer(png_ptr);
  188680. return;
  188681. }
  188682. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188683. }
  188684. #endif
  188685. #if defined(PNG_READ_hIST_SUPPORTED)
  188686. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188687. {
  188688. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188689. {
  188690. png_push_save_buffer(png_ptr);
  188691. return;
  188692. }
  188693. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188694. }
  188695. #endif
  188696. #if defined(PNG_READ_pHYs_SUPPORTED)
  188697. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188698. {
  188699. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188700. {
  188701. png_push_save_buffer(png_ptr);
  188702. return;
  188703. }
  188704. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188705. }
  188706. #endif
  188707. #if defined(PNG_READ_oFFs_SUPPORTED)
  188708. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188709. {
  188710. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188711. {
  188712. png_push_save_buffer(png_ptr);
  188713. return;
  188714. }
  188715. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188716. }
  188717. #endif
  188718. #if defined(PNG_READ_pCAL_SUPPORTED)
  188719. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188720. {
  188721. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188722. {
  188723. png_push_save_buffer(png_ptr);
  188724. return;
  188725. }
  188726. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188727. }
  188728. #endif
  188729. #if defined(PNG_READ_sCAL_SUPPORTED)
  188730. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188731. {
  188732. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188733. {
  188734. png_push_save_buffer(png_ptr);
  188735. return;
  188736. }
  188737. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188738. }
  188739. #endif
  188740. #if defined(PNG_READ_tIME_SUPPORTED)
  188741. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188742. {
  188743. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188744. {
  188745. png_push_save_buffer(png_ptr);
  188746. return;
  188747. }
  188748. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188749. }
  188750. #endif
  188751. #if defined(PNG_READ_tEXt_SUPPORTED)
  188752. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188753. {
  188754. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188755. {
  188756. png_push_save_buffer(png_ptr);
  188757. return;
  188758. }
  188759. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188760. }
  188761. #endif
  188762. #if defined(PNG_READ_zTXt_SUPPORTED)
  188763. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188764. {
  188765. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188766. {
  188767. png_push_save_buffer(png_ptr);
  188768. return;
  188769. }
  188770. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188771. }
  188772. #endif
  188773. #if defined(PNG_READ_iTXt_SUPPORTED)
  188774. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188775. {
  188776. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188777. {
  188778. png_push_save_buffer(png_ptr);
  188779. return;
  188780. }
  188781. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188782. }
  188783. #endif
  188784. else
  188785. {
  188786. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188787. {
  188788. png_push_save_buffer(png_ptr);
  188789. return;
  188790. }
  188791. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188792. }
  188793. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188794. }
  188795. void /* PRIVATE */
  188796. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188797. {
  188798. png_ptr->process_mode = PNG_SKIP_MODE;
  188799. png_ptr->skip_length = skip;
  188800. }
  188801. void /* PRIVATE */
  188802. png_push_crc_finish(png_structp png_ptr)
  188803. {
  188804. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188805. {
  188806. png_size_t save_size;
  188807. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188808. save_size = (png_size_t)png_ptr->skip_length;
  188809. else
  188810. save_size = png_ptr->save_buffer_size;
  188811. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188812. png_ptr->skip_length -= save_size;
  188813. png_ptr->buffer_size -= save_size;
  188814. png_ptr->save_buffer_size -= save_size;
  188815. png_ptr->save_buffer_ptr += save_size;
  188816. }
  188817. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188818. {
  188819. png_size_t save_size;
  188820. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188821. save_size = (png_size_t)png_ptr->skip_length;
  188822. else
  188823. save_size = png_ptr->current_buffer_size;
  188824. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188825. png_ptr->skip_length -= save_size;
  188826. png_ptr->buffer_size -= save_size;
  188827. png_ptr->current_buffer_size -= save_size;
  188828. png_ptr->current_buffer_ptr += save_size;
  188829. }
  188830. if (!png_ptr->skip_length)
  188831. {
  188832. if (png_ptr->buffer_size < 4)
  188833. {
  188834. png_push_save_buffer(png_ptr);
  188835. return;
  188836. }
  188837. png_crc_finish(png_ptr, 0);
  188838. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188839. }
  188840. }
  188841. void PNGAPI
  188842. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188843. {
  188844. png_bytep ptr;
  188845. if(png_ptr == NULL) return;
  188846. ptr = buffer;
  188847. if (png_ptr->save_buffer_size)
  188848. {
  188849. png_size_t save_size;
  188850. if (length < png_ptr->save_buffer_size)
  188851. save_size = length;
  188852. else
  188853. save_size = png_ptr->save_buffer_size;
  188854. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188855. length -= save_size;
  188856. ptr += save_size;
  188857. png_ptr->buffer_size -= save_size;
  188858. png_ptr->save_buffer_size -= save_size;
  188859. png_ptr->save_buffer_ptr += save_size;
  188860. }
  188861. if (length && png_ptr->current_buffer_size)
  188862. {
  188863. png_size_t save_size;
  188864. if (length < png_ptr->current_buffer_size)
  188865. save_size = length;
  188866. else
  188867. save_size = png_ptr->current_buffer_size;
  188868. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188869. png_ptr->buffer_size -= save_size;
  188870. png_ptr->current_buffer_size -= save_size;
  188871. png_ptr->current_buffer_ptr += save_size;
  188872. }
  188873. }
  188874. void /* PRIVATE */
  188875. png_push_save_buffer(png_structp png_ptr)
  188876. {
  188877. if (png_ptr->save_buffer_size)
  188878. {
  188879. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188880. {
  188881. png_size_t i,istop;
  188882. png_bytep sp;
  188883. png_bytep dp;
  188884. istop = png_ptr->save_buffer_size;
  188885. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188886. i < istop; i++, sp++, dp++)
  188887. {
  188888. *dp = *sp;
  188889. }
  188890. }
  188891. }
  188892. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188893. png_ptr->save_buffer_max)
  188894. {
  188895. png_size_t new_max;
  188896. png_bytep old_buffer;
  188897. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188898. (png_ptr->current_buffer_size + 256))
  188899. {
  188900. png_error(png_ptr, "Potential overflow of save_buffer");
  188901. }
  188902. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188903. old_buffer = png_ptr->save_buffer;
  188904. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188905. (png_uint_32)new_max);
  188906. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188907. png_free(png_ptr, old_buffer);
  188908. png_ptr->save_buffer_max = new_max;
  188909. }
  188910. if (png_ptr->current_buffer_size)
  188911. {
  188912. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188913. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188914. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188915. png_ptr->current_buffer_size = 0;
  188916. }
  188917. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188918. png_ptr->buffer_size = 0;
  188919. }
  188920. void /* PRIVATE */
  188921. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188922. png_size_t buffer_length)
  188923. {
  188924. png_ptr->current_buffer = buffer;
  188925. png_ptr->current_buffer_size = buffer_length;
  188926. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188927. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188928. }
  188929. void /* PRIVATE */
  188930. png_push_read_IDAT(png_structp png_ptr)
  188931. {
  188932. #ifdef PNG_USE_LOCAL_ARRAYS
  188933. PNG_CONST PNG_IDAT;
  188934. #endif
  188935. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188936. {
  188937. png_byte chunk_length[4];
  188938. if (png_ptr->buffer_size < 8)
  188939. {
  188940. png_push_save_buffer(png_ptr);
  188941. return;
  188942. }
  188943. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188944. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188945. png_reset_crc(png_ptr);
  188946. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188947. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188948. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188949. {
  188950. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188951. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188952. png_error(png_ptr, "Not enough compressed data");
  188953. return;
  188954. }
  188955. png_ptr->idat_size = png_ptr->push_length;
  188956. }
  188957. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188958. {
  188959. png_size_t save_size;
  188960. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188961. {
  188962. save_size = (png_size_t)png_ptr->idat_size;
  188963. /* check for overflow */
  188964. if((png_uint_32)save_size != png_ptr->idat_size)
  188965. png_error(png_ptr, "save_size overflowed in pngpread");
  188966. }
  188967. else
  188968. save_size = png_ptr->save_buffer_size;
  188969. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188970. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188971. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188972. png_ptr->idat_size -= save_size;
  188973. png_ptr->buffer_size -= save_size;
  188974. png_ptr->save_buffer_size -= save_size;
  188975. png_ptr->save_buffer_ptr += save_size;
  188976. }
  188977. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188978. {
  188979. png_size_t save_size;
  188980. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188981. {
  188982. save_size = (png_size_t)png_ptr->idat_size;
  188983. /* check for overflow */
  188984. if((png_uint_32)save_size != png_ptr->idat_size)
  188985. png_error(png_ptr, "save_size overflowed in pngpread");
  188986. }
  188987. else
  188988. save_size = png_ptr->current_buffer_size;
  188989. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188990. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188991. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188992. png_ptr->idat_size -= save_size;
  188993. png_ptr->buffer_size -= save_size;
  188994. png_ptr->current_buffer_size -= save_size;
  188995. png_ptr->current_buffer_ptr += save_size;
  188996. }
  188997. if (!png_ptr->idat_size)
  188998. {
  188999. if (png_ptr->buffer_size < 4)
  189000. {
  189001. png_push_save_buffer(png_ptr);
  189002. return;
  189003. }
  189004. png_crc_finish(png_ptr, 0);
  189005. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189006. png_ptr->mode |= PNG_AFTER_IDAT;
  189007. }
  189008. }
  189009. void /* PRIVATE */
  189010. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189011. png_size_t buffer_length)
  189012. {
  189013. int ret;
  189014. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189015. png_error(png_ptr, "Extra compression data");
  189016. png_ptr->zstream.next_in = buffer;
  189017. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189018. for(;;)
  189019. {
  189020. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189021. if (ret != Z_OK)
  189022. {
  189023. if (ret == Z_STREAM_END)
  189024. {
  189025. if (png_ptr->zstream.avail_in)
  189026. png_error(png_ptr, "Extra compressed data");
  189027. if (!(png_ptr->zstream.avail_out))
  189028. {
  189029. png_push_process_row(png_ptr);
  189030. }
  189031. png_ptr->mode |= PNG_AFTER_IDAT;
  189032. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189033. break;
  189034. }
  189035. else if (ret == Z_BUF_ERROR)
  189036. break;
  189037. else
  189038. png_error(png_ptr, "Decompression Error");
  189039. }
  189040. if (!(png_ptr->zstream.avail_out))
  189041. {
  189042. if ((
  189043. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189044. png_ptr->interlaced && png_ptr->pass > 6) ||
  189045. (!png_ptr->interlaced &&
  189046. #endif
  189047. png_ptr->row_number == png_ptr->num_rows))
  189048. {
  189049. if (png_ptr->zstream.avail_in)
  189050. {
  189051. png_warning(png_ptr, "Too much data in IDAT chunks");
  189052. }
  189053. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189054. break;
  189055. }
  189056. png_push_process_row(png_ptr);
  189057. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189058. png_ptr->zstream.next_out = png_ptr->row_buf;
  189059. }
  189060. else
  189061. break;
  189062. }
  189063. }
  189064. void /* PRIVATE */
  189065. png_push_process_row(png_structp png_ptr)
  189066. {
  189067. png_ptr->row_info.color_type = png_ptr->color_type;
  189068. png_ptr->row_info.width = png_ptr->iwidth;
  189069. png_ptr->row_info.channels = png_ptr->channels;
  189070. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189071. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189072. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189073. png_ptr->row_info.width);
  189074. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189075. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189076. (int)(png_ptr->row_buf[0]));
  189077. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189078. png_ptr->rowbytes + 1);
  189079. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189080. png_do_read_transformations(png_ptr);
  189081. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189082. /* blow up interlaced rows to full size */
  189083. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189084. {
  189085. if (png_ptr->pass < 6)
  189086. /* old interface (pre-1.0.9):
  189087. png_do_read_interlace(&(png_ptr->row_info),
  189088. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189089. */
  189090. png_do_read_interlace(png_ptr);
  189091. switch (png_ptr->pass)
  189092. {
  189093. case 0:
  189094. {
  189095. int i;
  189096. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189097. {
  189098. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189099. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189100. }
  189101. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189102. {
  189103. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189104. {
  189105. png_push_have_row(png_ptr, png_bytep_NULL);
  189106. png_read_push_finish_row(png_ptr);
  189107. }
  189108. }
  189109. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189110. {
  189111. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189112. {
  189113. png_push_have_row(png_ptr, png_bytep_NULL);
  189114. png_read_push_finish_row(png_ptr);
  189115. }
  189116. }
  189117. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189118. {
  189119. png_push_have_row(png_ptr, png_bytep_NULL);
  189120. png_read_push_finish_row(png_ptr);
  189121. }
  189122. break;
  189123. }
  189124. case 1:
  189125. {
  189126. int i;
  189127. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189128. {
  189129. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189130. png_read_push_finish_row(png_ptr);
  189131. }
  189132. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189133. {
  189134. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189135. {
  189136. png_push_have_row(png_ptr, png_bytep_NULL);
  189137. png_read_push_finish_row(png_ptr);
  189138. }
  189139. }
  189140. break;
  189141. }
  189142. case 2:
  189143. {
  189144. int i;
  189145. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189146. {
  189147. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189148. png_read_push_finish_row(png_ptr);
  189149. }
  189150. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189151. {
  189152. png_push_have_row(png_ptr, png_bytep_NULL);
  189153. png_read_push_finish_row(png_ptr);
  189154. }
  189155. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189156. {
  189157. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189158. {
  189159. png_push_have_row(png_ptr, png_bytep_NULL);
  189160. png_read_push_finish_row(png_ptr);
  189161. }
  189162. }
  189163. break;
  189164. }
  189165. case 3:
  189166. {
  189167. int i;
  189168. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189169. {
  189170. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189171. png_read_push_finish_row(png_ptr);
  189172. }
  189173. if (png_ptr->pass == 4) /* skip top two generated rows */
  189174. {
  189175. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189176. {
  189177. png_push_have_row(png_ptr, png_bytep_NULL);
  189178. png_read_push_finish_row(png_ptr);
  189179. }
  189180. }
  189181. break;
  189182. }
  189183. case 4:
  189184. {
  189185. int i;
  189186. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189187. {
  189188. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189189. png_read_push_finish_row(png_ptr);
  189190. }
  189191. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189192. {
  189193. png_push_have_row(png_ptr, png_bytep_NULL);
  189194. png_read_push_finish_row(png_ptr);
  189195. }
  189196. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189197. {
  189198. png_push_have_row(png_ptr, png_bytep_NULL);
  189199. png_read_push_finish_row(png_ptr);
  189200. }
  189201. break;
  189202. }
  189203. case 5:
  189204. {
  189205. int i;
  189206. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189207. {
  189208. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189209. png_read_push_finish_row(png_ptr);
  189210. }
  189211. if (png_ptr->pass == 6) /* skip top generated row */
  189212. {
  189213. png_push_have_row(png_ptr, png_bytep_NULL);
  189214. png_read_push_finish_row(png_ptr);
  189215. }
  189216. break;
  189217. }
  189218. case 6:
  189219. {
  189220. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189221. png_read_push_finish_row(png_ptr);
  189222. if (png_ptr->pass != 6)
  189223. break;
  189224. png_push_have_row(png_ptr, png_bytep_NULL);
  189225. png_read_push_finish_row(png_ptr);
  189226. }
  189227. }
  189228. }
  189229. else
  189230. #endif
  189231. {
  189232. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189233. png_read_push_finish_row(png_ptr);
  189234. }
  189235. }
  189236. void /* PRIVATE */
  189237. png_read_push_finish_row(png_structp png_ptr)
  189238. {
  189239. #ifdef PNG_USE_LOCAL_ARRAYS
  189240. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189241. /* start of interlace block */
  189242. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189243. /* offset to next interlace block */
  189244. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189245. /* start of interlace block in the y direction */
  189246. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189247. /* offset to next interlace block in the y direction */
  189248. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189249. /* Height of interlace block. This is not currently used - if you need
  189250. * it, uncomment it here and in png.h
  189251. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189252. */
  189253. #endif
  189254. png_ptr->row_number++;
  189255. if (png_ptr->row_number < png_ptr->num_rows)
  189256. return;
  189257. if (png_ptr->interlaced)
  189258. {
  189259. png_ptr->row_number = 0;
  189260. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189261. png_ptr->rowbytes + 1);
  189262. do
  189263. {
  189264. png_ptr->pass++;
  189265. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189266. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189267. (png_ptr->pass == 5 && png_ptr->width < 2))
  189268. png_ptr->pass++;
  189269. if (png_ptr->pass > 7)
  189270. png_ptr->pass--;
  189271. if (png_ptr->pass >= 7)
  189272. break;
  189273. png_ptr->iwidth = (png_ptr->width +
  189274. png_pass_inc[png_ptr->pass] - 1 -
  189275. png_pass_start[png_ptr->pass]) /
  189276. png_pass_inc[png_ptr->pass];
  189277. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189278. png_ptr->iwidth) + 1;
  189279. if (png_ptr->transformations & PNG_INTERLACE)
  189280. break;
  189281. png_ptr->num_rows = (png_ptr->height +
  189282. png_pass_yinc[png_ptr->pass] - 1 -
  189283. png_pass_ystart[png_ptr->pass]) /
  189284. png_pass_yinc[png_ptr->pass];
  189285. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189286. }
  189287. }
  189288. #if defined(PNG_READ_tEXt_SUPPORTED)
  189289. void /* PRIVATE */
  189290. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189291. length)
  189292. {
  189293. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189294. {
  189295. png_error(png_ptr, "Out of place tEXt");
  189296. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189297. }
  189298. #ifdef PNG_MAX_MALLOC_64K
  189299. png_ptr->skip_length = 0; /* This may not be necessary */
  189300. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189301. {
  189302. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189303. png_ptr->skip_length = length - (png_uint_32)65535L;
  189304. length = (png_uint_32)65535L;
  189305. }
  189306. #endif
  189307. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189308. (png_uint_32)(length+1));
  189309. png_ptr->current_text[length] = '\0';
  189310. png_ptr->current_text_ptr = png_ptr->current_text;
  189311. png_ptr->current_text_size = (png_size_t)length;
  189312. png_ptr->current_text_left = (png_size_t)length;
  189313. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189314. }
  189315. void /* PRIVATE */
  189316. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189317. {
  189318. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189319. {
  189320. png_size_t text_size;
  189321. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189322. text_size = png_ptr->buffer_size;
  189323. else
  189324. text_size = png_ptr->current_text_left;
  189325. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189326. png_ptr->current_text_left -= text_size;
  189327. png_ptr->current_text_ptr += text_size;
  189328. }
  189329. if (!(png_ptr->current_text_left))
  189330. {
  189331. png_textp text_ptr;
  189332. png_charp text;
  189333. png_charp key;
  189334. int ret;
  189335. if (png_ptr->buffer_size < 4)
  189336. {
  189337. png_push_save_buffer(png_ptr);
  189338. return;
  189339. }
  189340. png_push_crc_finish(png_ptr);
  189341. #if defined(PNG_MAX_MALLOC_64K)
  189342. if (png_ptr->skip_length)
  189343. return;
  189344. #endif
  189345. key = png_ptr->current_text;
  189346. for (text = key; *text; text++)
  189347. /* empty loop */ ;
  189348. if (text < key + png_ptr->current_text_size)
  189349. text++;
  189350. text_ptr = (png_textp)png_malloc(png_ptr,
  189351. (png_uint_32)png_sizeof(png_text));
  189352. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189353. text_ptr->key = key;
  189354. #ifdef PNG_iTXt_SUPPORTED
  189355. text_ptr->lang = NULL;
  189356. text_ptr->lang_key = NULL;
  189357. #endif
  189358. text_ptr->text = text;
  189359. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189360. png_free(png_ptr, key);
  189361. png_free(png_ptr, text_ptr);
  189362. png_ptr->current_text = NULL;
  189363. if (ret)
  189364. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189365. }
  189366. }
  189367. #endif
  189368. #if defined(PNG_READ_zTXt_SUPPORTED)
  189369. void /* PRIVATE */
  189370. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189371. length)
  189372. {
  189373. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189374. {
  189375. png_error(png_ptr, "Out of place zTXt");
  189376. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189377. }
  189378. #ifdef PNG_MAX_MALLOC_64K
  189379. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189380. * to be able to store the uncompressed data. Actually, the threshold
  189381. * is probably around 32K, but it isn't as definite as 64K is.
  189382. */
  189383. if (length > (png_uint_32)65535L)
  189384. {
  189385. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189386. png_push_crc_skip(png_ptr, length);
  189387. return;
  189388. }
  189389. #endif
  189390. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189391. (png_uint_32)(length+1));
  189392. png_ptr->current_text[length] = '\0';
  189393. png_ptr->current_text_ptr = png_ptr->current_text;
  189394. png_ptr->current_text_size = (png_size_t)length;
  189395. png_ptr->current_text_left = (png_size_t)length;
  189396. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189397. }
  189398. void /* PRIVATE */
  189399. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189400. {
  189401. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189402. {
  189403. png_size_t text_size;
  189404. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189405. text_size = png_ptr->buffer_size;
  189406. else
  189407. text_size = png_ptr->current_text_left;
  189408. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189409. png_ptr->current_text_left -= text_size;
  189410. png_ptr->current_text_ptr += text_size;
  189411. }
  189412. if (!(png_ptr->current_text_left))
  189413. {
  189414. png_textp text_ptr;
  189415. png_charp text;
  189416. png_charp key;
  189417. int ret;
  189418. png_size_t text_size, key_size;
  189419. if (png_ptr->buffer_size < 4)
  189420. {
  189421. png_push_save_buffer(png_ptr);
  189422. return;
  189423. }
  189424. png_push_crc_finish(png_ptr);
  189425. key = png_ptr->current_text;
  189426. for (text = key; *text; text++)
  189427. /* empty loop */ ;
  189428. /* zTXt can't have zero text */
  189429. if (text >= key + png_ptr->current_text_size)
  189430. {
  189431. png_ptr->current_text = NULL;
  189432. png_free(png_ptr, key);
  189433. return;
  189434. }
  189435. text++;
  189436. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189437. {
  189438. png_ptr->current_text = NULL;
  189439. png_free(png_ptr, key);
  189440. return;
  189441. }
  189442. text++;
  189443. png_ptr->zstream.next_in = (png_bytep )text;
  189444. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189445. (text - key));
  189446. png_ptr->zstream.next_out = png_ptr->zbuf;
  189447. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189448. key_size = text - key;
  189449. text_size = 0;
  189450. text = NULL;
  189451. ret = Z_STREAM_END;
  189452. while (png_ptr->zstream.avail_in)
  189453. {
  189454. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189455. if (ret != Z_OK && ret != Z_STREAM_END)
  189456. {
  189457. inflateReset(&png_ptr->zstream);
  189458. png_ptr->zstream.avail_in = 0;
  189459. png_ptr->current_text = NULL;
  189460. png_free(png_ptr, key);
  189461. png_free(png_ptr, text);
  189462. return;
  189463. }
  189464. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189465. {
  189466. if (text == NULL)
  189467. {
  189468. text = (png_charp)png_malloc(png_ptr,
  189469. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189470. + key_size + 1));
  189471. png_memcpy(text + key_size, png_ptr->zbuf,
  189472. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189473. png_memcpy(text, key, key_size);
  189474. text_size = key_size + png_ptr->zbuf_size -
  189475. png_ptr->zstream.avail_out;
  189476. *(text + text_size) = '\0';
  189477. }
  189478. else
  189479. {
  189480. png_charp tmp;
  189481. tmp = text;
  189482. text = (png_charp)png_malloc(png_ptr, text_size +
  189483. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189484. + 1));
  189485. png_memcpy(text, tmp, text_size);
  189486. png_free(png_ptr, tmp);
  189487. png_memcpy(text + text_size, png_ptr->zbuf,
  189488. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189489. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189490. *(text + text_size) = '\0';
  189491. }
  189492. if (ret != Z_STREAM_END)
  189493. {
  189494. png_ptr->zstream.next_out = png_ptr->zbuf;
  189495. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189496. }
  189497. }
  189498. else
  189499. {
  189500. break;
  189501. }
  189502. if (ret == Z_STREAM_END)
  189503. break;
  189504. }
  189505. inflateReset(&png_ptr->zstream);
  189506. png_ptr->zstream.avail_in = 0;
  189507. if (ret != Z_STREAM_END)
  189508. {
  189509. png_ptr->current_text = NULL;
  189510. png_free(png_ptr, key);
  189511. png_free(png_ptr, text);
  189512. return;
  189513. }
  189514. png_ptr->current_text = NULL;
  189515. png_free(png_ptr, key);
  189516. key = text;
  189517. text += key_size;
  189518. text_ptr = (png_textp)png_malloc(png_ptr,
  189519. (png_uint_32)png_sizeof(png_text));
  189520. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189521. text_ptr->key = key;
  189522. #ifdef PNG_iTXt_SUPPORTED
  189523. text_ptr->lang = NULL;
  189524. text_ptr->lang_key = NULL;
  189525. #endif
  189526. text_ptr->text = text;
  189527. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189528. png_free(png_ptr, key);
  189529. png_free(png_ptr, text_ptr);
  189530. if (ret)
  189531. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189532. }
  189533. }
  189534. #endif
  189535. #if defined(PNG_READ_iTXt_SUPPORTED)
  189536. void /* PRIVATE */
  189537. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189538. length)
  189539. {
  189540. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189541. {
  189542. png_error(png_ptr, "Out of place iTXt");
  189543. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189544. }
  189545. #ifdef PNG_MAX_MALLOC_64K
  189546. png_ptr->skip_length = 0; /* This may not be necessary */
  189547. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189548. {
  189549. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189550. png_ptr->skip_length = length - (png_uint_32)65535L;
  189551. length = (png_uint_32)65535L;
  189552. }
  189553. #endif
  189554. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189555. (png_uint_32)(length+1));
  189556. png_ptr->current_text[length] = '\0';
  189557. png_ptr->current_text_ptr = png_ptr->current_text;
  189558. png_ptr->current_text_size = (png_size_t)length;
  189559. png_ptr->current_text_left = (png_size_t)length;
  189560. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189561. }
  189562. void /* PRIVATE */
  189563. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189564. {
  189565. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189566. {
  189567. png_size_t text_size;
  189568. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189569. text_size = png_ptr->buffer_size;
  189570. else
  189571. text_size = png_ptr->current_text_left;
  189572. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189573. png_ptr->current_text_left -= text_size;
  189574. png_ptr->current_text_ptr += text_size;
  189575. }
  189576. if (!(png_ptr->current_text_left))
  189577. {
  189578. png_textp text_ptr;
  189579. png_charp key;
  189580. int comp_flag;
  189581. png_charp lang;
  189582. png_charp lang_key;
  189583. png_charp text;
  189584. int ret;
  189585. if (png_ptr->buffer_size < 4)
  189586. {
  189587. png_push_save_buffer(png_ptr);
  189588. return;
  189589. }
  189590. png_push_crc_finish(png_ptr);
  189591. #if defined(PNG_MAX_MALLOC_64K)
  189592. if (png_ptr->skip_length)
  189593. return;
  189594. #endif
  189595. key = png_ptr->current_text;
  189596. for (lang = key; *lang; lang++)
  189597. /* empty loop */ ;
  189598. if (lang < key + png_ptr->current_text_size - 3)
  189599. lang++;
  189600. comp_flag = *lang++;
  189601. lang++; /* skip comp_type, always zero */
  189602. for (lang_key = lang; *lang_key; lang_key++)
  189603. /* empty loop */ ;
  189604. lang_key++; /* skip NUL separator */
  189605. text=lang_key;
  189606. if (lang_key < key + png_ptr->current_text_size - 1)
  189607. {
  189608. for (; *text; text++)
  189609. /* empty loop */ ;
  189610. }
  189611. if (text < key + png_ptr->current_text_size)
  189612. text++;
  189613. text_ptr = (png_textp)png_malloc(png_ptr,
  189614. (png_uint_32)png_sizeof(png_text));
  189615. text_ptr->compression = comp_flag + 2;
  189616. text_ptr->key = key;
  189617. text_ptr->lang = lang;
  189618. text_ptr->lang_key = lang_key;
  189619. text_ptr->text = text;
  189620. text_ptr->text_length = 0;
  189621. text_ptr->itxt_length = png_strlen(text);
  189622. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189623. png_ptr->current_text = NULL;
  189624. png_free(png_ptr, text_ptr);
  189625. if (ret)
  189626. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189627. }
  189628. }
  189629. #endif
  189630. /* This function is called when we haven't found a handler for this
  189631. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189632. * name or a critical chunk), the chunk is (currently) silently ignored.
  189633. */
  189634. void /* PRIVATE */
  189635. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189636. length)
  189637. {
  189638. png_uint_32 skip=0;
  189639. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189640. if (!(png_ptr->chunk_name[0] & 0x20))
  189641. {
  189642. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189643. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189644. PNG_HANDLE_CHUNK_ALWAYS
  189645. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189646. && png_ptr->read_user_chunk_fn == NULL
  189647. #endif
  189648. )
  189649. #endif
  189650. png_chunk_error(png_ptr, "unknown critical chunk");
  189651. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189652. }
  189653. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189654. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189655. {
  189656. #ifdef PNG_MAX_MALLOC_64K
  189657. if (length > (png_uint_32)65535L)
  189658. {
  189659. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189660. skip = length - (png_uint_32)65535L;
  189661. length = (png_uint_32)65535L;
  189662. }
  189663. #endif
  189664. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189665. (png_charp)png_ptr->chunk_name, 5);
  189666. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189667. png_ptr->unknown_chunk.size = (png_size_t)length;
  189668. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189669. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189670. if(png_ptr->read_user_chunk_fn != NULL)
  189671. {
  189672. /* callback to user unknown chunk handler */
  189673. int ret;
  189674. ret = (*(png_ptr->read_user_chunk_fn))
  189675. (png_ptr, &png_ptr->unknown_chunk);
  189676. if (ret < 0)
  189677. png_chunk_error(png_ptr, "error in user chunk");
  189678. if (ret == 0)
  189679. {
  189680. if (!(png_ptr->chunk_name[0] & 0x20))
  189681. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189682. PNG_HANDLE_CHUNK_ALWAYS)
  189683. png_chunk_error(png_ptr, "unknown critical chunk");
  189684. png_set_unknown_chunks(png_ptr, info_ptr,
  189685. &png_ptr->unknown_chunk, 1);
  189686. }
  189687. }
  189688. #else
  189689. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189690. #endif
  189691. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189692. png_ptr->unknown_chunk.data = NULL;
  189693. }
  189694. else
  189695. #endif
  189696. skip=length;
  189697. png_push_crc_skip(png_ptr, skip);
  189698. }
  189699. void /* PRIVATE */
  189700. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189701. {
  189702. if (png_ptr->info_fn != NULL)
  189703. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189704. }
  189705. void /* PRIVATE */
  189706. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189707. {
  189708. if (png_ptr->end_fn != NULL)
  189709. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189710. }
  189711. void /* PRIVATE */
  189712. png_push_have_row(png_structp png_ptr, png_bytep row)
  189713. {
  189714. if (png_ptr->row_fn != NULL)
  189715. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189716. (int)png_ptr->pass);
  189717. }
  189718. void PNGAPI
  189719. png_progressive_combine_row (png_structp png_ptr,
  189720. png_bytep old_row, png_bytep new_row)
  189721. {
  189722. #ifdef PNG_USE_LOCAL_ARRAYS
  189723. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189724. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189725. #endif
  189726. if(png_ptr == NULL) return;
  189727. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189728. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189729. }
  189730. void PNGAPI
  189731. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189732. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189733. png_progressive_end_ptr end_fn)
  189734. {
  189735. if(png_ptr == NULL) return;
  189736. png_ptr->info_fn = info_fn;
  189737. png_ptr->row_fn = row_fn;
  189738. png_ptr->end_fn = end_fn;
  189739. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189740. }
  189741. png_voidp PNGAPI
  189742. png_get_progressive_ptr(png_structp png_ptr)
  189743. {
  189744. if(png_ptr == NULL) return (NULL);
  189745. return png_ptr->io_ptr;
  189746. }
  189747. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189748. /*** End of inlined file: pngpread.c ***/
  189749. /*** Start of inlined file: pngrio.c ***/
  189750. /* pngrio.c - functions for data input
  189751. *
  189752. * Last changed in libpng 1.2.13 November 13, 2006
  189753. * For conditions of distribution and use, see copyright notice in png.h
  189754. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189755. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189756. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189757. *
  189758. * This file provides a location for all input. Users who need
  189759. * special handling are expected to write a function that has the same
  189760. * arguments as this and performs a similar function, but that possibly
  189761. * has a different input method. Note that you shouldn't change this
  189762. * function, but rather write a replacement function and then make
  189763. * libpng use it at run time with png_set_read_fn(...).
  189764. */
  189765. #define PNG_INTERNAL
  189766. #if defined(PNG_READ_SUPPORTED)
  189767. /* Read the data from whatever input you are using. The default routine
  189768. reads from a file pointer. Note that this routine sometimes gets called
  189769. with very small lengths, so you should implement some kind of simple
  189770. buffering if you are using unbuffered reads. This should never be asked
  189771. to read more then 64K on a 16 bit machine. */
  189772. void /* PRIVATE */
  189773. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189774. {
  189775. png_debug1(4,"reading %d bytes\n", (int)length);
  189776. if (png_ptr->read_data_fn != NULL)
  189777. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189778. else
  189779. png_error(png_ptr, "Call to NULL read function");
  189780. }
  189781. #if !defined(PNG_NO_STDIO)
  189782. /* This is the function that does the actual reading of data. If you are
  189783. not reading from a standard C stream, you should create a replacement
  189784. read_data function and use it at run time with png_set_read_fn(), rather
  189785. than changing the library. */
  189786. #ifndef USE_FAR_KEYWORD
  189787. void PNGAPI
  189788. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189789. {
  189790. png_size_t check;
  189791. if(png_ptr == NULL) return;
  189792. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189793. * instead of an int, which is what fread() actually returns.
  189794. */
  189795. #if defined(_WIN32_WCE)
  189796. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189797. check = 0;
  189798. #else
  189799. check = (png_size_t)fread(data, (png_size_t)1, length,
  189800. (png_FILE_p)png_ptr->io_ptr);
  189801. #endif
  189802. if (check != length)
  189803. png_error(png_ptr, "Read Error");
  189804. }
  189805. #else
  189806. /* this is the model-independent version. Since the standard I/O library
  189807. can't handle far buffers in the medium and small models, we have to copy
  189808. the data.
  189809. */
  189810. #define NEAR_BUF_SIZE 1024
  189811. #define MIN(a,b) (a <= b ? a : b)
  189812. static void PNGAPI
  189813. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189814. {
  189815. int check;
  189816. png_byte *n_data;
  189817. png_FILE_p io_ptr;
  189818. if(png_ptr == NULL) return;
  189819. /* Check if data really is near. If so, use usual code. */
  189820. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189821. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189822. if ((png_bytep)n_data == data)
  189823. {
  189824. #if defined(_WIN32_WCE)
  189825. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189826. check = 0;
  189827. #else
  189828. check = fread(n_data, 1, length, io_ptr);
  189829. #endif
  189830. }
  189831. else
  189832. {
  189833. png_byte buf[NEAR_BUF_SIZE];
  189834. png_size_t read, remaining, err;
  189835. check = 0;
  189836. remaining = length;
  189837. do
  189838. {
  189839. read = MIN(NEAR_BUF_SIZE, remaining);
  189840. #if defined(_WIN32_WCE)
  189841. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189842. err = 0;
  189843. #else
  189844. err = fread(buf, (png_size_t)1, read, io_ptr);
  189845. #endif
  189846. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189847. if(err != read)
  189848. break;
  189849. else
  189850. check += err;
  189851. data += read;
  189852. remaining -= read;
  189853. }
  189854. while (remaining != 0);
  189855. }
  189856. if ((png_uint_32)check != (png_uint_32)length)
  189857. png_error(png_ptr, "read Error");
  189858. }
  189859. #endif
  189860. #endif
  189861. /* This function allows the application to supply a new input function
  189862. for libpng if standard C streams aren't being used.
  189863. This function takes as its arguments:
  189864. png_ptr - pointer to a png input data structure
  189865. io_ptr - pointer to user supplied structure containing info about
  189866. the input functions. May be NULL.
  189867. read_data_fn - pointer to a new input function that takes as its
  189868. arguments a pointer to a png_struct, a pointer to
  189869. a location where input data can be stored, and a 32-bit
  189870. unsigned int that is the number of bytes to be read.
  189871. To exit and output any fatal error messages the new write
  189872. function should call png_error(png_ptr, "Error msg"). */
  189873. void PNGAPI
  189874. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189875. png_rw_ptr read_data_fn)
  189876. {
  189877. if(png_ptr == NULL) return;
  189878. png_ptr->io_ptr = io_ptr;
  189879. #if !defined(PNG_NO_STDIO)
  189880. if (read_data_fn != NULL)
  189881. png_ptr->read_data_fn = read_data_fn;
  189882. else
  189883. png_ptr->read_data_fn = png_default_read_data;
  189884. #else
  189885. png_ptr->read_data_fn = read_data_fn;
  189886. #endif
  189887. /* It is an error to write to a read device */
  189888. if (png_ptr->write_data_fn != NULL)
  189889. {
  189890. png_ptr->write_data_fn = NULL;
  189891. png_warning(png_ptr,
  189892. "It's an error to set both read_data_fn and write_data_fn in the ");
  189893. png_warning(png_ptr,
  189894. "same structure. Resetting write_data_fn to NULL.");
  189895. }
  189896. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189897. png_ptr->output_flush_fn = NULL;
  189898. #endif
  189899. }
  189900. #endif /* PNG_READ_SUPPORTED */
  189901. /*** End of inlined file: pngrio.c ***/
  189902. /*** Start of inlined file: pngrtran.c ***/
  189903. /* pngrtran.c - transforms the data in a row for PNG readers
  189904. *
  189905. * Last changed in libpng 1.2.21 [October 4, 2007]
  189906. * For conditions of distribution and use, see copyright notice in png.h
  189907. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189908. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189909. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189910. *
  189911. * This file contains functions optionally called by an application
  189912. * in order to tell libpng how to handle data when reading a PNG.
  189913. * Transformations that are used in both reading and writing are
  189914. * in pngtrans.c.
  189915. */
  189916. #define PNG_INTERNAL
  189917. #if defined(PNG_READ_SUPPORTED)
  189918. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189919. void PNGAPI
  189920. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189921. {
  189922. png_debug(1, "in png_set_crc_action\n");
  189923. /* Tell libpng how we react to CRC errors in critical chunks */
  189924. if(png_ptr == NULL) return;
  189925. switch (crit_action)
  189926. {
  189927. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189928. break;
  189929. case PNG_CRC_WARN_USE: /* warn/use data */
  189930. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189931. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189932. break;
  189933. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189934. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189935. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189936. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189937. break;
  189938. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189939. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189940. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189941. case PNG_CRC_DEFAULT:
  189942. default:
  189943. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189944. break;
  189945. }
  189946. switch (ancil_action)
  189947. {
  189948. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189949. break;
  189950. case PNG_CRC_WARN_USE: /* warn/use data */
  189951. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189952. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189953. break;
  189954. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189955. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189956. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189957. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189958. break;
  189959. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189960. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189961. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189962. break;
  189963. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189964. case PNG_CRC_DEFAULT:
  189965. default:
  189966. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189967. break;
  189968. }
  189969. }
  189970. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189971. defined(PNG_FLOATING_POINT_SUPPORTED)
  189972. /* handle alpha and tRNS via a background color */
  189973. void PNGAPI
  189974. png_set_background(png_structp png_ptr,
  189975. png_color_16p background_color, int background_gamma_code,
  189976. int need_expand, double background_gamma)
  189977. {
  189978. png_debug(1, "in png_set_background\n");
  189979. if(png_ptr == NULL) return;
  189980. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189981. {
  189982. png_warning(png_ptr, "Application must supply a known background gamma");
  189983. return;
  189984. }
  189985. png_ptr->transformations |= PNG_BACKGROUND;
  189986. png_memcpy(&(png_ptr->background), background_color,
  189987. png_sizeof(png_color_16));
  189988. png_ptr->background_gamma = (float)background_gamma;
  189989. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189990. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189991. }
  189992. #endif
  189993. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189994. /* strip 16 bit depth files to 8 bit depth */
  189995. void PNGAPI
  189996. png_set_strip_16(png_structp png_ptr)
  189997. {
  189998. png_debug(1, "in png_set_strip_16\n");
  189999. if(png_ptr == NULL) return;
  190000. png_ptr->transformations |= PNG_16_TO_8;
  190001. }
  190002. #endif
  190003. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190004. void PNGAPI
  190005. png_set_strip_alpha(png_structp png_ptr)
  190006. {
  190007. png_debug(1, "in png_set_strip_alpha\n");
  190008. if(png_ptr == NULL) return;
  190009. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190010. }
  190011. #endif
  190012. #if defined(PNG_READ_DITHER_SUPPORTED)
  190013. /* Dither file to 8 bit. Supply a palette, the current number
  190014. * of elements in the palette, the maximum number of elements
  190015. * allowed, and a histogram if possible. If the current number
  190016. * of colors is greater then the maximum number, the palette will be
  190017. * modified to fit in the maximum number. "full_dither" indicates
  190018. * whether we need a dithering cube set up for RGB images, or if we
  190019. * simply are reducing the number of colors in a paletted image.
  190020. */
  190021. typedef struct png_dsort_struct
  190022. {
  190023. struct png_dsort_struct FAR * next;
  190024. png_byte left;
  190025. png_byte right;
  190026. } png_dsort;
  190027. typedef png_dsort FAR * png_dsortp;
  190028. typedef png_dsort FAR * FAR * png_dsortpp;
  190029. void PNGAPI
  190030. png_set_dither(png_structp png_ptr, png_colorp palette,
  190031. int num_palette, int maximum_colors, png_uint_16p histogram,
  190032. int full_dither)
  190033. {
  190034. png_debug(1, "in png_set_dither\n");
  190035. if(png_ptr == NULL) return;
  190036. png_ptr->transformations |= PNG_DITHER;
  190037. if (!full_dither)
  190038. {
  190039. int i;
  190040. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190041. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190042. for (i = 0; i < num_palette; i++)
  190043. png_ptr->dither_index[i] = (png_byte)i;
  190044. }
  190045. if (num_palette > maximum_colors)
  190046. {
  190047. if (histogram != NULL)
  190048. {
  190049. /* This is easy enough, just throw out the least used colors.
  190050. Perhaps not the best solution, but good enough. */
  190051. int i;
  190052. /* initialize an array to sort colors */
  190053. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190054. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190055. /* initialize the dither_sort array */
  190056. for (i = 0; i < num_palette; i++)
  190057. png_ptr->dither_sort[i] = (png_byte)i;
  190058. /* Find the least used palette entries by starting a
  190059. bubble sort, and running it until we have sorted
  190060. out enough colors. Note that we don't care about
  190061. sorting all the colors, just finding which are
  190062. least used. */
  190063. for (i = num_palette - 1; i >= maximum_colors; i--)
  190064. {
  190065. int done; /* to stop early if the list is pre-sorted */
  190066. int j;
  190067. done = 1;
  190068. for (j = 0; j < i; j++)
  190069. {
  190070. if (histogram[png_ptr->dither_sort[j]]
  190071. < histogram[png_ptr->dither_sort[j + 1]])
  190072. {
  190073. png_byte t;
  190074. t = png_ptr->dither_sort[j];
  190075. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190076. png_ptr->dither_sort[j + 1] = t;
  190077. done = 0;
  190078. }
  190079. }
  190080. if (done)
  190081. break;
  190082. }
  190083. /* swap the palette around, and set up a table, if necessary */
  190084. if (full_dither)
  190085. {
  190086. int j = num_palette;
  190087. /* put all the useful colors within the max, but don't
  190088. move the others */
  190089. for (i = 0; i < maximum_colors; i++)
  190090. {
  190091. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190092. {
  190093. do
  190094. j--;
  190095. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190096. palette[i] = palette[j];
  190097. }
  190098. }
  190099. }
  190100. else
  190101. {
  190102. int j = num_palette;
  190103. /* move all the used colors inside the max limit, and
  190104. develop a translation table */
  190105. for (i = 0; i < maximum_colors; i++)
  190106. {
  190107. /* only move the colors we need to */
  190108. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190109. {
  190110. png_color tmp_color;
  190111. do
  190112. j--;
  190113. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190114. tmp_color = palette[j];
  190115. palette[j] = palette[i];
  190116. palette[i] = tmp_color;
  190117. /* indicate where the color went */
  190118. png_ptr->dither_index[j] = (png_byte)i;
  190119. png_ptr->dither_index[i] = (png_byte)j;
  190120. }
  190121. }
  190122. /* find closest color for those colors we are not using */
  190123. for (i = 0; i < num_palette; i++)
  190124. {
  190125. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190126. {
  190127. int min_d, k, min_k, d_index;
  190128. /* find the closest color to one we threw out */
  190129. d_index = png_ptr->dither_index[i];
  190130. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190131. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190132. {
  190133. int d;
  190134. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190135. if (d < min_d)
  190136. {
  190137. min_d = d;
  190138. min_k = k;
  190139. }
  190140. }
  190141. /* point to closest color */
  190142. png_ptr->dither_index[i] = (png_byte)min_k;
  190143. }
  190144. }
  190145. }
  190146. png_free(png_ptr, png_ptr->dither_sort);
  190147. png_ptr->dither_sort=NULL;
  190148. }
  190149. else
  190150. {
  190151. /* This is much harder to do simply (and quickly). Perhaps
  190152. we need to go through a median cut routine, but those
  190153. don't always behave themselves with only a few colors
  190154. as input. So we will just find the closest two colors,
  190155. and throw out one of them (chosen somewhat randomly).
  190156. [We don't understand this at all, so if someone wants to
  190157. work on improving it, be our guest - AED, GRP]
  190158. */
  190159. int i;
  190160. int max_d;
  190161. int num_new_palette;
  190162. png_dsortp t;
  190163. png_dsortpp hash;
  190164. t=NULL;
  190165. /* initialize palette index arrays */
  190166. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190167. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190168. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190169. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190170. /* initialize the sort array */
  190171. for (i = 0; i < num_palette; i++)
  190172. {
  190173. png_ptr->index_to_palette[i] = (png_byte)i;
  190174. png_ptr->palette_to_index[i] = (png_byte)i;
  190175. }
  190176. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190177. png_sizeof (png_dsortp)));
  190178. for (i = 0; i < 769; i++)
  190179. hash[i] = NULL;
  190180. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190181. num_new_palette = num_palette;
  190182. /* initial wild guess at how far apart the farthest pixel
  190183. pair we will be eliminating will be. Larger
  190184. numbers mean more areas will be allocated, Smaller
  190185. numbers run the risk of not saving enough data, and
  190186. having to do this all over again.
  190187. I have not done extensive checking on this number.
  190188. */
  190189. max_d = 96;
  190190. while (num_new_palette > maximum_colors)
  190191. {
  190192. for (i = 0; i < num_new_palette - 1; i++)
  190193. {
  190194. int j;
  190195. for (j = i + 1; j < num_new_palette; j++)
  190196. {
  190197. int d;
  190198. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190199. if (d <= max_d)
  190200. {
  190201. t = (png_dsortp)png_malloc_warn(png_ptr,
  190202. (png_uint_32)(png_sizeof(png_dsort)));
  190203. if (t == NULL)
  190204. break;
  190205. t->next = hash[d];
  190206. t->left = (png_byte)i;
  190207. t->right = (png_byte)j;
  190208. hash[d] = t;
  190209. }
  190210. }
  190211. if (t == NULL)
  190212. break;
  190213. }
  190214. if (t != NULL)
  190215. for (i = 0; i <= max_d; i++)
  190216. {
  190217. if (hash[i] != NULL)
  190218. {
  190219. png_dsortp p;
  190220. for (p = hash[i]; p; p = p->next)
  190221. {
  190222. if ((int)png_ptr->index_to_palette[p->left]
  190223. < num_new_palette &&
  190224. (int)png_ptr->index_to_palette[p->right]
  190225. < num_new_palette)
  190226. {
  190227. int j, next_j;
  190228. if (num_new_palette & 0x01)
  190229. {
  190230. j = p->left;
  190231. next_j = p->right;
  190232. }
  190233. else
  190234. {
  190235. j = p->right;
  190236. next_j = p->left;
  190237. }
  190238. num_new_palette--;
  190239. palette[png_ptr->index_to_palette[j]]
  190240. = palette[num_new_palette];
  190241. if (!full_dither)
  190242. {
  190243. int k;
  190244. for (k = 0; k < num_palette; k++)
  190245. {
  190246. if (png_ptr->dither_index[k] ==
  190247. png_ptr->index_to_palette[j])
  190248. png_ptr->dither_index[k] =
  190249. png_ptr->index_to_palette[next_j];
  190250. if ((int)png_ptr->dither_index[k] ==
  190251. num_new_palette)
  190252. png_ptr->dither_index[k] =
  190253. png_ptr->index_to_palette[j];
  190254. }
  190255. }
  190256. png_ptr->index_to_palette[png_ptr->palette_to_index
  190257. [num_new_palette]] = png_ptr->index_to_palette[j];
  190258. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190259. = png_ptr->palette_to_index[num_new_palette];
  190260. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190261. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190262. }
  190263. if (num_new_palette <= maximum_colors)
  190264. break;
  190265. }
  190266. if (num_new_palette <= maximum_colors)
  190267. break;
  190268. }
  190269. }
  190270. for (i = 0; i < 769; i++)
  190271. {
  190272. if (hash[i] != NULL)
  190273. {
  190274. png_dsortp p = hash[i];
  190275. while (p)
  190276. {
  190277. t = p->next;
  190278. png_free(png_ptr, p);
  190279. p = t;
  190280. }
  190281. }
  190282. hash[i] = 0;
  190283. }
  190284. max_d += 96;
  190285. }
  190286. png_free(png_ptr, hash);
  190287. png_free(png_ptr, png_ptr->palette_to_index);
  190288. png_free(png_ptr, png_ptr->index_to_palette);
  190289. png_ptr->palette_to_index=NULL;
  190290. png_ptr->index_to_palette=NULL;
  190291. }
  190292. num_palette = maximum_colors;
  190293. }
  190294. if (png_ptr->palette == NULL)
  190295. {
  190296. png_ptr->palette = palette;
  190297. }
  190298. png_ptr->num_palette = (png_uint_16)num_palette;
  190299. if (full_dither)
  190300. {
  190301. int i;
  190302. png_bytep distance;
  190303. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190304. PNG_DITHER_BLUE_BITS;
  190305. int num_red = (1 << PNG_DITHER_RED_BITS);
  190306. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190307. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190308. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190309. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190310. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190311. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190312. png_sizeof (png_byte));
  190313. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190314. png_sizeof(png_byte)));
  190315. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190316. for (i = 0; i < num_palette; i++)
  190317. {
  190318. int ir, ig, ib;
  190319. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190320. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190321. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190322. for (ir = 0; ir < num_red; ir++)
  190323. {
  190324. /* int dr = abs(ir - r); */
  190325. int dr = ((ir > r) ? ir - r : r - ir);
  190326. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190327. for (ig = 0; ig < num_green; ig++)
  190328. {
  190329. /* int dg = abs(ig - g); */
  190330. int dg = ((ig > g) ? ig - g : g - ig);
  190331. int dt = dr + dg;
  190332. int dm = ((dr > dg) ? dr : dg);
  190333. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190334. for (ib = 0; ib < num_blue; ib++)
  190335. {
  190336. int d_index = index_g | ib;
  190337. /* int db = abs(ib - b); */
  190338. int db = ((ib > b) ? ib - b : b - ib);
  190339. int dmax = ((dm > db) ? dm : db);
  190340. int d = dmax + dt + db;
  190341. if (d < (int)distance[d_index])
  190342. {
  190343. distance[d_index] = (png_byte)d;
  190344. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190345. }
  190346. }
  190347. }
  190348. }
  190349. }
  190350. png_free(png_ptr, distance);
  190351. }
  190352. }
  190353. #endif
  190354. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190355. /* Transform the image from the file_gamma to the screen_gamma. We
  190356. * only do transformations on images where the file_gamma and screen_gamma
  190357. * are not close reciprocals, otherwise it slows things down slightly, and
  190358. * also needlessly introduces small errors.
  190359. *
  190360. * We will turn off gamma transformation later if no semitransparent entries
  190361. * are present in the tRNS array for palette images. We can't do it here
  190362. * because we don't necessarily have the tRNS chunk yet.
  190363. */
  190364. void PNGAPI
  190365. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190366. {
  190367. png_debug(1, "in png_set_gamma\n");
  190368. if(png_ptr == NULL) return;
  190369. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190370. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190371. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190372. png_ptr->transformations |= PNG_GAMMA;
  190373. png_ptr->gamma = (float)file_gamma;
  190374. png_ptr->screen_gamma = (float)scrn_gamma;
  190375. }
  190376. #endif
  190377. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190378. /* Expand paletted images to RGB, expand grayscale images of
  190379. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190380. * to alpha channels.
  190381. */
  190382. void PNGAPI
  190383. png_set_expand(png_structp png_ptr)
  190384. {
  190385. png_debug(1, "in png_set_expand\n");
  190386. if(png_ptr == NULL) return;
  190387. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190388. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190389. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190390. #endif
  190391. }
  190392. /* GRR 19990627: the following three functions currently are identical
  190393. * to png_set_expand(). However, it is entirely reasonable that someone
  190394. * might wish to expand an indexed image to RGB but *not* expand a single,
  190395. * fully transparent palette entry to a full alpha channel--perhaps instead
  190396. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190397. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190398. * IOW, a future version of the library may make the transformations flag
  190399. * a bit more fine-grained, with separate bits for each of these three
  190400. * functions.
  190401. *
  190402. * More to the point, these functions make it obvious what libpng will be
  190403. * doing, whereas "expand" can (and does) mean any number of things.
  190404. *
  190405. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190406. * to expand only the sample depth but not to expand the tRNS to alpha.
  190407. */
  190408. /* Expand paletted images to RGB. */
  190409. void PNGAPI
  190410. png_set_palette_to_rgb(png_structp png_ptr)
  190411. {
  190412. png_debug(1, "in png_set_palette_to_rgb\n");
  190413. if(png_ptr == NULL) return;
  190414. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190415. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190416. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190417. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190418. #endif
  190419. }
  190420. #if !defined(PNG_1_0_X)
  190421. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190422. void PNGAPI
  190423. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190424. {
  190425. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190426. if(png_ptr == NULL) return;
  190427. png_ptr->transformations |= PNG_EXPAND;
  190428. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190429. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190430. #endif
  190431. }
  190432. #endif
  190433. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190434. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190435. /* Deprecated as of libpng-1.2.9 */
  190436. void PNGAPI
  190437. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190438. {
  190439. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190440. if(png_ptr == NULL) return;
  190441. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190442. }
  190443. #endif
  190444. /* Expand tRNS chunks to alpha channels. */
  190445. void PNGAPI
  190446. png_set_tRNS_to_alpha(png_structp png_ptr)
  190447. {
  190448. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190449. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190450. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190451. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190452. #endif
  190453. }
  190454. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190455. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190456. void PNGAPI
  190457. png_set_gray_to_rgb(png_structp png_ptr)
  190458. {
  190459. png_debug(1, "in png_set_gray_to_rgb\n");
  190460. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190461. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190462. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190463. #endif
  190464. }
  190465. #endif
  190466. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190467. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190468. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190469. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190470. */
  190471. void PNGAPI
  190472. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190473. double green)
  190474. {
  190475. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190476. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190477. if(png_ptr == NULL) return;
  190478. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190479. }
  190480. #endif
  190481. void PNGAPI
  190482. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190483. png_fixed_point red, png_fixed_point green)
  190484. {
  190485. png_debug(1, "in png_set_rgb_to_gray\n");
  190486. if(png_ptr == NULL) return;
  190487. switch(error_action)
  190488. {
  190489. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190490. break;
  190491. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190492. break;
  190493. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190494. }
  190495. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190496. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190497. png_ptr->transformations |= PNG_EXPAND;
  190498. #else
  190499. {
  190500. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190501. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190502. }
  190503. #endif
  190504. {
  190505. png_uint_16 red_int, green_int;
  190506. if(red < 0 || green < 0)
  190507. {
  190508. red_int = 6968; /* .212671 * 32768 + .5 */
  190509. green_int = 23434; /* .715160 * 32768 + .5 */
  190510. }
  190511. else if(red + green < 100000L)
  190512. {
  190513. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190514. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190515. }
  190516. else
  190517. {
  190518. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190519. red_int = 6968;
  190520. green_int = 23434;
  190521. }
  190522. png_ptr->rgb_to_gray_red_coeff = red_int;
  190523. png_ptr->rgb_to_gray_green_coeff = green_int;
  190524. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190525. }
  190526. }
  190527. #endif
  190528. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190529. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190530. defined(PNG_LEGACY_SUPPORTED)
  190531. void PNGAPI
  190532. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190533. read_user_transform_fn)
  190534. {
  190535. png_debug(1, "in png_set_read_user_transform_fn\n");
  190536. if(png_ptr == NULL) return;
  190537. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190538. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190539. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190540. #endif
  190541. #ifdef PNG_LEGACY_SUPPORTED
  190542. if(read_user_transform_fn)
  190543. png_warning(png_ptr,
  190544. "This version of libpng does not support user transforms");
  190545. #endif
  190546. }
  190547. #endif
  190548. /* Initialize everything needed for the read. This includes modifying
  190549. * the palette.
  190550. */
  190551. void /* PRIVATE */
  190552. png_init_read_transformations(png_structp png_ptr)
  190553. {
  190554. png_debug(1, "in png_init_read_transformations\n");
  190555. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190556. if(png_ptr != NULL)
  190557. #endif
  190558. {
  190559. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190560. || defined(PNG_READ_GAMMA_SUPPORTED)
  190561. int color_type = png_ptr->color_type;
  190562. #endif
  190563. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190564. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190565. /* Detect gray background and attempt to enable optimization
  190566. * for gray --> RGB case */
  190567. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190568. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190569. * background color might actually be gray yet not be flagged as such.
  190570. * This is not a problem for the current code, which uses
  190571. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190572. * png_do_gray_to_rgb() transformation.
  190573. */
  190574. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190575. !(color_type & PNG_COLOR_MASK_COLOR))
  190576. {
  190577. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190578. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190579. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190580. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190581. png_ptr->background.red == png_ptr->background.green &&
  190582. png_ptr->background.red == png_ptr->background.blue)
  190583. {
  190584. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190585. png_ptr->background.gray = png_ptr->background.red;
  190586. }
  190587. #endif
  190588. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190589. (png_ptr->transformations & PNG_EXPAND))
  190590. {
  190591. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190592. {
  190593. /* expand background and tRNS chunks */
  190594. switch (png_ptr->bit_depth)
  190595. {
  190596. case 1:
  190597. png_ptr->background.gray *= (png_uint_16)0xff;
  190598. png_ptr->background.red = png_ptr->background.green
  190599. = png_ptr->background.blue = png_ptr->background.gray;
  190600. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190601. {
  190602. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190603. png_ptr->trans_values.red = png_ptr->trans_values.green
  190604. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190605. }
  190606. break;
  190607. case 2:
  190608. png_ptr->background.gray *= (png_uint_16)0x55;
  190609. png_ptr->background.red = png_ptr->background.green
  190610. = png_ptr->background.blue = png_ptr->background.gray;
  190611. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190612. {
  190613. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190614. png_ptr->trans_values.red = png_ptr->trans_values.green
  190615. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190616. }
  190617. break;
  190618. case 4:
  190619. png_ptr->background.gray *= (png_uint_16)0x11;
  190620. png_ptr->background.red = png_ptr->background.green
  190621. = png_ptr->background.blue = png_ptr->background.gray;
  190622. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190623. {
  190624. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190625. png_ptr->trans_values.red = png_ptr->trans_values.green
  190626. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190627. }
  190628. break;
  190629. case 8:
  190630. case 16:
  190631. png_ptr->background.red = png_ptr->background.green
  190632. = png_ptr->background.blue = png_ptr->background.gray;
  190633. break;
  190634. }
  190635. }
  190636. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190637. {
  190638. png_ptr->background.red =
  190639. png_ptr->palette[png_ptr->background.index].red;
  190640. png_ptr->background.green =
  190641. png_ptr->palette[png_ptr->background.index].green;
  190642. png_ptr->background.blue =
  190643. png_ptr->palette[png_ptr->background.index].blue;
  190644. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190645. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190646. {
  190647. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190648. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190649. #endif
  190650. {
  190651. /* invert the alpha channel (in tRNS) unless the pixels are
  190652. going to be expanded, in which case leave it for later */
  190653. int i,istop;
  190654. istop=(int)png_ptr->num_trans;
  190655. for (i=0; i<istop; i++)
  190656. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190657. }
  190658. }
  190659. #endif
  190660. }
  190661. }
  190662. #endif
  190663. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190664. png_ptr->background_1 = png_ptr->background;
  190665. #endif
  190666. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190667. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190668. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190669. < PNG_GAMMA_THRESHOLD))
  190670. {
  190671. int i,k;
  190672. k=0;
  190673. for (i=0; i<png_ptr->num_trans; i++)
  190674. {
  190675. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190676. k=1; /* partial transparency is present */
  190677. }
  190678. if (k == 0)
  190679. png_ptr->transformations &= (~PNG_GAMMA);
  190680. }
  190681. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190682. png_ptr->gamma != 0.0)
  190683. {
  190684. png_build_gamma_table(png_ptr);
  190685. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190686. if (png_ptr->transformations & PNG_BACKGROUND)
  190687. {
  190688. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190689. {
  190690. /* could skip if no transparency and
  190691. */
  190692. png_color back, back_1;
  190693. png_colorp palette = png_ptr->palette;
  190694. int num_palette = png_ptr->num_palette;
  190695. int i;
  190696. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190697. {
  190698. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190699. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190700. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190701. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190702. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190703. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190704. }
  190705. else
  190706. {
  190707. double g, gs;
  190708. switch (png_ptr->background_gamma_type)
  190709. {
  190710. case PNG_BACKGROUND_GAMMA_SCREEN:
  190711. g = (png_ptr->screen_gamma);
  190712. gs = 1.0;
  190713. break;
  190714. case PNG_BACKGROUND_GAMMA_FILE:
  190715. g = 1.0 / (png_ptr->gamma);
  190716. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190717. break;
  190718. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190719. g = 1.0 / (png_ptr->background_gamma);
  190720. gs = 1.0 / (png_ptr->background_gamma *
  190721. png_ptr->screen_gamma);
  190722. break;
  190723. default:
  190724. g = 1.0; /* back_1 */
  190725. gs = 1.0; /* back */
  190726. }
  190727. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190728. {
  190729. back.red = (png_byte)png_ptr->background.red;
  190730. back.green = (png_byte)png_ptr->background.green;
  190731. back.blue = (png_byte)png_ptr->background.blue;
  190732. }
  190733. else
  190734. {
  190735. back.red = (png_byte)(pow(
  190736. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190737. back.green = (png_byte)(pow(
  190738. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190739. back.blue = (png_byte)(pow(
  190740. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190741. }
  190742. back_1.red = (png_byte)(pow(
  190743. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190744. back_1.green = (png_byte)(pow(
  190745. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190746. back_1.blue = (png_byte)(pow(
  190747. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190748. }
  190749. for (i = 0; i < num_palette; i++)
  190750. {
  190751. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190752. {
  190753. if (png_ptr->trans[i] == 0)
  190754. {
  190755. palette[i] = back;
  190756. }
  190757. else /* if (png_ptr->trans[i] != 0xff) */
  190758. {
  190759. png_byte v, w;
  190760. v = png_ptr->gamma_to_1[palette[i].red];
  190761. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190762. palette[i].red = png_ptr->gamma_from_1[w];
  190763. v = png_ptr->gamma_to_1[palette[i].green];
  190764. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190765. palette[i].green = png_ptr->gamma_from_1[w];
  190766. v = png_ptr->gamma_to_1[palette[i].blue];
  190767. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190768. palette[i].blue = png_ptr->gamma_from_1[w];
  190769. }
  190770. }
  190771. else
  190772. {
  190773. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190774. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190775. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190776. }
  190777. }
  190778. }
  190779. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190780. else
  190781. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190782. {
  190783. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190784. double g = 1.0;
  190785. double gs = 1.0;
  190786. switch (png_ptr->background_gamma_type)
  190787. {
  190788. case PNG_BACKGROUND_GAMMA_SCREEN:
  190789. g = (png_ptr->screen_gamma);
  190790. gs = 1.0;
  190791. break;
  190792. case PNG_BACKGROUND_GAMMA_FILE:
  190793. g = 1.0 / (png_ptr->gamma);
  190794. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190795. break;
  190796. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190797. g = 1.0 / (png_ptr->background_gamma);
  190798. gs = 1.0 / (png_ptr->background_gamma *
  190799. png_ptr->screen_gamma);
  190800. break;
  190801. }
  190802. png_ptr->background_1.gray = (png_uint_16)(pow(
  190803. (double)png_ptr->background.gray / m, g) * m + .5);
  190804. png_ptr->background.gray = (png_uint_16)(pow(
  190805. (double)png_ptr->background.gray / m, gs) * m + .5);
  190806. if ((png_ptr->background.red != png_ptr->background.green) ||
  190807. (png_ptr->background.red != png_ptr->background.blue) ||
  190808. (png_ptr->background.red != png_ptr->background.gray))
  190809. {
  190810. /* RGB or RGBA with color background */
  190811. png_ptr->background_1.red = (png_uint_16)(pow(
  190812. (double)png_ptr->background.red / m, g) * m + .5);
  190813. png_ptr->background_1.green = (png_uint_16)(pow(
  190814. (double)png_ptr->background.green / m, g) * m + .5);
  190815. png_ptr->background_1.blue = (png_uint_16)(pow(
  190816. (double)png_ptr->background.blue / m, g) * m + .5);
  190817. png_ptr->background.red = (png_uint_16)(pow(
  190818. (double)png_ptr->background.red / m, gs) * m + .5);
  190819. png_ptr->background.green = (png_uint_16)(pow(
  190820. (double)png_ptr->background.green / m, gs) * m + .5);
  190821. png_ptr->background.blue = (png_uint_16)(pow(
  190822. (double)png_ptr->background.blue / m, gs) * m + .5);
  190823. }
  190824. else
  190825. {
  190826. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190827. png_ptr->background_1.red = png_ptr->background_1.green
  190828. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190829. png_ptr->background.red = png_ptr->background.green
  190830. = png_ptr->background.blue = png_ptr->background.gray;
  190831. }
  190832. }
  190833. }
  190834. else
  190835. /* transformation does not include PNG_BACKGROUND */
  190836. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190837. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190838. {
  190839. png_colorp palette = png_ptr->palette;
  190840. int num_palette = png_ptr->num_palette;
  190841. int i;
  190842. for (i = 0; i < num_palette; i++)
  190843. {
  190844. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190845. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190846. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190847. }
  190848. }
  190849. }
  190850. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190851. else
  190852. #endif
  190853. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190854. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190855. /* No GAMMA transformation */
  190856. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190857. (color_type == PNG_COLOR_TYPE_PALETTE))
  190858. {
  190859. int i;
  190860. int istop = (int)png_ptr->num_trans;
  190861. png_color back;
  190862. png_colorp palette = png_ptr->palette;
  190863. back.red = (png_byte)png_ptr->background.red;
  190864. back.green = (png_byte)png_ptr->background.green;
  190865. back.blue = (png_byte)png_ptr->background.blue;
  190866. for (i = 0; i < istop; i++)
  190867. {
  190868. if (png_ptr->trans[i] == 0)
  190869. {
  190870. palette[i] = back;
  190871. }
  190872. else if (png_ptr->trans[i] != 0xff)
  190873. {
  190874. /* The png_composite() macro is defined in png.h */
  190875. png_composite(palette[i].red, palette[i].red,
  190876. png_ptr->trans[i], back.red);
  190877. png_composite(palette[i].green, palette[i].green,
  190878. png_ptr->trans[i], back.green);
  190879. png_composite(palette[i].blue, palette[i].blue,
  190880. png_ptr->trans[i], back.blue);
  190881. }
  190882. }
  190883. }
  190884. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190885. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190886. if ((png_ptr->transformations & PNG_SHIFT) &&
  190887. (color_type == PNG_COLOR_TYPE_PALETTE))
  190888. {
  190889. png_uint_16 i;
  190890. png_uint_16 istop = png_ptr->num_palette;
  190891. int sr = 8 - png_ptr->sig_bit.red;
  190892. int sg = 8 - png_ptr->sig_bit.green;
  190893. int sb = 8 - png_ptr->sig_bit.blue;
  190894. if (sr < 0 || sr > 8)
  190895. sr = 0;
  190896. if (sg < 0 || sg > 8)
  190897. sg = 0;
  190898. if (sb < 0 || sb > 8)
  190899. sb = 0;
  190900. for (i = 0; i < istop; i++)
  190901. {
  190902. png_ptr->palette[i].red >>= sr;
  190903. png_ptr->palette[i].green >>= sg;
  190904. png_ptr->palette[i].blue >>= sb;
  190905. }
  190906. }
  190907. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190908. }
  190909. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190910. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190911. if(png_ptr)
  190912. return;
  190913. #endif
  190914. }
  190915. /* Modify the info structure to reflect the transformations. The
  190916. * info should be updated so a PNG file could be written with it,
  190917. * assuming the transformations result in valid PNG data.
  190918. */
  190919. void /* PRIVATE */
  190920. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190921. {
  190922. png_debug(1, "in png_read_transform_info\n");
  190923. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190924. if (png_ptr->transformations & PNG_EXPAND)
  190925. {
  190926. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190927. {
  190928. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190929. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190930. else
  190931. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190932. info_ptr->bit_depth = 8;
  190933. info_ptr->num_trans = 0;
  190934. }
  190935. else
  190936. {
  190937. if (png_ptr->num_trans)
  190938. {
  190939. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190940. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190941. else
  190942. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190943. }
  190944. if (info_ptr->bit_depth < 8)
  190945. info_ptr->bit_depth = 8;
  190946. info_ptr->num_trans = 0;
  190947. }
  190948. }
  190949. #endif
  190950. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190951. if (png_ptr->transformations & PNG_BACKGROUND)
  190952. {
  190953. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190954. info_ptr->num_trans = 0;
  190955. info_ptr->background = png_ptr->background;
  190956. }
  190957. #endif
  190958. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190959. if (png_ptr->transformations & PNG_GAMMA)
  190960. {
  190961. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190962. info_ptr->gamma = png_ptr->gamma;
  190963. #endif
  190964. #ifdef PNG_FIXED_POINT_SUPPORTED
  190965. info_ptr->int_gamma = png_ptr->int_gamma;
  190966. #endif
  190967. }
  190968. #endif
  190969. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190970. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190971. info_ptr->bit_depth = 8;
  190972. #endif
  190973. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190974. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190975. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190976. #endif
  190977. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190978. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190979. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190980. #endif
  190981. #if defined(PNG_READ_DITHER_SUPPORTED)
  190982. if (png_ptr->transformations & PNG_DITHER)
  190983. {
  190984. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190985. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190986. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190987. {
  190988. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190989. }
  190990. }
  190991. #endif
  190992. #if defined(PNG_READ_PACK_SUPPORTED)
  190993. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190994. info_ptr->bit_depth = 8;
  190995. #endif
  190996. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190997. info_ptr->channels = 1;
  190998. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190999. info_ptr->channels = 3;
  191000. else
  191001. info_ptr->channels = 1;
  191002. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191003. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191004. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191005. #endif
  191006. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191007. info_ptr->channels++;
  191008. #if defined(PNG_READ_FILLER_SUPPORTED)
  191009. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191010. if ((png_ptr->transformations & PNG_FILLER) &&
  191011. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191012. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191013. {
  191014. info_ptr->channels++;
  191015. /* if adding a true alpha channel not just filler */
  191016. #if !defined(PNG_1_0_X)
  191017. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191018. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191019. #endif
  191020. }
  191021. #endif
  191022. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191023. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191024. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191025. {
  191026. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191027. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191028. if(info_ptr->channels < png_ptr->user_transform_channels)
  191029. info_ptr->channels = png_ptr->user_transform_channels;
  191030. }
  191031. #endif
  191032. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191033. info_ptr->bit_depth);
  191034. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191035. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191036. if(png_ptr)
  191037. return;
  191038. #endif
  191039. }
  191040. /* Transform the row. The order of transformations is significant,
  191041. * and is very touchy. If you add a transformation, take care to
  191042. * decide how it fits in with the other transformations here.
  191043. */
  191044. void /* PRIVATE */
  191045. png_do_read_transformations(png_structp png_ptr)
  191046. {
  191047. png_debug(1, "in png_do_read_transformations\n");
  191048. if (png_ptr->row_buf == NULL)
  191049. {
  191050. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191051. char msg[50];
  191052. png_snprintf2(msg, 50,
  191053. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191054. png_ptr->pass);
  191055. png_error(png_ptr, msg);
  191056. #else
  191057. png_error(png_ptr, "NULL row buffer");
  191058. #endif
  191059. }
  191060. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191061. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191062. /* Application has failed to call either png_read_start_image()
  191063. * or png_read_update_info() after setting transforms that expand
  191064. * pixels. This check added to libpng-1.2.19 */
  191065. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191066. png_error(png_ptr, "Uninitialized row");
  191067. #else
  191068. png_warning(png_ptr, "Uninitialized row");
  191069. #endif
  191070. #endif
  191071. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191072. if (png_ptr->transformations & PNG_EXPAND)
  191073. {
  191074. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191075. {
  191076. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191077. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191078. }
  191079. else
  191080. {
  191081. if (png_ptr->num_trans &&
  191082. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191083. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191084. &(png_ptr->trans_values));
  191085. else
  191086. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191087. NULL);
  191088. }
  191089. }
  191090. #endif
  191091. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191092. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191093. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191094. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191095. #endif
  191096. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191097. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191098. {
  191099. int rgb_error =
  191100. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191101. if(rgb_error)
  191102. {
  191103. png_ptr->rgb_to_gray_status=1;
  191104. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191105. PNG_RGB_TO_GRAY_WARN)
  191106. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191107. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191108. PNG_RGB_TO_GRAY_ERR)
  191109. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191110. }
  191111. }
  191112. #endif
  191113. /*
  191114. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191115. In most cases, the "simple transparency" should be done prior to doing
  191116. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191117. pixel is transparent. You would also need to make sure that the
  191118. transparency information is upgraded to RGB.
  191119. To summarize, the current flow is:
  191120. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191121. with background "in place" if transparent,
  191122. convert to RGB if necessary
  191123. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191124. convert to RGB if necessary
  191125. To support RGB backgrounds for gray images we need:
  191126. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191127. 3 or 6 bytes and composite with background
  191128. "in place" if transparent (3x compare/pixel
  191129. compared to doing composite with gray bkgrnd)
  191130. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191131. remove alpha bytes (3x float operations/pixel
  191132. compared with composite on gray background)
  191133. Greg's change will do this. The reason it wasn't done before is for
  191134. performance, as this increases the per-pixel operations. If we would check
  191135. in advance if the background was gray or RGB, and position the gray-to-RGB
  191136. transform appropriately, then it would save a lot of work/time.
  191137. */
  191138. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191139. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191140. * for performance reasons */
  191141. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191142. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191143. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191144. #endif
  191145. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191146. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191147. ((png_ptr->num_trans != 0 ) ||
  191148. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191149. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191150. &(png_ptr->trans_values), &(png_ptr->background)
  191151. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191152. , &(png_ptr->background_1),
  191153. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191154. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191155. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191156. png_ptr->gamma_shift
  191157. #endif
  191158. );
  191159. #endif
  191160. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191161. if ((png_ptr->transformations & PNG_GAMMA) &&
  191162. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191163. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191164. ((png_ptr->num_trans != 0) ||
  191165. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191166. #endif
  191167. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191168. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191169. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191170. png_ptr->gamma_shift);
  191171. #endif
  191172. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191173. if (png_ptr->transformations & PNG_16_TO_8)
  191174. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191175. #endif
  191176. #if defined(PNG_READ_DITHER_SUPPORTED)
  191177. if (png_ptr->transformations & PNG_DITHER)
  191178. {
  191179. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191180. png_ptr->palette_lookup, png_ptr->dither_index);
  191181. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191182. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191183. }
  191184. #endif
  191185. #if defined(PNG_READ_INVERT_SUPPORTED)
  191186. if (png_ptr->transformations & PNG_INVERT_MONO)
  191187. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191188. #endif
  191189. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191190. if (png_ptr->transformations & PNG_SHIFT)
  191191. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191192. &(png_ptr->shift));
  191193. #endif
  191194. #if defined(PNG_READ_PACK_SUPPORTED)
  191195. if (png_ptr->transformations & PNG_PACK)
  191196. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191197. #endif
  191198. #if defined(PNG_READ_BGR_SUPPORTED)
  191199. if (png_ptr->transformations & PNG_BGR)
  191200. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191201. #endif
  191202. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191203. if (png_ptr->transformations & PNG_PACKSWAP)
  191204. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191205. #endif
  191206. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191207. /* if gray -> RGB, do so now only if we did not do so above */
  191208. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191209. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191210. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191211. #endif
  191212. #if defined(PNG_READ_FILLER_SUPPORTED)
  191213. if (png_ptr->transformations & PNG_FILLER)
  191214. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191215. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191216. #endif
  191217. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191218. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191219. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191220. #endif
  191221. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191222. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191223. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191224. #endif
  191225. #if defined(PNG_READ_SWAP_SUPPORTED)
  191226. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191227. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191228. #endif
  191229. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191230. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191231. {
  191232. if(png_ptr->read_user_transform_fn != NULL)
  191233. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191234. (png_ptr, /* png_ptr */
  191235. &(png_ptr->row_info), /* row_info: */
  191236. /* png_uint_32 width; width of row */
  191237. /* png_uint_32 rowbytes; number of bytes in row */
  191238. /* png_byte color_type; color type of pixels */
  191239. /* png_byte bit_depth; bit depth of samples */
  191240. /* png_byte channels; number of channels (1-4) */
  191241. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191242. png_ptr->row_buf + 1); /* start of pixel data for row */
  191243. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191244. if(png_ptr->user_transform_depth)
  191245. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191246. if(png_ptr->user_transform_channels)
  191247. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191248. #endif
  191249. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191250. png_ptr->row_info.channels);
  191251. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191252. png_ptr->row_info.width);
  191253. }
  191254. #endif
  191255. }
  191256. #if defined(PNG_READ_PACK_SUPPORTED)
  191257. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191258. * without changing the actual values. Thus, if you had a row with
  191259. * a bit depth of 1, you would end up with bytes that only contained
  191260. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191261. * png_do_shift() after this.
  191262. */
  191263. void /* PRIVATE */
  191264. png_do_unpack(png_row_infop row_info, png_bytep row)
  191265. {
  191266. png_debug(1, "in png_do_unpack\n");
  191267. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191268. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191269. #else
  191270. if (row_info->bit_depth < 8)
  191271. #endif
  191272. {
  191273. png_uint_32 i;
  191274. png_uint_32 row_width=row_info->width;
  191275. switch (row_info->bit_depth)
  191276. {
  191277. case 1:
  191278. {
  191279. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191280. png_bytep dp = row + (png_size_t)row_width - 1;
  191281. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191282. for (i = 0; i < row_width; i++)
  191283. {
  191284. *dp = (png_byte)((*sp >> shift) & 0x01);
  191285. if (shift == 7)
  191286. {
  191287. shift = 0;
  191288. sp--;
  191289. }
  191290. else
  191291. shift++;
  191292. dp--;
  191293. }
  191294. break;
  191295. }
  191296. case 2:
  191297. {
  191298. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191299. png_bytep dp = row + (png_size_t)row_width - 1;
  191300. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191301. for (i = 0; i < row_width; i++)
  191302. {
  191303. *dp = (png_byte)((*sp >> shift) & 0x03);
  191304. if (shift == 6)
  191305. {
  191306. shift = 0;
  191307. sp--;
  191308. }
  191309. else
  191310. shift += 2;
  191311. dp--;
  191312. }
  191313. break;
  191314. }
  191315. case 4:
  191316. {
  191317. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191318. png_bytep dp = row + (png_size_t)row_width - 1;
  191319. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191320. for (i = 0; i < row_width; i++)
  191321. {
  191322. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191323. if (shift == 4)
  191324. {
  191325. shift = 0;
  191326. sp--;
  191327. }
  191328. else
  191329. shift = 4;
  191330. dp--;
  191331. }
  191332. break;
  191333. }
  191334. }
  191335. row_info->bit_depth = 8;
  191336. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191337. row_info->rowbytes = row_width * row_info->channels;
  191338. }
  191339. }
  191340. #endif
  191341. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191342. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191343. * pixels back to their significant bits values. Thus, if you have
  191344. * a row of bit depth 8, but only 5 are significant, this will shift
  191345. * the values back to 0 through 31.
  191346. */
  191347. void /* PRIVATE */
  191348. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191349. {
  191350. png_debug(1, "in png_do_unshift\n");
  191351. if (
  191352. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191353. row != NULL && row_info != NULL && sig_bits != NULL &&
  191354. #endif
  191355. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191356. {
  191357. int shift[4];
  191358. int channels = 0;
  191359. int c;
  191360. png_uint_16 value = 0;
  191361. png_uint_32 row_width = row_info->width;
  191362. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191363. {
  191364. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191365. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191366. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191367. }
  191368. else
  191369. {
  191370. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191371. }
  191372. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191373. {
  191374. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191375. }
  191376. for (c = 0; c < channels; c++)
  191377. {
  191378. if (shift[c] <= 0)
  191379. shift[c] = 0;
  191380. else
  191381. value = 1;
  191382. }
  191383. if (!value)
  191384. return;
  191385. switch (row_info->bit_depth)
  191386. {
  191387. case 2:
  191388. {
  191389. png_bytep bp;
  191390. png_uint_32 i;
  191391. png_uint_32 istop = row_info->rowbytes;
  191392. for (bp = row, i = 0; i < istop; i++)
  191393. {
  191394. *bp >>= 1;
  191395. *bp++ &= 0x55;
  191396. }
  191397. break;
  191398. }
  191399. case 4:
  191400. {
  191401. png_bytep bp = row;
  191402. png_uint_32 i;
  191403. png_uint_32 istop = row_info->rowbytes;
  191404. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191405. (png_byte)((int)0xf >> shift[0]));
  191406. for (i = 0; i < istop; i++)
  191407. {
  191408. *bp >>= shift[0];
  191409. *bp++ &= mask;
  191410. }
  191411. break;
  191412. }
  191413. case 8:
  191414. {
  191415. png_bytep bp = row;
  191416. png_uint_32 i;
  191417. png_uint_32 istop = row_width * channels;
  191418. for (i = 0; i < istop; i++)
  191419. {
  191420. *bp++ >>= shift[i%channels];
  191421. }
  191422. break;
  191423. }
  191424. case 16:
  191425. {
  191426. png_bytep bp = row;
  191427. png_uint_32 i;
  191428. png_uint_32 istop = channels * row_width;
  191429. for (i = 0; i < istop; i++)
  191430. {
  191431. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191432. value >>= shift[i%channels];
  191433. *bp++ = (png_byte)(value >> 8);
  191434. *bp++ = (png_byte)(value & 0xff);
  191435. }
  191436. break;
  191437. }
  191438. }
  191439. }
  191440. }
  191441. #endif
  191442. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191443. /* chop rows of bit depth 16 down to 8 */
  191444. void /* PRIVATE */
  191445. png_do_chop(png_row_infop row_info, png_bytep row)
  191446. {
  191447. png_debug(1, "in png_do_chop\n");
  191448. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191449. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191450. #else
  191451. if (row_info->bit_depth == 16)
  191452. #endif
  191453. {
  191454. png_bytep sp = row;
  191455. png_bytep dp = row;
  191456. png_uint_32 i;
  191457. png_uint_32 istop = row_info->width * row_info->channels;
  191458. for (i = 0; i<istop; i++, sp += 2, dp++)
  191459. {
  191460. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191461. /* This does a more accurate scaling of the 16-bit color
  191462. * value, rather than a simple low-byte truncation.
  191463. *
  191464. * What the ideal calculation should be:
  191465. * *dp = (((((png_uint_32)(*sp) << 8) |
  191466. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191467. *
  191468. * GRR: no, I think this is what it really should be:
  191469. * *dp = (((((png_uint_32)(*sp) << 8) |
  191470. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191471. *
  191472. * GRR: here's the exact calculation with shifts:
  191473. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191474. * *dp = (temp - (temp >> 8)) >> 8;
  191475. *
  191476. * Approximate calculation with shift/add instead of multiply/divide:
  191477. * *dp = ((((png_uint_32)(*sp) << 8) |
  191478. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191479. *
  191480. * What we actually do to avoid extra shifting and conversion:
  191481. */
  191482. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191483. #else
  191484. /* Simply discard the low order byte */
  191485. *dp = *sp;
  191486. #endif
  191487. }
  191488. row_info->bit_depth = 8;
  191489. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191490. row_info->rowbytes = row_info->width * row_info->channels;
  191491. }
  191492. }
  191493. #endif
  191494. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191495. void /* PRIVATE */
  191496. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191497. {
  191498. png_debug(1, "in png_do_read_swap_alpha\n");
  191499. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191500. if (row != NULL && row_info != NULL)
  191501. #endif
  191502. {
  191503. png_uint_32 row_width = row_info->width;
  191504. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191505. {
  191506. /* This converts from RGBA to ARGB */
  191507. if (row_info->bit_depth == 8)
  191508. {
  191509. png_bytep sp = row + row_info->rowbytes;
  191510. png_bytep dp = sp;
  191511. png_byte save;
  191512. png_uint_32 i;
  191513. for (i = 0; i < row_width; i++)
  191514. {
  191515. save = *(--sp);
  191516. *(--dp) = *(--sp);
  191517. *(--dp) = *(--sp);
  191518. *(--dp) = *(--sp);
  191519. *(--dp) = save;
  191520. }
  191521. }
  191522. /* This converts from RRGGBBAA to AARRGGBB */
  191523. else
  191524. {
  191525. png_bytep sp = row + row_info->rowbytes;
  191526. png_bytep dp = sp;
  191527. png_byte save[2];
  191528. png_uint_32 i;
  191529. for (i = 0; i < row_width; i++)
  191530. {
  191531. save[0] = *(--sp);
  191532. save[1] = *(--sp);
  191533. *(--dp) = *(--sp);
  191534. *(--dp) = *(--sp);
  191535. *(--dp) = *(--sp);
  191536. *(--dp) = *(--sp);
  191537. *(--dp) = *(--sp);
  191538. *(--dp) = *(--sp);
  191539. *(--dp) = save[0];
  191540. *(--dp) = save[1];
  191541. }
  191542. }
  191543. }
  191544. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191545. {
  191546. /* This converts from GA to AG */
  191547. if (row_info->bit_depth == 8)
  191548. {
  191549. png_bytep sp = row + row_info->rowbytes;
  191550. png_bytep dp = sp;
  191551. png_byte save;
  191552. png_uint_32 i;
  191553. for (i = 0; i < row_width; i++)
  191554. {
  191555. save = *(--sp);
  191556. *(--dp) = *(--sp);
  191557. *(--dp) = save;
  191558. }
  191559. }
  191560. /* This converts from GGAA to AAGG */
  191561. else
  191562. {
  191563. png_bytep sp = row + row_info->rowbytes;
  191564. png_bytep dp = sp;
  191565. png_byte save[2];
  191566. png_uint_32 i;
  191567. for (i = 0; i < row_width; i++)
  191568. {
  191569. save[0] = *(--sp);
  191570. save[1] = *(--sp);
  191571. *(--dp) = *(--sp);
  191572. *(--dp) = *(--sp);
  191573. *(--dp) = save[0];
  191574. *(--dp) = save[1];
  191575. }
  191576. }
  191577. }
  191578. }
  191579. }
  191580. #endif
  191581. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191582. void /* PRIVATE */
  191583. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191584. {
  191585. png_debug(1, "in png_do_read_invert_alpha\n");
  191586. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191587. if (row != NULL && row_info != NULL)
  191588. #endif
  191589. {
  191590. png_uint_32 row_width = row_info->width;
  191591. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191592. {
  191593. /* This inverts the alpha channel in RGBA */
  191594. if (row_info->bit_depth == 8)
  191595. {
  191596. png_bytep sp = row + row_info->rowbytes;
  191597. png_bytep dp = sp;
  191598. png_uint_32 i;
  191599. for (i = 0; i < row_width; i++)
  191600. {
  191601. *(--dp) = (png_byte)(255 - *(--sp));
  191602. /* This does nothing:
  191603. *(--dp) = *(--sp);
  191604. *(--dp) = *(--sp);
  191605. *(--dp) = *(--sp);
  191606. We can replace it with:
  191607. */
  191608. sp-=3;
  191609. dp=sp;
  191610. }
  191611. }
  191612. /* This inverts the alpha channel in RRGGBBAA */
  191613. else
  191614. {
  191615. png_bytep sp = row + row_info->rowbytes;
  191616. png_bytep dp = sp;
  191617. png_uint_32 i;
  191618. for (i = 0; i < row_width; i++)
  191619. {
  191620. *(--dp) = (png_byte)(255 - *(--sp));
  191621. *(--dp) = (png_byte)(255 - *(--sp));
  191622. /* This does nothing:
  191623. *(--dp) = *(--sp);
  191624. *(--dp) = *(--sp);
  191625. *(--dp) = *(--sp);
  191626. *(--dp) = *(--sp);
  191627. *(--dp) = *(--sp);
  191628. *(--dp) = *(--sp);
  191629. We can replace it with:
  191630. */
  191631. sp-=6;
  191632. dp=sp;
  191633. }
  191634. }
  191635. }
  191636. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191637. {
  191638. /* This inverts the alpha channel in GA */
  191639. if (row_info->bit_depth == 8)
  191640. {
  191641. png_bytep sp = row + row_info->rowbytes;
  191642. png_bytep dp = sp;
  191643. png_uint_32 i;
  191644. for (i = 0; i < row_width; i++)
  191645. {
  191646. *(--dp) = (png_byte)(255 - *(--sp));
  191647. *(--dp) = *(--sp);
  191648. }
  191649. }
  191650. /* This inverts the alpha channel in GGAA */
  191651. else
  191652. {
  191653. png_bytep sp = row + row_info->rowbytes;
  191654. png_bytep dp = sp;
  191655. png_uint_32 i;
  191656. for (i = 0; i < row_width; i++)
  191657. {
  191658. *(--dp) = (png_byte)(255 - *(--sp));
  191659. *(--dp) = (png_byte)(255 - *(--sp));
  191660. /*
  191661. *(--dp) = *(--sp);
  191662. *(--dp) = *(--sp);
  191663. */
  191664. sp-=2;
  191665. dp=sp;
  191666. }
  191667. }
  191668. }
  191669. }
  191670. }
  191671. #endif
  191672. #if defined(PNG_READ_FILLER_SUPPORTED)
  191673. /* Add filler channel if we have RGB color */
  191674. void /* PRIVATE */
  191675. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191676. png_uint_32 filler, png_uint_32 flags)
  191677. {
  191678. png_uint_32 i;
  191679. png_uint_32 row_width = row_info->width;
  191680. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191681. png_byte lo_filler = (png_byte)(filler & 0xff);
  191682. png_debug(1, "in png_do_read_filler\n");
  191683. if (
  191684. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191685. row != NULL && row_info != NULL &&
  191686. #endif
  191687. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191688. {
  191689. if(row_info->bit_depth == 8)
  191690. {
  191691. /* This changes the data from G to GX */
  191692. if (flags & PNG_FLAG_FILLER_AFTER)
  191693. {
  191694. png_bytep sp = row + (png_size_t)row_width;
  191695. png_bytep dp = sp + (png_size_t)row_width;
  191696. for (i = 1; i < row_width; i++)
  191697. {
  191698. *(--dp) = lo_filler;
  191699. *(--dp) = *(--sp);
  191700. }
  191701. *(--dp) = lo_filler;
  191702. row_info->channels = 2;
  191703. row_info->pixel_depth = 16;
  191704. row_info->rowbytes = row_width * 2;
  191705. }
  191706. /* This changes the data from G to XG */
  191707. else
  191708. {
  191709. png_bytep sp = row + (png_size_t)row_width;
  191710. png_bytep dp = sp + (png_size_t)row_width;
  191711. for (i = 0; i < row_width; i++)
  191712. {
  191713. *(--dp) = *(--sp);
  191714. *(--dp) = lo_filler;
  191715. }
  191716. row_info->channels = 2;
  191717. row_info->pixel_depth = 16;
  191718. row_info->rowbytes = row_width * 2;
  191719. }
  191720. }
  191721. else if(row_info->bit_depth == 16)
  191722. {
  191723. /* This changes the data from GG to GGXX */
  191724. if (flags & PNG_FLAG_FILLER_AFTER)
  191725. {
  191726. png_bytep sp = row + (png_size_t)row_width * 2;
  191727. png_bytep dp = sp + (png_size_t)row_width * 2;
  191728. for (i = 1; i < row_width; i++)
  191729. {
  191730. *(--dp) = hi_filler;
  191731. *(--dp) = lo_filler;
  191732. *(--dp) = *(--sp);
  191733. *(--dp) = *(--sp);
  191734. }
  191735. *(--dp) = hi_filler;
  191736. *(--dp) = lo_filler;
  191737. row_info->channels = 2;
  191738. row_info->pixel_depth = 32;
  191739. row_info->rowbytes = row_width * 4;
  191740. }
  191741. /* This changes the data from GG to XXGG */
  191742. else
  191743. {
  191744. png_bytep sp = row + (png_size_t)row_width * 2;
  191745. png_bytep dp = sp + (png_size_t)row_width * 2;
  191746. for (i = 0; i < row_width; i++)
  191747. {
  191748. *(--dp) = *(--sp);
  191749. *(--dp) = *(--sp);
  191750. *(--dp) = hi_filler;
  191751. *(--dp) = lo_filler;
  191752. }
  191753. row_info->channels = 2;
  191754. row_info->pixel_depth = 32;
  191755. row_info->rowbytes = row_width * 4;
  191756. }
  191757. }
  191758. } /* COLOR_TYPE == GRAY */
  191759. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191760. {
  191761. if(row_info->bit_depth == 8)
  191762. {
  191763. /* This changes the data from RGB to RGBX */
  191764. if (flags & PNG_FLAG_FILLER_AFTER)
  191765. {
  191766. png_bytep sp = row + (png_size_t)row_width * 3;
  191767. png_bytep dp = sp + (png_size_t)row_width;
  191768. for (i = 1; i < row_width; i++)
  191769. {
  191770. *(--dp) = lo_filler;
  191771. *(--dp) = *(--sp);
  191772. *(--dp) = *(--sp);
  191773. *(--dp) = *(--sp);
  191774. }
  191775. *(--dp) = lo_filler;
  191776. row_info->channels = 4;
  191777. row_info->pixel_depth = 32;
  191778. row_info->rowbytes = row_width * 4;
  191779. }
  191780. /* This changes the data from RGB to XRGB */
  191781. else
  191782. {
  191783. png_bytep sp = row + (png_size_t)row_width * 3;
  191784. png_bytep dp = sp + (png_size_t)row_width;
  191785. for (i = 0; i < row_width; i++)
  191786. {
  191787. *(--dp) = *(--sp);
  191788. *(--dp) = *(--sp);
  191789. *(--dp) = *(--sp);
  191790. *(--dp) = lo_filler;
  191791. }
  191792. row_info->channels = 4;
  191793. row_info->pixel_depth = 32;
  191794. row_info->rowbytes = row_width * 4;
  191795. }
  191796. }
  191797. else if(row_info->bit_depth == 16)
  191798. {
  191799. /* This changes the data from RRGGBB to RRGGBBXX */
  191800. if (flags & PNG_FLAG_FILLER_AFTER)
  191801. {
  191802. png_bytep sp = row + (png_size_t)row_width * 6;
  191803. png_bytep dp = sp + (png_size_t)row_width * 2;
  191804. for (i = 1; i < row_width; i++)
  191805. {
  191806. *(--dp) = hi_filler;
  191807. *(--dp) = lo_filler;
  191808. *(--dp) = *(--sp);
  191809. *(--dp) = *(--sp);
  191810. *(--dp) = *(--sp);
  191811. *(--dp) = *(--sp);
  191812. *(--dp) = *(--sp);
  191813. *(--dp) = *(--sp);
  191814. }
  191815. *(--dp) = hi_filler;
  191816. *(--dp) = lo_filler;
  191817. row_info->channels = 4;
  191818. row_info->pixel_depth = 64;
  191819. row_info->rowbytes = row_width * 8;
  191820. }
  191821. /* This changes the data from RRGGBB to XXRRGGBB */
  191822. else
  191823. {
  191824. png_bytep sp = row + (png_size_t)row_width * 6;
  191825. png_bytep dp = sp + (png_size_t)row_width * 2;
  191826. for (i = 0; i < row_width; i++)
  191827. {
  191828. *(--dp) = *(--sp);
  191829. *(--dp) = *(--sp);
  191830. *(--dp) = *(--sp);
  191831. *(--dp) = *(--sp);
  191832. *(--dp) = *(--sp);
  191833. *(--dp) = *(--sp);
  191834. *(--dp) = hi_filler;
  191835. *(--dp) = lo_filler;
  191836. }
  191837. row_info->channels = 4;
  191838. row_info->pixel_depth = 64;
  191839. row_info->rowbytes = row_width * 8;
  191840. }
  191841. }
  191842. } /* COLOR_TYPE == RGB */
  191843. }
  191844. #endif
  191845. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191846. /* expand grayscale files to RGB, with or without alpha */
  191847. void /* PRIVATE */
  191848. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191849. {
  191850. png_uint_32 i;
  191851. png_uint_32 row_width = row_info->width;
  191852. png_debug(1, "in png_do_gray_to_rgb\n");
  191853. if (row_info->bit_depth >= 8 &&
  191854. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191855. row != NULL && row_info != NULL &&
  191856. #endif
  191857. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191858. {
  191859. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191860. {
  191861. if (row_info->bit_depth == 8)
  191862. {
  191863. png_bytep sp = row + (png_size_t)row_width - 1;
  191864. png_bytep dp = sp + (png_size_t)row_width * 2;
  191865. for (i = 0; i < row_width; i++)
  191866. {
  191867. *(dp--) = *sp;
  191868. *(dp--) = *sp;
  191869. *(dp--) = *(sp--);
  191870. }
  191871. }
  191872. else
  191873. {
  191874. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191875. png_bytep dp = sp + (png_size_t)row_width * 4;
  191876. for (i = 0; i < row_width; i++)
  191877. {
  191878. *(dp--) = *sp;
  191879. *(dp--) = *(sp - 1);
  191880. *(dp--) = *sp;
  191881. *(dp--) = *(sp - 1);
  191882. *(dp--) = *(sp--);
  191883. *(dp--) = *(sp--);
  191884. }
  191885. }
  191886. }
  191887. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191888. {
  191889. if (row_info->bit_depth == 8)
  191890. {
  191891. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191892. png_bytep dp = sp + (png_size_t)row_width * 2;
  191893. for (i = 0; i < row_width; i++)
  191894. {
  191895. *(dp--) = *(sp--);
  191896. *(dp--) = *sp;
  191897. *(dp--) = *sp;
  191898. *(dp--) = *(sp--);
  191899. }
  191900. }
  191901. else
  191902. {
  191903. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191904. png_bytep dp = sp + (png_size_t)row_width * 4;
  191905. for (i = 0; i < row_width; i++)
  191906. {
  191907. *(dp--) = *(sp--);
  191908. *(dp--) = *(sp--);
  191909. *(dp--) = *sp;
  191910. *(dp--) = *(sp - 1);
  191911. *(dp--) = *sp;
  191912. *(dp--) = *(sp - 1);
  191913. *(dp--) = *(sp--);
  191914. *(dp--) = *(sp--);
  191915. }
  191916. }
  191917. }
  191918. row_info->channels += (png_byte)2;
  191919. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191920. row_info->pixel_depth = (png_byte)(row_info->channels *
  191921. row_info->bit_depth);
  191922. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191923. }
  191924. }
  191925. #endif
  191926. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191927. /* reduce RGB files to grayscale, with or without alpha
  191928. * using the equation given in Poynton's ColorFAQ at
  191929. * <http://www.inforamp.net/~poynton/>
  191930. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191931. *
  191932. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191933. *
  191934. * We approximate this with
  191935. *
  191936. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191937. *
  191938. * which can be expressed with integers as
  191939. *
  191940. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191941. *
  191942. * The calculation is to be done in a linear colorspace.
  191943. *
  191944. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191945. */
  191946. int /* PRIVATE */
  191947. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191948. {
  191949. png_uint_32 i;
  191950. png_uint_32 row_width = row_info->width;
  191951. int rgb_error = 0;
  191952. png_debug(1, "in png_do_rgb_to_gray\n");
  191953. if (
  191954. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191955. row != NULL && row_info != NULL &&
  191956. #endif
  191957. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191958. {
  191959. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191960. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191961. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191962. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191963. {
  191964. if (row_info->bit_depth == 8)
  191965. {
  191966. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191967. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191968. {
  191969. png_bytep sp = row;
  191970. png_bytep dp = row;
  191971. for (i = 0; i < row_width; i++)
  191972. {
  191973. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191974. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191975. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191976. if(red != green || red != blue)
  191977. {
  191978. rgb_error |= 1;
  191979. *(dp++) = png_ptr->gamma_from_1[
  191980. (rc*red+gc*green+bc*blue)>>15];
  191981. }
  191982. else
  191983. *(dp++) = *(sp-1);
  191984. }
  191985. }
  191986. else
  191987. #endif
  191988. {
  191989. png_bytep sp = row;
  191990. png_bytep dp = row;
  191991. for (i = 0; i < row_width; i++)
  191992. {
  191993. png_byte red = *(sp++);
  191994. png_byte green = *(sp++);
  191995. png_byte blue = *(sp++);
  191996. if(red != green || red != blue)
  191997. {
  191998. rgb_error |= 1;
  191999. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192000. }
  192001. else
  192002. *(dp++) = *(sp-1);
  192003. }
  192004. }
  192005. }
  192006. else /* RGB bit_depth == 16 */
  192007. {
  192008. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192009. if (png_ptr->gamma_16_to_1 != NULL &&
  192010. png_ptr->gamma_16_from_1 != NULL)
  192011. {
  192012. png_bytep sp = row;
  192013. png_bytep dp = row;
  192014. for (i = 0; i < row_width; i++)
  192015. {
  192016. png_uint_16 red, green, blue, w;
  192017. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192018. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192019. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192020. if(red == green && red == blue)
  192021. w = red;
  192022. else
  192023. {
  192024. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192025. png_ptr->gamma_shift][red>>8];
  192026. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192027. png_ptr->gamma_shift][green>>8];
  192028. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192029. png_ptr->gamma_shift][blue>>8];
  192030. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192031. + bc*blue_1)>>15);
  192032. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192033. png_ptr->gamma_shift][gray16 >> 8];
  192034. rgb_error |= 1;
  192035. }
  192036. *(dp++) = (png_byte)((w>>8) & 0xff);
  192037. *(dp++) = (png_byte)(w & 0xff);
  192038. }
  192039. }
  192040. else
  192041. #endif
  192042. {
  192043. png_bytep sp = row;
  192044. png_bytep dp = row;
  192045. for (i = 0; i < row_width; i++)
  192046. {
  192047. png_uint_16 red, green, blue, gray16;
  192048. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192049. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192050. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192051. if(red != green || red != blue)
  192052. rgb_error |= 1;
  192053. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192054. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192055. *(dp++) = (png_byte)(gray16 & 0xff);
  192056. }
  192057. }
  192058. }
  192059. }
  192060. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192061. {
  192062. if (row_info->bit_depth == 8)
  192063. {
  192064. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192065. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192066. {
  192067. png_bytep sp = row;
  192068. png_bytep dp = row;
  192069. for (i = 0; i < row_width; i++)
  192070. {
  192071. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192072. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192073. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192074. if(red != green || red != blue)
  192075. rgb_error |= 1;
  192076. *(dp++) = png_ptr->gamma_from_1
  192077. [(rc*red + gc*green + bc*blue)>>15];
  192078. *(dp++) = *(sp++); /* alpha */
  192079. }
  192080. }
  192081. else
  192082. #endif
  192083. {
  192084. png_bytep sp = row;
  192085. png_bytep dp = row;
  192086. for (i = 0; i < row_width; i++)
  192087. {
  192088. png_byte red = *(sp++);
  192089. png_byte green = *(sp++);
  192090. png_byte blue = *(sp++);
  192091. if(red != green || red != blue)
  192092. rgb_error |= 1;
  192093. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192094. *(dp++) = *(sp++); /* alpha */
  192095. }
  192096. }
  192097. }
  192098. else /* RGBA bit_depth == 16 */
  192099. {
  192100. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192101. if (png_ptr->gamma_16_to_1 != NULL &&
  192102. png_ptr->gamma_16_from_1 != NULL)
  192103. {
  192104. png_bytep sp = row;
  192105. png_bytep dp = row;
  192106. for (i = 0; i < row_width; i++)
  192107. {
  192108. png_uint_16 red, green, blue, w;
  192109. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192110. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192111. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192112. if(red == green && red == blue)
  192113. w = red;
  192114. else
  192115. {
  192116. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192117. png_ptr->gamma_shift][red>>8];
  192118. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192119. png_ptr->gamma_shift][green>>8];
  192120. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192121. png_ptr->gamma_shift][blue>>8];
  192122. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192123. + gc * green_1 + bc * blue_1)>>15);
  192124. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192125. png_ptr->gamma_shift][gray16 >> 8];
  192126. rgb_error |= 1;
  192127. }
  192128. *(dp++) = (png_byte)((w>>8) & 0xff);
  192129. *(dp++) = (png_byte)(w & 0xff);
  192130. *(dp++) = *(sp++); /* alpha */
  192131. *(dp++) = *(sp++);
  192132. }
  192133. }
  192134. else
  192135. #endif
  192136. {
  192137. png_bytep sp = row;
  192138. png_bytep dp = row;
  192139. for (i = 0; i < row_width; i++)
  192140. {
  192141. png_uint_16 red, green, blue, gray16;
  192142. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192143. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192144. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192145. if(red != green || red != blue)
  192146. rgb_error |= 1;
  192147. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192148. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192149. *(dp++) = (png_byte)(gray16 & 0xff);
  192150. *(dp++) = *(sp++); /* alpha */
  192151. *(dp++) = *(sp++);
  192152. }
  192153. }
  192154. }
  192155. }
  192156. row_info->channels -= (png_byte)2;
  192157. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192158. row_info->pixel_depth = (png_byte)(row_info->channels *
  192159. row_info->bit_depth);
  192160. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192161. }
  192162. return rgb_error;
  192163. }
  192164. #endif
  192165. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192166. * large of png_color. This lets grayscale images be treated as
  192167. * paletted. Most useful for gamma correction and simplification
  192168. * of code.
  192169. */
  192170. void PNGAPI
  192171. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192172. {
  192173. int num_palette;
  192174. int color_inc;
  192175. int i;
  192176. int v;
  192177. png_debug(1, "in png_do_build_grayscale_palette\n");
  192178. if (palette == NULL)
  192179. return;
  192180. switch (bit_depth)
  192181. {
  192182. case 1:
  192183. num_palette = 2;
  192184. color_inc = 0xff;
  192185. break;
  192186. case 2:
  192187. num_palette = 4;
  192188. color_inc = 0x55;
  192189. break;
  192190. case 4:
  192191. num_palette = 16;
  192192. color_inc = 0x11;
  192193. break;
  192194. case 8:
  192195. num_palette = 256;
  192196. color_inc = 1;
  192197. break;
  192198. default:
  192199. num_palette = 0;
  192200. color_inc = 0;
  192201. break;
  192202. }
  192203. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192204. {
  192205. palette[i].red = (png_byte)v;
  192206. palette[i].green = (png_byte)v;
  192207. palette[i].blue = (png_byte)v;
  192208. }
  192209. }
  192210. /* This function is currently unused. Do we really need it? */
  192211. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192212. void /* PRIVATE */
  192213. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192214. int num_palette)
  192215. {
  192216. png_debug(1, "in png_correct_palette\n");
  192217. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192218. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192219. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192220. {
  192221. png_color back, back_1;
  192222. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192223. {
  192224. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192225. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192226. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192227. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192228. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192229. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192230. }
  192231. else
  192232. {
  192233. double g;
  192234. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192235. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192236. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192237. {
  192238. back.red = png_ptr->background.red;
  192239. back.green = png_ptr->background.green;
  192240. back.blue = png_ptr->background.blue;
  192241. }
  192242. else
  192243. {
  192244. back.red =
  192245. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192246. 255.0 + 0.5);
  192247. back.green =
  192248. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192249. 255.0 + 0.5);
  192250. back.blue =
  192251. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192252. 255.0 + 0.5);
  192253. }
  192254. g = 1.0 / png_ptr->background_gamma;
  192255. back_1.red =
  192256. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192257. 255.0 + 0.5);
  192258. back_1.green =
  192259. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192260. 255.0 + 0.5);
  192261. back_1.blue =
  192262. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192263. 255.0 + 0.5);
  192264. }
  192265. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192266. {
  192267. png_uint_32 i;
  192268. for (i = 0; i < (png_uint_32)num_palette; i++)
  192269. {
  192270. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192271. {
  192272. palette[i] = back;
  192273. }
  192274. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192275. {
  192276. png_byte v, w;
  192277. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192278. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192279. palette[i].red = png_ptr->gamma_from_1[w];
  192280. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192281. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192282. palette[i].green = png_ptr->gamma_from_1[w];
  192283. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192284. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192285. palette[i].blue = png_ptr->gamma_from_1[w];
  192286. }
  192287. else
  192288. {
  192289. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192290. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192291. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192292. }
  192293. }
  192294. }
  192295. else
  192296. {
  192297. int i;
  192298. for (i = 0; i < num_palette; i++)
  192299. {
  192300. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192301. {
  192302. palette[i] = back;
  192303. }
  192304. else
  192305. {
  192306. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192307. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192308. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192309. }
  192310. }
  192311. }
  192312. }
  192313. else
  192314. #endif
  192315. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192316. if (png_ptr->transformations & PNG_GAMMA)
  192317. {
  192318. int i;
  192319. for (i = 0; i < num_palette; i++)
  192320. {
  192321. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192322. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192323. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192324. }
  192325. }
  192326. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192327. else
  192328. #endif
  192329. #endif
  192330. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192331. if (png_ptr->transformations & PNG_BACKGROUND)
  192332. {
  192333. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192334. {
  192335. png_color back;
  192336. back.red = (png_byte)png_ptr->background.red;
  192337. back.green = (png_byte)png_ptr->background.green;
  192338. back.blue = (png_byte)png_ptr->background.blue;
  192339. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192340. {
  192341. if (png_ptr->trans[i] == 0)
  192342. {
  192343. palette[i].red = back.red;
  192344. palette[i].green = back.green;
  192345. palette[i].blue = back.blue;
  192346. }
  192347. else if (png_ptr->trans[i] != 0xff)
  192348. {
  192349. png_composite(palette[i].red, png_ptr->palette[i].red,
  192350. png_ptr->trans[i], back.red);
  192351. png_composite(palette[i].green, png_ptr->palette[i].green,
  192352. png_ptr->trans[i], back.green);
  192353. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192354. png_ptr->trans[i], back.blue);
  192355. }
  192356. }
  192357. }
  192358. else /* assume grayscale palette (what else could it be?) */
  192359. {
  192360. int i;
  192361. for (i = 0; i < num_palette; i++)
  192362. {
  192363. if (i == (png_byte)png_ptr->trans_values.gray)
  192364. {
  192365. palette[i].red = (png_byte)png_ptr->background.red;
  192366. palette[i].green = (png_byte)png_ptr->background.green;
  192367. palette[i].blue = (png_byte)png_ptr->background.blue;
  192368. }
  192369. }
  192370. }
  192371. }
  192372. #endif
  192373. }
  192374. #endif
  192375. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192376. /* Replace any alpha or transparency with the supplied background color.
  192377. * "background" is already in the screen gamma, while "background_1" is
  192378. * at a gamma of 1.0. Paletted files have already been taken care of.
  192379. */
  192380. void /* PRIVATE */
  192381. png_do_background(png_row_infop row_info, png_bytep row,
  192382. png_color_16p trans_values, png_color_16p background
  192383. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192384. , png_color_16p background_1,
  192385. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192386. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192387. png_uint_16pp gamma_16_to_1, int gamma_shift
  192388. #endif
  192389. )
  192390. {
  192391. png_bytep sp, dp;
  192392. png_uint_32 i;
  192393. png_uint_32 row_width=row_info->width;
  192394. int shift;
  192395. png_debug(1, "in png_do_background\n");
  192396. if (background != NULL &&
  192397. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192398. row != NULL && row_info != NULL &&
  192399. #endif
  192400. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192401. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192402. {
  192403. switch (row_info->color_type)
  192404. {
  192405. case PNG_COLOR_TYPE_GRAY:
  192406. {
  192407. switch (row_info->bit_depth)
  192408. {
  192409. case 1:
  192410. {
  192411. sp = row;
  192412. shift = 7;
  192413. for (i = 0; i < row_width; i++)
  192414. {
  192415. if ((png_uint_16)((*sp >> shift) & 0x01)
  192416. == trans_values->gray)
  192417. {
  192418. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192419. *sp |= (png_byte)(background->gray << shift);
  192420. }
  192421. if (!shift)
  192422. {
  192423. shift = 7;
  192424. sp++;
  192425. }
  192426. else
  192427. shift--;
  192428. }
  192429. break;
  192430. }
  192431. case 2:
  192432. {
  192433. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192434. if (gamma_table != NULL)
  192435. {
  192436. sp = row;
  192437. shift = 6;
  192438. for (i = 0; i < row_width; i++)
  192439. {
  192440. if ((png_uint_16)((*sp >> shift) & 0x03)
  192441. == trans_values->gray)
  192442. {
  192443. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192444. *sp |= (png_byte)(background->gray << shift);
  192445. }
  192446. else
  192447. {
  192448. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192449. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192450. (p << 4) | (p << 6)] >> 6) & 0x03);
  192451. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192452. *sp |= (png_byte)(g << shift);
  192453. }
  192454. if (!shift)
  192455. {
  192456. shift = 6;
  192457. sp++;
  192458. }
  192459. else
  192460. shift -= 2;
  192461. }
  192462. }
  192463. else
  192464. #endif
  192465. {
  192466. sp = row;
  192467. shift = 6;
  192468. for (i = 0; i < row_width; i++)
  192469. {
  192470. if ((png_uint_16)((*sp >> shift) & 0x03)
  192471. == trans_values->gray)
  192472. {
  192473. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192474. *sp |= (png_byte)(background->gray << shift);
  192475. }
  192476. if (!shift)
  192477. {
  192478. shift = 6;
  192479. sp++;
  192480. }
  192481. else
  192482. shift -= 2;
  192483. }
  192484. }
  192485. break;
  192486. }
  192487. case 4:
  192488. {
  192489. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192490. if (gamma_table != NULL)
  192491. {
  192492. sp = row;
  192493. shift = 4;
  192494. for (i = 0; i < row_width; i++)
  192495. {
  192496. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192497. == trans_values->gray)
  192498. {
  192499. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192500. *sp |= (png_byte)(background->gray << shift);
  192501. }
  192502. else
  192503. {
  192504. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192505. png_byte g = (png_byte)((gamma_table[p |
  192506. (p << 4)] >> 4) & 0x0f);
  192507. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192508. *sp |= (png_byte)(g << shift);
  192509. }
  192510. if (!shift)
  192511. {
  192512. shift = 4;
  192513. sp++;
  192514. }
  192515. else
  192516. shift -= 4;
  192517. }
  192518. }
  192519. else
  192520. #endif
  192521. {
  192522. sp = row;
  192523. shift = 4;
  192524. for (i = 0; i < row_width; i++)
  192525. {
  192526. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192527. == trans_values->gray)
  192528. {
  192529. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192530. *sp |= (png_byte)(background->gray << shift);
  192531. }
  192532. if (!shift)
  192533. {
  192534. shift = 4;
  192535. sp++;
  192536. }
  192537. else
  192538. shift -= 4;
  192539. }
  192540. }
  192541. break;
  192542. }
  192543. case 8:
  192544. {
  192545. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192546. if (gamma_table != NULL)
  192547. {
  192548. sp = row;
  192549. for (i = 0; i < row_width; i++, sp++)
  192550. {
  192551. if (*sp == trans_values->gray)
  192552. {
  192553. *sp = (png_byte)background->gray;
  192554. }
  192555. else
  192556. {
  192557. *sp = gamma_table[*sp];
  192558. }
  192559. }
  192560. }
  192561. else
  192562. #endif
  192563. {
  192564. sp = row;
  192565. for (i = 0; i < row_width; i++, sp++)
  192566. {
  192567. if (*sp == trans_values->gray)
  192568. {
  192569. *sp = (png_byte)background->gray;
  192570. }
  192571. }
  192572. }
  192573. break;
  192574. }
  192575. case 16:
  192576. {
  192577. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192578. if (gamma_16 != NULL)
  192579. {
  192580. sp = row;
  192581. for (i = 0; i < row_width; i++, sp += 2)
  192582. {
  192583. png_uint_16 v;
  192584. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192585. if (v == trans_values->gray)
  192586. {
  192587. /* background is already in screen gamma */
  192588. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192589. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192590. }
  192591. else
  192592. {
  192593. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192594. *sp = (png_byte)((v >> 8) & 0xff);
  192595. *(sp + 1) = (png_byte)(v & 0xff);
  192596. }
  192597. }
  192598. }
  192599. else
  192600. #endif
  192601. {
  192602. sp = row;
  192603. for (i = 0; i < row_width; i++, sp += 2)
  192604. {
  192605. png_uint_16 v;
  192606. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192607. if (v == trans_values->gray)
  192608. {
  192609. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192610. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192611. }
  192612. }
  192613. }
  192614. break;
  192615. }
  192616. }
  192617. break;
  192618. }
  192619. case PNG_COLOR_TYPE_RGB:
  192620. {
  192621. if (row_info->bit_depth == 8)
  192622. {
  192623. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192624. if (gamma_table != NULL)
  192625. {
  192626. sp = row;
  192627. for (i = 0; i < row_width; i++, sp += 3)
  192628. {
  192629. if (*sp == trans_values->red &&
  192630. *(sp + 1) == trans_values->green &&
  192631. *(sp + 2) == trans_values->blue)
  192632. {
  192633. *sp = (png_byte)background->red;
  192634. *(sp + 1) = (png_byte)background->green;
  192635. *(sp + 2) = (png_byte)background->blue;
  192636. }
  192637. else
  192638. {
  192639. *sp = gamma_table[*sp];
  192640. *(sp + 1) = gamma_table[*(sp + 1)];
  192641. *(sp + 2) = gamma_table[*(sp + 2)];
  192642. }
  192643. }
  192644. }
  192645. else
  192646. #endif
  192647. {
  192648. sp = row;
  192649. for (i = 0; i < row_width; i++, sp += 3)
  192650. {
  192651. if (*sp == trans_values->red &&
  192652. *(sp + 1) == trans_values->green &&
  192653. *(sp + 2) == trans_values->blue)
  192654. {
  192655. *sp = (png_byte)background->red;
  192656. *(sp + 1) = (png_byte)background->green;
  192657. *(sp + 2) = (png_byte)background->blue;
  192658. }
  192659. }
  192660. }
  192661. }
  192662. else /* if (row_info->bit_depth == 16) */
  192663. {
  192664. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192665. if (gamma_16 != NULL)
  192666. {
  192667. sp = row;
  192668. for (i = 0; i < row_width; i++, sp += 6)
  192669. {
  192670. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192671. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192672. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192673. if (r == trans_values->red && g == trans_values->green &&
  192674. b == trans_values->blue)
  192675. {
  192676. /* background is already in screen gamma */
  192677. *sp = (png_byte)((background->red >> 8) & 0xff);
  192678. *(sp + 1) = (png_byte)(background->red & 0xff);
  192679. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192680. *(sp + 3) = (png_byte)(background->green & 0xff);
  192681. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192682. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192683. }
  192684. else
  192685. {
  192686. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192687. *sp = (png_byte)((v >> 8) & 0xff);
  192688. *(sp + 1) = (png_byte)(v & 0xff);
  192689. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192690. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192691. *(sp + 3) = (png_byte)(v & 0xff);
  192692. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192693. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192694. *(sp + 5) = (png_byte)(v & 0xff);
  192695. }
  192696. }
  192697. }
  192698. else
  192699. #endif
  192700. {
  192701. sp = row;
  192702. for (i = 0; i < row_width; i++, sp += 6)
  192703. {
  192704. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192705. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192706. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192707. if (r == trans_values->red && g == trans_values->green &&
  192708. b == trans_values->blue)
  192709. {
  192710. *sp = (png_byte)((background->red >> 8) & 0xff);
  192711. *(sp + 1) = (png_byte)(background->red & 0xff);
  192712. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192713. *(sp + 3) = (png_byte)(background->green & 0xff);
  192714. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192715. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192716. }
  192717. }
  192718. }
  192719. }
  192720. break;
  192721. }
  192722. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192723. {
  192724. if (row_info->bit_depth == 8)
  192725. {
  192726. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192727. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192728. gamma_table != NULL)
  192729. {
  192730. sp = row;
  192731. dp = row;
  192732. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192733. {
  192734. png_uint_16 a = *(sp + 1);
  192735. if (a == 0xff)
  192736. {
  192737. *dp = gamma_table[*sp];
  192738. }
  192739. else if (a == 0)
  192740. {
  192741. /* background is already in screen gamma */
  192742. *dp = (png_byte)background->gray;
  192743. }
  192744. else
  192745. {
  192746. png_byte v, w;
  192747. v = gamma_to_1[*sp];
  192748. png_composite(w, v, a, background_1->gray);
  192749. *dp = gamma_from_1[w];
  192750. }
  192751. }
  192752. }
  192753. else
  192754. #endif
  192755. {
  192756. sp = row;
  192757. dp = row;
  192758. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192759. {
  192760. png_byte a = *(sp + 1);
  192761. if (a == 0xff)
  192762. {
  192763. *dp = *sp;
  192764. }
  192765. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192766. else if (a == 0)
  192767. {
  192768. *dp = (png_byte)background->gray;
  192769. }
  192770. else
  192771. {
  192772. png_composite(*dp, *sp, a, background_1->gray);
  192773. }
  192774. #else
  192775. *dp = (png_byte)background->gray;
  192776. #endif
  192777. }
  192778. }
  192779. }
  192780. else /* if (png_ptr->bit_depth == 16) */
  192781. {
  192782. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192783. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192784. gamma_16_to_1 != NULL)
  192785. {
  192786. sp = row;
  192787. dp = row;
  192788. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192789. {
  192790. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192791. if (a == (png_uint_16)0xffff)
  192792. {
  192793. png_uint_16 v;
  192794. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192795. *dp = (png_byte)((v >> 8) & 0xff);
  192796. *(dp + 1) = (png_byte)(v & 0xff);
  192797. }
  192798. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192799. else if (a == 0)
  192800. #else
  192801. else
  192802. #endif
  192803. {
  192804. /* background is already in screen gamma */
  192805. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192806. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192807. }
  192808. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192809. else
  192810. {
  192811. png_uint_16 g, v, w;
  192812. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192813. png_composite_16(v, g, a, background_1->gray);
  192814. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192815. *dp = (png_byte)((w >> 8) & 0xff);
  192816. *(dp + 1) = (png_byte)(w & 0xff);
  192817. }
  192818. #endif
  192819. }
  192820. }
  192821. else
  192822. #endif
  192823. {
  192824. sp = row;
  192825. dp = row;
  192826. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192827. {
  192828. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192829. if (a == (png_uint_16)0xffff)
  192830. {
  192831. png_memcpy(dp, sp, 2);
  192832. }
  192833. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192834. else if (a == 0)
  192835. #else
  192836. else
  192837. #endif
  192838. {
  192839. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192840. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192841. }
  192842. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192843. else
  192844. {
  192845. png_uint_16 g, v;
  192846. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192847. png_composite_16(v, g, a, background_1->gray);
  192848. *dp = (png_byte)((v >> 8) & 0xff);
  192849. *(dp + 1) = (png_byte)(v & 0xff);
  192850. }
  192851. #endif
  192852. }
  192853. }
  192854. }
  192855. break;
  192856. }
  192857. case PNG_COLOR_TYPE_RGB_ALPHA:
  192858. {
  192859. if (row_info->bit_depth == 8)
  192860. {
  192861. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192862. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192863. gamma_table != NULL)
  192864. {
  192865. sp = row;
  192866. dp = row;
  192867. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192868. {
  192869. png_byte a = *(sp + 3);
  192870. if (a == 0xff)
  192871. {
  192872. *dp = gamma_table[*sp];
  192873. *(dp + 1) = gamma_table[*(sp + 1)];
  192874. *(dp + 2) = gamma_table[*(sp + 2)];
  192875. }
  192876. else if (a == 0)
  192877. {
  192878. /* background is already in screen gamma */
  192879. *dp = (png_byte)background->red;
  192880. *(dp + 1) = (png_byte)background->green;
  192881. *(dp + 2) = (png_byte)background->blue;
  192882. }
  192883. else
  192884. {
  192885. png_byte v, w;
  192886. v = gamma_to_1[*sp];
  192887. png_composite(w, v, a, background_1->red);
  192888. *dp = gamma_from_1[w];
  192889. v = gamma_to_1[*(sp + 1)];
  192890. png_composite(w, v, a, background_1->green);
  192891. *(dp + 1) = gamma_from_1[w];
  192892. v = gamma_to_1[*(sp + 2)];
  192893. png_composite(w, v, a, background_1->blue);
  192894. *(dp + 2) = gamma_from_1[w];
  192895. }
  192896. }
  192897. }
  192898. else
  192899. #endif
  192900. {
  192901. sp = row;
  192902. dp = row;
  192903. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192904. {
  192905. png_byte a = *(sp + 3);
  192906. if (a == 0xff)
  192907. {
  192908. *dp = *sp;
  192909. *(dp + 1) = *(sp + 1);
  192910. *(dp + 2) = *(sp + 2);
  192911. }
  192912. else if (a == 0)
  192913. {
  192914. *dp = (png_byte)background->red;
  192915. *(dp + 1) = (png_byte)background->green;
  192916. *(dp + 2) = (png_byte)background->blue;
  192917. }
  192918. else
  192919. {
  192920. png_composite(*dp, *sp, a, background->red);
  192921. png_composite(*(dp + 1), *(sp + 1), a,
  192922. background->green);
  192923. png_composite(*(dp + 2), *(sp + 2), a,
  192924. background->blue);
  192925. }
  192926. }
  192927. }
  192928. }
  192929. else /* if (row_info->bit_depth == 16) */
  192930. {
  192931. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192932. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192933. gamma_16_to_1 != NULL)
  192934. {
  192935. sp = row;
  192936. dp = row;
  192937. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192938. {
  192939. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192940. << 8) + (png_uint_16)(*(sp + 7)));
  192941. if (a == (png_uint_16)0xffff)
  192942. {
  192943. png_uint_16 v;
  192944. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192945. *dp = (png_byte)((v >> 8) & 0xff);
  192946. *(dp + 1) = (png_byte)(v & 0xff);
  192947. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192948. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192949. *(dp + 3) = (png_byte)(v & 0xff);
  192950. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192951. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192952. *(dp + 5) = (png_byte)(v & 0xff);
  192953. }
  192954. else if (a == 0)
  192955. {
  192956. /* background is already in screen gamma */
  192957. *dp = (png_byte)((background->red >> 8) & 0xff);
  192958. *(dp + 1) = (png_byte)(background->red & 0xff);
  192959. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192960. *(dp + 3) = (png_byte)(background->green & 0xff);
  192961. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192962. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192963. }
  192964. else
  192965. {
  192966. png_uint_16 v, w, x;
  192967. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192968. png_composite_16(w, v, a, background_1->red);
  192969. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192970. *dp = (png_byte)((x >> 8) & 0xff);
  192971. *(dp + 1) = (png_byte)(x & 0xff);
  192972. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192973. png_composite_16(w, v, a, background_1->green);
  192974. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192975. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192976. *(dp + 3) = (png_byte)(x & 0xff);
  192977. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192978. png_composite_16(w, v, a, background_1->blue);
  192979. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192980. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192981. *(dp + 5) = (png_byte)(x & 0xff);
  192982. }
  192983. }
  192984. }
  192985. else
  192986. #endif
  192987. {
  192988. sp = row;
  192989. dp = row;
  192990. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192991. {
  192992. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192993. << 8) + (png_uint_16)(*(sp + 7)));
  192994. if (a == (png_uint_16)0xffff)
  192995. {
  192996. png_memcpy(dp, sp, 6);
  192997. }
  192998. else if (a == 0)
  192999. {
  193000. *dp = (png_byte)((background->red >> 8) & 0xff);
  193001. *(dp + 1) = (png_byte)(background->red & 0xff);
  193002. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193003. *(dp + 3) = (png_byte)(background->green & 0xff);
  193004. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193005. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193006. }
  193007. else
  193008. {
  193009. png_uint_16 v;
  193010. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193011. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193012. + *(sp + 3));
  193013. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193014. + *(sp + 5));
  193015. png_composite_16(v, r, a, background->red);
  193016. *dp = (png_byte)((v >> 8) & 0xff);
  193017. *(dp + 1) = (png_byte)(v & 0xff);
  193018. png_composite_16(v, g, a, background->green);
  193019. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193020. *(dp + 3) = (png_byte)(v & 0xff);
  193021. png_composite_16(v, b, a, background->blue);
  193022. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193023. *(dp + 5) = (png_byte)(v & 0xff);
  193024. }
  193025. }
  193026. }
  193027. }
  193028. break;
  193029. }
  193030. }
  193031. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193032. {
  193033. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193034. row_info->channels--;
  193035. row_info->pixel_depth = (png_byte)(row_info->channels *
  193036. row_info->bit_depth);
  193037. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193038. }
  193039. }
  193040. }
  193041. #endif
  193042. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193043. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193044. * you do this after you deal with the transparency issue on grayscale
  193045. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193046. * is 16, use gamma_16_table and gamma_shift. Build these with
  193047. * build_gamma_table().
  193048. */
  193049. void /* PRIVATE */
  193050. png_do_gamma(png_row_infop row_info, png_bytep row,
  193051. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193052. int gamma_shift)
  193053. {
  193054. png_bytep sp;
  193055. png_uint_32 i;
  193056. png_uint_32 row_width=row_info->width;
  193057. png_debug(1, "in png_do_gamma\n");
  193058. if (
  193059. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193060. row != NULL && row_info != NULL &&
  193061. #endif
  193062. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193063. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193064. {
  193065. switch (row_info->color_type)
  193066. {
  193067. case PNG_COLOR_TYPE_RGB:
  193068. {
  193069. if (row_info->bit_depth == 8)
  193070. {
  193071. sp = row;
  193072. for (i = 0; i < row_width; i++)
  193073. {
  193074. *sp = gamma_table[*sp];
  193075. sp++;
  193076. *sp = gamma_table[*sp];
  193077. sp++;
  193078. *sp = gamma_table[*sp];
  193079. sp++;
  193080. }
  193081. }
  193082. else /* if (row_info->bit_depth == 16) */
  193083. {
  193084. sp = row;
  193085. for (i = 0; i < row_width; i++)
  193086. {
  193087. png_uint_16 v;
  193088. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193089. *sp = (png_byte)((v >> 8) & 0xff);
  193090. *(sp + 1) = (png_byte)(v & 0xff);
  193091. sp += 2;
  193092. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193093. *sp = (png_byte)((v >> 8) & 0xff);
  193094. *(sp + 1) = (png_byte)(v & 0xff);
  193095. sp += 2;
  193096. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193097. *sp = (png_byte)((v >> 8) & 0xff);
  193098. *(sp + 1) = (png_byte)(v & 0xff);
  193099. sp += 2;
  193100. }
  193101. }
  193102. break;
  193103. }
  193104. case PNG_COLOR_TYPE_RGB_ALPHA:
  193105. {
  193106. if (row_info->bit_depth == 8)
  193107. {
  193108. sp = row;
  193109. for (i = 0; i < row_width; i++)
  193110. {
  193111. *sp = gamma_table[*sp];
  193112. sp++;
  193113. *sp = gamma_table[*sp];
  193114. sp++;
  193115. *sp = gamma_table[*sp];
  193116. sp++;
  193117. sp++;
  193118. }
  193119. }
  193120. else /* if (row_info->bit_depth == 16) */
  193121. {
  193122. sp = row;
  193123. for (i = 0; i < row_width; i++)
  193124. {
  193125. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193126. *sp = (png_byte)((v >> 8) & 0xff);
  193127. *(sp + 1) = (png_byte)(v & 0xff);
  193128. sp += 2;
  193129. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193130. *sp = (png_byte)((v >> 8) & 0xff);
  193131. *(sp + 1) = (png_byte)(v & 0xff);
  193132. sp += 2;
  193133. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193134. *sp = (png_byte)((v >> 8) & 0xff);
  193135. *(sp + 1) = (png_byte)(v & 0xff);
  193136. sp += 4;
  193137. }
  193138. }
  193139. break;
  193140. }
  193141. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193142. {
  193143. if (row_info->bit_depth == 8)
  193144. {
  193145. sp = row;
  193146. for (i = 0; i < row_width; i++)
  193147. {
  193148. *sp = gamma_table[*sp];
  193149. sp += 2;
  193150. }
  193151. }
  193152. else /* if (row_info->bit_depth == 16) */
  193153. {
  193154. sp = row;
  193155. for (i = 0; i < row_width; i++)
  193156. {
  193157. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193158. *sp = (png_byte)((v >> 8) & 0xff);
  193159. *(sp + 1) = (png_byte)(v & 0xff);
  193160. sp += 4;
  193161. }
  193162. }
  193163. break;
  193164. }
  193165. case PNG_COLOR_TYPE_GRAY:
  193166. {
  193167. if (row_info->bit_depth == 2)
  193168. {
  193169. sp = row;
  193170. for (i = 0; i < row_width; i += 4)
  193171. {
  193172. int a = *sp & 0xc0;
  193173. int b = *sp & 0x30;
  193174. int c = *sp & 0x0c;
  193175. int d = *sp & 0x03;
  193176. *sp = (png_byte)(
  193177. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193178. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193179. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193180. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193181. sp++;
  193182. }
  193183. }
  193184. if (row_info->bit_depth == 4)
  193185. {
  193186. sp = row;
  193187. for (i = 0; i < row_width; i += 2)
  193188. {
  193189. int msb = *sp & 0xf0;
  193190. int lsb = *sp & 0x0f;
  193191. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193192. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193193. sp++;
  193194. }
  193195. }
  193196. else if (row_info->bit_depth == 8)
  193197. {
  193198. sp = row;
  193199. for (i = 0; i < row_width; i++)
  193200. {
  193201. *sp = gamma_table[*sp];
  193202. sp++;
  193203. }
  193204. }
  193205. else if (row_info->bit_depth == 16)
  193206. {
  193207. sp = row;
  193208. for (i = 0; i < row_width; i++)
  193209. {
  193210. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193211. *sp = (png_byte)((v >> 8) & 0xff);
  193212. *(sp + 1) = (png_byte)(v & 0xff);
  193213. sp += 2;
  193214. }
  193215. }
  193216. break;
  193217. }
  193218. }
  193219. }
  193220. }
  193221. #endif
  193222. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193223. /* Expands a palette row to an RGB or RGBA row depending
  193224. * upon whether you supply trans and num_trans.
  193225. */
  193226. void /* PRIVATE */
  193227. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193228. png_colorp palette, png_bytep trans, int num_trans)
  193229. {
  193230. int shift, value;
  193231. png_bytep sp, dp;
  193232. png_uint_32 i;
  193233. png_uint_32 row_width=row_info->width;
  193234. png_debug(1, "in png_do_expand_palette\n");
  193235. if (
  193236. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193237. row != NULL && row_info != NULL &&
  193238. #endif
  193239. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193240. {
  193241. if (row_info->bit_depth < 8)
  193242. {
  193243. switch (row_info->bit_depth)
  193244. {
  193245. case 1:
  193246. {
  193247. sp = row + (png_size_t)((row_width - 1) >> 3);
  193248. dp = row + (png_size_t)row_width - 1;
  193249. shift = 7 - (int)((row_width + 7) & 0x07);
  193250. for (i = 0; i < row_width; i++)
  193251. {
  193252. if ((*sp >> shift) & 0x01)
  193253. *dp = 1;
  193254. else
  193255. *dp = 0;
  193256. if (shift == 7)
  193257. {
  193258. shift = 0;
  193259. sp--;
  193260. }
  193261. else
  193262. shift++;
  193263. dp--;
  193264. }
  193265. break;
  193266. }
  193267. case 2:
  193268. {
  193269. sp = row + (png_size_t)((row_width - 1) >> 2);
  193270. dp = row + (png_size_t)row_width - 1;
  193271. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193272. for (i = 0; i < row_width; i++)
  193273. {
  193274. value = (*sp >> shift) & 0x03;
  193275. *dp = (png_byte)value;
  193276. if (shift == 6)
  193277. {
  193278. shift = 0;
  193279. sp--;
  193280. }
  193281. else
  193282. shift += 2;
  193283. dp--;
  193284. }
  193285. break;
  193286. }
  193287. case 4:
  193288. {
  193289. sp = row + (png_size_t)((row_width - 1) >> 1);
  193290. dp = row + (png_size_t)row_width - 1;
  193291. shift = (int)((row_width & 0x01) << 2);
  193292. for (i = 0; i < row_width; i++)
  193293. {
  193294. value = (*sp >> shift) & 0x0f;
  193295. *dp = (png_byte)value;
  193296. if (shift == 4)
  193297. {
  193298. shift = 0;
  193299. sp--;
  193300. }
  193301. else
  193302. shift += 4;
  193303. dp--;
  193304. }
  193305. break;
  193306. }
  193307. }
  193308. row_info->bit_depth = 8;
  193309. row_info->pixel_depth = 8;
  193310. row_info->rowbytes = row_width;
  193311. }
  193312. switch (row_info->bit_depth)
  193313. {
  193314. case 8:
  193315. {
  193316. if (trans != NULL)
  193317. {
  193318. sp = row + (png_size_t)row_width - 1;
  193319. dp = row + (png_size_t)(row_width << 2) - 1;
  193320. for (i = 0; i < row_width; i++)
  193321. {
  193322. if ((int)(*sp) >= num_trans)
  193323. *dp-- = 0xff;
  193324. else
  193325. *dp-- = trans[*sp];
  193326. *dp-- = palette[*sp].blue;
  193327. *dp-- = palette[*sp].green;
  193328. *dp-- = palette[*sp].red;
  193329. sp--;
  193330. }
  193331. row_info->bit_depth = 8;
  193332. row_info->pixel_depth = 32;
  193333. row_info->rowbytes = row_width * 4;
  193334. row_info->color_type = 6;
  193335. row_info->channels = 4;
  193336. }
  193337. else
  193338. {
  193339. sp = row + (png_size_t)row_width - 1;
  193340. dp = row + (png_size_t)(row_width * 3) - 1;
  193341. for (i = 0; i < row_width; i++)
  193342. {
  193343. *dp-- = palette[*sp].blue;
  193344. *dp-- = palette[*sp].green;
  193345. *dp-- = palette[*sp].red;
  193346. sp--;
  193347. }
  193348. row_info->bit_depth = 8;
  193349. row_info->pixel_depth = 24;
  193350. row_info->rowbytes = row_width * 3;
  193351. row_info->color_type = 2;
  193352. row_info->channels = 3;
  193353. }
  193354. break;
  193355. }
  193356. }
  193357. }
  193358. }
  193359. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193360. * expanded transparency value is supplied, an alpha channel is built.
  193361. */
  193362. void /* PRIVATE */
  193363. png_do_expand(png_row_infop row_info, png_bytep row,
  193364. png_color_16p trans_value)
  193365. {
  193366. int shift, value;
  193367. png_bytep sp, dp;
  193368. png_uint_32 i;
  193369. png_uint_32 row_width=row_info->width;
  193370. png_debug(1, "in png_do_expand\n");
  193371. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193372. if (row != NULL && row_info != NULL)
  193373. #endif
  193374. {
  193375. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193376. {
  193377. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193378. if (row_info->bit_depth < 8)
  193379. {
  193380. switch (row_info->bit_depth)
  193381. {
  193382. case 1:
  193383. {
  193384. gray = (png_uint_16)((gray&0x01)*0xff);
  193385. sp = row + (png_size_t)((row_width - 1) >> 3);
  193386. dp = row + (png_size_t)row_width - 1;
  193387. shift = 7 - (int)((row_width + 7) & 0x07);
  193388. for (i = 0; i < row_width; i++)
  193389. {
  193390. if ((*sp >> shift) & 0x01)
  193391. *dp = 0xff;
  193392. else
  193393. *dp = 0;
  193394. if (shift == 7)
  193395. {
  193396. shift = 0;
  193397. sp--;
  193398. }
  193399. else
  193400. shift++;
  193401. dp--;
  193402. }
  193403. break;
  193404. }
  193405. case 2:
  193406. {
  193407. gray = (png_uint_16)((gray&0x03)*0x55);
  193408. sp = row + (png_size_t)((row_width - 1) >> 2);
  193409. dp = row + (png_size_t)row_width - 1;
  193410. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193411. for (i = 0; i < row_width; i++)
  193412. {
  193413. value = (*sp >> shift) & 0x03;
  193414. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193415. (value << 6));
  193416. if (shift == 6)
  193417. {
  193418. shift = 0;
  193419. sp--;
  193420. }
  193421. else
  193422. shift += 2;
  193423. dp--;
  193424. }
  193425. break;
  193426. }
  193427. case 4:
  193428. {
  193429. gray = (png_uint_16)((gray&0x0f)*0x11);
  193430. sp = row + (png_size_t)((row_width - 1) >> 1);
  193431. dp = row + (png_size_t)row_width - 1;
  193432. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193433. for (i = 0; i < row_width; i++)
  193434. {
  193435. value = (*sp >> shift) & 0x0f;
  193436. *dp = (png_byte)(value | (value << 4));
  193437. if (shift == 4)
  193438. {
  193439. shift = 0;
  193440. sp--;
  193441. }
  193442. else
  193443. shift = 4;
  193444. dp--;
  193445. }
  193446. break;
  193447. }
  193448. }
  193449. row_info->bit_depth = 8;
  193450. row_info->pixel_depth = 8;
  193451. row_info->rowbytes = row_width;
  193452. }
  193453. if (trans_value != NULL)
  193454. {
  193455. if (row_info->bit_depth == 8)
  193456. {
  193457. gray = gray & 0xff;
  193458. sp = row + (png_size_t)row_width - 1;
  193459. dp = row + (png_size_t)(row_width << 1) - 1;
  193460. for (i = 0; i < row_width; i++)
  193461. {
  193462. if (*sp == gray)
  193463. *dp-- = 0;
  193464. else
  193465. *dp-- = 0xff;
  193466. *dp-- = *sp--;
  193467. }
  193468. }
  193469. else if (row_info->bit_depth == 16)
  193470. {
  193471. png_byte gray_high = (gray >> 8) & 0xff;
  193472. png_byte gray_low = gray & 0xff;
  193473. sp = row + row_info->rowbytes - 1;
  193474. dp = row + (row_info->rowbytes << 1) - 1;
  193475. for (i = 0; i < row_width; i++)
  193476. {
  193477. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193478. {
  193479. *dp-- = 0;
  193480. *dp-- = 0;
  193481. }
  193482. else
  193483. {
  193484. *dp-- = 0xff;
  193485. *dp-- = 0xff;
  193486. }
  193487. *dp-- = *sp--;
  193488. *dp-- = *sp--;
  193489. }
  193490. }
  193491. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193492. row_info->channels = 2;
  193493. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193494. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193495. row_width);
  193496. }
  193497. }
  193498. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193499. {
  193500. if (row_info->bit_depth == 8)
  193501. {
  193502. png_byte red = trans_value->red & 0xff;
  193503. png_byte green = trans_value->green & 0xff;
  193504. png_byte blue = trans_value->blue & 0xff;
  193505. sp = row + (png_size_t)row_info->rowbytes - 1;
  193506. dp = row + (png_size_t)(row_width << 2) - 1;
  193507. for (i = 0; i < row_width; i++)
  193508. {
  193509. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193510. *dp-- = 0;
  193511. else
  193512. *dp-- = 0xff;
  193513. *dp-- = *sp--;
  193514. *dp-- = *sp--;
  193515. *dp-- = *sp--;
  193516. }
  193517. }
  193518. else if (row_info->bit_depth == 16)
  193519. {
  193520. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193521. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193522. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193523. png_byte red_low = trans_value->red & 0xff;
  193524. png_byte green_low = trans_value->green & 0xff;
  193525. png_byte blue_low = trans_value->blue & 0xff;
  193526. sp = row + row_info->rowbytes - 1;
  193527. dp = row + (png_size_t)(row_width << 3) - 1;
  193528. for (i = 0; i < row_width; i++)
  193529. {
  193530. if (*(sp - 5) == red_high &&
  193531. *(sp - 4) == red_low &&
  193532. *(sp - 3) == green_high &&
  193533. *(sp - 2) == green_low &&
  193534. *(sp - 1) == blue_high &&
  193535. *(sp ) == blue_low)
  193536. {
  193537. *dp-- = 0;
  193538. *dp-- = 0;
  193539. }
  193540. else
  193541. {
  193542. *dp-- = 0xff;
  193543. *dp-- = 0xff;
  193544. }
  193545. *dp-- = *sp--;
  193546. *dp-- = *sp--;
  193547. *dp-- = *sp--;
  193548. *dp-- = *sp--;
  193549. *dp-- = *sp--;
  193550. *dp-- = *sp--;
  193551. }
  193552. }
  193553. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193554. row_info->channels = 4;
  193555. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193556. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193557. }
  193558. }
  193559. }
  193560. #endif
  193561. #if defined(PNG_READ_DITHER_SUPPORTED)
  193562. void /* PRIVATE */
  193563. png_do_dither(png_row_infop row_info, png_bytep row,
  193564. png_bytep palette_lookup, png_bytep dither_lookup)
  193565. {
  193566. png_bytep sp, dp;
  193567. png_uint_32 i;
  193568. png_uint_32 row_width=row_info->width;
  193569. png_debug(1, "in png_do_dither\n");
  193570. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193571. if (row != NULL && row_info != NULL)
  193572. #endif
  193573. {
  193574. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193575. palette_lookup && row_info->bit_depth == 8)
  193576. {
  193577. int r, g, b, p;
  193578. sp = row;
  193579. dp = row;
  193580. for (i = 0; i < row_width; i++)
  193581. {
  193582. r = *sp++;
  193583. g = *sp++;
  193584. b = *sp++;
  193585. /* this looks real messy, but the compiler will reduce
  193586. it down to a reasonable formula. For example, with
  193587. 5 bits per color, we get:
  193588. p = (((r >> 3) & 0x1f) << 10) |
  193589. (((g >> 3) & 0x1f) << 5) |
  193590. ((b >> 3) & 0x1f);
  193591. */
  193592. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193593. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193594. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193595. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193596. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193597. (PNG_DITHER_BLUE_BITS)) |
  193598. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193599. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193600. *dp++ = palette_lookup[p];
  193601. }
  193602. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193603. row_info->channels = 1;
  193604. row_info->pixel_depth = row_info->bit_depth;
  193605. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193606. }
  193607. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193608. palette_lookup != NULL && row_info->bit_depth == 8)
  193609. {
  193610. int r, g, b, p;
  193611. sp = row;
  193612. dp = row;
  193613. for (i = 0; i < row_width; i++)
  193614. {
  193615. r = *sp++;
  193616. g = *sp++;
  193617. b = *sp++;
  193618. sp++;
  193619. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193620. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193621. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193622. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193623. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193624. (PNG_DITHER_BLUE_BITS)) |
  193625. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193626. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193627. *dp++ = palette_lookup[p];
  193628. }
  193629. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193630. row_info->channels = 1;
  193631. row_info->pixel_depth = row_info->bit_depth;
  193632. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193633. }
  193634. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193635. dither_lookup && row_info->bit_depth == 8)
  193636. {
  193637. sp = row;
  193638. for (i = 0; i < row_width; i++, sp++)
  193639. {
  193640. *sp = dither_lookup[*sp];
  193641. }
  193642. }
  193643. }
  193644. }
  193645. #endif
  193646. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193647. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193648. static PNG_CONST int png_gamma_shift[] =
  193649. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193650. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193651. * tables, we don't make a full table if we are reducing to 8-bit in
  193652. * the future. Note also how the gamma_16 tables are segmented so that
  193653. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193654. */
  193655. void /* PRIVATE */
  193656. png_build_gamma_table(png_structp png_ptr)
  193657. {
  193658. png_debug(1, "in png_build_gamma_table\n");
  193659. if (png_ptr->bit_depth <= 8)
  193660. {
  193661. int i;
  193662. double g;
  193663. if (png_ptr->screen_gamma > .000001)
  193664. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193665. else
  193666. g = 1.0;
  193667. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193668. (png_uint_32)256);
  193669. for (i = 0; i < 256; i++)
  193670. {
  193671. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193672. g) * 255.0 + .5);
  193673. }
  193674. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193675. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193676. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193677. {
  193678. g = 1.0 / (png_ptr->gamma);
  193679. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193680. (png_uint_32)256);
  193681. for (i = 0; i < 256; i++)
  193682. {
  193683. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193684. g) * 255.0 + .5);
  193685. }
  193686. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193687. (png_uint_32)256);
  193688. if(png_ptr->screen_gamma > 0.000001)
  193689. g = 1.0 / png_ptr->screen_gamma;
  193690. else
  193691. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193692. for (i = 0; i < 256; i++)
  193693. {
  193694. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193695. g) * 255.0 + .5);
  193696. }
  193697. }
  193698. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193699. }
  193700. else
  193701. {
  193702. double g;
  193703. int i, j, shift, num;
  193704. int sig_bit;
  193705. png_uint_32 ig;
  193706. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193707. {
  193708. sig_bit = (int)png_ptr->sig_bit.red;
  193709. if ((int)png_ptr->sig_bit.green > sig_bit)
  193710. sig_bit = png_ptr->sig_bit.green;
  193711. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193712. sig_bit = png_ptr->sig_bit.blue;
  193713. }
  193714. else
  193715. {
  193716. sig_bit = (int)png_ptr->sig_bit.gray;
  193717. }
  193718. if (sig_bit > 0)
  193719. shift = 16 - sig_bit;
  193720. else
  193721. shift = 0;
  193722. if (png_ptr->transformations & PNG_16_TO_8)
  193723. {
  193724. if (shift < (16 - PNG_MAX_GAMMA_8))
  193725. shift = (16 - PNG_MAX_GAMMA_8);
  193726. }
  193727. if (shift > 8)
  193728. shift = 8;
  193729. if (shift < 0)
  193730. shift = 0;
  193731. png_ptr->gamma_shift = (png_byte)shift;
  193732. num = (1 << (8 - shift));
  193733. if (png_ptr->screen_gamma > .000001)
  193734. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193735. else
  193736. g = 1.0;
  193737. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193738. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193739. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193740. {
  193741. double fin, fout;
  193742. png_uint_32 last, max;
  193743. for (i = 0; i < num; i++)
  193744. {
  193745. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193746. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193747. }
  193748. g = 1.0 / g;
  193749. last = 0;
  193750. for (i = 0; i < 256; i++)
  193751. {
  193752. fout = ((double)i + 0.5) / 256.0;
  193753. fin = pow(fout, g);
  193754. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193755. while (last <= max)
  193756. {
  193757. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193758. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193759. (png_uint_16)i | ((png_uint_16)i << 8));
  193760. last++;
  193761. }
  193762. }
  193763. while (last < ((png_uint_32)num << 8))
  193764. {
  193765. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193766. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193767. last++;
  193768. }
  193769. }
  193770. else
  193771. {
  193772. for (i = 0; i < num; i++)
  193773. {
  193774. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193775. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193776. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193777. for (j = 0; j < 256; j++)
  193778. {
  193779. png_ptr->gamma_16_table[i][j] =
  193780. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193781. 65535.0, g) * 65535.0 + .5);
  193782. }
  193783. }
  193784. }
  193785. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193786. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193787. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193788. {
  193789. g = 1.0 / (png_ptr->gamma);
  193790. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193791. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193792. for (i = 0; i < num; i++)
  193793. {
  193794. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193795. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193796. ig = (((png_uint_32)i *
  193797. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193798. for (j = 0; j < 256; j++)
  193799. {
  193800. png_ptr->gamma_16_to_1[i][j] =
  193801. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193802. 65535.0, g) * 65535.0 + .5);
  193803. }
  193804. }
  193805. if(png_ptr->screen_gamma > 0.000001)
  193806. g = 1.0 / png_ptr->screen_gamma;
  193807. else
  193808. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193809. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193810. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193811. for (i = 0; i < num; i++)
  193812. {
  193813. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193814. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193815. ig = (((png_uint_32)i *
  193816. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193817. for (j = 0; j < 256; j++)
  193818. {
  193819. png_ptr->gamma_16_from_1[i][j] =
  193820. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193821. 65535.0, g) * 65535.0 + .5);
  193822. }
  193823. }
  193824. }
  193825. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193826. }
  193827. }
  193828. #endif
  193829. /* To do: install integer version of png_build_gamma_table here */
  193830. #endif
  193831. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193832. /* undoes intrapixel differencing */
  193833. void /* PRIVATE */
  193834. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193835. {
  193836. png_debug(1, "in png_do_read_intrapixel\n");
  193837. if (
  193838. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193839. row != NULL && row_info != NULL &&
  193840. #endif
  193841. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193842. {
  193843. int bytes_per_pixel;
  193844. png_uint_32 row_width = row_info->width;
  193845. if (row_info->bit_depth == 8)
  193846. {
  193847. png_bytep rp;
  193848. png_uint_32 i;
  193849. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193850. bytes_per_pixel = 3;
  193851. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193852. bytes_per_pixel = 4;
  193853. else
  193854. return;
  193855. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193856. {
  193857. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193858. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193859. }
  193860. }
  193861. else if (row_info->bit_depth == 16)
  193862. {
  193863. png_bytep rp;
  193864. png_uint_32 i;
  193865. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193866. bytes_per_pixel = 6;
  193867. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193868. bytes_per_pixel = 8;
  193869. else
  193870. return;
  193871. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193872. {
  193873. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193874. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193875. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193876. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193877. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193878. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193879. *(rp+1) = (png_byte)(red & 0xff);
  193880. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193881. *(rp+5) = (png_byte)(blue & 0xff);
  193882. }
  193883. }
  193884. }
  193885. }
  193886. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193887. #endif /* PNG_READ_SUPPORTED */
  193888. /*** End of inlined file: pngrtran.c ***/
  193889. /*** Start of inlined file: pngrutil.c ***/
  193890. /* pngrutil.c - utilities to read a PNG file
  193891. *
  193892. * Last changed in libpng 1.2.21 [October 4, 2007]
  193893. * For conditions of distribution and use, see copyright notice in png.h
  193894. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193895. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193896. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193897. *
  193898. * This file contains routines that are only called from within
  193899. * libpng itself during the course of reading an image.
  193900. */
  193901. #define PNG_INTERNAL
  193902. #if defined(PNG_READ_SUPPORTED)
  193903. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193904. # define WIN32_WCE_OLD
  193905. #endif
  193906. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193907. # if defined(WIN32_WCE_OLD)
  193908. /* strtod() function is not supported on WindowsCE */
  193909. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193910. {
  193911. double result = 0;
  193912. int len;
  193913. wchar_t *str, *end;
  193914. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193915. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193916. if ( NULL != str )
  193917. {
  193918. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193919. result = wcstod(str, &end);
  193920. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193921. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193922. png_free(png_ptr, str);
  193923. }
  193924. return result;
  193925. }
  193926. # else
  193927. # define png_strtod(p,a,b) strtod(a,b)
  193928. # endif
  193929. #endif
  193930. png_uint_32 PNGAPI
  193931. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193932. {
  193933. png_uint_32 i = png_get_uint_32(buf);
  193934. if (i > PNG_UINT_31_MAX)
  193935. png_error(png_ptr, "PNG unsigned integer out of range.");
  193936. return (i);
  193937. }
  193938. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193939. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193940. png_uint_32 PNGAPI
  193941. png_get_uint_32(png_bytep buf)
  193942. {
  193943. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193944. ((png_uint_32)(*(buf + 1)) << 16) +
  193945. ((png_uint_32)(*(buf + 2)) << 8) +
  193946. (png_uint_32)(*(buf + 3));
  193947. return (i);
  193948. }
  193949. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193950. * data is stored in the PNG file in two's complement format, and it is
  193951. * assumed that the machine format for signed integers is the same. */
  193952. png_int_32 PNGAPI
  193953. png_get_int_32(png_bytep buf)
  193954. {
  193955. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193956. ((png_int_32)(*(buf + 1)) << 16) +
  193957. ((png_int_32)(*(buf + 2)) << 8) +
  193958. (png_int_32)(*(buf + 3));
  193959. return (i);
  193960. }
  193961. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193962. png_uint_16 PNGAPI
  193963. png_get_uint_16(png_bytep buf)
  193964. {
  193965. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193966. (png_uint_16)(*(buf + 1)));
  193967. return (i);
  193968. }
  193969. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193970. /* Read data, and (optionally) run it through the CRC. */
  193971. void /* PRIVATE */
  193972. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193973. {
  193974. if(png_ptr == NULL) return;
  193975. png_read_data(png_ptr, buf, length);
  193976. png_calculate_crc(png_ptr, buf, length);
  193977. }
  193978. /* Optionally skip data and then check the CRC. Depending on whether we
  193979. are reading a ancillary or critical chunk, and how the program has set
  193980. things up, we may calculate the CRC on the data and print a message.
  193981. Returns '1' if there was a CRC error, '0' otherwise. */
  193982. int /* PRIVATE */
  193983. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193984. {
  193985. png_size_t i;
  193986. png_size_t istop = png_ptr->zbuf_size;
  193987. for (i = (png_size_t)skip; i > istop; i -= istop)
  193988. {
  193989. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193990. }
  193991. if (i)
  193992. {
  193993. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193994. }
  193995. if (png_crc_error(png_ptr))
  193996. {
  193997. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193998. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193999. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194000. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194001. {
  194002. png_chunk_warning(png_ptr, "CRC error");
  194003. }
  194004. else
  194005. {
  194006. png_chunk_error(png_ptr, "CRC error");
  194007. }
  194008. return (1);
  194009. }
  194010. return (0);
  194011. }
  194012. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194013. the data it has read thus far. */
  194014. int /* PRIVATE */
  194015. png_crc_error(png_structp png_ptr)
  194016. {
  194017. png_byte crc_bytes[4];
  194018. png_uint_32 crc;
  194019. int need_crc = 1;
  194020. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194021. {
  194022. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194023. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194024. need_crc = 0;
  194025. }
  194026. else /* critical */
  194027. {
  194028. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194029. need_crc = 0;
  194030. }
  194031. png_read_data(png_ptr, crc_bytes, 4);
  194032. if (need_crc)
  194033. {
  194034. crc = png_get_uint_32(crc_bytes);
  194035. return ((int)(crc != png_ptr->crc));
  194036. }
  194037. else
  194038. return (0);
  194039. }
  194040. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194041. defined(PNG_READ_iCCP_SUPPORTED)
  194042. /*
  194043. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194044. * points at an allocated area holding the contents of a chunk with a
  194045. * trailing compressed part. What we get back is an allocated area
  194046. * holding the original prefix part and an uncompressed version of the
  194047. * trailing part (the malloc area passed in is freed).
  194048. */
  194049. png_charp /* PRIVATE */
  194050. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194051. png_charp chunkdata, png_size_t chunklength,
  194052. png_size_t prefix_size, png_size_t *newlength)
  194053. {
  194054. static PNG_CONST char msg[] = "Error decoding compressed text";
  194055. png_charp text;
  194056. png_size_t text_size;
  194057. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194058. {
  194059. int ret = Z_OK;
  194060. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194061. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194062. png_ptr->zstream.next_out = png_ptr->zbuf;
  194063. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194064. text_size = 0;
  194065. text = NULL;
  194066. while (png_ptr->zstream.avail_in)
  194067. {
  194068. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194069. if (ret != Z_OK && ret != Z_STREAM_END)
  194070. {
  194071. if (png_ptr->zstream.msg != NULL)
  194072. png_warning(png_ptr, png_ptr->zstream.msg);
  194073. else
  194074. png_warning(png_ptr, msg);
  194075. inflateReset(&png_ptr->zstream);
  194076. png_ptr->zstream.avail_in = 0;
  194077. if (text == NULL)
  194078. {
  194079. text_size = prefix_size + png_sizeof(msg) + 1;
  194080. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194081. if (text == NULL)
  194082. {
  194083. png_free(png_ptr,chunkdata);
  194084. png_error(png_ptr,"Not enough memory to decompress chunk");
  194085. }
  194086. png_memcpy(text, chunkdata, prefix_size);
  194087. }
  194088. text[text_size - 1] = 0x00;
  194089. /* Copy what we can of the error message into the text chunk */
  194090. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194091. text_size = png_sizeof(msg) > text_size ? text_size :
  194092. png_sizeof(msg);
  194093. png_memcpy(text + prefix_size, msg, text_size + 1);
  194094. break;
  194095. }
  194096. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194097. {
  194098. if (text == NULL)
  194099. {
  194100. text_size = prefix_size +
  194101. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194102. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194103. if (text == NULL)
  194104. {
  194105. png_free(png_ptr,chunkdata);
  194106. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194107. }
  194108. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194109. text_size - prefix_size);
  194110. png_memcpy(text, chunkdata, prefix_size);
  194111. *(text + text_size) = 0x00;
  194112. }
  194113. else
  194114. {
  194115. png_charp tmp;
  194116. tmp = text;
  194117. text = (png_charp)png_malloc_warn(png_ptr,
  194118. (png_uint_32)(text_size +
  194119. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194120. if (text == NULL)
  194121. {
  194122. png_free(png_ptr, tmp);
  194123. png_free(png_ptr, chunkdata);
  194124. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194125. }
  194126. png_memcpy(text, tmp, text_size);
  194127. png_free(png_ptr, tmp);
  194128. png_memcpy(text + text_size, png_ptr->zbuf,
  194129. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194130. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194131. *(text + text_size) = 0x00;
  194132. }
  194133. if (ret == Z_STREAM_END)
  194134. break;
  194135. else
  194136. {
  194137. png_ptr->zstream.next_out = png_ptr->zbuf;
  194138. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194139. }
  194140. }
  194141. }
  194142. if (ret != Z_STREAM_END)
  194143. {
  194144. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194145. char umsg[52];
  194146. if (ret == Z_BUF_ERROR)
  194147. png_snprintf(umsg, 52,
  194148. "Buffer error in compressed datastream in %s chunk",
  194149. png_ptr->chunk_name);
  194150. else if (ret == Z_DATA_ERROR)
  194151. png_snprintf(umsg, 52,
  194152. "Data error in compressed datastream in %s chunk",
  194153. png_ptr->chunk_name);
  194154. else
  194155. png_snprintf(umsg, 52,
  194156. "Incomplete compressed datastream in %s chunk",
  194157. png_ptr->chunk_name);
  194158. png_warning(png_ptr, umsg);
  194159. #else
  194160. png_warning(png_ptr,
  194161. "Incomplete compressed datastream in chunk other than IDAT");
  194162. #endif
  194163. text_size=prefix_size;
  194164. if (text == NULL)
  194165. {
  194166. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194167. if (text == NULL)
  194168. {
  194169. png_free(png_ptr, chunkdata);
  194170. png_error(png_ptr,"Not enough memory for text.");
  194171. }
  194172. png_memcpy(text, chunkdata, prefix_size);
  194173. }
  194174. *(text + text_size) = 0x00;
  194175. }
  194176. inflateReset(&png_ptr->zstream);
  194177. png_ptr->zstream.avail_in = 0;
  194178. png_free(png_ptr, chunkdata);
  194179. chunkdata = text;
  194180. *newlength=text_size;
  194181. }
  194182. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194183. {
  194184. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194185. char umsg[50];
  194186. png_snprintf(umsg, 50,
  194187. "Unknown zTXt compression type %d", comp_type);
  194188. png_warning(png_ptr, umsg);
  194189. #else
  194190. png_warning(png_ptr, "Unknown zTXt compression type");
  194191. #endif
  194192. *(chunkdata + prefix_size) = 0x00;
  194193. *newlength=prefix_size;
  194194. }
  194195. return chunkdata;
  194196. }
  194197. #endif
  194198. /* read and check the IDHR chunk */
  194199. void /* PRIVATE */
  194200. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194201. {
  194202. png_byte buf[13];
  194203. png_uint_32 width, height;
  194204. int bit_depth, color_type, compression_type, filter_type;
  194205. int interlace_type;
  194206. png_debug(1, "in png_handle_IHDR\n");
  194207. if (png_ptr->mode & PNG_HAVE_IHDR)
  194208. png_error(png_ptr, "Out of place IHDR");
  194209. /* check the length */
  194210. if (length != 13)
  194211. png_error(png_ptr, "Invalid IHDR chunk");
  194212. png_ptr->mode |= PNG_HAVE_IHDR;
  194213. png_crc_read(png_ptr, buf, 13);
  194214. png_crc_finish(png_ptr, 0);
  194215. width = png_get_uint_31(png_ptr, buf);
  194216. height = png_get_uint_31(png_ptr, buf + 4);
  194217. bit_depth = buf[8];
  194218. color_type = buf[9];
  194219. compression_type = buf[10];
  194220. filter_type = buf[11];
  194221. interlace_type = buf[12];
  194222. /* set internal variables */
  194223. png_ptr->width = width;
  194224. png_ptr->height = height;
  194225. png_ptr->bit_depth = (png_byte)bit_depth;
  194226. png_ptr->interlaced = (png_byte)interlace_type;
  194227. png_ptr->color_type = (png_byte)color_type;
  194228. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194229. png_ptr->filter_type = (png_byte)filter_type;
  194230. #endif
  194231. png_ptr->compression_type = (png_byte)compression_type;
  194232. /* find number of channels */
  194233. switch (png_ptr->color_type)
  194234. {
  194235. case PNG_COLOR_TYPE_GRAY:
  194236. case PNG_COLOR_TYPE_PALETTE:
  194237. png_ptr->channels = 1;
  194238. break;
  194239. case PNG_COLOR_TYPE_RGB:
  194240. png_ptr->channels = 3;
  194241. break;
  194242. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194243. png_ptr->channels = 2;
  194244. break;
  194245. case PNG_COLOR_TYPE_RGB_ALPHA:
  194246. png_ptr->channels = 4;
  194247. break;
  194248. }
  194249. /* set up other useful info */
  194250. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194251. png_ptr->channels);
  194252. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194253. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194254. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194255. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194256. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194257. color_type, interlace_type, compression_type, filter_type);
  194258. }
  194259. /* read and check the palette */
  194260. void /* PRIVATE */
  194261. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194262. {
  194263. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194264. int num, i;
  194265. #ifndef PNG_NO_POINTER_INDEXING
  194266. png_colorp pal_ptr;
  194267. #endif
  194268. png_debug(1, "in png_handle_PLTE\n");
  194269. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194270. png_error(png_ptr, "Missing IHDR before PLTE");
  194271. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194272. {
  194273. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194274. png_crc_finish(png_ptr, length);
  194275. return;
  194276. }
  194277. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194278. png_error(png_ptr, "Duplicate PLTE chunk");
  194279. png_ptr->mode |= PNG_HAVE_PLTE;
  194280. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194281. {
  194282. png_warning(png_ptr,
  194283. "Ignoring PLTE chunk in grayscale PNG");
  194284. png_crc_finish(png_ptr, length);
  194285. return;
  194286. }
  194287. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194288. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194289. {
  194290. png_crc_finish(png_ptr, length);
  194291. return;
  194292. }
  194293. #endif
  194294. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194295. {
  194296. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194297. {
  194298. png_warning(png_ptr, "Invalid palette chunk");
  194299. png_crc_finish(png_ptr, length);
  194300. return;
  194301. }
  194302. else
  194303. {
  194304. png_error(png_ptr, "Invalid palette chunk");
  194305. }
  194306. }
  194307. num = (int)length / 3;
  194308. #ifndef PNG_NO_POINTER_INDEXING
  194309. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194310. {
  194311. png_byte buf[3];
  194312. png_crc_read(png_ptr, buf, 3);
  194313. pal_ptr->red = buf[0];
  194314. pal_ptr->green = buf[1];
  194315. pal_ptr->blue = buf[2];
  194316. }
  194317. #else
  194318. for (i = 0; i < num; i++)
  194319. {
  194320. png_byte buf[3];
  194321. png_crc_read(png_ptr, buf, 3);
  194322. /* don't depend upon png_color being any order */
  194323. palette[i].red = buf[0];
  194324. palette[i].green = buf[1];
  194325. palette[i].blue = buf[2];
  194326. }
  194327. #endif
  194328. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194329. whatever the normal CRC configuration tells us. However, if we
  194330. have an RGB image, the PLTE can be considered ancillary, so
  194331. we will act as though it is. */
  194332. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194333. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194334. #endif
  194335. {
  194336. png_crc_finish(png_ptr, 0);
  194337. }
  194338. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194339. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194340. {
  194341. /* If we don't want to use the data from an ancillary chunk,
  194342. we have two options: an error abort, or a warning and we
  194343. ignore the data in this chunk (which should be OK, since
  194344. it's considered ancillary for a RGB or RGBA image). */
  194345. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194346. {
  194347. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194348. {
  194349. png_chunk_error(png_ptr, "CRC error");
  194350. }
  194351. else
  194352. {
  194353. png_chunk_warning(png_ptr, "CRC error");
  194354. return;
  194355. }
  194356. }
  194357. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194358. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194359. {
  194360. png_chunk_warning(png_ptr, "CRC error");
  194361. }
  194362. }
  194363. #endif
  194364. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194365. #if defined(PNG_READ_tRNS_SUPPORTED)
  194366. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194367. {
  194368. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194369. {
  194370. if (png_ptr->num_trans > (png_uint_16)num)
  194371. {
  194372. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194373. png_ptr->num_trans = (png_uint_16)num;
  194374. }
  194375. if (info_ptr->num_trans > (png_uint_16)num)
  194376. {
  194377. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194378. info_ptr->num_trans = (png_uint_16)num;
  194379. }
  194380. }
  194381. }
  194382. #endif
  194383. }
  194384. void /* PRIVATE */
  194385. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194386. {
  194387. png_debug(1, "in png_handle_IEND\n");
  194388. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194389. {
  194390. png_error(png_ptr, "No image in file");
  194391. }
  194392. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194393. if (length != 0)
  194394. {
  194395. png_warning(png_ptr, "Incorrect IEND chunk length");
  194396. }
  194397. png_crc_finish(png_ptr, length);
  194398. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194399. }
  194400. #if defined(PNG_READ_gAMA_SUPPORTED)
  194401. void /* PRIVATE */
  194402. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194403. {
  194404. png_fixed_point igamma;
  194405. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194406. float file_gamma;
  194407. #endif
  194408. png_byte buf[4];
  194409. png_debug(1, "in png_handle_gAMA\n");
  194410. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194411. png_error(png_ptr, "Missing IHDR before gAMA");
  194412. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194413. {
  194414. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194415. png_crc_finish(png_ptr, length);
  194416. return;
  194417. }
  194418. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194419. /* Should be an error, but we can cope with it */
  194420. png_warning(png_ptr, "Out of place gAMA chunk");
  194421. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194422. #if defined(PNG_READ_sRGB_SUPPORTED)
  194423. && !(info_ptr->valid & PNG_INFO_sRGB)
  194424. #endif
  194425. )
  194426. {
  194427. png_warning(png_ptr, "Duplicate gAMA chunk");
  194428. png_crc_finish(png_ptr, length);
  194429. return;
  194430. }
  194431. if (length != 4)
  194432. {
  194433. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194434. png_crc_finish(png_ptr, length);
  194435. return;
  194436. }
  194437. png_crc_read(png_ptr, buf, 4);
  194438. if (png_crc_finish(png_ptr, 0))
  194439. return;
  194440. igamma = (png_fixed_point)png_get_uint_32(buf);
  194441. /* check for zero gamma */
  194442. if (igamma == 0)
  194443. {
  194444. png_warning(png_ptr,
  194445. "Ignoring gAMA chunk with gamma=0");
  194446. return;
  194447. }
  194448. #if defined(PNG_READ_sRGB_SUPPORTED)
  194449. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194450. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194451. {
  194452. png_warning(png_ptr,
  194453. "Ignoring incorrect gAMA value when sRGB is also present");
  194454. #ifndef PNG_NO_CONSOLE_IO
  194455. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194456. #endif
  194457. return;
  194458. }
  194459. #endif /* PNG_READ_sRGB_SUPPORTED */
  194460. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194461. file_gamma = (float)igamma / (float)100000.0;
  194462. # ifdef PNG_READ_GAMMA_SUPPORTED
  194463. png_ptr->gamma = file_gamma;
  194464. # endif
  194465. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194466. #endif
  194467. #ifdef PNG_FIXED_POINT_SUPPORTED
  194468. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194469. #endif
  194470. }
  194471. #endif
  194472. #if defined(PNG_READ_sBIT_SUPPORTED)
  194473. void /* PRIVATE */
  194474. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194475. {
  194476. png_size_t truelen;
  194477. png_byte buf[4];
  194478. png_debug(1, "in png_handle_sBIT\n");
  194479. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194480. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194481. png_error(png_ptr, "Missing IHDR before sBIT");
  194482. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194483. {
  194484. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194485. png_crc_finish(png_ptr, length);
  194486. return;
  194487. }
  194488. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194489. {
  194490. /* Should be an error, but we can cope with it */
  194491. png_warning(png_ptr, "Out of place sBIT chunk");
  194492. }
  194493. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194494. {
  194495. png_warning(png_ptr, "Duplicate sBIT chunk");
  194496. png_crc_finish(png_ptr, length);
  194497. return;
  194498. }
  194499. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194500. truelen = 3;
  194501. else
  194502. truelen = (png_size_t)png_ptr->channels;
  194503. if (length != truelen || length > 4)
  194504. {
  194505. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194506. png_crc_finish(png_ptr, length);
  194507. return;
  194508. }
  194509. png_crc_read(png_ptr, buf, truelen);
  194510. if (png_crc_finish(png_ptr, 0))
  194511. return;
  194512. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194513. {
  194514. png_ptr->sig_bit.red = buf[0];
  194515. png_ptr->sig_bit.green = buf[1];
  194516. png_ptr->sig_bit.blue = buf[2];
  194517. png_ptr->sig_bit.alpha = buf[3];
  194518. }
  194519. else
  194520. {
  194521. png_ptr->sig_bit.gray = buf[0];
  194522. png_ptr->sig_bit.red = buf[0];
  194523. png_ptr->sig_bit.green = buf[0];
  194524. png_ptr->sig_bit.blue = buf[0];
  194525. png_ptr->sig_bit.alpha = buf[1];
  194526. }
  194527. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194528. }
  194529. #endif
  194530. #if defined(PNG_READ_cHRM_SUPPORTED)
  194531. void /* PRIVATE */
  194532. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194533. {
  194534. png_byte buf[4];
  194535. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194536. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194537. #endif
  194538. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194539. int_y_green, int_x_blue, int_y_blue;
  194540. png_uint_32 uint_x, uint_y;
  194541. png_debug(1, "in png_handle_cHRM\n");
  194542. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194543. png_error(png_ptr, "Missing IHDR before cHRM");
  194544. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194545. {
  194546. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194547. png_crc_finish(png_ptr, length);
  194548. return;
  194549. }
  194550. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194551. /* Should be an error, but we can cope with it */
  194552. png_warning(png_ptr, "Missing PLTE before cHRM");
  194553. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194554. #if defined(PNG_READ_sRGB_SUPPORTED)
  194555. && !(info_ptr->valid & PNG_INFO_sRGB)
  194556. #endif
  194557. )
  194558. {
  194559. png_warning(png_ptr, "Duplicate cHRM chunk");
  194560. png_crc_finish(png_ptr, length);
  194561. return;
  194562. }
  194563. if (length != 32)
  194564. {
  194565. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194566. png_crc_finish(png_ptr, length);
  194567. return;
  194568. }
  194569. png_crc_read(png_ptr, buf, 4);
  194570. uint_x = png_get_uint_32(buf);
  194571. png_crc_read(png_ptr, buf, 4);
  194572. uint_y = png_get_uint_32(buf);
  194573. if (uint_x > 80000L || uint_y > 80000L ||
  194574. uint_x + uint_y > 100000L)
  194575. {
  194576. png_warning(png_ptr, "Invalid cHRM white point");
  194577. png_crc_finish(png_ptr, 24);
  194578. return;
  194579. }
  194580. int_x_white = (png_fixed_point)uint_x;
  194581. int_y_white = (png_fixed_point)uint_y;
  194582. png_crc_read(png_ptr, buf, 4);
  194583. uint_x = png_get_uint_32(buf);
  194584. png_crc_read(png_ptr, buf, 4);
  194585. uint_y = png_get_uint_32(buf);
  194586. if (uint_x + uint_y > 100000L)
  194587. {
  194588. png_warning(png_ptr, "Invalid cHRM red point");
  194589. png_crc_finish(png_ptr, 16);
  194590. return;
  194591. }
  194592. int_x_red = (png_fixed_point)uint_x;
  194593. int_y_red = (png_fixed_point)uint_y;
  194594. png_crc_read(png_ptr, buf, 4);
  194595. uint_x = png_get_uint_32(buf);
  194596. png_crc_read(png_ptr, buf, 4);
  194597. uint_y = png_get_uint_32(buf);
  194598. if (uint_x + uint_y > 100000L)
  194599. {
  194600. png_warning(png_ptr, "Invalid cHRM green point");
  194601. png_crc_finish(png_ptr, 8);
  194602. return;
  194603. }
  194604. int_x_green = (png_fixed_point)uint_x;
  194605. int_y_green = (png_fixed_point)uint_y;
  194606. png_crc_read(png_ptr, buf, 4);
  194607. uint_x = png_get_uint_32(buf);
  194608. png_crc_read(png_ptr, buf, 4);
  194609. uint_y = png_get_uint_32(buf);
  194610. if (uint_x + uint_y > 100000L)
  194611. {
  194612. png_warning(png_ptr, "Invalid cHRM blue point");
  194613. png_crc_finish(png_ptr, 0);
  194614. return;
  194615. }
  194616. int_x_blue = (png_fixed_point)uint_x;
  194617. int_y_blue = (png_fixed_point)uint_y;
  194618. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194619. white_x = (float)int_x_white / (float)100000.0;
  194620. white_y = (float)int_y_white / (float)100000.0;
  194621. red_x = (float)int_x_red / (float)100000.0;
  194622. red_y = (float)int_y_red / (float)100000.0;
  194623. green_x = (float)int_x_green / (float)100000.0;
  194624. green_y = (float)int_y_green / (float)100000.0;
  194625. blue_x = (float)int_x_blue / (float)100000.0;
  194626. blue_y = (float)int_y_blue / (float)100000.0;
  194627. #endif
  194628. #if defined(PNG_READ_sRGB_SUPPORTED)
  194629. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194630. {
  194631. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194632. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194633. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194634. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194635. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194636. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194637. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194638. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194639. {
  194640. png_warning(png_ptr,
  194641. "Ignoring incorrect cHRM value when sRGB is also present");
  194642. #ifndef PNG_NO_CONSOLE_IO
  194643. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194644. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194645. white_x, white_y, red_x, red_y);
  194646. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194647. green_x, green_y, blue_x, blue_y);
  194648. #else
  194649. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194650. int_x_white, int_y_white, int_x_red, int_y_red);
  194651. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194652. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194653. #endif
  194654. #endif /* PNG_NO_CONSOLE_IO */
  194655. }
  194656. png_crc_finish(png_ptr, 0);
  194657. return;
  194658. }
  194659. #endif /* PNG_READ_sRGB_SUPPORTED */
  194660. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194661. png_set_cHRM(png_ptr, info_ptr,
  194662. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194663. #endif
  194664. #ifdef PNG_FIXED_POINT_SUPPORTED
  194665. png_set_cHRM_fixed(png_ptr, info_ptr,
  194666. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194667. int_y_green, int_x_blue, int_y_blue);
  194668. #endif
  194669. if (png_crc_finish(png_ptr, 0))
  194670. return;
  194671. }
  194672. #endif
  194673. #if defined(PNG_READ_sRGB_SUPPORTED)
  194674. void /* PRIVATE */
  194675. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194676. {
  194677. int intent;
  194678. png_byte buf[1];
  194679. png_debug(1, "in png_handle_sRGB\n");
  194680. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194681. png_error(png_ptr, "Missing IHDR before sRGB");
  194682. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194683. {
  194684. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194685. png_crc_finish(png_ptr, length);
  194686. return;
  194687. }
  194688. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194689. /* Should be an error, but we can cope with it */
  194690. png_warning(png_ptr, "Out of place sRGB chunk");
  194691. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194692. {
  194693. png_warning(png_ptr, "Duplicate sRGB chunk");
  194694. png_crc_finish(png_ptr, length);
  194695. return;
  194696. }
  194697. if (length != 1)
  194698. {
  194699. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194700. png_crc_finish(png_ptr, length);
  194701. return;
  194702. }
  194703. png_crc_read(png_ptr, buf, 1);
  194704. if (png_crc_finish(png_ptr, 0))
  194705. return;
  194706. intent = buf[0];
  194707. /* check for bad intent */
  194708. if (intent >= PNG_sRGB_INTENT_LAST)
  194709. {
  194710. png_warning(png_ptr, "Unknown sRGB intent");
  194711. return;
  194712. }
  194713. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194714. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194715. {
  194716. png_fixed_point igamma;
  194717. #ifdef PNG_FIXED_POINT_SUPPORTED
  194718. igamma=info_ptr->int_gamma;
  194719. #else
  194720. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194721. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194722. # endif
  194723. #endif
  194724. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194725. {
  194726. png_warning(png_ptr,
  194727. "Ignoring incorrect gAMA value when sRGB is also present");
  194728. #ifndef PNG_NO_CONSOLE_IO
  194729. # ifdef PNG_FIXED_POINT_SUPPORTED
  194730. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194731. # else
  194732. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194733. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194734. # endif
  194735. # endif
  194736. #endif
  194737. }
  194738. }
  194739. #endif /* PNG_READ_gAMA_SUPPORTED */
  194740. #ifdef PNG_READ_cHRM_SUPPORTED
  194741. #ifdef PNG_FIXED_POINT_SUPPORTED
  194742. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194743. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194744. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194745. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194746. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194747. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194748. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194749. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194750. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194751. {
  194752. png_warning(png_ptr,
  194753. "Ignoring incorrect cHRM value when sRGB is also present");
  194754. }
  194755. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194756. #endif /* PNG_READ_cHRM_SUPPORTED */
  194757. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194758. }
  194759. #endif /* PNG_READ_sRGB_SUPPORTED */
  194760. #if defined(PNG_READ_iCCP_SUPPORTED)
  194761. void /* PRIVATE */
  194762. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194763. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194764. {
  194765. png_charp chunkdata;
  194766. png_byte compression_type;
  194767. png_bytep pC;
  194768. png_charp profile;
  194769. png_uint_32 skip = 0;
  194770. png_uint_32 profile_size, profile_length;
  194771. png_size_t slength, prefix_length, data_length;
  194772. png_debug(1, "in png_handle_iCCP\n");
  194773. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194774. png_error(png_ptr, "Missing IHDR before iCCP");
  194775. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194776. {
  194777. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194778. png_crc_finish(png_ptr, length);
  194779. return;
  194780. }
  194781. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194782. /* Should be an error, but we can cope with it */
  194783. png_warning(png_ptr, "Out of place iCCP chunk");
  194784. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194785. {
  194786. png_warning(png_ptr, "Duplicate iCCP chunk");
  194787. png_crc_finish(png_ptr, length);
  194788. return;
  194789. }
  194790. #ifdef PNG_MAX_MALLOC_64K
  194791. if (length > (png_uint_32)65535L)
  194792. {
  194793. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194794. skip = length - (png_uint_32)65535L;
  194795. length = (png_uint_32)65535L;
  194796. }
  194797. #endif
  194798. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194799. slength = (png_size_t)length;
  194800. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194801. if (png_crc_finish(png_ptr, skip))
  194802. {
  194803. png_free(png_ptr, chunkdata);
  194804. return;
  194805. }
  194806. chunkdata[slength] = 0x00;
  194807. for (profile = chunkdata; *profile; profile++)
  194808. /* empty loop to find end of name */ ;
  194809. ++profile;
  194810. /* there should be at least one zero (the compression type byte)
  194811. following the separator, and we should be on it */
  194812. if ( profile >= chunkdata + slength - 1)
  194813. {
  194814. png_free(png_ptr, chunkdata);
  194815. png_warning(png_ptr, "Malformed iCCP chunk");
  194816. return;
  194817. }
  194818. /* compression_type should always be zero */
  194819. compression_type = *profile++;
  194820. if (compression_type)
  194821. {
  194822. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194823. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194824. wrote nonzero) */
  194825. }
  194826. prefix_length = profile - chunkdata;
  194827. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194828. slength, prefix_length, &data_length);
  194829. profile_length = data_length - prefix_length;
  194830. if ( prefix_length > data_length || profile_length < 4)
  194831. {
  194832. png_free(png_ptr, chunkdata);
  194833. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194834. return;
  194835. }
  194836. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194837. pC = (png_bytep)(chunkdata+prefix_length);
  194838. profile_size = ((*(pC ))<<24) |
  194839. ((*(pC+1))<<16) |
  194840. ((*(pC+2))<< 8) |
  194841. ((*(pC+3)) );
  194842. if(profile_size < profile_length)
  194843. profile_length = profile_size;
  194844. if(profile_size > profile_length)
  194845. {
  194846. png_free(png_ptr, chunkdata);
  194847. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194848. return;
  194849. }
  194850. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194851. chunkdata + prefix_length, profile_length);
  194852. png_free(png_ptr, chunkdata);
  194853. }
  194854. #endif /* PNG_READ_iCCP_SUPPORTED */
  194855. #if defined(PNG_READ_sPLT_SUPPORTED)
  194856. void /* PRIVATE */
  194857. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194858. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194859. {
  194860. png_bytep chunkdata;
  194861. png_bytep entry_start;
  194862. png_sPLT_t new_palette;
  194863. #ifdef PNG_NO_POINTER_INDEXING
  194864. png_sPLT_entryp pp;
  194865. #endif
  194866. int data_length, entry_size, i;
  194867. png_uint_32 skip = 0;
  194868. png_size_t slength;
  194869. png_debug(1, "in png_handle_sPLT\n");
  194870. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194871. png_error(png_ptr, "Missing IHDR before sPLT");
  194872. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194873. {
  194874. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194875. png_crc_finish(png_ptr, length);
  194876. return;
  194877. }
  194878. #ifdef PNG_MAX_MALLOC_64K
  194879. if (length > (png_uint_32)65535L)
  194880. {
  194881. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194882. skip = length - (png_uint_32)65535L;
  194883. length = (png_uint_32)65535L;
  194884. }
  194885. #endif
  194886. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194887. slength = (png_size_t)length;
  194888. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194889. if (png_crc_finish(png_ptr, skip))
  194890. {
  194891. png_free(png_ptr, chunkdata);
  194892. return;
  194893. }
  194894. chunkdata[slength] = 0x00;
  194895. for (entry_start = chunkdata; *entry_start; entry_start++)
  194896. /* empty loop to find end of name */ ;
  194897. ++entry_start;
  194898. /* a sample depth should follow the separator, and we should be on it */
  194899. if (entry_start > chunkdata + slength - 2)
  194900. {
  194901. png_free(png_ptr, chunkdata);
  194902. png_warning(png_ptr, "malformed sPLT chunk");
  194903. return;
  194904. }
  194905. new_palette.depth = *entry_start++;
  194906. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194907. data_length = (slength - (entry_start - chunkdata));
  194908. /* integrity-check the data length */
  194909. if (data_length % entry_size)
  194910. {
  194911. png_free(png_ptr, chunkdata);
  194912. png_warning(png_ptr, "sPLT chunk has bad length");
  194913. return;
  194914. }
  194915. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194916. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194917. png_sizeof(png_sPLT_entry)))
  194918. {
  194919. png_warning(png_ptr, "sPLT chunk too long");
  194920. return;
  194921. }
  194922. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194923. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194924. if (new_palette.entries == NULL)
  194925. {
  194926. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194927. return;
  194928. }
  194929. #ifndef PNG_NO_POINTER_INDEXING
  194930. for (i = 0; i < new_palette.nentries; i++)
  194931. {
  194932. png_sPLT_entryp pp = new_palette.entries + i;
  194933. if (new_palette.depth == 8)
  194934. {
  194935. pp->red = *entry_start++;
  194936. pp->green = *entry_start++;
  194937. pp->blue = *entry_start++;
  194938. pp->alpha = *entry_start++;
  194939. }
  194940. else
  194941. {
  194942. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194943. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194944. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194945. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194946. }
  194947. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194948. }
  194949. #else
  194950. pp = new_palette.entries;
  194951. for (i = 0; i < new_palette.nentries; i++)
  194952. {
  194953. if (new_palette.depth == 8)
  194954. {
  194955. pp[i].red = *entry_start++;
  194956. pp[i].green = *entry_start++;
  194957. pp[i].blue = *entry_start++;
  194958. pp[i].alpha = *entry_start++;
  194959. }
  194960. else
  194961. {
  194962. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194963. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194964. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194965. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194966. }
  194967. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194968. }
  194969. #endif
  194970. /* discard all chunk data except the name and stash that */
  194971. new_palette.name = (png_charp)chunkdata;
  194972. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194973. png_free(png_ptr, chunkdata);
  194974. png_free(png_ptr, new_palette.entries);
  194975. }
  194976. #endif /* PNG_READ_sPLT_SUPPORTED */
  194977. #if defined(PNG_READ_tRNS_SUPPORTED)
  194978. void /* PRIVATE */
  194979. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194980. {
  194981. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194982. int bit_mask;
  194983. png_debug(1, "in png_handle_tRNS\n");
  194984. /* For non-indexed color, mask off any bits in the tRNS value that
  194985. * exceed the bit depth. Some creators were writing extra bits there.
  194986. * This is not needed for indexed color. */
  194987. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194988. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194989. png_error(png_ptr, "Missing IHDR before tRNS");
  194990. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194991. {
  194992. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194993. png_crc_finish(png_ptr, length);
  194994. return;
  194995. }
  194996. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194997. {
  194998. png_warning(png_ptr, "Duplicate tRNS chunk");
  194999. png_crc_finish(png_ptr, length);
  195000. return;
  195001. }
  195002. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195003. {
  195004. png_byte buf[2];
  195005. if (length != 2)
  195006. {
  195007. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195008. png_crc_finish(png_ptr, length);
  195009. return;
  195010. }
  195011. png_crc_read(png_ptr, buf, 2);
  195012. png_ptr->num_trans = 1;
  195013. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195014. }
  195015. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195016. {
  195017. png_byte buf[6];
  195018. if (length != 6)
  195019. {
  195020. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195021. png_crc_finish(png_ptr, length);
  195022. return;
  195023. }
  195024. png_crc_read(png_ptr, buf, (png_size_t)length);
  195025. png_ptr->num_trans = 1;
  195026. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195027. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195028. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195029. }
  195030. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195031. {
  195032. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195033. {
  195034. /* Should be an error, but we can cope with it. */
  195035. png_warning(png_ptr, "Missing PLTE before tRNS");
  195036. }
  195037. if (length > (png_uint_32)png_ptr->num_palette ||
  195038. length > PNG_MAX_PALETTE_LENGTH)
  195039. {
  195040. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195041. png_crc_finish(png_ptr, length);
  195042. return;
  195043. }
  195044. if (length == 0)
  195045. {
  195046. png_warning(png_ptr, "Zero length tRNS chunk");
  195047. png_crc_finish(png_ptr, length);
  195048. return;
  195049. }
  195050. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195051. png_ptr->num_trans = (png_uint_16)length;
  195052. }
  195053. else
  195054. {
  195055. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195056. png_crc_finish(png_ptr, length);
  195057. return;
  195058. }
  195059. if (png_crc_finish(png_ptr, 0))
  195060. {
  195061. png_ptr->num_trans = 0;
  195062. return;
  195063. }
  195064. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195065. &(png_ptr->trans_values));
  195066. }
  195067. #endif
  195068. #if defined(PNG_READ_bKGD_SUPPORTED)
  195069. void /* PRIVATE */
  195070. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195071. {
  195072. png_size_t truelen;
  195073. png_byte buf[6];
  195074. png_debug(1, "in png_handle_bKGD\n");
  195075. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195076. png_error(png_ptr, "Missing IHDR before bKGD");
  195077. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195078. {
  195079. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195080. png_crc_finish(png_ptr, length);
  195081. return;
  195082. }
  195083. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195084. !(png_ptr->mode & PNG_HAVE_PLTE))
  195085. {
  195086. png_warning(png_ptr, "Missing PLTE before bKGD");
  195087. png_crc_finish(png_ptr, length);
  195088. return;
  195089. }
  195090. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195091. {
  195092. png_warning(png_ptr, "Duplicate bKGD chunk");
  195093. png_crc_finish(png_ptr, length);
  195094. return;
  195095. }
  195096. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195097. truelen = 1;
  195098. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195099. truelen = 6;
  195100. else
  195101. truelen = 2;
  195102. if (length != truelen)
  195103. {
  195104. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195105. png_crc_finish(png_ptr, length);
  195106. return;
  195107. }
  195108. png_crc_read(png_ptr, buf, truelen);
  195109. if (png_crc_finish(png_ptr, 0))
  195110. return;
  195111. /* We convert the index value into RGB components so that we can allow
  195112. * arbitrary RGB values for background when we have transparency, and
  195113. * so it is easy to determine the RGB values of the background color
  195114. * from the info_ptr struct. */
  195115. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195116. {
  195117. png_ptr->background.index = buf[0];
  195118. if(info_ptr->num_palette)
  195119. {
  195120. if(buf[0] > info_ptr->num_palette)
  195121. {
  195122. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195123. return;
  195124. }
  195125. png_ptr->background.red =
  195126. (png_uint_16)png_ptr->palette[buf[0]].red;
  195127. png_ptr->background.green =
  195128. (png_uint_16)png_ptr->palette[buf[0]].green;
  195129. png_ptr->background.blue =
  195130. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195131. }
  195132. }
  195133. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195134. {
  195135. png_ptr->background.red =
  195136. png_ptr->background.green =
  195137. png_ptr->background.blue =
  195138. png_ptr->background.gray = png_get_uint_16(buf);
  195139. }
  195140. else
  195141. {
  195142. png_ptr->background.red = png_get_uint_16(buf);
  195143. png_ptr->background.green = png_get_uint_16(buf + 2);
  195144. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195145. }
  195146. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195147. }
  195148. #endif
  195149. #if defined(PNG_READ_hIST_SUPPORTED)
  195150. void /* PRIVATE */
  195151. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195152. {
  195153. unsigned int num, i;
  195154. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195155. png_debug(1, "in png_handle_hIST\n");
  195156. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195157. png_error(png_ptr, "Missing IHDR before hIST");
  195158. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195159. {
  195160. png_warning(png_ptr, "Invalid hIST after IDAT");
  195161. png_crc_finish(png_ptr, length);
  195162. return;
  195163. }
  195164. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195165. {
  195166. png_warning(png_ptr, "Missing PLTE before hIST");
  195167. png_crc_finish(png_ptr, length);
  195168. return;
  195169. }
  195170. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195171. {
  195172. png_warning(png_ptr, "Duplicate hIST chunk");
  195173. png_crc_finish(png_ptr, length);
  195174. return;
  195175. }
  195176. num = length / 2 ;
  195177. if (num != (unsigned int) png_ptr->num_palette || num >
  195178. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195179. {
  195180. png_warning(png_ptr, "Incorrect hIST chunk length");
  195181. png_crc_finish(png_ptr, length);
  195182. return;
  195183. }
  195184. for (i = 0; i < num; i++)
  195185. {
  195186. png_byte buf[2];
  195187. png_crc_read(png_ptr, buf, 2);
  195188. readbuf[i] = png_get_uint_16(buf);
  195189. }
  195190. if (png_crc_finish(png_ptr, 0))
  195191. return;
  195192. png_set_hIST(png_ptr, info_ptr, readbuf);
  195193. }
  195194. #endif
  195195. #if defined(PNG_READ_pHYs_SUPPORTED)
  195196. void /* PRIVATE */
  195197. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195198. {
  195199. png_byte buf[9];
  195200. png_uint_32 res_x, res_y;
  195201. int unit_type;
  195202. png_debug(1, "in png_handle_pHYs\n");
  195203. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195204. png_error(png_ptr, "Missing IHDR before pHYs");
  195205. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195206. {
  195207. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195208. png_crc_finish(png_ptr, length);
  195209. return;
  195210. }
  195211. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195212. {
  195213. png_warning(png_ptr, "Duplicate pHYs chunk");
  195214. png_crc_finish(png_ptr, length);
  195215. return;
  195216. }
  195217. if (length != 9)
  195218. {
  195219. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195220. png_crc_finish(png_ptr, length);
  195221. return;
  195222. }
  195223. png_crc_read(png_ptr, buf, 9);
  195224. if (png_crc_finish(png_ptr, 0))
  195225. return;
  195226. res_x = png_get_uint_32(buf);
  195227. res_y = png_get_uint_32(buf + 4);
  195228. unit_type = buf[8];
  195229. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195230. }
  195231. #endif
  195232. #if defined(PNG_READ_oFFs_SUPPORTED)
  195233. void /* PRIVATE */
  195234. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195235. {
  195236. png_byte buf[9];
  195237. png_int_32 offset_x, offset_y;
  195238. int unit_type;
  195239. png_debug(1, "in png_handle_oFFs\n");
  195240. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195241. png_error(png_ptr, "Missing IHDR before oFFs");
  195242. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195243. {
  195244. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195245. png_crc_finish(png_ptr, length);
  195246. return;
  195247. }
  195248. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195249. {
  195250. png_warning(png_ptr, "Duplicate oFFs chunk");
  195251. png_crc_finish(png_ptr, length);
  195252. return;
  195253. }
  195254. if (length != 9)
  195255. {
  195256. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195257. png_crc_finish(png_ptr, length);
  195258. return;
  195259. }
  195260. png_crc_read(png_ptr, buf, 9);
  195261. if (png_crc_finish(png_ptr, 0))
  195262. return;
  195263. offset_x = png_get_int_32(buf);
  195264. offset_y = png_get_int_32(buf + 4);
  195265. unit_type = buf[8];
  195266. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195267. }
  195268. #endif
  195269. #if defined(PNG_READ_pCAL_SUPPORTED)
  195270. /* read the pCAL chunk (described in the PNG Extensions document) */
  195271. void /* PRIVATE */
  195272. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195273. {
  195274. png_charp purpose;
  195275. png_int_32 X0, X1;
  195276. png_byte type, nparams;
  195277. png_charp buf, units, endptr;
  195278. png_charpp params;
  195279. png_size_t slength;
  195280. int i;
  195281. png_debug(1, "in png_handle_pCAL\n");
  195282. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195283. png_error(png_ptr, "Missing IHDR before pCAL");
  195284. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195285. {
  195286. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195287. png_crc_finish(png_ptr, length);
  195288. return;
  195289. }
  195290. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195291. {
  195292. png_warning(png_ptr, "Duplicate pCAL chunk");
  195293. png_crc_finish(png_ptr, length);
  195294. return;
  195295. }
  195296. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195297. length + 1);
  195298. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195299. if (purpose == NULL)
  195300. {
  195301. png_warning(png_ptr, "No memory for pCAL purpose.");
  195302. return;
  195303. }
  195304. slength = (png_size_t)length;
  195305. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195306. if (png_crc_finish(png_ptr, 0))
  195307. {
  195308. png_free(png_ptr, purpose);
  195309. return;
  195310. }
  195311. purpose[slength] = 0x00; /* null terminate the last string */
  195312. png_debug(3, "Finding end of pCAL purpose string\n");
  195313. for (buf = purpose; *buf; buf++)
  195314. /* empty loop */ ;
  195315. endptr = purpose + slength;
  195316. /* We need to have at least 12 bytes after the purpose string
  195317. in order to get the parameter information. */
  195318. if (endptr <= buf + 12)
  195319. {
  195320. png_warning(png_ptr, "Invalid pCAL data");
  195321. png_free(png_ptr, purpose);
  195322. return;
  195323. }
  195324. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195325. X0 = png_get_int_32((png_bytep)buf+1);
  195326. X1 = png_get_int_32((png_bytep)buf+5);
  195327. type = buf[9];
  195328. nparams = buf[10];
  195329. units = buf + 11;
  195330. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195331. /* Check that we have the right number of parameters for known
  195332. equation types. */
  195333. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195334. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195335. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195336. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195337. {
  195338. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195339. png_free(png_ptr, purpose);
  195340. return;
  195341. }
  195342. else if (type >= PNG_EQUATION_LAST)
  195343. {
  195344. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195345. }
  195346. for (buf = units; *buf; buf++)
  195347. /* Empty loop to move past the units string. */ ;
  195348. png_debug(3, "Allocating pCAL parameters array\n");
  195349. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195350. *png_sizeof(png_charp))) ;
  195351. if (params == NULL)
  195352. {
  195353. png_free(png_ptr, purpose);
  195354. png_warning(png_ptr, "No memory for pCAL params.");
  195355. return;
  195356. }
  195357. /* Get pointers to the start of each parameter string. */
  195358. for (i = 0; i < (int)nparams; i++)
  195359. {
  195360. buf++; /* Skip the null string terminator from previous parameter. */
  195361. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195362. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195363. /* Empty loop to move past each parameter string */ ;
  195364. /* Make sure we haven't run out of data yet */
  195365. if (buf > endptr)
  195366. {
  195367. png_warning(png_ptr, "Invalid pCAL data");
  195368. png_free(png_ptr, purpose);
  195369. png_free(png_ptr, params);
  195370. return;
  195371. }
  195372. }
  195373. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195374. units, params);
  195375. png_free(png_ptr, purpose);
  195376. png_free(png_ptr, params);
  195377. }
  195378. #endif
  195379. #if defined(PNG_READ_sCAL_SUPPORTED)
  195380. /* read the sCAL chunk */
  195381. void /* PRIVATE */
  195382. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195383. {
  195384. png_charp buffer, ep;
  195385. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195386. double width, height;
  195387. png_charp vp;
  195388. #else
  195389. #ifdef PNG_FIXED_POINT_SUPPORTED
  195390. png_charp swidth, sheight;
  195391. #endif
  195392. #endif
  195393. png_size_t slength;
  195394. png_debug(1, "in png_handle_sCAL\n");
  195395. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195396. png_error(png_ptr, "Missing IHDR before sCAL");
  195397. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195398. {
  195399. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195400. png_crc_finish(png_ptr, length);
  195401. return;
  195402. }
  195403. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195404. {
  195405. png_warning(png_ptr, "Duplicate sCAL chunk");
  195406. png_crc_finish(png_ptr, length);
  195407. return;
  195408. }
  195409. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195410. length + 1);
  195411. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195412. if (buffer == NULL)
  195413. {
  195414. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195415. return;
  195416. }
  195417. slength = (png_size_t)length;
  195418. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195419. if (png_crc_finish(png_ptr, 0))
  195420. {
  195421. png_free(png_ptr, buffer);
  195422. return;
  195423. }
  195424. buffer[slength] = 0x00; /* null terminate the last string */
  195425. ep = buffer + 1; /* skip unit byte */
  195426. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195427. width = png_strtod(png_ptr, ep, &vp);
  195428. if (*vp)
  195429. {
  195430. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195431. return;
  195432. }
  195433. #else
  195434. #ifdef PNG_FIXED_POINT_SUPPORTED
  195435. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195436. if (swidth == NULL)
  195437. {
  195438. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195439. return;
  195440. }
  195441. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195442. #endif
  195443. #endif
  195444. for (ep = buffer; *ep; ep++)
  195445. /* empty loop */ ;
  195446. ep++;
  195447. if (buffer + slength < ep)
  195448. {
  195449. png_warning(png_ptr, "Truncated sCAL chunk");
  195450. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195451. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195452. png_free(png_ptr, swidth);
  195453. #endif
  195454. png_free(png_ptr, buffer);
  195455. return;
  195456. }
  195457. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195458. height = png_strtod(png_ptr, ep, &vp);
  195459. if (*vp)
  195460. {
  195461. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195462. return;
  195463. }
  195464. #else
  195465. #ifdef PNG_FIXED_POINT_SUPPORTED
  195466. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195467. if (swidth == NULL)
  195468. {
  195469. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195470. return;
  195471. }
  195472. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195473. #endif
  195474. #endif
  195475. if (buffer + slength < ep
  195476. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195477. || width <= 0. || height <= 0.
  195478. #endif
  195479. )
  195480. {
  195481. png_warning(png_ptr, "Invalid sCAL data");
  195482. png_free(png_ptr, buffer);
  195483. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195484. png_free(png_ptr, swidth);
  195485. png_free(png_ptr, sheight);
  195486. #endif
  195487. return;
  195488. }
  195489. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195490. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195491. #else
  195492. #ifdef PNG_FIXED_POINT_SUPPORTED
  195493. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195494. #endif
  195495. #endif
  195496. png_free(png_ptr, buffer);
  195497. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195498. png_free(png_ptr, swidth);
  195499. png_free(png_ptr, sheight);
  195500. #endif
  195501. }
  195502. #endif
  195503. #if defined(PNG_READ_tIME_SUPPORTED)
  195504. void /* PRIVATE */
  195505. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195506. {
  195507. png_byte buf[7];
  195508. png_time mod_time;
  195509. png_debug(1, "in png_handle_tIME\n");
  195510. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195511. png_error(png_ptr, "Out of place tIME chunk");
  195512. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195513. {
  195514. png_warning(png_ptr, "Duplicate tIME chunk");
  195515. png_crc_finish(png_ptr, length);
  195516. return;
  195517. }
  195518. if (png_ptr->mode & PNG_HAVE_IDAT)
  195519. png_ptr->mode |= PNG_AFTER_IDAT;
  195520. if (length != 7)
  195521. {
  195522. png_warning(png_ptr, "Incorrect tIME chunk length");
  195523. png_crc_finish(png_ptr, length);
  195524. return;
  195525. }
  195526. png_crc_read(png_ptr, buf, 7);
  195527. if (png_crc_finish(png_ptr, 0))
  195528. return;
  195529. mod_time.second = buf[6];
  195530. mod_time.minute = buf[5];
  195531. mod_time.hour = buf[4];
  195532. mod_time.day = buf[3];
  195533. mod_time.month = buf[2];
  195534. mod_time.year = png_get_uint_16(buf);
  195535. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195536. }
  195537. #endif
  195538. #if defined(PNG_READ_tEXt_SUPPORTED)
  195539. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195540. void /* PRIVATE */
  195541. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195542. {
  195543. png_textp text_ptr;
  195544. png_charp key;
  195545. png_charp text;
  195546. png_uint_32 skip = 0;
  195547. png_size_t slength;
  195548. int ret;
  195549. png_debug(1, "in png_handle_tEXt\n");
  195550. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195551. png_error(png_ptr, "Missing IHDR before tEXt");
  195552. if (png_ptr->mode & PNG_HAVE_IDAT)
  195553. png_ptr->mode |= PNG_AFTER_IDAT;
  195554. #ifdef PNG_MAX_MALLOC_64K
  195555. if (length > (png_uint_32)65535L)
  195556. {
  195557. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195558. skip = length - (png_uint_32)65535L;
  195559. length = (png_uint_32)65535L;
  195560. }
  195561. #endif
  195562. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195563. if (key == NULL)
  195564. {
  195565. png_warning(png_ptr, "No memory to process text chunk.");
  195566. return;
  195567. }
  195568. slength = (png_size_t)length;
  195569. png_crc_read(png_ptr, (png_bytep)key, slength);
  195570. if (png_crc_finish(png_ptr, skip))
  195571. {
  195572. png_free(png_ptr, key);
  195573. return;
  195574. }
  195575. key[slength] = 0x00;
  195576. for (text = key; *text; text++)
  195577. /* empty loop to find end of key */ ;
  195578. if (text != key + slength)
  195579. text++;
  195580. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195581. (png_uint_32)png_sizeof(png_text));
  195582. if (text_ptr == NULL)
  195583. {
  195584. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195585. png_free(png_ptr, key);
  195586. return;
  195587. }
  195588. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195589. text_ptr->key = key;
  195590. #ifdef PNG_iTXt_SUPPORTED
  195591. text_ptr->lang = NULL;
  195592. text_ptr->lang_key = NULL;
  195593. text_ptr->itxt_length = 0;
  195594. #endif
  195595. text_ptr->text = text;
  195596. text_ptr->text_length = png_strlen(text);
  195597. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195598. png_free(png_ptr, key);
  195599. png_free(png_ptr, text_ptr);
  195600. if (ret)
  195601. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195602. }
  195603. #endif
  195604. #if defined(PNG_READ_zTXt_SUPPORTED)
  195605. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195606. void /* PRIVATE */
  195607. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195608. {
  195609. png_textp text_ptr;
  195610. png_charp chunkdata;
  195611. png_charp text;
  195612. int comp_type;
  195613. int ret;
  195614. png_size_t slength, prefix_len, data_len;
  195615. png_debug(1, "in png_handle_zTXt\n");
  195616. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195617. png_error(png_ptr, "Missing IHDR before zTXt");
  195618. if (png_ptr->mode & PNG_HAVE_IDAT)
  195619. png_ptr->mode |= PNG_AFTER_IDAT;
  195620. #ifdef PNG_MAX_MALLOC_64K
  195621. /* We will no doubt have problems with chunks even half this size, but
  195622. there is no hard and fast rule to tell us where to stop. */
  195623. if (length > (png_uint_32)65535L)
  195624. {
  195625. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195626. png_crc_finish(png_ptr, length);
  195627. return;
  195628. }
  195629. #endif
  195630. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195631. if (chunkdata == NULL)
  195632. {
  195633. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195634. return;
  195635. }
  195636. slength = (png_size_t)length;
  195637. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195638. if (png_crc_finish(png_ptr, 0))
  195639. {
  195640. png_free(png_ptr, chunkdata);
  195641. return;
  195642. }
  195643. chunkdata[slength] = 0x00;
  195644. for (text = chunkdata; *text; text++)
  195645. /* empty loop */ ;
  195646. /* zTXt must have some text after the chunkdataword */
  195647. if (text >= chunkdata + slength - 2)
  195648. {
  195649. png_warning(png_ptr, "Truncated zTXt chunk");
  195650. png_free(png_ptr, chunkdata);
  195651. return;
  195652. }
  195653. else
  195654. {
  195655. comp_type = *(++text);
  195656. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195657. {
  195658. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195659. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195660. }
  195661. text++; /* skip the compression_method byte */
  195662. }
  195663. prefix_len = text - chunkdata;
  195664. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195665. (png_size_t)length, prefix_len, &data_len);
  195666. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195667. (png_uint_32)png_sizeof(png_text));
  195668. if (text_ptr == NULL)
  195669. {
  195670. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195671. png_free(png_ptr, chunkdata);
  195672. return;
  195673. }
  195674. text_ptr->compression = comp_type;
  195675. text_ptr->key = chunkdata;
  195676. #ifdef PNG_iTXt_SUPPORTED
  195677. text_ptr->lang = NULL;
  195678. text_ptr->lang_key = NULL;
  195679. text_ptr->itxt_length = 0;
  195680. #endif
  195681. text_ptr->text = chunkdata + prefix_len;
  195682. text_ptr->text_length = data_len;
  195683. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195684. png_free(png_ptr, text_ptr);
  195685. png_free(png_ptr, chunkdata);
  195686. if (ret)
  195687. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195688. }
  195689. #endif
  195690. #if defined(PNG_READ_iTXt_SUPPORTED)
  195691. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195692. void /* PRIVATE */
  195693. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195694. {
  195695. png_textp text_ptr;
  195696. png_charp chunkdata;
  195697. png_charp key, lang, text, lang_key;
  195698. int comp_flag;
  195699. int comp_type = 0;
  195700. int ret;
  195701. png_size_t slength, prefix_len, data_len;
  195702. png_debug(1, "in png_handle_iTXt\n");
  195703. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195704. png_error(png_ptr, "Missing IHDR before iTXt");
  195705. if (png_ptr->mode & PNG_HAVE_IDAT)
  195706. png_ptr->mode |= PNG_AFTER_IDAT;
  195707. #ifdef PNG_MAX_MALLOC_64K
  195708. /* We will no doubt have problems with chunks even half this size, but
  195709. there is no hard and fast rule to tell us where to stop. */
  195710. if (length > (png_uint_32)65535L)
  195711. {
  195712. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195713. png_crc_finish(png_ptr, length);
  195714. return;
  195715. }
  195716. #endif
  195717. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195718. if (chunkdata == NULL)
  195719. {
  195720. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195721. return;
  195722. }
  195723. slength = (png_size_t)length;
  195724. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195725. if (png_crc_finish(png_ptr, 0))
  195726. {
  195727. png_free(png_ptr, chunkdata);
  195728. return;
  195729. }
  195730. chunkdata[slength] = 0x00;
  195731. for (lang = chunkdata; *lang; lang++)
  195732. /* empty loop */ ;
  195733. lang++; /* skip NUL separator */
  195734. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195735. translated keyword (possibly empty), and possibly some text after the
  195736. keyword */
  195737. if (lang >= chunkdata + slength - 3)
  195738. {
  195739. png_warning(png_ptr, "Truncated iTXt chunk");
  195740. png_free(png_ptr, chunkdata);
  195741. return;
  195742. }
  195743. else
  195744. {
  195745. comp_flag = *lang++;
  195746. comp_type = *lang++;
  195747. }
  195748. for (lang_key = lang; *lang_key; lang_key++)
  195749. /* empty loop */ ;
  195750. lang_key++; /* skip NUL separator */
  195751. if (lang_key >= chunkdata + slength)
  195752. {
  195753. png_warning(png_ptr, "Truncated iTXt chunk");
  195754. png_free(png_ptr, chunkdata);
  195755. return;
  195756. }
  195757. for (text = lang_key; *text; text++)
  195758. /* empty loop */ ;
  195759. text++; /* skip NUL separator */
  195760. if (text >= chunkdata + slength)
  195761. {
  195762. png_warning(png_ptr, "Malformed iTXt chunk");
  195763. png_free(png_ptr, chunkdata);
  195764. return;
  195765. }
  195766. prefix_len = text - chunkdata;
  195767. key=chunkdata;
  195768. if (comp_flag)
  195769. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195770. (size_t)length, prefix_len, &data_len);
  195771. else
  195772. data_len=png_strlen(chunkdata + prefix_len);
  195773. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195774. (png_uint_32)png_sizeof(png_text));
  195775. if (text_ptr == NULL)
  195776. {
  195777. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195778. png_free(png_ptr, chunkdata);
  195779. return;
  195780. }
  195781. text_ptr->compression = (int)comp_flag + 1;
  195782. text_ptr->lang_key = chunkdata+(lang_key-key);
  195783. text_ptr->lang = chunkdata+(lang-key);
  195784. text_ptr->itxt_length = data_len;
  195785. text_ptr->text_length = 0;
  195786. text_ptr->key = chunkdata;
  195787. text_ptr->text = chunkdata + prefix_len;
  195788. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195789. png_free(png_ptr, text_ptr);
  195790. png_free(png_ptr, chunkdata);
  195791. if (ret)
  195792. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195793. }
  195794. #endif
  195795. /* This function is called when we haven't found a handler for a
  195796. chunk. If there isn't a problem with the chunk itself (ie bad
  195797. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195798. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195799. case it will be saved away to be written out later. */
  195800. void /* PRIVATE */
  195801. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195802. {
  195803. png_uint_32 skip = 0;
  195804. png_debug(1, "in png_handle_unknown\n");
  195805. if (png_ptr->mode & PNG_HAVE_IDAT)
  195806. {
  195807. #ifdef PNG_USE_LOCAL_ARRAYS
  195808. PNG_CONST PNG_IDAT;
  195809. #endif
  195810. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195811. png_ptr->mode |= PNG_AFTER_IDAT;
  195812. }
  195813. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195814. if (!(png_ptr->chunk_name[0] & 0x20))
  195815. {
  195816. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195817. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195818. PNG_HANDLE_CHUNK_ALWAYS
  195819. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195820. && png_ptr->read_user_chunk_fn == NULL
  195821. #endif
  195822. )
  195823. #endif
  195824. png_chunk_error(png_ptr, "unknown critical chunk");
  195825. }
  195826. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195827. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195828. (png_ptr->read_user_chunk_fn != NULL))
  195829. {
  195830. #ifdef PNG_MAX_MALLOC_64K
  195831. if (length > (png_uint_32)65535L)
  195832. {
  195833. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195834. skip = length - (png_uint_32)65535L;
  195835. length = (png_uint_32)65535L;
  195836. }
  195837. #endif
  195838. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195839. (png_charp)png_ptr->chunk_name, 5);
  195840. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195841. png_ptr->unknown_chunk.size = (png_size_t)length;
  195842. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195843. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195844. if(png_ptr->read_user_chunk_fn != NULL)
  195845. {
  195846. /* callback to user unknown chunk handler */
  195847. int ret;
  195848. ret = (*(png_ptr->read_user_chunk_fn))
  195849. (png_ptr, &png_ptr->unknown_chunk);
  195850. if (ret < 0)
  195851. png_chunk_error(png_ptr, "error in user chunk");
  195852. if (ret == 0)
  195853. {
  195854. if (!(png_ptr->chunk_name[0] & 0x20))
  195855. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195856. PNG_HANDLE_CHUNK_ALWAYS)
  195857. png_chunk_error(png_ptr, "unknown critical chunk");
  195858. png_set_unknown_chunks(png_ptr, info_ptr,
  195859. &png_ptr->unknown_chunk, 1);
  195860. }
  195861. }
  195862. #else
  195863. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195864. #endif
  195865. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195866. png_ptr->unknown_chunk.data = NULL;
  195867. }
  195868. else
  195869. #endif
  195870. skip = length;
  195871. png_crc_finish(png_ptr, skip);
  195872. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195873. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195874. #endif
  195875. }
  195876. /* This function is called to verify that a chunk name is valid.
  195877. This function can't have the "critical chunk check" incorporated
  195878. into it, since in the future we will need to be able to call user
  195879. functions to handle unknown critical chunks after we check that
  195880. the chunk name itself is valid. */
  195881. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195882. void /* PRIVATE */
  195883. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195884. {
  195885. png_debug(1, "in png_check_chunk_name\n");
  195886. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195887. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195888. {
  195889. png_chunk_error(png_ptr, "invalid chunk type");
  195890. }
  195891. }
  195892. /* Combines the row recently read in with the existing pixels in the
  195893. row. This routine takes care of alpha and transparency if requested.
  195894. This routine also handles the two methods of progressive display
  195895. of interlaced images, depending on the mask value.
  195896. The mask value describes which pixels are to be combined with
  195897. the row. The pattern always repeats every 8 pixels, so just 8
  195898. bits are needed. A one indicates the pixel is to be combined,
  195899. a zero indicates the pixel is to be skipped. This is in addition
  195900. to any alpha or transparency value associated with the pixel. If
  195901. you want all pixels to be combined, pass 0xff (255) in mask. */
  195902. void /* PRIVATE */
  195903. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195904. {
  195905. png_debug(1,"in png_combine_row\n");
  195906. if (mask == 0xff)
  195907. {
  195908. png_memcpy(row, png_ptr->row_buf + 1,
  195909. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195910. }
  195911. else
  195912. {
  195913. switch (png_ptr->row_info.pixel_depth)
  195914. {
  195915. case 1:
  195916. {
  195917. png_bytep sp = png_ptr->row_buf + 1;
  195918. png_bytep dp = row;
  195919. int s_inc, s_start, s_end;
  195920. int m = 0x80;
  195921. int shift;
  195922. png_uint_32 i;
  195923. png_uint_32 row_width = png_ptr->width;
  195924. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195925. if (png_ptr->transformations & PNG_PACKSWAP)
  195926. {
  195927. s_start = 0;
  195928. s_end = 7;
  195929. s_inc = 1;
  195930. }
  195931. else
  195932. #endif
  195933. {
  195934. s_start = 7;
  195935. s_end = 0;
  195936. s_inc = -1;
  195937. }
  195938. shift = s_start;
  195939. for (i = 0; i < row_width; i++)
  195940. {
  195941. if (m & mask)
  195942. {
  195943. int value;
  195944. value = (*sp >> shift) & 0x01;
  195945. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195946. *dp |= (png_byte)(value << shift);
  195947. }
  195948. if (shift == s_end)
  195949. {
  195950. shift = s_start;
  195951. sp++;
  195952. dp++;
  195953. }
  195954. else
  195955. shift += s_inc;
  195956. if (m == 1)
  195957. m = 0x80;
  195958. else
  195959. m >>= 1;
  195960. }
  195961. break;
  195962. }
  195963. case 2:
  195964. {
  195965. png_bytep sp = png_ptr->row_buf + 1;
  195966. png_bytep dp = row;
  195967. int s_start, s_end, s_inc;
  195968. int m = 0x80;
  195969. int shift;
  195970. png_uint_32 i;
  195971. png_uint_32 row_width = png_ptr->width;
  195972. int value;
  195973. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195974. if (png_ptr->transformations & PNG_PACKSWAP)
  195975. {
  195976. s_start = 0;
  195977. s_end = 6;
  195978. s_inc = 2;
  195979. }
  195980. else
  195981. #endif
  195982. {
  195983. s_start = 6;
  195984. s_end = 0;
  195985. s_inc = -2;
  195986. }
  195987. shift = s_start;
  195988. for (i = 0; i < row_width; i++)
  195989. {
  195990. if (m & mask)
  195991. {
  195992. value = (*sp >> shift) & 0x03;
  195993. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195994. *dp |= (png_byte)(value << shift);
  195995. }
  195996. if (shift == s_end)
  195997. {
  195998. shift = s_start;
  195999. sp++;
  196000. dp++;
  196001. }
  196002. else
  196003. shift += s_inc;
  196004. if (m == 1)
  196005. m = 0x80;
  196006. else
  196007. m >>= 1;
  196008. }
  196009. break;
  196010. }
  196011. case 4:
  196012. {
  196013. png_bytep sp = png_ptr->row_buf + 1;
  196014. png_bytep dp = row;
  196015. int s_start, s_end, s_inc;
  196016. int m = 0x80;
  196017. int shift;
  196018. png_uint_32 i;
  196019. png_uint_32 row_width = png_ptr->width;
  196020. int value;
  196021. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196022. if (png_ptr->transformations & PNG_PACKSWAP)
  196023. {
  196024. s_start = 0;
  196025. s_end = 4;
  196026. s_inc = 4;
  196027. }
  196028. else
  196029. #endif
  196030. {
  196031. s_start = 4;
  196032. s_end = 0;
  196033. s_inc = -4;
  196034. }
  196035. shift = s_start;
  196036. for (i = 0; i < row_width; i++)
  196037. {
  196038. if (m & mask)
  196039. {
  196040. value = (*sp >> shift) & 0xf;
  196041. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196042. *dp |= (png_byte)(value << shift);
  196043. }
  196044. if (shift == s_end)
  196045. {
  196046. shift = s_start;
  196047. sp++;
  196048. dp++;
  196049. }
  196050. else
  196051. shift += s_inc;
  196052. if (m == 1)
  196053. m = 0x80;
  196054. else
  196055. m >>= 1;
  196056. }
  196057. break;
  196058. }
  196059. default:
  196060. {
  196061. png_bytep sp = png_ptr->row_buf + 1;
  196062. png_bytep dp = row;
  196063. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196064. png_uint_32 i;
  196065. png_uint_32 row_width = png_ptr->width;
  196066. png_byte m = 0x80;
  196067. for (i = 0; i < row_width; i++)
  196068. {
  196069. if (m & mask)
  196070. {
  196071. png_memcpy(dp, sp, pixel_bytes);
  196072. }
  196073. sp += pixel_bytes;
  196074. dp += pixel_bytes;
  196075. if (m == 1)
  196076. m = 0x80;
  196077. else
  196078. m >>= 1;
  196079. }
  196080. break;
  196081. }
  196082. }
  196083. }
  196084. }
  196085. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196086. /* OLD pre-1.0.9 interface:
  196087. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196088. png_uint_32 transformations)
  196089. */
  196090. void /* PRIVATE */
  196091. png_do_read_interlace(png_structp png_ptr)
  196092. {
  196093. png_row_infop row_info = &(png_ptr->row_info);
  196094. png_bytep row = png_ptr->row_buf + 1;
  196095. int pass = png_ptr->pass;
  196096. png_uint_32 transformations = png_ptr->transformations;
  196097. #ifdef PNG_USE_LOCAL_ARRAYS
  196098. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196099. /* offset to next interlace block */
  196100. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196101. #endif
  196102. png_debug(1,"in png_do_read_interlace\n");
  196103. if (row != NULL && row_info != NULL)
  196104. {
  196105. png_uint_32 final_width;
  196106. final_width = row_info->width * png_pass_inc[pass];
  196107. switch (row_info->pixel_depth)
  196108. {
  196109. case 1:
  196110. {
  196111. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196112. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196113. int sshift, dshift;
  196114. int s_start, s_end, s_inc;
  196115. int jstop = png_pass_inc[pass];
  196116. png_byte v;
  196117. png_uint_32 i;
  196118. int j;
  196119. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196120. if (transformations & PNG_PACKSWAP)
  196121. {
  196122. sshift = (int)((row_info->width + 7) & 0x07);
  196123. dshift = (int)((final_width + 7) & 0x07);
  196124. s_start = 7;
  196125. s_end = 0;
  196126. s_inc = -1;
  196127. }
  196128. else
  196129. #endif
  196130. {
  196131. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196132. dshift = 7 - (int)((final_width + 7) & 0x07);
  196133. s_start = 0;
  196134. s_end = 7;
  196135. s_inc = 1;
  196136. }
  196137. for (i = 0; i < row_info->width; i++)
  196138. {
  196139. v = (png_byte)((*sp >> sshift) & 0x01);
  196140. for (j = 0; j < jstop; j++)
  196141. {
  196142. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196143. *dp |= (png_byte)(v << dshift);
  196144. if (dshift == s_end)
  196145. {
  196146. dshift = s_start;
  196147. dp--;
  196148. }
  196149. else
  196150. dshift += s_inc;
  196151. }
  196152. if (sshift == s_end)
  196153. {
  196154. sshift = s_start;
  196155. sp--;
  196156. }
  196157. else
  196158. sshift += s_inc;
  196159. }
  196160. break;
  196161. }
  196162. case 2:
  196163. {
  196164. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196165. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196166. int sshift, dshift;
  196167. int s_start, s_end, s_inc;
  196168. int jstop = png_pass_inc[pass];
  196169. png_uint_32 i;
  196170. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196171. if (transformations & PNG_PACKSWAP)
  196172. {
  196173. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196174. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196175. s_start = 6;
  196176. s_end = 0;
  196177. s_inc = -2;
  196178. }
  196179. else
  196180. #endif
  196181. {
  196182. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196183. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196184. s_start = 0;
  196185. s_end = 6;
  196186. s_inc = 2;
  196187. }
  196188. for (i = 0; i < row_info->width; i++)
  196189. {
  196190. png_byte v;
  196191. int j;
  196192. v = (png_byte)((*sp >> sshift) & 0x03);
  196193. for (j = 0; j < jstop; j++)
  196194. {
  196195. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196196. *dp |= (png_byte)(v << dshift);
  196197. if (dshift == s_end)
  196198. {
  196199. dshift = s_start;
  196200. dp--;
  196201. }
  196202. else
  196203. dshift += s_inc;
  196204. }
  196205. if (sshift == s_end)
  196206. {
  196207. sshift = s_start;
  196208. sp--;
  196209. }
  196210. else
  196211. sshift += s_inc;
  196212. }
  196213. break;
  196214. }
  196215. case 4:
  196216. {
  196217. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196218. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196219. int sshift, dshift;
  196220. int s_start, s_end, s_inc;
  196221. png_uint_32 i;
  196222. int jstop = png_pass_inc[pass];
  196223. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196224. if (transformations & PNG_PACKSWAP)
  196225. {
  196226. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196227. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196228. s_start = 4;
  196229. s_end = 0;
  196230. s_inc = -4;
  196231. }
  196232. else
  196233. #endif
  196234. {
  196235. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196236. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196237. s_start = 0;
  196238. s_end = 4;
  196239. s_inc = 4;
  196240. }
  196241. for (i = 0; i < row_info->width; i++)
  196242. {
  196243. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196244. int j;
  196245. for (j = 0; j < jstop; j++)
  196246. {
  196247. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196248. *dp |= (png_byte)(v << dshift);
  196249. if (dshift == s_end)
  196250. {
  196251. dshift = s_start;
  196252. dp--;
  196253. }
  196254. else
  196255. dshift += s_inc;
  196256. }
  196257. if (sshift == s_end)
  196258. {
  196259. sshift = s_start;
  196260. sp--;
  196261. }
  196262. else
  196263. sshift += s_inc;
  196264. }
  196265. break;
  196266. }
  196267. default:
  196268. {
  196269. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196270. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196271. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196272. int jstop = png_pass_inc[pass];
  196273. png_uint_32 i;
  196274. for (i = 0; i < row_info->width; i++)
  196275. {
  196276. png_byte v[8];
  196277. int j;
  196278. png_memcpy(v, sp, pixel_bytes);
  196279. for (j = 0; j < jstop; j++)
  196280. {
  196281. png_memcpy(dp, v, pixel_bytes);
  196282. dp -= pixel_bytes;
  196283. }
  196284. sp -= pixel_bytes;
  196285. }
  196286. break;
  196287. }
  196288. }
  196289. row_info->width = final_width;
  196290. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196291. }
  196292. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196293. transformations = transformations; /* silence compiler warning */
  196294. #endif
  196295. }
  196296. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196297. void /* PRIVATE */
  196298. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196299. png_bytep prev_row, int filter)
  196300. {
  196301. png_debug(1, "in png_read_filter_row\n");
  196302. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196303. switch (filter)
  196304. {
  196305. case PNG_FILTER_VALUE_NONE:
  196306. break;
  196307. case PNG_FILTER_VALUE_SUB:
  196308. {
  196309. png_uint_32 i;
  196310. png_uint_32 istop = row_info->rowbytes;
  196311. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196312. png_bytep rp = row + bpp;
  196313. png_bytep lp = row;
  196314. for (i = bpp; i < istop; i++)
  196315. {
  196316. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196317. rp++;
  196318. }
  196319. break;
  196320. }
  196321. case PNG_FILTER_VALUE_UP:
  196322. {
  196323. png_uint_32 i;
  196324. png_uint_32 istop = row_info->rowbytes;
  196325. png_bytep rp = row;
  196326. png_bytep pp = prev_row;
  196327. for (i = 0; i < istop; i++)
  196328. {
  196329. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196330. rp++;
  196331. }
  196332. break;
  196333. }
  196334. case PNG_FILTER_VALUE_AVG:
  196335. {
  196336. png_uint_32 i;
  196337. png_bytep rp = row;
  196338. png_bytep pp = prev_row;
  196339. png_bytep lp = row;
  196340. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196341. png_uint_32 istop = row_info->rowbytes - bpp;
  196342. for (i = 0; i < bpp; i++)
  196343. {
  196344. *rp = (png_byte)(((int)(*rp) +
  196345. ((int)(*pp++) / 2 )) & 0xff);
  196346. rp++;
  196347. }
  196348. for (i = 0; i < istop; i++)
  196349. {
  196350. *rp = (png_byte)(((int)(*rp) +
  196351. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196352. rp++;
  196353. }
  196354. break;
  196355. }
  196356. case PNG_FILTER_VALUE_PAETH:
  196357. {
  196358. png_uint_32 i;
  196359. png_bytep rp = row;
  196360. png_bytep pp = prev_row;
  196361. png_bytep lp = row;
  196362. png_bytep cp = prev_row;
  196363. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196364. png_uint_32 istop=row_info->rowbytes - bpp;
  196365. for (i = 0; i < bpp; i++)
  196366. {
  196367. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196368. rp++;
  196369. }
  196370. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196371. {
  196372. int a, b, c, pa, pb, pc, p;
  196373. a = *lp++;
  196374. b = *pp++;
  196375. c = *cp++;
  196376. p = b - c;
  196377. pc = a - c;
  196378. #ifdef PNG_USE_ABS
  196379. pa = abs(p);
  196380. pb = abs(pc);
  196381. pc = abs(p + pc);
  196382. #else
  196383. pa = p < 0 ? -p : p;
  196384. pb = pc < 0 ? -pc : pc;
  196385. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196386. #endif
  196387. /*
  196388. if (pa <= pb && pa <= pc)
  196389. p = a;
  196390. else if (pb <= pc)
  196391. p = b;
  196392. else
  196393. p = c;
  196394. */
  196395. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196396. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196397. rp++;
  196398. }
  196399. break;
  196400. }
  196401. default:
  196402. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196403. *row=0;
  196404. break;
  196405. }
  196406. }
  196407. void /* PRIVATE */
  196408. png_read_finish_row(png_structp png_ptr)
  196409. {
  196410. #ifdef PNG_USE_LOCAL_ARRAYS
  196411. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196412. /* start of interlace block */
  196413. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196414. /* offset to next interlace block */
  196415. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196416. /* start of interlace block in the y direction */
  196417. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196418. /* offset to next interlace block in the y direction */
  196419. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196420. #endif
  196421. png_debug(1, "in png_read_finish_row\n");
  196422. png_ptr->row_number++;
  196423. if (png_ptr->row_number < png_ptr->num_rows)
  196424. return;
  196425. if (png_ptr->interlaced)
  196426. {
  196427. png_ptr->row_number = 0;
  196428. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196429. png_ptr->rowbytes + 1);
  196430. do
  196431. {
  196432. png_ptr->pass++;
  196433. if (png_ptr->pass >= 7)
  196434. break;
  196435. png_ptr->iwidth = (png_ptr->width +
  196436. png_pass_inc[png_ptr->pass] - 1 -
  196437. png_pass_start[png_ptr->pass]) /
  196438. png_pass_inc[png_ptr->pass];
  196439. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196440. png_ptr->iwidth) + 1;
  196441. if (!(png_ptr->transformations & PNG_INTERLACE))
  196442. {
  196443. png_ptr->num_rows = (png_ptr->height +
  196444. png_pass_yinc[png_ptr->pass] - 1 -
  196445. png_pass_ystart[png_ptr->pass]) /
  196446. png_pass_yinc[png_ptr->pass];
  196447. if (!(png_ptr->num_rows))
  196448. continue;
  196449. }
  196450. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196451. break;
  196452. } while (png_ptr->iwidth == 0);
  196453. if (png_ptr->pass < 7)
  196454. return;
  196455. }
  196456. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196457. {
  196458. #ifdef PNG_USE_LOCAL_ARRAYS
  196459. PNG_CONST PNG_IDAT;
  196460. #endif
  196461. char extra;
  196462. int ret;
  196463. png_ptr->zstream.next_out = (Bytef *)&extra;
  196464. png_ptr->zstream.avail_out = (uInt)1;
  196465. for(;;)
  196466. {
  196467. if (!(png_ptr->zstream.avail_in))
  196468. {
  196469. while (!png_ptr->idat_size)
  196470. {
  196471. png_byte chunk_length[4];
  196472. png_crc_finish(png_ptr, 0);
  196473. png_read_data(png_ptr, chunk_length, 4);
  196474. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196475. png_reset_crc(png_ptr);
  196476. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196477. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196478. png_error(png_ptr, "Not enough image data");
  196479. }
  196480. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196481. png_ptr->zstream.next_in = png_ptr->zbuf;
  196482. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196483. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196484. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196485. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196486. }
  196487. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196488. if (ret == Z_STREAM_END)
  196489. {
  196490. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196491. png_ptr->idat_size)
  196492. png_warning(png_ptr, "Extra compressed data");
  196493. png_ptr->mode |= PNG_AFTER_IDAT;
  196494. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196495. break;
  196496. }
  196497. if (ret != Z_OK)
  196498. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196499. "Decompression Error");
  196500. if (!(png_ptr->zstream.avail_out))
  196501. {
  196502. png_warning(png_ptr, "Extra compressed data.");
  196503. png_ptr->mode |= PNG_AFTER_IDAT;
  196504. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196505. break;
  196506. }
  196507. }
  196508. png_ptr->zstream.avail_out = 0;
  196509. }
  196510. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196511. png_warning(png_ptr, "Extra compression data");
  196512. inflateReset(&png_ptr->zstream);
  196513. png_ptr->mode |= PNG_AFTER_IDAT;
  196514. }
  196515. void /* PRIVATE */
  196516. png_read_start_row(png_structp png_ptr)
  196517. {
  196518. #ifdef PNG_USE_LOCAL_ARRAYS
  196519. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196520. /* start of interlace block */
  196521. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196522. /* offset to next interlace block */
  196523. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196524. /* start of interlace block in the y direction */
  196525. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196526. /* offset to next interlace block in the y direction */
  196527. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196528. #endif
  196529. int max_pixel_depth;
  196530. png_uint_32 row_bytes;
  196531. png_debug(1, "in png_read_start_row\n");
  196532. png_ptr->zstream.avail_in = 0;
  196533. png_init_read_transformations(png_ptr);
  196534. if (png_ptr->interlaced)
  196535. {
  196536. if (!(png_ptr->transformations & PNG_INTERLACE))
  196537. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196538. png_pass_ystart[0]) / png_pass_yinc[0];
  196539. else
  196540. png_ptr->num_rows = png_ptr->height;
  196541. png_ptr->iwidth = (png_ptr->width +
  196542. png_pass_inc[png_ptr->pass] - 1 -
  196543. png_pass_start[png_ptr->pass]) /
  196544. png_pass_inc[png_ptr->pass];
  196545. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196546. png_ptr->irowbytes = (png_size_t)row_bytes;
  196547. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196548. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196549. }
  196550. else
  196551. {
  196552. png_ptr->num_rows = png_ptr->height;
  196553. png_ptr->iwidth = png_ptr->width;
  196554. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196555. }
  196556. max_pixel_depth = png_ptr->pixel_depth;
  196557. #if defined(PNG_READ_PACK_SUPPORTED)
  196558. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196559. max_pixel_depth = 8;
  196560. #endif
  196561. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196562. if (png_ptr->transformations & PNG_EXPAND)
  196563. {
  196564. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196565. {
  196566. if (png_ptr->num_trans)
  196567. max_pixel_depth = 32;
  196568. else
  196569. max_pixel_depth = 24;
  196570. }
  196571. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196572. {
  196573. if (max_pixel_depth < 8)
  196574. max_pixel_depth = 8;
  196575. if (png_ptr->num_trans)
  196576. max_pixel_depth *= 2;
  196577. }
  196578. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196579. {
  196580. if (png_ptr->num_trans)
  196581. {
  196582. max_pixel_depth *= 4;
  196583. max_pixel_depth /= 3;
  196584. }
  196585. }
  196586. }
  196587. #endif
  196588. #if defined(PNG_READ_FILLER_SUPPORTED)
  196589. if (png_ptr->transformations & (PNG_FILLER))
  196590. {
  196591. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196592. max_pixel_depth = 32;
  196593. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196594. {
  196595. if (max_pixel_depth <= 8)
  196596. max_pixel_depth = 16;
  196597. else
  196598. max_pixel_depth = 32;
  196599. }
  196600. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196601. {
  196602. if (max_pixel_depth <= 32)
  196603. max_pixel_depth = 32;
  196604. else
  196605. max_pixel_depth = 64;
  196606. }
  196607. }
  196608. #endif
  196609. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196610. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196611. {
  196612. if (
  196613. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196614. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196615. #endif
  196616. #if defined(PNG_READ_FILLER_SUPPORTED)
  196617. (png_ptr->transformations & (PNG_FILLER)) ||
  196618. #endif
  196619. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196620. {
  196621. if (max_pixel_depth <= 16)
  196622. max_pixel_depth = 32;
  196623. else
  196624. max_pixel_depth = 64;
  196625. }
  196626. else
  196627. {
  196628. if (max_pixel_depth <= 8)
  196629. {
  196630. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196631. max_pixel_depth = 32;
  196632. else
  196633. max_pixel_depth = 24;
  196634. }
  196635. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196636. max_pixel_depth = 64;
  196637. else
  196638. max_pixel_depth = 48;
  196639. }
  196640. }
  196641. #endif
  196642. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196643. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196644. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196645. {
  196646. int user_pixel_depth=png_ptr->user_transform_depth*
  196647. png_ptr->user_transform_channels;
  196648. if(user_pixel_depth > max_pixel_depth)
  196649. max_pixel_depth=user_pixel_depth;
  196650. }
  196651. #endif
  196652. /* align the width on the next larger 8 pixels. Mainly used
  196653. for interlacing */
  196654. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196655. /* calculate the maximum bytes needed, adding a byte and a pixel
  196656. for safety's sake */
  196657. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196658. 1 + ((max_pixel_depth + 7) >> 3);
  196659. #ifdef PNG_MAX_MALLOC_64K
  196660. if (row_bytes > (png_uint_32)65536L)
  196661. png_error(png_ptr, "This image requires a row greater than 64KB");
  196662. #endif
  196663. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196664. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196665. #ifdef PNG_MAX_MALLOC_64K
  196666. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196667. png_error(png_ptr, "This image requires a row greater than 64KB");
  196668. #endif
  196669. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196670. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196671. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196672. png_ptr->rowbytes + 1));
  196673. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196674. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196675. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196676. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196677. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196678. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196679. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196680. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196681. }
  196682. #endif /* PNG_READ_SUPPORTED */
  196683. /*** End of inlined file: pngrutil.c ***/
  196684. /*** Start of inlined file: pngset.c ***/
  196685. /* pngset.c - storage of image information into info struct
  196686. *
  196687. * Last changed in libpng 1.2.21 [October 4, 2007]
  196688. * For conditions of distribution and use, see copyright notice in png.h
  196689. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196690. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196691. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196692. *
  196693. * The functions here are used during reads to store data from the file
  196694. * into the info struct, and during writes to store application data
  196695. * into the info struct for writing into the file. This abstracts the
  196696. * info struct and allows us to change the structure in the future.
  196697. */
  196698. #define PNG_INTERNAL
  196699. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196700. #if defined(PNG_bKGD_SUPPORTED)
  196701. void PNGAPI
  196702. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196703. {
  196704. png_debug1(1, "in %s storage function\n", "bKGD");
  196705. if (png_ptr == NULL || info_ptr == NULL)
  196706. return;
  196707. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196708. info_ptr->valid |= PNG_INFO_bKGD;
  196709. }
  196710. #endif
  196711. #if defined(PNG_cHRM_SUPPORTED)
  196712. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196713. void PNGAPI
  196714. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196715. double white_x, double white_y, double red_x, double red_y,
  196716. double green_x, double green_y, double blue_x, double blue_y)
  196717. {
  196718. png_debug1(1, "in %s storage function\n", "cHRM");
  196719. if (png_ptr == NULL || info_ptr == NULL)
  196720. return;
  196721. if (white_x < 0.0 || white_y < 0.0 ||
  196722. red_x < 0.0 || red_y < 0.0 ||
  196723. green_x < 0.0 || green_y < 0.0 ||
  196724. blue_x < 0.0 || blue_y < 0.0)
  196725. {
  196726. png_warning(png_ptr,
  196727. "Ignoring attempt to set negative chromaticity value");
  196728. return;
  196729. }
  196730. if (white_x > 21474.83 || white_y > 21474.83 ||
  196731. red_x > 21474.83 || red_y > 21474.83 ||
  196732. green_x > 21474.83 || green_y > 21474.83 ||
  196733. blue_x > 21474.83 || blue_y > 21474.83)
  196734. {
  196735. png_warning(png_ptr,
  196736. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196737. return;
  196738. }
  196739. info_ptr->x_white = (float)white_x;
  196740. info_ptr->y_white = (float)white_y;
  196741. info_ptr->x_red = (float)red_x;
  196742. info_ptr->y_red = (float)red_y;
  196743. info_ptr->x_green = (float)green_x;
  196744. info_ptr->y_green = (float)green_y;
  196745. info_ptr->x_blue = (float)blue_x;
  196746. info_ptr->y_blue = (float)blue_y;
  196747. #ifdef PNG_FIXED_POINT_SUPPORTED
  196748. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196749. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196750. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196751. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196752. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196753. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196754. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196755. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196756. #endif
  196757. info_ptr->valid |= PNG_INFO_cHRM;
  196758. }
  196759. #endif
  196760. #ifdef PNG_FIXED_POINT_SUPPORTED
  196761. void PNGAPI
  196762. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196763. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196764. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196765. png_fixed_point blue_x, png_fixed_point blue_y)
  196766. {
  196767. png_debug1(1, "in %s storage function\n", "cHRM");
  196768. if (png_ptr == NULL || info_ptr == NULL)
  196769. return;
  196770. if (white_x < 0 || white_y < 0 ||
  196771. red_x < 0 || red_y < 0 ||
  196772. green_x < 0 || green_y < 0 ||
  196773. blue_x < 0 || blue_y < 0)
  196774. {
  196775. png_warning(png_ptr,
  196776. "Ignoring attempt to set negative chromaticity value");
  196777. return;
  196778. }
  196779. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196780. if (white_x > (double) PNG_UINT_31_MAX ||
  196781. white_y > (double) PNG_UINT_31_MAX ||
  196782. red_x > (double) PNG_UINT_31_MAX ||
  196783. red_y > (double) PNG_UINT_31_MAX ||
  196784. green_x > (double) PNG_UINT_31_MAX ||
  196785. green_y > (double) PNG_UINT_31_MAX ||
  196786. blue_x > (double) PNG_UINT_31_MAX ||
  196787. blue_y > (double) PNG_UINT_31_MAX)
  196788. #else
  196789. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196790. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196791. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196792. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196793. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196794. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196795. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196796. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196797. #endif
  196798. {
  196799. png_warning(png_ptr,
  196800. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196801. return;
  196802. }
  196803. info_ptr->int_x_white = white_x;
  196804. info_ptr->int_y_white = white_y;
  196805. info_ptr->int_x_red = red_x;
  196806. info_ptr->int_y_red = red_y;
  196807. info_ptr->int_x_green = green_x;
  196808. info_ptr->int_y_green = green_y;
  196809. info_ptr->int_x_blue = blue_x;
  196810. info_ptr->int_y_blue = blue_y;
  196811. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196812. info_ptr->x_white = (float)(white_x/100000.);
  196813. info_ptr->y_white = (float)(white_y/100000.);
  196814. info_ptr->x_red = (float)( red_x/100000.);
  196815. info_ptr->y_red = (float)( red_y/100000.);
  196816. info_ptr->x_green = (float)(green_x/100000.);
  196817. info_ptr->y_green = (float)(green_y/100000.);
  196818. info_ptr->x_blue = (float)( blue_x/100000.);
  196819. info_ptr->y_blue = (float)( blue_y/100000.);
  196820. #endif
  196821. info_ptr->valid |= PNG_INFO_cHRM;
  196822. }
  196823. #endif
  196824. #endif
  196825. #if defined(PNG_gAMA_SUPPORTED)
  196826. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196827. void PNGAPI
  196828. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196829. {
  196830. double gamma;
  196831. png_debug1(1, "in %s storage function\n", "gAMA");
  196832. if (png_ptr == NULL || info_ptr == NULL)
  196833. return;
  196834. /* Check for overflow */
  196835. if (file_gamma > 21474.83)
  196836. {
  196837. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196838. gamma=21474.83;
  196839. }
  196840. else
  196841. gamma=file_gamma;
  196842. info_ptr->gamma = (float)gamma;
  196843. #ifdef PNG_FIXED_POINT_SUPPORTED
  196844. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196845. #endif
  196846. info_ptr->valid |= PNG_INFO_gAMA;
  196847. if(gamma == 0.0)
  196848. png_warning(png_ptr, "Setting gamma=0");
  196849. }
  196850. #endif
  196851. void PNGAPI
  196852. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196853. int_gamma)
  196854. {
  196855. png_fixed_point gamma;
  196856. png_debug1(1, "in %s storage function\n", "gAMA");
  196857. if (png_ptr == NULL || info_ptr == NULL)
  196858. return;
  196859. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196860. {
  196861. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196862. gamma=PNG_UINT_31_MAX;
  196863. }
  196864. else
  196865. {
  196866. if (int_gamma < 0)
  196867. {
  196868. png_warning(png_ptr, "Setting negative gamma to zero");
  196869. gamma=0;
  196870. }
  196871. else
  196872. gamma=int_gamma;
  196873. }
  196874. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196875. info_ptr->gamma = (float)(gamma/100000.);
  196876. #endif
  196877. #ifdef PNG_FIXED_POINT_SUPPORTED
  196878. info_ptr->int_gamma = gamma;
  196879. #endif
  196880. info_ptr->valid |= PNG_INFO_gAMA;
  196881. if(gamma == 0)
  196882. png_warning(png_ptr, "Setting gamma=0");
  196883. }
  196884. #endif
  196885. #if defined(PNG_hIST_SUPPORTED)
  196886. void PNGAPI
  196887. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196888. {
  196889. int i;
  196890. png_debug1(1, "in %s storage function\n", "hIST");
  196891. if (png_ptr == NULL || info_ptr == NULL)
  196892. return;
  196893. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196894. > PNG_MAX_PALETTE_LENGTH)
  196895. {
  196896. png_warning(png_ptr,
  196897. "Invalid palette size, hIST allocation skipped.");
  196898. return;
  196899. }
  196900. #ifdef PNG_FREE_ME_SUPPORTED
  196901. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196902. #endif
  196903. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196904. 1.2.1 */
  196905. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196906. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196907. if (png_ptr->hist == NULL)
  196908. {
  196909. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196910. return;
  196911. }
  196912. for (i = 0; i < info_ptr->num_palette; i++)
  196913. png_ptr->hist[i] = hist[i];
  196914. info_ptr->hist = png_ptr->hist;
  196915. info_ptr->valid |= PNG_INFO_hIST;
  196916. #ifdef PNG_FREE_ME_SUPPORTED
  196917. info_ptr->free_me |= PNG_FREE_HIST;
  196918. #else
  196919. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196920. #endif
  196921. }
  196922. #endif
  196923. void PNGAPI
  196924. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196925. png_uint_32 width, png_uint_32 height, int bit_depth,
  196926. int color_type, int interlace_type, int compression_type,
  196927. int filter_type)
  196928. {
  196929. png_debug1(1, "in %s storage function\n", "IHDR");
  196930. if (png_ptr == NULL || info_ptr == NULL)
  196931. return;
  196932. /* check for width and height valid values */
  196933. if (width == 0 || height == 0)
  196934. png_error(png_ptr, "Image width or height is zero in IHDR");
  196935. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196936. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196937. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196938. #else
  196939. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196940. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196941. #endif
  196942. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196943. png_error(png_ptr, "Invalid image size in IHDR");
  196944. if ( width > (PNG_UINT_32_MAX
  196945. >> 3) /* 8-byte RGBA pixels */
  196946. - 64 /* bigrowbuf hack */
  196947. - 1 /* filter byte */
  196948. - 7*8 /* rounding of width to multiple of 8 pixels */
  196949. - 8) /* extra max_pixel_depth pad */
  196950. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196951. /* check other values */
  196952. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196953. bit_depth != 8 && bit_depth != 16)
  196954. png_error(png_ptr, "Invalid bit depth in IHDR");
  196955. if (color_type < 0 || color_type == 1 ||
  196956. color_type == 5 || color_type > 6)
  196957. png_error(png_ptr, "Invalid color type in IHDR");
  196958. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196959. ((color_type == PNG_COLOR_TYPE_RGB ||
  196960. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196961. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196962. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196963. if (interlace_type >= PNG_INTERLACE_LAST)
  196964. png_error(png_ptr, "Unknown interlace method in IHDR");
  196965. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196966. png_error(png_ptr, "Unknown compression method in IHDR");
  196967. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196968. /* Accept filter_method 64 (intrapixel differencing) only if
  196969. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196970. * 2. Libpng did not read a PNG signature (this filter_method is only
  196971. * used in PNG datastreams that are embedded in MNG datastreams) and
  196972. * 3. The application called png_permit_mng_features with a mask that
  196973. * included PNG_FLAG_MNG_FILTER_64 and
  196974. * 4. The filter_method is 64 and
  196975. * 5. The color_type is RGB or RGBA
  196976. */
  196977. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196978. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196979. if(filter_type != PNG_FILTER_TYPE_BASE)
  196980. {
  196981. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196982. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196983. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196984. (color_type == PNG_COLOR_TYPE_RGB ||
  196985. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196986. png_error(png_ptr, "Unknown filter method in IHDR");
  196987. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196988. png_warning(png_ptr, "Invalid filter method in IHDR");
  196989. }
  196990. #else
  196991. if(filter_type != PNG_FILTER_TYPE_BASE)
  196992. png_error(png_ptr, "Unknown filter method in IHDR");
  196993. #endif
  196994. info_ptr->width = width;
  196995. info_ptr->height = height;
  196996. info_ptr->bit_depth = (png_byte)bit_depth;
  196997. info_ptr->color_type =(png_byte) color_type;
  196998. info_ptr->compression_type = (png_byte)compression_type;
  196999. info_ptr->filter_type = (png_byte)filter_type;
  197000. info_ptr->interlace_type = (png_byte)interlace_type;
  197001. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197002. info_ptr->channels = 1;
  197003. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197004. info_ptr->channels = 3;
  197005. else
  197006. info_ptr->channels = 1;
  197007. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197008. info_ptr->channels++;
  197009. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197010. /* check for potential overflow */
  197011. if (width > (PNG_UINT_32_MAX
  197012. >> 3) /* 8-byte RGBA pixels */
  197013. - 64 /* bigrowbuf hack */
  197014. - 1 /* filter byte */
  197015. - 7*8 /* rounding of width to multiple of 8 pixels */
  197016. - 8) /* extra max_pixel_depth pad */
  197017. info_ptr->rowbytes = (png_size_t)0;
  197018. else
  197019. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197020. }
  197021. #if defined(PNG_oFFs_SUPPORTED)
  197022. void PNGAPI
  197023. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197024. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197025. {
  197026. png_debug1(1, "in %s storage function\n", "oFFs");
  197027. if (png_ptr == NULL || info_ptr == NULL)
  197028. return;
  197029. info_ptr->x_offset = offset_x;
  197030. info_ptr->y_offset = offset_y;
  197031. info_ptr->offset_unit_type = (png_byte)unit_type;
  197032. info_ptr->valid |= PNG_INFO_oFFs;
  197033. }
  197034. #endif
  197035. #if defined(PNG_pCAL_SUPPORTED)
  197036. void PNGAPI
  197037. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197038. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197039. png_charp units, png_charpp params)
  197040. {
  197041. png_uint_32 length;
  197042. int i;
  197043. png_debug1(1, "in %s storage function\n", "pCAL");
  197044. if (png_ptr == NULL || info_ptr == NULL)
  197045. return;
  197046. length = png_strlen(purpose) + 1;
  197047. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197048. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197049. if (info_ptr->pcal_purpose == NULL)
  197050. {
  197051. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197052. return;
  197053. }
  197054. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197055. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197056. info_ptr->pcal_X0 = X0;
  197057. info_ptr->pcal_X1 = X1;
  197058. info_ptr->pcal_type = (png_byte)type;
  197059. info_ptr->pcal_nparams = (png_byte)nparams;
  197060. length = png_strlen(units) + 1;
  197061. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197062. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197063. if (info_ptr->pcal_units == NULL)
  197064. {
  197065. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197066. return;
  197067. }
  197068. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197069. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197070. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197071. if (info_ptr->pcal_params == NULL)
  197072. {
  197073. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197074. return;
  197075. }
  197076. info_ptr->pcal_params[nparams] = NULL;
  197077. for (i = 0; i < nparams; i++)
  197078. {
  197079. length = png_strlen(params[i]) + 1;
  197080. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197081. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197082. if (info_ptr->pcal_params[i] == NULL)
  197083. {
  197084. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197085. return;
  197086. }
  197087. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197088. }
  197089. info_ptr->valid |= PNG_INFO_pCAL;
  197090. #ifdef PNG_FREE_ME_SUPPORTED
  197091. info_ptr->free_me |= PNG_FREE_PCAL;
  197092. #endif
  197093. }
  197094. #endif
  197095. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197096. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197097. void PNGAPI
  197098. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197099. int unit, double width, double height)
  197100. {
  197101. png_debug1(1, "in %s storage function\n", "sCAL");
  197102. if (png_ptr == NULL || info_ptr == NULL)
  197103. return;
  197104. info_ptr->scal_unit = (png_byte)unit;
  197105. info_ptr->scal_pixel_width = width;
  197106. info_ptr->scal_pixel_height = height;
  197107. info_ptr->valid |= PNG_INFO_sCAL;
  197108. }
  197109. #else
  197110. #ifdef PNG_FIXED_POINT_SUPPORTED
  197111. void PNGAPI
  197112. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197113. int unit, png_charp swidth, png_charp sheight)
  197114. {
  197115. png_uint_32 length;
  197116. png_debug1(1, "in %s storage function\n", "sCAL");
  197117. if (png_ptr == NULL || info_ptr == NULL)
  197118. return;
  197119. info_ptr->scal_unit = (png_byte)unit;
  197120. length = png_strlen(swidth) + 1;
  197121. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197122. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197123. if (info_ptr->scal_s_width == NULL)
  197124. {
  197125. png_warning(png_ptr,
  197126. "Memory allocation failed while processing sCAL.");
  197127. }
  197128. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197129. length = png_strlen(sheight) + 1;
  197130. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197131. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197132. if (info_ptr->scal_s_height == NULL)
  197133. {
  197134. png_free (png_ptr, info_ptr->scal_s_width);
  197135. png_warning(png_ptr,
  197136. "Memory allocation failed while processing sCAL.");
  197137. }
  197138. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197139. info_ptr->valid |= PNG_INFO_sCAL;
  197140. #ifdef PNG_FREE_ME_SUPPORTED
  197141. info_ptr->free_me |= PNG_FREE_SCAL;
  197142. #endif
  197143. }
  197144. #endif
  197145. #endif
  197146. #endif
  197147. #if defined(PNG_pHYs_SUPPORTED)
  197148. void PNGAPI
  197149. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197150. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197151. {
  197152. png_debug1(1, "in %s storage function\n", "pHYs");
  197153. if (png_ptr == NULL || info_ptr == NULL)
  197154. return;
  197155. info_ptr->x_pixels_per_unit = res_x;
  197156. info_ptr->y_pixels_per_unit = res_y;
  197157. info_ptr->phys_unit_type = (png_byte)unit_type;
  197158. info_ptr->valid |= PNG_INFO_pHYs;
  197159. }
  197160. #endif
  197161. void PNGAPI
  197162. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197163. png_colorp palette, int num_palette)
  197164. {
  197165. png_debug1(1, "in %s storage function\n", "PLTE");
  197166. if (png_ptr == NULL || info_ptr == NULL)
  197167. return;
  197168. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197169. {
  197170. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197171. png_error(png_ptr, "Invalid palette length");
  197172. else
  197173. {
  197174. png_warning(png_ptr, "Invalid palette length");
  197175. return;
  197176. }
  197177. }
  197178. /*
  197179. * It may not actually be necessary to set png_ptr->palette here;
  197180. * we do it for backward compatibility with the way the png_handle_tRNS
  197181. * function used to do the allocation.
  197182. */
  197183. #ifdef PNG_FREE_ME_SUPPORTED
  197184. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197185. #endif
  197186. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197187. of num_palette entries,
  197188. in case of an invalid PNG file that has too-large sample values. */
  197189. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197190. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197191. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197192. png_sizeof(png_color));
  197193. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197194. info_ptr->palette = png_ptr->palette;
  197195. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197196. #ifdef PNG_FREE_ME_SUPPORTED
  197197. info_ptr->free_me |= PNG_FREE_PLTE;
  197198. #else
  197199. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197200. #endif
  197201. info_ptr->valid |= PNG_INFO_PLTE;
  197202. }
  197203. #if defined(PNG_sBIT_SUPPORTED)
  197204. void PNGAPI
  197205. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197206. png_color_8p sig_bit)
  197207. {
  197208. png_debug1(1, "in %s storage function\n", "sBIT");
  197209. if (png_ptr == NULL || info_ptr == NULL)
  197210. return;
  197211. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197212. info_ptr->valid |= PNG_INFO_sBIT;
  197213. }
  197214. #endif
  197215. #if defined(PNG_sRGB_SUPPORTED)
  197216. void PNGAPI
  197217. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197218. {
  197219. png_debug1(1, "in %s storage function\n", "sRGB");
  197220. if (png_ptr == NULL || info_ptr == NULL)
  197221. return;
  197222. info_ptr->srgb_intent = (png_byte)intent;
  197223. info_ptr->valid |= PNG_INFO_sRGB;
  197224. }
  197225. void PNGAPI
  197226. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197227. int intent)
  197228. {
  197229. #if defined(PNG_gAMA_SUPPORTED)
  197230. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197231. float file_gamma;
  197232. #endif
  197233. #ifdef PNG_FIXED_POINT_SUPPORTED
  197234. png_fixed_point int_file_gamma;
  197235. #endif
  197236. #endif
  197237. #if defined(PNG_cHRM_SUPPORTED)
  197238. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197239. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197240. #endif
  197241. #ifdef PNG_FIXED_POINT_SUPPORTED
  197242. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197243. int_green_y, int_blue_x, int_blue_y;
  197244. #endif
  197245. #endif
  197246. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197247. if (png_ptr == NULL || info_ptr == NULL)
  197248. return;
  197249. png_set_sRGB(png_ptr, info_ptr, intent);
  197250. #if defined(PNG_gAMA_SUPPORTED)
  197251. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197252. file_gamma = (float).45455;
  197253. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197254. #endif
  197255. #ifdef PNG_FIXED_POINT_SUPPORTED
  197256. int_file_gamma = 45455L;
  197257. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197258. #endif
  197259. #endif
  197260. #if defined(PNG_cHRM_SUPPORTED)
  197261. #ifdef PNG_FIXED_POINT_SUPPORTED
  197262. int_white_x = 31270L;
  197263. int_white_y = 32900L;
  197264. int_red_x = 64000L;
  197265. int_red_y = 33000L;
  197266. int_green_x = 30000L;
  197267. int_green_y = 60000L;
  197268. int_blue_x = 15000L;
  197269. int_blue_y = 6000L;
  197270. png_set_cHRM_fixed(png_ptr, info_ptr,
  197271. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197272. int_blue_x, int_blue_y);
  197273. #endif
  197274. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197275. white_x = (float).3127;
  197276. white_y = (float).3290;
  197277. red_x = (float).64;
  197278. red_y = (float).33;
  197279. green_x = (float).30;
  197280. green_y = (float).60;
  197281. blue_x = (float).15;
  197282. blue_y = (float).06;
  197283. png_set_cHRM(png_ptr, info_ptr,
  197284. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197285. #endif
  197286. #endif
  197287. }
  197288. #endif
  197289. #if defined(PNG_iCCP_SUPPORTED)
  197290. void PNGAPI
  197291. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197292. png_charp name, int compression_type,
  197293. png_charp profile, png_uint_32 proflen)
  197294. {
  197295. png_charp new_iccp_name;
  197296. png_charp new_iccp_profile;
  197297. png_debug1(1, "in %s storage function\n", "iCCP");
  197298. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197299. return;
  197300. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197301. if (new_iccp_name == NULL)
  197302. {
  197303. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197304. return;
  197305. }
  197306. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197307. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197308. if (new_iccp_profile == NULL)
  197309. {
  197310. png_free (png_ptr, new_iccp_name);
  197311. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197312. return;
  197313. }
  197314. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197315. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197316. info_ptr->iccp_proflen = proflen;
  197317. info_ptr->iccp_name = new_iccp_name;
  197318. info_ptr->iccp_profile = new_iccp_profile;
  197319. /* Compression is always zero but is here so the API and info structure
  197320. * does not have to change if we introduce multiple compression types */
  197321. info_ptr->iccp_compression = (png_byte)compression_type;
  197322. #ifdef PNG_FREE_ME_SUPPORTED
  197323. info_ptr->free_me |= PNG_FREE_ICCP;
  197324. #endif
  197325. info_ptr->valid |= PNG_INFO_iCCP;
  197326. }
  197327. #endif
  197328. #if defined(PNG_TEXT_SUPPORTED)
  197329. void PNGAPI
  197330. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197331. int num_text)
  197332. {
  197333. int ret;
  197334. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197335. if (ret)
  197336. png_error(png_ptr, "Insufficient memory to store text");
  197337. }
  197338. int /* PRIVATE */
  197339. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197340. int num_text)
  197341. {
  197342. int i;
  197343. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197344. "text" : (png_const_charp)png_ptr->chunk_name));
  197345. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197346. return(0);
  197347. /* Make sure we have enough space in the "text" array in info_struct
  197348. * to hold all of the incoming text_ptr objects.
  197349. */
  197350. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197351. {
  197352. if (info_ptr->text != NULL)
  197353. {
  197354. png_textp old_text;
  197355. int old_max;
  197356. old_max = info_ptr->max_text;
  197357. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197358. old_text = info_ptr->text;
  197359. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197360. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197361. if (info_ptr->text == NULL)
  197362. {
  197363. png_free(png_ptr, old_text);
  197364. return(1);
  197365. }
  197366. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197367. png_sizeof(png_text)));
  197368. png_free(png_ptr, old_text);
  197369. }
  197370. else
  197371. {
  197372. info_ptr->max_text = num_text + 8;
  197373. info_ptr->num_text = 0;
  197374. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197375. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197376. if (info_ptr->text == NULL)
  197377. return(1);
  197378. #ifdef PNG_FREE_ME_SUPPORTED
  197379. info_ptr->free_me |= PNG_FREE_TEXT;
  197380. #endif
  197381. }
  197382. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197383. info_ptr->max_text);
  197384. }
  197385. for (i = 0; i < num_text; i++)
  197386. {
  197387. png_size_t text_length,key_len;
  197388. png_size_t lang_len,lang_key_len;
  197389. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197390. if (text_ptr[i].key == NULL)
  197391. continue;
  197392. key_len = png_strlen(text_ptr[i].key);
  197393. if(text_ptr[i].compression <= 0)
  197394. {
  197395. lang_len = 0;
  197396. lang_key_len = 0;
  197397. }
  197398. else
  197399. #ifdef PNG_iTXt_SUPPORTED
  197400. {
  197401. /* set iTXt data */
  197402. if (text_ptr[i].lang != NULL)
  197403. lang_len = png_strlen(text_ptr[i].lang);
  197404. else
  197405. lang_len = 0;
  197406. if (text_ptr[i].lang_key != NULL)
  197407. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197408. else
  197409. lang_key_len = 0;
  197410. }
  197411. #else
  197412. {
  197413. png_warning(png_ptr, "iTXt chunk not supported.");
  197414. continue;
  197415. }
  197416. #endif
  197417. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197418. {
  197419. text_length = 0;
  197420. #ifdef PNG_iTXt_SUPPORTED
  197421. if(text_ptr[i].compression > 0)
  197422. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197423. else
  197424. #endif
  197425. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197426. }
  197427. else
  197428. {
  197429. text_length = png_strlen(text_ptr[i].text);
  197430. textp->compression = text_ptr[i].compression;
  197431. }
  197432. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197433. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197434. if (textp->key == NULL)
  197435. return(1);
  197436. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197437. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197438. (int)textp->key);
  197439. png_memcpy(textp->key, text_ptr[i].key,
  197440. (png_size_t)(key_len));
  197441. *(textp->key+key_len) = '\0';
  197442. #ifdef PNG_iTXt_SUPPORTED
  197443. if (text_ptr[i].compression > 0)
  197444. {
  197445. textp->lang=textp->key + key_len + 1;
  197446. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197447. *(textp->lang+lang_len) = '\0';
  197448. textp->lang_key=textp->lang + lang_len + 1;
  197449. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197450. *(textp->lang_key+lang_key_len) = '\0';
  197451. textp->text=textp->lang_key + lang_key_len + 1;
  197452. }
  197453. else
  197454. #endif
  197455. {
  197456. #ifdef PNG_iTXt_SUPPORTED
  197457. textp->lang=NULL;
  197458. textp->lang_key=NULL;
  197459. #endif
  197460. textp->text=textp->key + key_len + 1;
  197461. }
  197462. if(text_length)
  197463. png_memcpy(textp->text, text_ptr[i].text,
  197464. (png_size_t)(text_length));
  197465. *(textp->text+text_length) = '\0';
  197466. #ifdef PNG_iTXt_SUPPORTED
  197467. if(textp->compression > 0)
  197468. {
  197469. textp->text_length = 0;
  197470. textp->itxt_length = text_length;
  197471. }
  197472. else
  197473. #endif
  197474. {
  197475. textp->text_length = text_length;
  197476. #ifdef PNG_iTXt_SUPPORTED
  197477. textp->itxt_length = 0;
  197478. #endif
  197479. }
  197480. info_ptr->num_text++;
  197481. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197482. }
  197483. return(0);
  197484. }
  197485. #endif
  197486. #if defined(PNG_tIME_SUPPORTED)
  197487. void PNGAPI
  197488. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197489. {
  197490. png_debug1(1, "in %s storage function\n", "tIME");
  197491. if (png_ptr == NULL || info_ptr == NULL ||
  197492. (png_ptr->mode & PNG_WROTE_tIME))
  197493. return;
  197494. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197495. info_ptr->valid |= PNG_INFO_tIME;
  197496. }
  197497. #endif
  197498. #if defined(PNG_tRNS_SUPPORTED)
  197499. void PNGAPI
  197500. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197501. png_bytep trans, int num_trans, png_color_16p trans_values)
  197502. {
  197503. png_debug1(1, "in %s storage function\n", "tRNS");
  197504. if (png_ptr == NULL || info_ptr == NULL)
  197505. return;
  197506. if (trans != NULL)
  197507. {
  197508. /*
  197509. * It may not actually be necessary to set png_ptr->trans here;
  197510. * we do it for backward compatibility with the way the png_handle_tRNS
  197511. * function used to do the allocation.
  197512. */
  197513. #ifdef PNG_FREE_ME_SUPPORTED
  197514. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197515. #endif
  197516. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197517. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197518. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197519. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197520. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197521. #ifdef PNG_FREE_ME_SUPPORTED
  197522. info_ptr->free_me |= PNG_FREE_TRNS;
  197523. #else
  197524. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197525. #endif
  197526. }
  197527. if (trans_values != NULL)
  197528. {
  197529. png_memcpy(&(info_ptr->trans_values), trans_values,
  197530. png_sizeof(png_color_16));
  197531. if (num_trans == 0)
  197532. num_trans = 1;
  197533. }
  197534. info_ptr->num_trans = (png_uint_16)num_trans;
  197535. info_ptr->valid |= PNG_INFO_tRNS;
  197536. }
  197537. #endif
  197538. #if defined(PNG_sPLT_SUPPORTED)
  197539. void PNGAPI
  197540. png_set_sPLT(png_structp png_ptr,
  197541. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197542. {
  197543. png_sPLT_tp np;
  197544. int i;
  197545. if (png_ptr == NULL || info_ptr == NULL)
  197546. return;
  197547. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197548. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197549. if (np == NULL)
  197550. {
  197551. png_warning(png_ptr, "No memory for sPLT palettes.");
  197552. return;
  197553. }
  197554. png_memcpy(np, info_ptr->splt_palettes,
  197555. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197556. png_free(png_ptr, info_ptr->splt_palettes);
  197557. info_ptr->splt_palettes=NULL;
  197558. for (i = 0; i < nentries; i++)
  197559. {
  197560. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197561. png_sPLT_tp from = entries + i;
  197562. to->name = (png_charp)png_malloc_warn(png_ptr,
  197563. png_strlen(from->name) + 1);
  197564. if (to->name == NULL)
  197565. {
  197566. png_warning(png_ptr,
  197567. "Out of memory while processing sPLT chunk");
  197568. }
  197569. /* TODO: use png_malloc_warn */
  197570. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197571. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197572. from->nentries * png_sizeof(png_sPLT_entry));
  197573. /* TODO: use png_malloc_warn */
  197574. png_memcpy(to->entries, from->entries,
  197575. from->nentries * png_sizeof(png_sPLT_entry));
  197576. if (to->entries == NULL)
  197577. {
  197578. png_warning(png_ptr,
  197579. "Out of memory while processing sPLT chunk");
  197580. png_free(png_ptr,to->name);
  197581. to->name = NULL;
  197582. }
  197583. to->nentries = from->nentries;
  197584. to->depth = from->depth;
  197585. }
  197586. info_ptr->splt_palettes = np;
  197587. info_ptr->splt_palettes_num += nentries;
  197588. info_ptr->valid |= PNG_INFO_sPLT;
  197589. #ifdef PNG_FREE_ME_SUPPORTED
  197590. info_ptr->free_me |= PNG_FREE_SPLT;
  197591. #endif
  197592. }
  197593. #endif /* PNG_sPLT_SUPPORTED */
  197594. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197595. void PNGAPI
  197596. png_set_unknown_chunks(png_structp png_ptr,
  197597. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197598. {
  197599. png_unknown_chunkp np;
  197600. int i;
  197601. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197602. return;
  197603. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197604. (info_ptr->unknown_chunks_num + num_unknowns) *
  197605. png_sizeof(png_unknown_chunk));
  197606. if (np == NULL)
  197607. {
  197608. png_warning(png_ptr,
  197609. "Out of memory while processing unknown chunk.");
  197610. return;
  197611. }
  197612. png_memcpy(np, info_ptr->unknown_chunks,
  197613. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197614. png_free(png_ptr, info_ptr->unknown_chunks);
  197615. info_ptr->unknown_chunks=NULL;
  197616. for (i = 0; i < num_unknowns; i++)
  197617. {
  197618. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197619. png_unknown_chunkp from = unknowns + i;
  197620. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197621. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197622. if (to->data == NULL)
  197623. {
  197624. png_warning(png_ptr,
  197625. "Out of memory while processing unknown chunk.");
  197626. }
  197627. else
  197628. {
  197629. png_memcpy(to->data, from->data, from->size);
  197630. to->size = from->size;
  197631. /* note our location in the read or write sequence */
  197632. to->location = (png_byte)(png_ptr->mode & 0xff);
  197633. }
  197634. }
  197635. info_ptr->unknown_chunks = np;
  197636. info_ptr->unknown_chunks_num += num_unknowns;
  197637. #ifdef PNG_FREE_ME_SUPPORTED
  197638. info_ptr->free_me |= PNG_FREE_UNKN;
  197639. #endif
  197640. }
  197641. void PNGAPI
  197642. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197643. int chunk, int location)
  197644. {
  197645. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197646. (int)info_ptr->unknown_chunks_num)
  197647. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197648. }
  197649. #endif
  197650. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197651. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197652. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197653. void PNGAPI
  197654. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197655. {
  197656. /* This function is deprecated in favor of png_permit_mng_features()
  197657. and will be removed from libpng-1.3.0 */
  197658. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197659. if (png_ptr == NULL)
  197660. return;
  197661. png_ptr->mng_features_permitted = (png_byte)
  197662. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197663. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197664. }
  197665. #endif
  197666. #endif
  197667. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197668. png_uint_32 PNGAPI
  197669. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197670. {
  197671. png_debug(1, "in png_permit_mng_features\n");
  197672. if (png_ptr == NULL)
  197673. return (png_uint_32)0;
  197674. png_ptr->mng_features_permitted =
  197675. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197676. return (png_uint_32)png_ptr->mng_features_permitted;
  197677. }
  197678. #endif
  197679. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197680. void PNGAPI
  197681. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197682. chunk_list, int num_chunks)
  197683. {
  197684. png_bytep new_list, p;
  197685. int i, old_num_chunks;
  197686. if (png_ptr == NULL)
  197687. return;
  197688. if (num_chunks == 0)
  197689. {
  197690. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197691. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197692. else
  197693. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197694. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197695. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197696. else
  197697. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197698. return;
  197699. }
  197700. if (chunk_list == NULL)
  197701. return;
  197702. old_num_chunks=png_ptr->num_chunk_list;
  197703. new_list=(png_bytep)png_malloc(png_ptr,
  197704. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197705. if(png_ptr->chunk_list != NULL)
  197706. {
  197707. png_memcpy(new_list, png_ptr->chunk_list,
  197708. (png_size_t)(5*old_num_chunks));
  197709. png_free(png_ptr, png_ptr->chunk_list);
  197710. png_ptr->chunk_list=NULL;
  197711. }
  197712. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197713. (png_size_t)(5*num_chunks));
  197714. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197715. *p=(png_byte)keep;
  197716. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197717. png_ptr->chunk_list=new_list;
  197718. #ifdef PNG_FREE_ME_SUPPORTED
  197719. png_ptr->free_me |= PNG_FREE_LIST;
  197720. #endif
  197721. }
  197722. #endif
  197723. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197724. void PNGAPI
  197725. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197726. png_user_chunk_ptr read_user_chunk_fn)
  197727. {
  197728. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197729. if (png_ptr == NULL)
  197730. return;
  197731. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197732. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197733. }
  197734. #endif
  197735. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197736. void PNGAPI
  197737. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197738. {
  197739. png_debug1(1, "in %s storage function\n", "rows");
  197740. if (png_ptr == NULL || info_ptr == NULL)
  197741. return;
  197742. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197743. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197744. info_ptr->row_pointers = row_pointers;
  197745. if(row_pointers)
  197746. info_ptr->valid |= PNG_INFO_IDAT;
  197747. }
  197748. #endif
  197749. #ifdef PNG_WRITE_SUPPORTED
  197750. void PNGAPI
  197751. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197752. {
  197753. if (png_ptr == NULL)
  197754. return;
  197755. if(png_ptr->zbuf)
  197756. png_free(png_ptr, png_ptr->zbuf);
  197757. png_ptr->zbuf_size = (png_size_t)size;
  197758. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197759. png_ptr->zstream.next_out = png_ptr->zbuf;
  197760. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197761. }
  197762. #endif
  197763. void PNGAPI
  197764. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197765. {
  197766. if (png_ptr && info_ptr)
  197767. info_ptr->valid &= ~(mask);
  197768. }
  197769. #ifndef PNG_1_0_X
  197770. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197771. /* function was added to libpng 1.2.0 and should always exist by default */
  197772. void PNGAPI
  197773. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197774. {
  197775. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197776. if (png_ptr != NULL)
  197777. png_ptr->asm_flags = 0;
  197778. }
  197779. /* this function was added to libpng 1.2.0 */
  197780. void PNGAPI
  197781. png_set_mmx_thresholds (png_structp png_ptr,
  197782. png_byte,
  197783. png_uint_32)
  197784. {
  197785. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197786. if (png_ptr == NULL)
  197787. return;
  197788. }
  197789. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197790. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197791. /* this function was added to libpng 1.2.6 */
  197792. void PNGAPI
  197793. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197794. png_uint_32 user_height_max)
  197795. {
  197796. /* Images with dimensions larger than these limits will be
  197797. * rejected by png_set_IHDR(). To accept any PNG datastream
  197798. * regardless of dimensions, set both limits to 0x7ffffffL.
  197799. */
  197800. if(png_ptr == NULL) return;
  197801. png_ptr->user_width_max = user_width_max;
  197802. png_ptr->user_height_max = user_height_max;
  197803. }
  197804. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197805. #endif /* ?PNG_1_0_X */
  197806. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197807. /*** End of inlined file: pngset.c ***/
  197808. /*** Start of inlined file: pngtrans.c ***/
  197809. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197810. *
  197811. * Last changed in libpng 1.2.17 May 15, 2007
  197812. * For conditions of distribution and use, see copyright notice in png.h
  197813. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197814. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197815. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197816. */
  197817. #define PNG_INTERNAL
  197818. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197819. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197820. /* turn on BGR-to-RGB mapping */
  197821. void PNGAPI
  197822. png_set_bgr(png_structp png_ptr)
  197823. {
  197824. png_debug(1, "in png_set_bgr\n");
  197825. if(png_ptr == NULL) return;
  197826. png_ptr->transformations |= PNG_BGR;
  197827. }
  197828. #endif
  197829. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197830. /* turn on 16 bit byte swapping */
  197831. void PNGAPI
  197832. png_set_swap(png_structp png_ptr)
  197833. {
  197834. png_debug(1, "in png_set_swap\n");
  197835. if(png_ptr == NULL) return;
  197836. if (png_ptr->bit_depth == 16)
  197837. png_ptr->transformations |= PNG_SWAP_BYTES;
  197838. }
  197839. #endif
  197840. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197841. /* turn on pixel packing */
  197842. void PNGAPI
  197843. png_set_packing(png_structp png_ptr)
  197844. {
  197845. png_debug(1, "in png_set_packing\n");
  197846. if(png_ptr == NULL) return;
  197847. if (png_ptr->bit_depth < 8)
  197848. {
  197849. png_ptr->transformations |= PNG_PACK;
  197850. png_ptr->usr_bit_depth = 8;
  197851. }
  197852. }
  197853. #endif
  197854. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197855. /* turn on packed pixel swapping */
  197856. void PNGAPI
  197857. png_set_packswap(png_structp png_ptr)
  197858. {
  197859. png_debug(1, "in png_set_packswap\n");
  197860. if(png_ptr == NULL) return;
  197861. if (png_ptr->bit_depth < 8)
  197862. png_ptr->transformations |= PNG_PACKSWAP;
  197863. }
  197864. #endif
  197865. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197866. void PNGAPI
  197867. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197868. {
  197869. png_debug(1, "in png_set_shift\n");
  197870. if(png_ptr == NULL) return;
  197871. png_ptr->transformations |= PNG_SHIFT;
  197872. png_ptr->shift = *true_bits;
  197873. }
  197874. #endif
  197875. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197876. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197877. int PNGAPI
  197878. png_set_interlace_handling(png_structp png_ptr)
  197879. {
  197880. png_debug(1, "in png_set_interlace handling\n");
  197881. if (png_ptr && png_ptr->interlaced)
  197882. {
  197883. png_ptr->transformations |= PNG_INTERLACE;
  197884. return (7);
  197885. }
  197886. return (1);
  197887. }
  197888. #endif
  197889. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197890. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197891. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197892. * for 48-bit input data, as well as to avoid problems with some compilers
  197893. * that don't like bytes as parameters.
  197894. */
  197895. void PNGAPI
  197896. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197897. {
  197898. png_debug(1, "in png_set_filler\n");
  197899. if(png_ptr == NULL) return;
  197900. png_ptr->transformations |= PNG_FILLER;
  197901. png_ptr->filler = (png_byte)filler;
  197902. if (filler_loc == PNG_FILLER_AFTER)
  197903. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197904. else
  197905. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197906. /* This should probably go in the "do_read_filler" routine.
  197907. * I attempted to do that in libpng-1.0.1a but that caused problems
  197908. * so I restored it in libpng-1.0.2a
  197909. */
  197910. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197911. {
  197912. png_ptr->usr_channels = 4;
  197913. }
  197914. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197915. * a less-than-8-bit grayscale to GA? */
  197916. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197917. {
  197918. png_ptr->usr_channels = 2;
  197919. }
  197920. }
  197921. #if !defined(PNG_1_0_X)
  197922. /* Added to libpng-1.2.7 */
  197923. void PNGAPI
  197924. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197925. {
  197926. png_debug(1, "in png_set_add_alpha\n");
  197927. if(png_ptr == NULL) return;
  197928. png_set_filler(png_ptr, filler, filler_loc);
  197929. png_ptr->transformations |= PNG_ADD_ALPHA;
  197930. }
  197931. #endif
  197932. #endif
  197933. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197934. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197935. void PNGAPI
  197936. png_set_swap_alpha(png_structp png_ptr)
  197937. {
  197938. png_debug(1, "in png_set_swap_alpha\n");
  197939. if(png_ptr == NULL) return;
  197940. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197941. }
  197942. #endif
  197943. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197944. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197945. void PNGAPI
  197946. png_set_invert_alpha(png_structp png_ptr)
  197947. {
  197948. png_debug(1, "in png_set_invert_alpha\n");
  197949. if(png_ptr == NULL) return;
  197950. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197951. }
  197952. #endif
  197953. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197954. void PNGAPI
  197955. png_set_invert_mono(png_structp png_ptr)
  197956. {
  197957. png_debug(1, "in png_set_invert_mono\n");
  197958. if(png_ptr == NULL) return;
  197959. png_ptr->transformations |= PNG_INVERT_MONO;
  197960. }
  197961. /* invert monochrome grayscale data */
  197962. void /* PRIVATE */
  197963. png_do_invert(png_row_infop row_info, png_bytep row)
  197964. {
  197965. png_debug(1, "in png_do_invert\n");
  197966. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197967. * if (row_info->bit_depth == 1 &&
  197968. */
  197969. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197970. if (row == NULL || row_info == NULL)
  197971. return;
  197972. #endif
  197973. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197974. {
  197975. png_bytep rp = row;
  197976. png_uint_32 i;
  197977. png_uint_32 istop = row_info->rowbytes;
  197978. for (i = 0; i < istop; i++)
  197979. {
  197980. *rp = (png_byte)(~(*rp));
  197981. rp++;
  197982. }
  197983. }
  197984. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197985. row_info->bit_depth == 8)
  197986. {
  197987. png_bytep rp = row;
  197988. png_uint_32 i;
  197989. png_uint_32 istop = row_info->rowbytes;
  197990. for (i = 0; i < istop; i+=2)
  197991. {
  197992. *rp = (png_byte)(~(*rp));
  197993. rp+=2;
  197994. }
  197995. }
  197996. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197997. row_info->bit_depth == 16)
  197998. {
  197999. png_bytep rp = row;
  198000. png_uint_32 i;
  198001. png_uint_32 istop = row_info->rowbytes;
  198002. for (i = 0; i < istop; i+=4)
  198003. {
  198004. *rp = (png_byte)(~(*rp));
  198005. *(rp+1) = (png_byte)(~(*(rp+1)));
  198006. rp+=4;
  198007. }
  198008. }
  198009. }
  198010. #endif
  198011. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198012. /* swaps byte order on 16 bit depth images */
  198013. void /* PRIVATE */
  198014. png_do_swap(png_row_infop row_info, png_bytep row)
  198015. {
  198016. png_debug(1, "in png_do_swap\n");
  198017. if (
  198018. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198019. row != NULL && row_info != NULL &&
  198020. #endif
  198021. row_info->bit_depth == 16)
  198022. {
  198023. png_bytep rp = row;
  198024. png_uint_32 i;
  198025. png_uint_32 istop= row_info->width * row_info->channels;
  198026. for (i = 0; i < istop; i++, rp += 2)
  198027. {
  198028. png_byte t = *rp;
  198029. *rp = *(rp + 1);
  198030. *(rp + 1) = t;
  198031. }
  198032. }
  198033. }
  198034. #endif
  198035. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198036. static PNG_CONST png_byte onebppswaptable[256] = {
  198037. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198038. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198039. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198040. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198041. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198042. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198043. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198044. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198045. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198046. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198047. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198048. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198049. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198050. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198051. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198052. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198053. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198054. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198055. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198056. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198057. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198058. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198059. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198060. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198061. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198062. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198063. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198064. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198065. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198066. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198067. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198068. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198069. };
  198070. static PNG_CONST png_byte twobppswaptable[256] = {
  198071. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198072. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198073. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198074. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198075. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198076. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198077. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198078. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198079. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198080. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198081. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198082. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198083. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198084. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198085. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198086. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198087. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198088. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198089. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198090. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198091. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198092. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198093. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198094. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198095. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198096. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198097. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198098. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198099. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198100. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198101. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198102. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198103. };
  198104. static PNG_CONST png_byte fourbppswaptable[256] = {
  198105. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198106. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198107. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198108. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198109. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198110. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198111. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198112. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198113. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198114. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198115. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198116. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198117. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198118. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198119. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198120. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198121. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198122. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198123. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198124. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198125. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198126. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198127. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198128. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198129. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198130. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198131. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198132. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198133. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198134. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198135. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198136. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198137. };
  198138. /* swaps pixel packing order within bytes */
  198139. void /* PRIVATE */
  198140. png_do_packswap(png_row_infop row_info, png_bytep row)
  198141. {
  198142. png_debug(1, "in png_do_packswap\n");
  198143. if (
  198144. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198145. row != NULL && row_info != NULL &&
  198146. #endif
  198147. row_info->bit_depth < 8)
  198148. {
  198149. png_bytep rp, end, table;
  198150. end = row + row_info->rowbytes;
  198151. if (row_info->bit_depth == 1)
  198152. table = (png_bytep)onebppswaptable;
  198153. else if (row_info->bit_depth == 2)
  198154. table = (png_bytep)twobppswaptable;
  198155. else if (row_info->bit_depth == 4)
  198156. table = (png_bytep)fourbppswaptable;
  198157. else
  198158. return;
  198159. for (rp = row; rp < end; rp++)
  198160. *rp = table[*rp];
  198161. }
  198162. }
  198163. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198164. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198165. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198166. /* remove filler or alpha byte(s) */
  198167. void /* PRIVATE */
  198168. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198169. {
  198170. png_debug(1, "in png_do_strip_filler\n");
  198171. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198172. if (row != NULL && row_info != NULL)
  198173. #endif
  198174. {
  198175. png_bytep sp=row;
  198176. png_bytep dp=row;
  198177. png_uint_32 row_width=row_info->width;
  198178. png_uint_32 i;
  198179. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198180. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198181. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198182. row_info->channels == 4)
  198183. {
  198184. if (row_info->bit_depth == 8)
  198185. {
  198186. /* This converts from RGBX or RGBA to RGB */
  198187. if (flags & PNG_FLAG_FILLER_AFTER)
  198188. {
  198189. dp+=3; sp+=4;
  198190. for (i = 1; i < row_width; i++)
  198191. {
  198192. *dp++ = *sp++;
  198193. *dp++ = *sp++;
  198194. *dp++ = *sp++;
  198195. sp++;
  198196. }
  198197. }
  198198. /* This converts from XRGB or ARGB to RGB */
  198199. else
  198200. {
  198201. for (i = 0; i < row_width; i++)
  198202. {
  198203. sp++;
  198204. *dp++ = *sp++;
  198205. *dp++ = *sp++;
  198206. *dp++ = *sp++;
  198207. }
  198208. }
  198209. row_info->pixel_depth = 24;
  198210. row_info->rowbytes = row_width * 3;
  198211. }
  198212. else /* if (row_info->bit_depth == 16) */
  198213. {
  198214. if (flags & PNG_FLAG_FILLER_AFTER)
  198215. {
  198216. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198217. sp += 8; dp += 6;
  198218. for (i = 1; i < row_width; i++)
  198219. {
  198220. /* This could be (although png_memcpy is probably slower):
  198221. png_memcpy(dp, sp, 6);
  198222. sp += 8;
  198223. dp += 6;
  198224. */
  198225. *dp++ = *sp++;
  198226. *dp++ = *sp++;
  198227. *dp++ = *sp++;
  198228. *dp++ = *sp++;
  198229. *dp++ = *sp++;
  198230. *dp++ = *sp++;
  198231. sp += 2;
  198232. }
  198233. }
  198234. else
  198235. {
  198236. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198237. for (i = 0; i < row_width; i++)
  198238. {
  198239. /* This could be (although png_memcpy is probably slower):
  198240. png_memcpy(dp, sp, 6);
  198241. sp += 8;
  198242. dp += 6;
  198243. */
  198244. sp+=2;
  198245. *dp++ = *sp++;
  198246. *dp++ = *sp++;
  198247. *dp++ = *sp++;
  198248. *dp++ = *sp++;
  198249. *dp++ = *sp++;
  198250. *dp++ = *sp++;
  198251. }
  198252. }
  198253. row_info->pixel_depth = 48;
  198254. row_info->rowbytes = row_width * 6;
  198255. }
  198256. row_info->channels = 3;
  198257. }
  198258. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198259. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198260. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198261. row_info->channels == 2)
  198262. {
  198263. if (row_info->bit_depth == 8)
  198264. {
  198265. /* This converts from GX or GA to G */
  198266. if (flags & PNG_FLAG_FILLER_AFTER)
  198267. {
  198268. for (i = 0; i < row_width; i++)
  198269. {
  198270. *dp++ = *sp++;
  198271. sp++;
  198272. }
  198273. }
  198274. /* This converts from XG or AG to G */
  198275. else
  198276. {
  198277. for (i = 0; i < row_width; i++)
  198278. {
  198279. sp++;
  198280. *dp++ = *sp++;
  198281. }
  198282. }
  198283. row_info->pixel_depth = 8;
  198284. row_info->rowbytes = row_width;
  198285. }
  198286. else /* if (row_info->bit_depth == 16) */
  198287. {
  198288. if (flags & PNG_FLAG_FILLER_AFTER)
  198289. {
  198290. /* This converts from GGXX or GGAA to GG */
  198291. sp += 4; dp += 2;
  198292. for (i = 1; i < row_width; i++)
  198293. {
  198294. *dp++ = *sp++;
  198295. *dp++ = *sp++;
  198296. sp += 2;
  198297. }
  198298. }
  198299. else
  198300. {
  198301. /* This converts from XXGG or AAGG to GG */
  198302. for (i = 0; i < row_width; i++)
  198303. {
  198304. sp += 2;
  198305. *dp++ = *sp++;
  198306. *dp++ = *sp++;
  198307. }
  198308. }
  198309. row_info->pixel_depth = 16;
  198310. row_info->rowbytes = row_width * 2;
  198311. }
  198312. row_info->channels = 1;
  198313. }
  198314. if (flags & PNG_FLAG_STRIP_ALPHA)
  198315. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198316. }
  198317. }
  198318. #endif
  198319. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198320. /* swaps red and blue bytes within a pixel */
  198321. void /* PRIVATE */
  198322. png_do_bgr(png_row_infop row_info, png_bytep row)
  198323. {
  198324. png_debug(1, "in png_do_bgr\n");
  198325. if (
  198326. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198327. row != NULL && row_info != NULL &&
  198328. #endif
  198329. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198330. {
  198331. png_uint_32 row_width = row_info->width;
  198332. if (row_info->bit_depth == 8)
  198333. {
  198334. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198335. {
  198336. png_bytep rp;
  198337. png_uint_32 i;
  198338. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198339. {
  198340. png_byte save = *rp;
  198341. *rp = *(rp + 2);
  198342. *(rp + 2) = save;
  198343. }
  198344. }
  198345. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198346. {
  198347. png_bytep rp;
  198348. png_uint_32 i;
  198349. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198350. {
  198351. png_byte save = *rp;
  198352. *rp = *(rp + 2);
  198353. *(rp + 2) = save;
  198354. }
  198355. }
  198356. }
  198357. else if (row_info->bit_depth == 16)
  198358. {
  198359. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198360. {
  198361. png_bytep rp;
  198362. png_uint_32 i;
  198363. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198364. {
  198365. png_byte save = *rp;
  198366. *rp = *(rp + 4);
  198367. *(rp + 4) = save;
  198368. save = *(rp + 1);
  198369. *(rp + 1) = *(rp + 5);
  198370. *(rp + 5) = save;
  198371. }
  198372. }
  198373. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198374. {
  198375. png_bytep rp;
  198376. png_uint_32 i;
  198377. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198378. {
  198379. png_byte save = *rp;
  198380. *rp = *(rp + 4);
  198381. *(rp + 4) = save;
  198382. save = *(rp + 1);
  198383. *(rp + 1) = *(rp + 5);
  198384. *(rp + 5) = save;
  198385. }
  198386. }
  198387. }
  198388. }
  198389. }
  198390. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198391. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198392. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198393. defined(PNG_LEGACY_SUPPORTED)
  198394. void PNGAPI
  198395. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198396. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198397. {
  198398. png_debug(1, "in png_set_user_transform_info\n");
  198399. if(png_ptr == NULL) return;
  198400. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198401. png_ptr->user_transform_ptr = user_transform_ptr;
  198402. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198403. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198404. #else
  198405. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198406. png_warning(png_ptr,
  198407. "This version of libpng does not support user transform info");
  198408. #endif
  198409. }
  198410. #endif
  198411. /* This function returns a pointer to the user_transform_ptr associated with
  198412. * the user transform functions. The application should free any memory
  198413. * associated with this pointer before png_write_destroy and png_read_destroy
  198414. * are called.
  198415. */
  198416. png_voidp PNGAPI
  198417. png_get_user_transform_ptr(png_structp png_ptr)
  198418. {
  198419. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198420. if (png_ptr == NULL) return (NULL);
  198421. return ((png_voidp)png_ptr->user_transform_ptr);
  198422. #else
  198423. return (NULL);
  198424. #endif
  198425. }
  198426. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198427. /*** End of inlined file: pngtrans.c ***/
  198428. /*** Start of inlined file: pngwio.c ***/
  198429. /* pngwio.c - functions for data output
  198430. *
  198431. * Last changed in libpng 1.2.13 November 13, 2006
  198432. * For conditions of distribution and use, see copyright notice in png.h
  198433. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198434. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198435. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198436. *
  198437. * This file provides a location for all output. Users who need
  198438. * special handling are expected to write functions that have the same
  198439. * arguments as these and perform similar functions, but that possibly
  198440. * use different output methods. Note that you shouldn't change these
  198441. * functions, but rather write replacement functions and then change
  198442. * them at run time with png_set_write_fn(...).
  198443. */
  198444. #define PNG_INTERNAL
  198445. #ifdef PNG_WRITE_SUPPORTED
  198446. /* Write the data to whatever output you are using. The default routine
  198447. writes to a file pointer. Note that this routine sometimes gets called
  198448. with very small lengths, so you should implement some kind of simple
  198449. buffering if you are using unbuffered writes. This should never be asked
  198450. to write more than 64K on a 16 bit machine. */
  198451. void /* PRIVATE */
  198452. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198453. {
  198454. if (png_ptr->write_data_fn != NULL )
  198455. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198456. else
  198457. png_error(png_ptr, "Call to NULL write function");
  198458. }
  198459. #if !defined(PNG_NO_STDIO)
  198460. /* This is the function that does the actual writing of data. If you are
  198461. not writing to a standard C stream, you should create a replacement
  198462. write_data function and use it at run time with png_set_write_fn(), rather
  198463. than changing the library. */
  198464. #ifndef USE_FAR_KEYWORD
  198465. void PNGAPI
  198466. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198467. {
  198468. png_uint_32 check;
  198469. if(png_ptr == NULL) return;
  198470. #if defined(_WIN32_WCE)
  198471. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198472. check = 0;
  198473. #else
  198474. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198475. #endif
  198476. if (check != length)
  198477. png_error(png_ptr, "Write Error");
  198478. }
  198479. #else
  198480. /* this is the model-independent version. Since the standard I/O library
  198481. can't handle far buffers in the medium and small models, we have to copy
  198482. the data.
  198483. */
  198484. #define NEAR_BUF_SIZE 1024
  198485. #define MIN(a,b) (a <= b ? a : b)
  198486. void PNGAPI
  198487. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198488. {
  198489. png_uint_32 check;
  198490. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198491. png_FILE_p io_ptr;
  198492. if(png_ptr == NULL) return;
  198493. /* Check if data really is near. If so, use usual code. */
  198494. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198495. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198496. if ((png_bytep)near_data == data)
  198497. {
  198498. #if defined(_WIN32_WCE)
  198499. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198500. check = 0;
  198501. #else
  198502. check = fwrite(near_data, 1, length, io_ptr);
  198503. #endif
  198504. }
  198505. else
  198506. {
  198507. png_byte buf[NEAR_BUF_SIZE];
  198508. png_size_t written, remaining, err;
  198509. check = 0;
  198510. remaining = length;
  198511. do
  198512. {
  198513. written = MIN(NEAR_BUF_SIZE, remaining);
  198514. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198515. #if defined(_WIN32_WCE)
  198516. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198517. err = 0;
  198518. #else
  198519. err = fwrite(buf, 1, written, io_ptr);
  198520. #endif
  198521. if (err != written)
  198522. break;
  198523. else
  198524. check += err;
  198525. data += written;
  198526. remaining -= written;
  198527. }
  198528. while (remaining != 0);
  198529. }
  198530. if (check != length)
  198531. png_error(png_ptr, "Write Error");
  198532. }
  198533. #endif
  198534. #endif
  198535. /* This function is called to output any data pending writing (normally
  198536. to disk). After png_flush is called, there should be no data pending
  198537. writing in any buffers. */
  198538. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198539. void /* PRIVATE */
  198540. png_flush(png_structp png_ptr)
  198541. {
  198542. if (png_ptr->output_flush_fn != NULL)
  198543. (*(png_ptr->output_flush_fn))(png_ptr);
  198544. }
  198545. #if !defined(PNG_NO_STDIO)
  198546. void PNGAPI
  198547. png_default_flush(png_structp png_ptr)
  198548. {
  198549. #if !defined(_WIN32_WCE)
  198550. png_FILE_p io_ptr;
  198551. #endif
  198552. if(png_ptr == NULL) return;
  198553. #if !defined(_WIN32_WCE)
  198554. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198555. if (io_ptr != NULL)
  198556. fflush(io_ptr);
  198557. #endif
  198558. }
  198559. #endif
  198560. #endif
  198561. /* This function allows the application to supply new output functions for
  198562. libpng if standard C streams aren't being used.
  198563. This function takes as its arguments:
  198564. png_ptr - pointer to a png output data structure
  198565. io_ptr - pointer to user supplied structure containing info about
  198566. the output functions. May be NULL.
  198567. write_data_fn - pointer to a new output function that takes as its
  198568. arguments a pointer to a png_struct, a pointer to
  198569. data to be written, and a 32-bit unsigned int that is
  198570. the number of bytes to be written. The new write
  198571. function should call png_error(png_ptr, "Error msg")
  198572. to exit and output any fatal error messages.
  198573. flush_data_fn - pointer to a new flush function that takes as its
  198574. arguments a pointer to a png_struct. After a call to
  198575. the flush function, there should be no data in any buffers
  198576. or pending transmission. If the output method doesn't do
  198577. any buffering of ouput, a function prototype must still be
  198578. supplied although it doesn't have to do anything. If
  198579. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198580. time, output_flush_fn will be ignored, although it must be
  198581. supplied for compatibility. */
  198582. void PNGAPI
  198583. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198584. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198585. {
  198586. if(png_ptr == NULL) return;
  198587. png_ptr->io_ptr = io_ptr;
  198588. #if !defined(PNG_NO_STDIO)
  198589. if (write_data_fn != NULL)
  198590. png_ptr->write_data_fn = write_data_fn;
  198591. else
  198592. png_ptr->write_data_fn = png_default_write_data;
  198593. #else
  198594. png_ptr->write_data_fn = write_data_fn;
  198595. #endif
  198596. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198597. #if !defined(PNG_NO_STDIO)
  198598. if (output_flush_fn != NULL)
  198599. png_ptr->output_flush_fn = output_flush_fn;
  198600. else
  198601. png_ptr->output_flush_fn = png_default_flush;
  198602. #else
  198603. png_ptr->output_flush_fn = output_flush_fn;
  198604. #endif
  198605. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198606. /* It is an error to read while writing a png file */
  198607. if (png_ptr->read_data_fn != NULL)
  198608. {
  198609. png_ptr->read_data_fn = NULL;
  198610. png_warning(png_ptr,
  198611. "Attempted to set both read_data_fn and write_data_fn in");
  198612. png_warning(png_ptr,
  198613. "the same structure. Resetting read_data_fn to NULL.");
  198614. }
  198615. }
  198616. #if defined(USE_FAR_KEYWORD)
  198617. #if defined(_MSC_VER)
  198618. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198619. {
  198620. void *near_ptr;
  198621. void FAR *far_ptr;
  198622. FP_OFF(near_ptr) = FP_OFF(ptr);
  198623. far_ptr = (void FAR *)near_ptr;
  198624. if(check != 0)
  198625. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198626. png_error(png_ptr,"segment lost in conversion");
  198627. return(near_ptr);
  198628. }
  198629. # else
  198630. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198631. {
  198632. void *near_ptr;
  198633. void FAR *far_ptr;
  198634. near_ptr = (void FAR *)ptr;
  198635. far_ptr = (void FAR *)near_ptr;
  198636. if(check != 0)
  198637. if(far_ptr != ptr)
  198638. png_error(png_ptr,"segment lost in conversion");
  198639. return(near_ptr);
  198640. }
  198641. # endif
  198642. # endif
  198643. #endif /* PNG_WRITE_SUPPORTED */
  198644. /*** End of inlined file: pngwio.c ***/
  198645. /*** Start of inlined file: pngwrite.c ***/
  198646. /* pngwrite.c - general routines to write a PNG file
  198647. *
  198648. * Last changed in libpng 1.2.15 January 5, 2007
  198649. * For conditions of distribution and use, see copyright notice in png.h
  198650. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198651. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198652. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198653. */
  198654. /* get internal access to png.h */
  198655. #define PNG_INTERNAL
  198656. #ifdef PNG_WRITE_SUPPORTED
  198657. /* Writes all the PNG information. This is the suggested way to use the
  198658. * library. If you have a new chunk to add, make a function to write it,
  198659. * and put it in the correct location here. If you want the chunk written
  198660. * after the image data, put it in png_write_end(). I strongly encourage
  198661. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198662. * the chunk, as that will keep the code from breaking if you want to just
  198663. * write a plain PNG file. If you have long comments, I suggest writing
  198664. * them in png_write_end(), and compressing them.
  198665. */
  198666. void PNGAPI
  198667. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198668. {
  198669. png_debug(1, "in png_write_info_before_PLTE\n");
  198670. if (png_ptr == NULL || info_ptr == NULL)
  198671. return;
  198672. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198673. {
  198674. png_write_sig(png_ptr); /* write PNG signature */
  198675. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198676. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198677. {
  198678. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198679. png_ptr->mng_features_permitted=0;
  198680. }
  198681. #endif
  198682. /* write IHDR information. */
  198683. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198684. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198685. info_ptr->filter_type,
  198686. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198687. info_ptr->interlace_type);
  198688. #else
  198689. 0);
  198690. #endif
  198691. /* the rest of these check to see if the valid field has the appropriate
  198692. flag set, and if it does, writes the chunk. */
  198693. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198694. if (info_ptr->valid & PNG_INFO_gAMA)
  198695. {
  198696. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198697. png_write_gAMA(png_ptr, info_ptr->gamma);
  198698. #else
  198699. #ifdef PNG_FIXED_POINT_SUPPORTED
  198700. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198701. # endif
  198702. #endif
  198703. }
  198704. #endif
  198705. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198706. if (info_ptr->valid & PNG_INFO_sRGB)
  198707. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198708. #endif
  198709. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198710. if (info_ptr->valid & PNG_INFO_iCCP)
  198711. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198712. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198713. #endif
  198714. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198715. if (info_ptr->valid & PNG_INFO_sBIT)
  198716. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198717. #endif
  198718. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198719. if (info_ptr->valid & PNG_INFO_cHRM)
  198720. {
  198721. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198722. png_write_cHRM(png_ptr,
  198723. info_ptr->x_white, info_ptr->y_white,
  198724. info_ptr->x_red, info_ptr->y_red,
  198725. info_ptr->x_green, info_ptr->y_green,
  198726. info_ptr->x_blue, info_ptr->y_blue);
  198727. #else
  198728. # ifdef PNG_FIXED_POINT_SUPPORTED
  198729. png_write_cHRM_fixed(png_ptr,
  198730. info_ptr->int_x_white, info_ptr->int_y_white,
  198731. info_ptr->int_x_red, info_ptr->int_y_red,
  198732. info_ptr->int_x_green, info_ptr->int_y_green,
  198733. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198734. # endif
  198735. #endif
  198736. }
  198737. #endif
  198738. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198739. if (info_ptr->unknown_chunks_num)
  198740. {
  198741. png_unknown_chunk *up;
  198742. png_debug(5, "writing extra chunks\n");
  198743. for (up = info_ptr->unknown_chunks;
  198744. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198745. up++)
  198746. {
  198747. int keep=png_handle_as_unknown(png_ptr, up->name);
  198748. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198749. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198750. !(up->location & PNG_HAVE_IDAT) &&
  198751. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198752. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198753. {
  198754. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198755. }
  198756. }
  198757. }
  198758. #endif
  198759. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198760. }
  198761. }
  198762. void PNGAPI
  198763. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198764. {
  198765. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198766. int i;
  198767. #endif
  198768. png_debug(1, "in png_write_info\n");
  198769. if (png_ptr == NULL || info_ptr == NULL)
  198770. return;
  198771. png_write_info_before_PLTE(png_ptr, info_ptr);
  198772. if (info_ptr->valid & PNG_INFO_PLTE)
  198773. png_write_PLTE(png_ptr, info_ptr->palette,
  198774. (png_uint_32)info_ptr->num_palette);
  198775. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198776. png_error(png_ptr, "Valid palette required for paletted images");
  198777. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198778. if (info_ptr->valid & PNG_INFO_tRNS)
  198779. {
  198780. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198781. /* invert the alpha channel (in tRNS) */
  198782. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198783. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198784. {
  198785. int j;
  198786. for (j=0; j<(int)info_ptr->num_trans; j++)
  198787. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198788. }
  198789. #endif
  198790. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198791. info_ptr->num_trans, info_ptr->color_type);
  198792. }
  198793. #endif
  198794. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198795. if (info_ptr->valid & PNG_INFO_bKGD)
  198796. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198797. #endif
  198798. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198799. if (info_ptr->valid & PNG_INFO_hIST)
  198800. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198801. #endif
  198802. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198803. if (info_ptr->valid & PNG_INFO_oFFs)
  198804. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198805. info_ptr->offset_unit_type);
  198806. #endif
  198807. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198808. if (info_ptr->valid & PNG_INFO_pCAL)
  198809. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198810. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198811. info_ptr->pcal_units, info_ptr->pcal_params);
  198812. #endif
  198813. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198814. if (info_ptr->valid & PNG_INFO_sCAL)
  198815. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198816. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198817. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198818. #else
  198819. #ifdef PNG_FIXED_POINT_SUPPORTED
  198820. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198821. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198822. #else
  198823. png_warning(png_ptr,
  198824. "png_write_sCAL not supported; sCAL chunk not written.");
  198825. #endif
  198826. #endif
  198827. #endif
  198828. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198829. if (info_ptr->valid & PNG_INFO_pHYs)
  198830. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198831. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198832. #endif
  198833. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198834. if (info_ptr->valid & PNG_INFO_tIME)
  198835. {
  198836. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198837. png_ptr->mode |= PNG_WROTE_tIME;
  198838. }
  198839. #endif
  198840. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198841. if (info_ptr->valid & PNG_INFO_sPLT)
  198842. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198843. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198844. #endif
  198845. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198846. /* Check to see if we need to write text chunks */
  198847. for (i = 0; i < info_ptr->num_text; i++)
  198848. {
  198849. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198850. info_ptr->text[i].compression);
  198851. /* an internationalized chunk? */
  198852. if (info_ptr->text[i].compression > 0)
  198853. {
  198854. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198855. /* write international chunk */
  198856. png_write_iTXt(png_ptr,
  198857. info_ptr->text[i].compression,
  198858. info_ptr->text[i].key,
  198859. info_ptr->text[i].lang,
  198860. info_ptr->text[i].lang_key,
  198861. info_ptr->text[i].text);
  198862. #else
  198863. png_warning(png_ptr, "Unable to write international text");
  198864. #endif
  198865. /* Mark this chunk as written */
  198866. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198867. }
  198868. /* If we want a compressed text chunk */
  198869. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198870. {
  198871. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198872. /* write compressed chunk */
  198873. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198874. info_ptr->text[i].text, 0,
  198875. info_ptr->text[i].compression);
  198876. #else
  198877. png_warning(png_ptr, "Unable to write compressed text");
  198878. #endif
  198879. /* Mark this chunk as written */
  198880. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198881. }
  198882. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198883. {
  198884. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198885. /* write uncompressed chunk */
  198886. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198887. info_ptr->text[i].text,
  198888. 0);
  198889. #else
  198890. png_warning(png_ptr, "Unable to write uncompressed text");
  198891. #endif
  198892. /* Mark this chunk as written */
  198893. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198894. }
  198895. }
  198896. #endif
  198897. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198898. if (info_ptr->unknown_chunks_num)
  198899. {
  198900. png_unknown_chunk *up;
  198901. png_debug(5, "writing extra chunks\n");
  198902. for (up = info_ptr->unknown_chunks;
  198903. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198904. up++)
  198905. {
  198906. int keep=png_handle_as_unknown(png_ptr, up->name);
  198907. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198908. up->location && (up->location & PNG_HAVE_PLTE) &&
  198909. !(up->location & PNG_HAVE_IDAT) &&
  198910. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198911. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198912. {
  198913. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198914. }
  198915. }
  198916. }
  198917. #endif
  198918. }
  198919. /* Writes the end of the PNG file. If you don't want to write comments or
  198920. * time information, you can pass NULL for info. If you already wrote these
  198921. * in png_write_info(), do not write them again here. If you have long
  198922. * comments, I suggest writing them here, and compressing them.
  198923. */
  198924. void PNGAPI
  198925. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198926. {
  198927. png_debug(1, "in png_write_end\n");
  198928. if (png_ptr == NULL)
  198929. return;
  198930. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198931. png_error(png_ptr, "No IDATs written into file");
  198932. /* see if user wants us to write information chunks */
  198933. if (info_ptr != NULL)
  198934. {
  198935. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198936. int i; /* local index variable */
  198937. #endif
  198938. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198939. /* check to see if user has supplied a time chunk */
  198940. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198941. !(png_ptr->mode & PNG_WROTE_tIME))
  198942. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198943. #endif
  198944. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198945. /* loop through comment chunks */
  198946. for (i = 0; i < info_ptr->num_text; i++)
  198947. {
  198948. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198949. info_ptr->text[i].compression);
  198950. /* an internationalized chunk? */
  198951. if (info_ptr->text[i].compression > 0)
  198952. {
  198953. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198954. /* write international chunk */
  198955. png_write_iTXt(png_ptr,
  198956. info_ptr->text[i].compression,
  198957. info_ptr->text[i].key,
  198958. info_ptr->text[i].lang,
  198959. info_ptr->text[i].lang_key,
  198960. info_ptr->text[i].text);
  198961. #else
  198962. png_warning(png_ptr, "Unable to write international text");
  198963. #endif
  198964. /* Mark this chunk as written */
  198965. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198966. }
  198967. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198968. {
  198969. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198970. /* write compressed chunk */
  198971. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198972. info_ptr->text[i].text, 0,
  198973. info_ptr->text[i].compression);
  198974. #else
  198975. png_warning(png_ptr, "Unable to write compressed text");
  198976. #endif
  198977. /* Mark this chunk as written */
  198978. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198979. }
  198980. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198981. {
  198982. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198983. /* write uncompressed chunk */
  198984. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198985. info_ptr->text[i].text, 0);
  198986. #else
  198987. png_warning(png_ptr, "Unable to write uncompressed text");
  198988. #endif
  198989. /* Mark this chunk as written */
  198990. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198991. }
  198992. }
  198993. #endif
  198994. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198995. if (info_ptr->unknown_chunks_num)
  198996. {
  198997. png_unknown_chunk *up;
  198998. png_debug(5, "writing extra chunks\n");
  198999. for (up = info_ptr->unknown_chunks;
  199000. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199001. up++)
  199002. {
  199003. int keep=png_handle_as_unknown(png_ptr, up->name);
  199004. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199005. up->location && (up->location & PNG_AFTER_IDAT) &&
  199006. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199007. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199008. {
  199009. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199010. }
  199011. }
  199012. }
  199013. #endif
  199014. }
  199015. png_ptr->mode |= PNG_AFTER_IDAT;
  199016. /* write end of PNG file */
  199017. png_write_IEND(png_ptr);
  199018. }
  199019. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199020. #if !defined(_WIN32_WCE)
  199021. /* "time.h" functions are not supported on WindowsCE */
  199022. void PNGAPI
  199023. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199024. {
  199025. png_debug(1, "in png_convert_from_struct_tm\n");
  199026. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199027. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199028. ptime->day = (png_byte)ttime->tm_mday;
  199029. ptime->hour = (png_byte)ttime->tm_hour;
  199030. ptime->minute = (png_byte)ttime->tm_min;
  199031. ptime->second = (png_byte)ttime->tm_sec;
  199032. }
  199033. void PNGAPI
  199034. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199035. {
  199036. struct tm *tbuf;
  199037. png_debug(1, "in png_convert_from_time_t\n");
  199038. tbuf = gmtime(&ttime);
  199039. png_convert_from_struct_tm(ptime, tbuf);
  199040. }
  199041. #endif
  199042. #endif
  199043. /* Initialize png_ptr structure, and allocate any memory needed */
  199044. png_structp PNGAPI
  199045. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199046. png_error_ptr error_fn, png_error_ptr warn_fn)
  199047. {
  199048. #ifdef PNG_USER_MEM_SUPPORTED
  199049. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199050. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199051. }
  199052. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199053. png_structp PNGAPI
  199054. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199055. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199056. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199057. {
  199058. #endif /* PNG_USER_MEM_SUPPORTED */
  199059. png_structp png_ptr;
  199060. #ifdef PNG_SETJMP_SUPPORTED
  199061. #ifdef USE_FAR_KEYWORD
  199062. jmp_buf jmpbuf;
  199063. #endif
  199064. #endif
  199065. int i;
  199066. png_debug(1, "in png_create_write_struct\n");
  199067. #ifdef PNG_USER_MEM_SUPPORTED
  199068. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199069. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199070. #else
  199071. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199072. #endif /* PNG_USER_MEM_SUPPORTED */
  199073. if (png_ptr == NULL)
  199074. return (NULL);
  199075. /* added at libpng-1.2.6 */
  199076. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199077. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199078. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199079. #endif
  199080. #ifdef PNG_SETJMP_SUPPORTED
  199081. #ifdef USE_FAR_KEYWORD
  199082. if (setjmp(jmpbuf))
  199083. #else
  199084. if (setjmp(png_ptr->jmpbuf))
  199085. #endif
  199086. {
  199087. png_free(png_ptr, png_ptr->zbuf);
  199088. png_ptr->zbuf=NULL;
  199089. png_destroy_struct(png_ptr);
  199090. return (NULL);
  199091. }
  199092. #ifdef USE_FAR_KEYWORD
  199093. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199094. #endif
  199095. #endif
  199096. #ifdef PNG_USER_MEM_SUPPORTED
  199097. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199098. #endif /* PNG_USER_MEM_SUPPORTED */
  199099. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199100. i=0;
  199101. do
  199102. {
  199103. if(user_png_ver[i] != png_libpng_ver[i])
  199104. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199105. } while (png_libpng_ver[i++]);
  199106. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199107. {
  199108. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199109. * we must recompile any applications that use any older library version.
  199110. * For versions after libpng 1.0, we will be compatible, so we need
  199111. * only check the first digit.
  199112. */
  199113. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199114. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199115. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199116. {
  199117. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199118. char msg[80];
  199119. if (user_png_ver)
  199120. {
  199121. png_snprintf(msg, 80,
  199122. "Application was compiled with png.h from libpng-%.20s",
  199123. user_png_ver);
  199124. png_warning(png_ptr, msg);
  199125. }
  199126. png_snprintf(msg, 80,
  199127. "Application is running with png.c from libpng-%.20s",
  199128. png_libpng_ver);
  199129. png_warning(png_ptr, msg);
  199130. #endif
  199131. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199132. png_ptr->flags=0;
  199133. #endif
  199134. png_error(png_ptr,
  199135. "Incompatible libpng version in application and library");
  199136. }
  199137. }
  199138. /* initialize zbuf - compression buffer */
  199139. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199140. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199141. (png_uint_32)png_ptr->zbuf_size);
  199142. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199143. png_flush_ptr_NULL);
  199144. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199145. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199146. 1, png_doublep_NULL, png_doublep_NULL);
  199147. #endif
  199148. #ifdef PNG_SETJMP_SUPPORTED
  199149. /* Applications that neglect to set up their own setjmp() and then encounter
  199150. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199151. abort instead of returning. */
  199152. #ifdef USE_FAR_KEYWORD
  199153. if (setjmp(jmpbuf))
  199154. PNG_ABORT();
  199155. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199156. #else
  199157. if (setjmp(png_ptr->jmpbuf))
  199158. PNG_ABORT();
  199159. #endif
  199160. #endif
  199161. return (png_ptr);
  199162. }
  199163. /* Initialize png_ptr structure, and allocate any memory needed */
  199164. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199165. /* Deprecated. */
  199166. #undef png_write_init
  199167. void PNGAPI
  199168. png_write_init(png_structp png_ptr)
  199169. {
  199170. /* We only come here via pre-1.0.7-compiled applications */
  199171. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199172. }
  199173. void PNGAPI
  199174. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199175. png_size_t png_struct_size, png_size_t png_info_size)
  199176. {
  199177. /* We only come here via pre-1.0.12-compiled applications */
  199178. if(png_ptr == NULL) return;
  199179. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199180. if(png_sizeof(png_struct) > png_struct_size ||
  199181. png_sizeof(png_info) > png_info_size)
  199182. {
  199183. char msg[80];
  199184. png_ptr->warning_fn=NULL;
  199185. if (user_png_ver)
  199186. {
  199187. png_snprintf(msg, 80,
  199188. "Application was compiled with png.h from libpng-%.20s",
  199189. user_png_ver);
  199190. png_warning(png_ptr, msg);
  199191. }
  199192. png_snprintf(msg, 80,
  199193. "Application is running with png.c from libpng-%.20s",
  199194. png_libpng_ver);
  199195. png_warning(png_ptr, msg);
  199196. }
  199197. #endif
  199198. if(png_sizeof(png_struct) > png_struct_size)
  199199. {
  199200. png_ptr->error_fn=NULL;
  199201. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199202. png_ptr->flags=0;
  199203. #endif
  199204. png_error(png_ptr,
  199205. "The png struct allocated by the application for writing is too small.");
  199206. }
  199207. if(png_sizeof(png_info) > png_info_size)
  199208. {
  199209. png_ptr->error_fn=NULL;
  199210. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199211. png_ptr->flags=0;
  199212. #endif
  199213. png_error(png_ptr,
  199214. "The info struct allocated by the application for writing is too small.");
  199215. }
  199216. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199217. }
  199218. #endif /* PNG_1_0_X || PNG_1_2_X */
  199219. void PNGAPI
  199220. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199221. png_size_t png_struct_size)
  199222. {
  199223. png_structp png_ptr=*ptr_ptr;
  199224. #ifdef PNG_SETJMP_SUPPORTED
  199225. jmp_buf tmp_jmp; /* to save current jump buffer */
  199226. #endif
  199227. int i = 0;
  199228. if (png_ptr == NULL)
  199229. return;
  199230. do
  199231. {
  199232. if (user_png_ver[i] != png_libpng_ver[i])
  199233. {
  199234. #ifdef PNG_LEGACY_SUPPORTED
  199235. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199236. #else
  199237. png_ptr->warning_fn=NULL;
  199238. png_warning(png_ptr,
  199239. "Application uses deprecated png_write_init() and should be recompiled.");
  199240. break;
  199241. #endif
  199242. }
  199243. } while (png_libpng_ver[i++]);
  199244. png_debug(1, "in png_write_init_3\n");
  199245. #ifdef PNG_SETJMP_SUPPORTED
  199246. /* save jump buffer and error functions */
  199247. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199248. #endif
  199249. if (png_sizeof(png_struct) > png_struct_size)
  199250. {
  199251. png_destroy_struct(png_ptr);
  199252. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199253. *ptr_ptr = png_ptr;
  199254. }
  199255. /* reset all variables to 0 */
  199256. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199257. /* added at libpng-1.2.6 */
  199258. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199259. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199260. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199261. #endif
  199262. #ifdef PNG_SETJMP_SUPPORTED
  199263. /* restore jump buffer */
  199264. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199265. #endif
  199266. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199267. png_flush_ptr_NULL);
  199268. /* initialize zbuf - compression buffer */
  199269. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199270. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199271. (png_uint_32)png_ptr->zbuf_size);
  199272. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199273. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199274. 1, png_doublep_NULL, png_doublep_NULL);
  199275. #endif
  199276. }
  199277. /* Write a few rows of image data. If the image is interlaced,
  199278. * either you will have to write the 7 sub images, or, if you
  199279. * have called png_set_interlace_handling(), you will have to
  199280. * "write" the image seven times.
  199281. */
  199282. void PNGAPI
  199283. png_write_rows(png_structp png_ptr, png_bytepp row,
  199284. png_uint_32 num_rows)
  199285. {
  199286. png_uint_32 i; /* row counter */
  199287. png_bytepp rp; /* row pointer */
  199288. png_debug(1, "in png_write_rows\n");
  199289. if (png_ptr == NULL)
  199290. return;
  199291. /* loop through the rows */
  199292. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199293. {
  199294. png_write_row(png_ptr, *rp);
  199295. }
  199296. }
  199297. /* Write the image. You only need to call this function once, even
  199298. * if you are writing an interlaced image.
  199299. */
  199300. void PNGAPI
  199301. png_write_image(png_structp png_ptr, png_bytepp image)
  199302. {
  199303. png_uint_32 i; /* row index */
  199304. int pass, num_pass; /* pass variables */
  199305. png_bytepp rp; /* points to current row */
  199306. if (png_ptr == NULL)
  199307. return;
  199308. png_debug(1, "in png_write_image\n");
  199309. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199310. /* intialize interlace handling. If image is not interlaced,
  199311. this will set pass to 1 */
  199312. num_pass = png_set_interlace_handling(png_ptr);
  199313. #else
  199314. num_pass = 1;
  199315. #endif
  199316. /* loop through passes */
  199317. for (pass = 0; pass < num_pass; pass++)
  199318. {
  199319. /* loop through image */
  199320. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199321. {
  199322. png_write_row(png_ptr, *rp);
  199323. }
  199324. }
  199325. }
  199326. /* called by user to write a row of image data */
  199327. void PNGAPI
  199328. png_write_row(png_structp png_ptr, png_bytep row)
  199329. {
  199330. if (png_ptr == NULL)
  199331. return;
  199332. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199333. png_ptr->row_number, png_ptr->pass);
  199334. /* initialize transformations and other stuff if first time */
  199335. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199336. {
  199337. /* make sure we wrote the header info */
  199338. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199339. png_error(png_ptr,
  199340. "png_write_info was never called before png_write_row.");
  199341. /* check for transforms that have been set but were defined out */
  199342. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199343. if (png_ptr->transformations & PNG_INVERT_MONO)
  199344. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199345. #endif
  199346. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199347. if (png_ptr->transformations & PNG_FILLER)
  199348. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199349. #endif
  199350. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199351. if (png_ptr->transformations & PNG_PACKSWAP)
  199352. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199353. #endif
  199354. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199355. if (png_ptr->transformations & PNG_PACK)
  199356. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199357. #endif
  199358. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199359. if (png_ptr->transformations & PNG_SHIFT)
  199360. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199361. #endif
  199362. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199363. if (png_ptr->transformations & PNG_BGR)
  199364. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199365. #endif
  199366. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199367. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199368. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199369. #endif
  199370. png_write_start_row(png_ptr);
  199371. }
  199372. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199373. /* if interlaced and not interested in row, return */
  199374. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199375. {
  199376. switch (png_ptr->pass)
  199377. {
  199378. case 0:
  199379. if (png_ptr->row_number & 0x07)
  199380. {
  199381. png_write_finish_row(png_ptr);
  199382. return;
  199383. }
  199384. break;
  199385. case 1:
  199386. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199387. {
  199388. png_write_finish_row(png_ptr);
  199389. return;
  199390. }
  199391. break;
  199392. case 2:
  199393. if ((png_ptr->row_number & 0x07) != 4)
  199394. {
  199395. png_write_finish_row(png_ptr);
  199396. return;
  199397. }
  199398. break;
  199399. case 3:
  199400. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199401. {
  199402. png_write_finish_row(png_ptr);
  199403. return;
  199404. }
  199405. break;
  199406. case 4:
  199407. if ((png_ptr->row_number & 0x03) != 2)
  199408. {
  199409. png_write_finish_row(png_ptr);
  199410. return;
  199411. }
  199412. break;
  199413. case 5:
  199414. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199415. {
  199416. png_write_finish_row(png_ptr);
  199417. return;
  199418. }
  199419. break;
  199420. case 6:
  199421. if (!(png_ptr->row_number & 0x01))
  199422. {
  199423. png_write_finish_row(png_ptr);
  199424. return;
  199425. }
  199426. break;
  199427. }
  199428. }
  199429. #endif
  199430. /* set up row info for transformations */
  199431. png_ptr->row_info.color_type = png_ptr->color_type;
  199432. png_ptr->row_info.width = png_ptr->usr_width;
  199433. png_ptr->row_info.channels = png_ptr->usr_channels;
  199434. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199435. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199436. png_ptr->row_info.channels);
  199437. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199438. png_ptr->row_info.width);
  199439. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199440. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199441. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199442. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199443. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199444. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199445. /* Copy user's row into buffer, leaving room for filter byte. */
  199446. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199447. png_ptr->row_info.rowbytes);
  199448. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199449. /* handle interlacing */
  199450. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199451. (png_ptr->transformations & PNG_INTERLACE))
  199452. {
  199453. png_do_write_interlace(&(png_ptr->row_info),
  199454. png_ptr->row_buf + 1, png_ptr->pass);
  199455. /* this should always get caught above, but still ... */
  199456. if (!(png_ptr->row_info.width))
  199457. {
  199458. png_write_finish_row(png_ptr);
  199459. return;
  199460. }
  199461. }
  199462. #endif
  199463. /* handle other transformations */
  199464. if (png_ptr->transformations)
  199465. png_do_write_transformations(png_ptr);
  199466. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199467. /* Write filter_method 64 (intrapixel differencing) only if
  199468. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199469. * 2. Libpng did not write a PNG signature (this filter_method is only
  199470. * used in PNG datastreams that are embedded in MNG datastreams) and
  199471. * 3. The application called png_permit_mng_features with a mask that
  199472. * included PNG_FLAG_MNG_FILTER_64 and
  199473. * 4. The filter_method is 64 and
  199474. * 5. The color_type is RGB or RGBA
  199475. */
  199476. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199477. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199478. {
  199479. /* Intrapixel differencing */
  199480. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199481. }
  199482. #endif
  199483. /* Find a filter if necessary, filter the row and write it out. */
  199484. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199485. if (png_ptr->write_row_fn != NULL)
  199486. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199487. }
  199488. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199489. /* Set the automatic flush interval or 0 to turn flushing off */
  199490. void PNGAPI
  199491. png_set_flush(png_structp png_ptr, int nrows)
  199492. {
  199493. png_debug(1, "in png_set_flush\n");
  199494. if (png_ptr == NULL)
  199495. return;
  199496. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199497. }
  199498. /* flush the current output buffers now */
  199499. void PNGAPI
  199500. png_write_flush(png_structp png_ptr)
  199501. {
  199502. int wrote_IDAT;
  199503. png_debug(1, "in png_write_flush\n");
  199504. if (png_ptr == NULL)
  199505. return;
  199506. /* We have already written out all of the data */
  199507. if (png_ptr->row_number >= png_ptr->num_rows)
  199508. return;
  199509. do
  199510. {
  199511. int ret;
  199512. /* compress the data */
  199513. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199514. wrote_IDAT = 0;
  199515. /* check for compression errors */
  199516. if (ret != Z_OK)
  199517. {
  199518. if (png_ptr->zstream.msg != NULL)
  199519. png_error(png_ptr, png_ptr->zstream.msg);
  199520. else
  199521. png_error(png_ptr, "zlib error");
  199522. }
  199523. if (!(png_ptr->zstream.avail_out))
  199524. {
  199525. /* write the IDAT and reset the zlib output buffer */
  199526. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199527. png_ptr->zbuf_size);
  199528. png_ptr->zstream.next_out = png_ptr->zbuf;
  199529. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199530. wrote_IDAT = 1;
  199531. }
  199532. } while(wrote_IDAT == 1);
  199533. /* If there is any data left to be output, write it into a new IDAT */
  199534. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199535. {
  199536. /* write the IDAT and reset the zlib output buffer */
  199537. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199538. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199539. png_ptr->zstream.next_out = png_ptr->zbuf;
  199540. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199541. }
  199542. png_ptr->flush_rows = 0;
  199543. png_flush(png_ptr);
  199544. }
  199545. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199546. /* free all memory used by the write */
  199547. void PNGAPI
  199548. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199549. {
  199550. png_structp png_ptr = NULL;
  199551. png_infop info_ptr = NULL;
  199552. #ifdef PNG_USER_MEM_SUPPORTED
  199553. png_free_ptr free_fn = NULL;
  199554. png_voidp mem_ptr = NULL;
  199555. #endif
  199556. png_debug(1, "in png_destroy_write_struct\n");
  199557. if (png_ptr_ptr != NULL)
  199558. {
  199559. png_ptr = *png_ptr_ptr;
  199560. #ifdef PNG_USER_MEM_SUPPORTED
  199561. free_fn = png_ptr->free_fn;
  199562. mem_ptr = png_ptr->mem_ptr;
  199563. #endif
  199564. }
  199565. if (info_ptr_ptr != NULL)
  199566. info_ptr = *info_ptr_ptr;
  199567. if (info_ptr != NULL)
  199568. {
  199569. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199570. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199571. if (png_ptr->num_chunk_list)
  199572. {
  199573. png_free(png_ptr, png_ptr->chunk_list);
  199574. png_ptr->chunk_list=NULL;
  199575. png_ptr->num_chunk_list=0;
  199576. }
  199577. #endif
  199578. #ifdef PNG_USER_MEM_SUPPORTED
  199579. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199580. (png_voidp)mem_ptr);
  199581. #else
  199582. png_destroy_struct((png_voidp)info_ptr);
  199583. #endif
  199584. *info_ptr_ptr = NULL;
  199585. }
  199586. if (png_ptr != NULL)
  199587. {
  199588. png_write_destroy(png_ptr);
  199589. #ifdef PNG_USER_MEM_SUPPORTED
  199590. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199591. (png_voidp)mem_ptr);
  199592. #else
  199593. png_destroy_struct((png_voidp)png_ptr);
  199594. #endif
  199595. *png_ptr_ptr = NULL;
  199596. }
  199597. }
  199598. /* Free any memory used in png_ptr struct (old method) */
  199599. void /* PRIVATE */
  199600. png_write_destroy(png_structp png_ptr)
  199601. {
  199602. #ifdef PNG_SETJMP_SUPPORTED
  199603. jmp_buf tmp_jmp; /* save jump buffer */
  199604. #endif
  199605. png_error_ptr error_fn;
  199606. png_error_ptr warning_fn;
  199607. png_voidp error_ptr;
  199608. #ifdef PNG_USER_MEM_SUPPORTED
  199609. png_free_ptr free_fn;
  199610. #endif
  199611. png_debug(1, "in png_write_destroy\n");
  199612. /* free any memory zlib uses */
  199613. deflateEnd(&png_ptr->zstream);
  199614. /* free our memory. png_free checks NULL for us. */
  199615. png_free(png_ptr, png_ptr->zbuf);
  199616. png_free(png_ptr, png_ptr->row_buf);
  199617. png_free(png_ptr, png_ptr->prev_row);
  199618. png_free(png_ptr, png_ptr->sub_row);
  199619. png_free(png_ptr, png_ptr->up_row);
  199620. png_free(png_ptr, png_ptr->avg_row);
  199621. png_free(png_ptr, png_ptr->paeth_row);
  199622. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199623. png_free(png_ptr, png_ptr->time_buffer);
  199624. #endif
  199625. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199626. png_free(png_ptr, png_ptr->prev_filters);
  199627. png_free(png_ptr, png_ptr->filter_weights);
  199628. png_free(png_ptr, png_ptr->inv_filter_weights);
  199629. png_free(png_ptr, png_ptr->filter_costs);
  199630. png_free(png_ptr, png_ptr->inv_filter_costs);
  199631. #endif
  199632. #ifdef PNG_SETJMP_SUPPORTED
  199633. /* reset structure */
  199634. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199635. #endif
  199636. error_fn = png_ptr->error_fn;
  199637. warning_fn = png_ptr->warning_fn;
  199638. error_ptr = png_ptr->error_ptr;
  199639. #ifdef PNG_USER_MEM_SUPPORTED
  199640. free_fn = png_ptr->free_fn;
  199641. #endif
  199642. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199643. png_ptr->error_fn = error_fn;
  199644. png_ptr->warning_fn = warning_fn;
  199645. png_ptr->error_ptr = error_ptr;
  199646. #ifdef PNG_USER_MEM_SUPPORTED
  199647. png_ptr->free_fn = free_fn;
  199648. #endif
  199649. #ifdef PNG_SETJMP_SUPPORTED
  199650. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199651. #endif
  199652. }
  199653. /* Allow the application to select one or more row filters to use. */
  199654. void PNGAPI
  199655. png_set_filter(png_structp png_ptr, int method, int filters)
  199656. {
  199657. png_debug(1, "in png_set_filter\n");
  199658. if (png_ptr == NULL)
  199659. return;
  199660. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199661. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199662. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199663. method = PNG_FILTER_TYPE_BASE;
  199664. #endif
  199665. if (method == PNG_FILTER_TYPE_BASE)
  199666. {
  199667. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199668. {
  199669. #ifndef PNG_NO_WRITE_FILTER
  199670. case 5:
  199671. case 6:
  199672. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199673. #endif /* PNG_NO_WRITE_FILTER */
  199674. case PNG_FILTER_VALUE_NONE:
  199675. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199676. #ifndef PNG_NO_WRITE_FILTER
  199677. case PNG_FILTER_VALUE_SUB:
  199678. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199679. case PNG_FILTER_VALUE_UP:
  199680. png_ptr->do_filter=PNG_FILTER_UP; break;
  199681. case PNG_FILTER_VALUE_AVG:
  199682. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199683. case PNG_FILTER_VALUE_PAETH:
  199684. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199685. default: png_ptr->do_filter = (png_byte)filters; break;
  199686. #else
  199687. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199688. #endif /* PNG_NO_WRITE_FILTER */
  199689. }
  199690. /* If we have allocated the row_buf, this means we have already started
  199691. * with the image and we should have allocated all of the filter buffers
  199692. * that have been selected. If prev_row isn't already allocated, then
  199693. * it is too late to start using the filters that need it, since we
  199694. * will be missing the data in the previous row. If an application
  199695. * wants to start and stop using particular filters during compression,
  199696. * it should start out with all of the filters, and then add and
  199697. * remove them after the start of compression.
  199698. */
  199699. if (png_ptr->row_buf != NULL)
  199700. {
  199701. #ifndef PNG_NO_WRITE_FILTER
  199702. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199703. {
  199704. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199705. (png_ptr->rowbytes + 1));
  199706. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199707. }
  199708. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199709. {
  199710. if (png_ptr->prev_row == NULL)
  199711. {
  199712. png_warning(png_ptr, "Can't add Up filter after starting");
  199713. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199714. }
  199715. else
  199716. {
  199717. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199718. (png_ptr->rowbytes + 1));
  199719. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199720. }
  199721. }
  199722. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199723. {
  199724. if (png_ptr->prev_row == NULL)
  199725. {
  199726. png_warning(png_ptr, "Can't add Average filter after starting");
  199727. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199728. }
  199729. else
  199730. {
  199731. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199732. (png_ptr->rowbytes + 1));
  199733. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199734. }
  199735. }
  199736. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199737. png_ptr->paeth_row == NULL)
  199738. {
  199739. if (png_ptr->prev_row == NULL)
  199740. {
  199741. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199742. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199743. }
  199744. else
  199745. {
  199746. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199747. (png_ptr->rowbytes + 1));
  199748. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199749. }
  199750. }
  199751. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199752. #endif /* PNG_NO_WRITE_FILTER */
  199753. png_ptr->do_filter = PNG_FILTER_NONE;
  199754. }
  199755. }
  199756. else
  199757. png_error(png_ptr, "Unknown custom filter method");
  199758. }
  199759. /* This allows us to influence the way in which libpng chooses the "best"
  199760. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199761. * differences metric is relatively fast and effective, there is some
  199762. * question as to whether it can be improved upon by trying to keep the
  199763. * filtered data going to zlib more consistent, hopefully resulting in
  199764. * better compression.
  199765. */
  199766. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199767. void PNGAPI
  199768. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199769. int num_weights, png_doublep filter_weights,
  199770. png_doublep filter_costs)
  199771. {
  199772. int i;
  199773. png_debug(1, "in png_set_filter_heuristics\n");
  199774. if (png_ptr == NULL)
  199775. return;
  199776. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199777. {
  199778. png_warning(png_ptr, "Unknown filter heuristic method");
  199779. return;
  199780. }
  199781. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199782. {
  199783. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199784. }
  199785. if (num_weights < 0 || filter_weights == NULL ||
  199786. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199787. {
  199788. num_weights = 0;
  199789. }
  199790. png_ptr->num_prev_filters = (png_byte)num_weights;
  199791. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199792. if (num_weights > 0)
  199793. {
  199794. if (png_ptr->prev_filters == NULL)
  199795. {
  199796. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199797. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199798. /* To make sure that the weighting starts out fairly */
  199799. for (i = 0; i < num_weights; i++)
  199800. {
  199801. png_ptr->prev_filters[i] = 255;
  199802. }
  199803. }
  199804. if (png_ptr->filter_weights == NULL)
  199805. {
  199806. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199807. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199808. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199809. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199810. for (i = 0; i < num_weights; i++)
  199811. {
  199812. png_ptr->inv_filter_weights[i] =
  199813. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199814. }
  199815. }
  199816. for (i = 0; i < num_weights; i++)
  199817. {
  199818. if (filter_weights[i] < 0.0)
  199819. {
  199820. png_ptr->inv_filter_weights[i] =
  199821. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199822. }
  199823. else
  199824. {
  199825. png_ptr->inv_filter_weights[i] =
  199826. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199827. png_ptr->filter_weights[i] =
  199828. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199829. }
  199830. }
  199831. }
  199832. /* If, in the future, there are other filter methods, this would
  199833. * need to be based on png_ptr->filter.
  199834. */
  199835. if (png_ptr->filter_costs == NULL)
  199836. {
  199837. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199838. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199839. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199840. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199841. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199842. {
  199843. png_ptr->inv_filter_costs[i] =
  199844. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199845. }
  199846. }
  199847. /* Here is where we set the relative costs of the different filters. We
  199848. * should take the desired compression level into account when setting
  199849. * the costs, so that Paeth, for instance, has a high relative cost at low
  199850. * compression levels, while it has a lower relative cost at higher
  199851. * compression settings. The filter types are in order of increasing
  199852. * relative cost, so it would be possible to do this with an algorithm.
  199853. */
  199854. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199855. {
  199856. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199857. {
  199858. png_ptr->inv_filter_costs[i] =
  199859. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199860. }
  199861. else if (filter_costs[i] >= 1.0)
  199862. {
  199863. png_ptr->inv_filter_costs[i] =
  199864. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199865. png_ptr->filter_costs[i] =
  199866. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199867. }
  199868. }
  199869. }
  199870. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199871. void PNGAPI
  199872. png_set_compression_level(png_structp png_ptr, int level)
  199873. {
  199874. png_debug(1, "in png_set_compression_level\n");
  199875. if (png_ptr == NULL)
  199876. return;
  199877. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199878. png_ptr->zlib_level = level;
  199879. }
  199880. void PNGAPI
  199881. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199882. {
  199883. png_debug(1, "in png_set_compression_mem_level\n");
  199884. if (png_ptr == NULL)
  199885. return;
  199886. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199887. png_ptr->zlib_mem_level = mem_level;
  199888. }
  199889. void PNGAPI
  199890. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199891. {
  199892. png_debug(1, "in png_set_compression_strategy\n");
  199893. if (png_ptr == NULL)
  199894. return;
  199895. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199896. png_ptr->zlib_strategy = strategy;
  199897. }
  199898. void PNGAPI
  199899. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199900. {
  199901. if (png_ptr == NULL)
  199902. return;
  199903. if (window_bits > 15)
  199904. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199905. else if (window_bits < 8)
  199906. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199907. #ifndef WBITS_8_OK
  199908. /* avoid libpng bug with 256-byte windows */
  199909. if (window_bits == 8)
  199910. {
  199911. png_warning(png_ptr, "Compression window is being reset to 512");
  199912. window_bits=9;
  199913. }
  199914. #endif
  199915. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199916. png_ptr->zlib_window_bits = window_bits;
  199917. }
  199918. void PNGAPI
  199919. png_set_compression_method(png_structp png_ptr, int method)
  199920. {
  199921. png_debug(1, "in png_set_compression_method\n");
  199922. if (png_ptr == NULL)
  199923. return;
  199924. if (method != 8)
  199925. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199926. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199927. png_ptr->zlib_method = method;
  199928. }
  199929. void PNGAPI
  199930. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199931. {
  199932. if (png_ptr == NULL)
  199933. return;
  199934. png_ptr->write_row_fn = write_row_fn;
  199935. }
  199936. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199937. void PNGAPI
  199938. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199939. write_user_transform_fn)
  199940. {
  199941. png_debug(1, "in png_set_write_user_transform_fn\n");
  199942. if (png_ptr == NULL)
  199943. return;
  199944. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199945. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199946. }
  199947. #endif
  199948. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199949. void PNGAPI
  199950. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199951. int transforms, voidp params)
  199952. {
  199953. if (png_ptr == NULL || info_ptr == NULL)
  199954. return;
  199955. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199956. /* invert the alpha channel from opacity to transparency */
  199957. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199958. png_set_invert_alpha(png_ptr);
  199959. #endif
  199960. /* Write the file header information. */
  199961. png_write_info(png_ptr, info_ptr);
  199962. /* ------ these transformations don't touch the info structure ------- */
  199963. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199964. /* invert monochrome pixels */
  199965. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199966. png_set_invert_mono(png_ptr);
  199967. #endif
  199968. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199969. /* Shift the pixels up to a legal bit depth and fill in
  199970. * as appropriate to correctly scale the image.
  199971. */
  199972. if ((transforms & PNG_TRANSFORM_SHIFT)
  199973. && (info_ptr->valid & PNG_INFO_sBIT))
  199974. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199975. #endif
  199976. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199977. /* pack pixels into bytes */
  199978. if (transforms & PNG_TRANSFORM_PACKING)
  199979. png_set_packing(png_ptr);
  199980. #endif
  199981. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199982. /* swap location of alpha bytes from ARGB to RGBA */
  199983. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199984. png_set_swap_alpha(png_ptr);
  199985. #endif
  199986. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199987. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199988. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199989. */
  199990. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199991. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199992. #endif
  199993. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199994. /* flip BGR pixels to RGB */
  199995. if (transforms & PNG_TRANSFORM_BGR)
  199996. png_set_bgr(png_ptr);
  199997. #endif
  199998. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199999. /* swap bytes of 16-bit files to most significant byte first */
  200000. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200001. png_set_swap(png_ptr);
  200002. #endif
  200003. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200004. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200005. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200006. png_set_packswap(png_ptr);
  200007. #endif
  200008. /* ----------------------- end of transformations ------------------- */
  200009. /* write the bits */
  200010. if (info_ptr->valid & PNG_INFO_IDAT)
  200011. png_write_image(png_ptr, info_ptr->row_pointers);
  200012. /* It is REQUIRED to call this to finish writing the rest of the file */
  200013. png_write_end(png_ptr, info_ptr);
  200014. transforms = transforms; /* quiet compiler warnings */
  200015. params = params;
  200016. }
  200017. #endif
  200018. #endif /* PNG_WRITE_SUPPORTED */
  200019. /*** End of inlined file: pngwrite.c ***/
  200020. /*** Start of inlined file: pngwtran.c ***/
  200021. /* pngwtran.c - transforms the data in a row for PNG writers
  200022. *
  200023. * Last changed in libpng 1.2.9 April 14, 2006
  200024. * For conditions of distribution and use, see copyright notice in png.h
  200025. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200026. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200027. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200028. */
  200029. #define PNG_INTERNAL
  200030. #ifdef PNG_WRITE_SUPPORTED
  200031. /* Transform the data according to the user's wishes. The order of
  200032. * transformations is significant.
  200033. */
  200034. void /* PRIVATE */
  200035. png_do_write_transformations(png_structp png_ptr)
  200036. {
  200037. png_debug(1, "in png_do_write_transformations\n");
  200038. if (png_ptr == NULL)
  200039. return;
  200040. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200041. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200042. if(png_ptr->write_user_transform_fn != NULL)
  200043. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200044. (png_ptr, /* png_ptr */
  200045. &(png_ptr->row_info), /* row_info: */
  200046. /* png_uint_32 width; width of row */
  200047. /* png_uint_32 rowbytes; number of bytes in row */
  200048. /* png_byte color_type; color type of pixels */
  200049. /* png_byte bit_depth; bit depth of samples */
  200050. /* png_byte channels; number of channels (1-4) */
  200051. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200052. png_ptr->row_buf + 1); /* start of pixel data for row */
  200053. #endif
  200054. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200055. if (png_ptr->transformations & PNG_FILLER)
  200056. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200057. png_ptr->flags);
  200058. #endif
  200059. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200060. if (png_ptr->transformations & PNG_PACKSWAP)
  200061. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200062. #endif
  200063. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200064. if (png_ptr->transformations & PNG_PACK)
  200065. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200066. (png_uint_32)png_ptr->bit_depth);
  200067. #endif
  200068. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200069. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200070. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200071. #endif
  200072. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200073. if (png_ptr->transformations & PNG_SHIFT)
  200074. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200075. &(png_ptr->shift));
  200076. #endif
  200077. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200078. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200079. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200080. #endif
  200081. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200082. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200083. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200084. #endif
  200085. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200086. if (png_ptr->transformations & PNG_BGR)
  200087. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200088. #endif
  200089. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200090. if (png_ptr->transformations & PNG_INVERT_MONO)
  200091. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200092. #endif
  200093. }
  200094. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200095. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200096. * row_info bit depth should be 8 (one pixel per byte). The channels
  200097. * should be 1 (this only happens on grayscale and paletted images).
  200098. */
  200099. void /* PRIVATE */
  200100. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200101. {
  200102. png_debug(1, "in png_do_pack\n");
  200103. if (row_info->bit_depth == 8 &&
  200104. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200105. row != NULL && row_info != NULL &&
  200106. #endif
  200107. row_info->channels == 1)
  200108. {
  200109. switch ((int)bit_depth)
  200110. {
  200111. case 1:
  200112. {
  200113. png_bytep sp, dp;
  200114. int mask, v;
  200115. png_uint_32 i;
  200116. png_uint_32 row_width = row_info->width;
  200117. sp = row;
  200118. dp = row;
  200119. mask = 0x80;
  200120. v = 0;
  200121. for (i = 0; i < row_width; i++)
  200122. {
  200123. if (*sp != 0)
  200124. v |= mask;
  200125. sp++;
  200126. if (mask > 1)
  200127. mask >>= 1;
  200128. else
  200129. {
  200130. mask = 0x80;
  200131. *dp = (png_byte)v;
  200132. dp++;
  200133. v = 0;
  200134. }
  200135. }
  200136. if (mask != 0x80)
  200137. *dp = (png_byte)v;
  200138. break;
  200139. }
  200140. case 2:
  200141. {
  200142. png_bytep sp, dp;
  200143. int shift, v;
  200144. png_uint_32 i;
  200145. png_uint_32 row_width = row_info->width;
  200146. sp = row;
  200147. dp = row;
  200148. shift = 6;
  200149. v = 0;
  200150. for (i = 0; i < row_width; i++)
  200151. {
  200152. png_byte value;
  200153. value = (png_byte)(*sp & 0x03);
  200154. v |= (value << shift);
  200155. if (shift == 0)
  200156. {
  200157. shift = 6;
  200158. *dp = (png_byte)v;
  200159. dp++;
  200160. v = 0;
  200161. }
  200162. else
  200163. shift -= 2;
  200164. sp++;
  200165. }
  200166. if (shift != 6)
  200167. *dp = (png_byte)v;
  200168. break;
  200169. }
  200170. case 4:
  200171. {
  200172. png_bytep sp, dp;
  200173. int shift, v;
  200174. png_uint_32 i;
  200175. png_uint_32 row_width = row_info->width;
  200176. sp = row;
  200177. dp = row;
  200178. shift = 4;
  200179. v = 0;
  200180. for (i = 0; i < row_width; i++)
  200181. {
  200182. png_byte value;
  200183. value = (png_byte)(*sp & 0x0f);
  200184. v |= (value << shift);
  200185. if (shift == 0)
  200186. {
  200187. shift = 4;
  200188. *dp = (png_byte)v;
  200189. dp++;
  200190. v = 0;
  200191. }
  200192. else
  200193. shift -= 4;
  200194. sp++;
  200195. }
  200196. if (shift != 4)
  200197. *dp = (png_byte)v;
  200198. break;
  200199. }
  200200. }
  200201. row_info->bit_depth = (png_byte)bit_depth;
  200202. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200203. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200204. row_info->width);
  200205. }
  200206. }
  200207. #endif
  200208. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200209. /* Shift pixel values to take advantage of whole range. Pass the
  200210. * true number of bits in bit_depth. The row should be packed
  200211. * according to row_info->bit_depth. Thus, if you had a row of
  200212. * bit depth 4, but the pixels only had values from 0 to 7, you
  200213. * would pass 3 as bit_depth, and this routine would translate the
  200214. * data to 0 to 15.
  200215. */
  200216. void /* PRIVATE */
  200217. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200218. {
  200219. png_debug(1, "in png_do_shift\n");
  200220. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200221. if (row != NULL && row_info != NULL &&
  200222. #else
  200223. if (
  200224. #endif
  200225. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200226. {
  200227. int shift_start[4], shift_dec[4];
  200228. int channels = 0;
  200229. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200230. {
  200231. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200232. shift_dec[channels] = bit_depth->red;
  200233. channels++;
  200234. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200235. shift_dec[channels] = bit_depth->green;
  200236. channels++;
  200237. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200238. shift_dec[channels] = bit_depth->blue;
  200239. channels++;
  200240. }
  200241. else
  200242. {
  200243. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200244. shift_dec[channels] = bit_depth->gray;
  200245. channels++;
  200246. }
  200247. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200248. {
  200249. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200250. shift_dec[channels] = bit_depth->alpha;
  200251. channels++;
  200252. }
  200253. /* with low row depths, could only be grayscale, so one channel */
  200254. if (row_info->bit_depth < 8)
  200255. {
  200256. png_bytep bp = row;
  200257. png_uint_32 i;
  200258. png_byte mask;
  200259. png_uint_32 row_bytes = row_info->rowbytes;
  200260. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200261. mask = 0x55;
  200262. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200263. mask = 0x11;
  200264. else
  200265. mask = 0xff;
  200266. for (i = 0; i < row_bytes; i++, bp++)
  200267. {
  200268. png_uint_16 v;
  200269. int j;
  200270. v = *bp;
  200271. *bp = 0;
  200272. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200273. {
  200274. if (j > 0)
  200275. *bp |= (png_byte)((v << j) & 0xff);
  200276. else
  200277. *bp |= (png_byte)((v >> (-j)) & mask);
  200278. }
  200279. }
  200280. }
  200281. else if (row_info->bit_depth == 8)
  200282. {
  200283. png_bytep bp = row;
  200284. png_uint_32 i;
  200285. png_uint_32 istop = channels * row_info->width;
  200286. for (i = 0; i < istop; i++, bp++)
  200287. {
  200288. png_uint_16 v;
  200289. int j;
  200290. int c = (int)(i%channels);
  200291. v = *bp;
  200292. *bp = 0;
  200293. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200294. {
  200295. if (j > 0)
  200296. *bp |= (png_byte)((v << j) & 0xff);
  200297. else
  200298. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200299. }
  200300. }
  200301. }
  200302. else
  200303. {
  200304. png_bytep bp;
  200305. png_uint_32 i;
  200306. png_uint_32 istop = channels * row_info->width;
  200307. for (bp = row, i = 0; i < istop; i++)
  200308. {
  200309. int c = (int)(i%channels);
  200310. png_uint_16 value, v;
  200311. int j;
  200312. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200313. value = 0;
  200314. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200315. {
  200316. if (j > 0)
  200317. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200318. else
  200319. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200320. }
  200321. *bp++ = (png_byte)(value >> 8);
  200322. *bp++ = (png_byte)(value & 0xff);
  200323. }
  200324. }
  200325. }
  200326. }
  200327. #endif
  200328. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200329. void /* PRIVATE */
  200330. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200331. {
  200332. png_debug(1, "in png_do_write_swap_alpha\n");
  200333. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200334. if (row != NULL && row_info != NULL)
  200335. #endif
  200336. {
  200337. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200338. {
  200339. /* This converts from ARGB to RGBA */
  200340. if (row_info->bit_depth == 8)
  200341. {
  200342. png_bytep sp, dp;
  200343. png_uint_32 i;
  200344. png_uint_32 row_width = row_info->width;
  200345. for (i = 0, sp = dp = row; i < row_width; i++)
  200346. {
  200347. png_byte save = *(sp++);
  200348. *(dp++) = *(sp++);
  200349. *(dp++) = *(sp++);
  200350. *(dp++) = *(sp++);
  200351. *(dp++) = save;
  200352. }
  200353. }
  200354. /* This converts from AARRGGBB to RRGGBBAA */
  200355. else
  200356. {
  200357. png_bytep sp, dp;
  200358. png_uint_32 i;
  200359. png_uint_32 row_width = row_info->width;
  200360. for (i = 0, sp = dp = row; i < row_width; i++)
  200361. {
  200362. png_byte save[2];
  200363. save[0] = *(sp++);
  200364. save[1] = *(sp++);
  200365. *(dp++) = *(sp++);
  200366. *(dp++) = *(sp++);
  200367. *(dp++) = *(sp++);
  200368. *(dp++) = *(sp++);
  200369. *(dp++) = *(sp++);
  200370. *(dp++) = *(sp++);
  200371. *(dp++) = save[0];
  200372. *(dp++) = save[1];
  200373. }
  200374. }
  200375. }
  200376. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200377. {
  200378. /* This converts from AG to GA */
  200379. if (row_info->bit_depth == 8)
  200380. {
  200381. png_bytep sp, dp;
  200382. png_uint_32 i;
  200383. png_uint_32 row_width = row_info->width;
  200384. for (i = 0, sp = dp = row; i < row_width; i++)
  200385. {
  200386. png_byte save = *(sp++);
  200387. *(dp++) = *(sp++);
  200388. *(dp++) = save;
  200389. }
  200390. }
  200391. /* This converts from AAGG to GGAA */
  200392. else
  200393. {
  200394. png_bytep sp, dp;
  200395. png_uint_32 i;
  200396. png_uint_32 row_width = row_info->width;
  200397. for (i = 0, sp = dp = row; i < row_width; i++)
  200398. {
  200399. png_byte save[2];
  200400. save[0] = *(sp++);
  200401. save[1] = *(sp++);
  200402. *(dp++) = *(sp++);
  200403. *(dp++) = *(sp++);
  200404. *(dp++) = save[0];
  200405. *(dp++) = save[1];
  200406. }
  200407. }
  200408. }
  200409. }
  200410. }
  200411. #endif
  200412. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200413. void /* PRIVATE */
  200414. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200415. {
  200416. png_debug(1, "in png_do_write_invert_alpha\n");
  200417. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200418. if (row != NULL && row_info != NULL)
  200419. #endif
  200420. {
  200421. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200422. {
  200423. /* This inverts the alpha channel in RGBA */
  200424. if (row_info->bit_depth == 8)
  200425. {
  200426. png_bytep sp, dp;
  200427. png_uint_32 i;
  200428. png_uint_32 row_width = row_info->width;
  200429. for (i = 0, sp = dp = row; i < row_width; i++)
  200430. {
  200431. /* does nothing
  200432. *(dp++) = *(sp++);
  200433. *(dp++) = *(sp++);
  200434. *(dp++) = *(sp++);
  200435. */
  200436. sp+=3; dp = sp;
  200437. *(dp++) = (png_byte)(255 - *(sp++));
  200438. }
  200439. }
  200440. /* This inverts the alpha channel in RRGGBBAA */
  200441. else
  200442. {
  200443. png_bytep sp, dp;
  200444. png_uint_32 i;
  200445. png_uint_32 row_width = row_info->width;
  200446. for (i = 0, sp = dp = row; i < row_width; i++)
  200447. {
  200448. /* does nothing
  200449. *(dp++) = *(sp++);
  200450. *(dp++) = *(sp++);
  200451. *(dp++) = *(sp++);
  200452. *(dp++) = *(sp++);
  200453. *(dp++) = *(sp++);
  200454. *(dp++) = *(sp++);
  200455. */
  200456. sp+=6; dp = sp;
  200457. *(dp++) = (png_byte)(255 - *(sp++));
  200458. *(dp++) = (png_byte)(255 - *(sp++));
  200459. }
  200460. }
  200461. }
  200462. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200463. {
  200464. /* This inverts the alpha channel in GA */
  200465. if (row_info->bit_depth == 8)
  200466. {
  200467. png_bytep sp, dp;
  200468. png_uint_32 i;
  200469. png_uint_32 row_width = row_info->width;
  200470. for (i = 0, sp = dp = row; i < row_width; i++)
  200471. {
  200472. *(dp++) = *(sp++);
  200473. *(dp++) = (png_byte)(255 - *(sp++));
  200474. }
  200475. }
  200476. /* This inverts the alpha channel in GGAA */
  200477. else
  200478. {
  200479. png_bytep sp, dp;
  200480. png_uint_32 i;
  200481. png_uint_32 row_width = row_info->width;
  200482. for (i = 0, sp = dp = row; i < row_width; i++)
  200483. {
  200484. /* does nothing
  200485. *(dp++) = *(sp++);
  200486. *(dp++) = *(sp++);
  200487. */
  200488. sp+=2; dp = sp;
  200489. *(dp++) = (png_byte)(255 - *(sp++));
  200490. *(dp++) = (png_byte)(255 - *(sp++));
  200491. }
  200492. }
  200493. }
  200494. }
  200495. }
  200496. #endif
  200497. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200498. /* undoes intrapixel differencing */
  200499. void /* PRIVATE */
  200500. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200501. {
  200502. png_debug(1, "in png_do_write_intrapixel\n");
  200503. if (
  200504. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200505. row != NULL && row_info != NULL &&
  200506. #endif
  200507. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200508. {
  200509. int bytes_per_pixel;
  200510. png_uint_32 row_width = row_info->width;
  200511. if (row_info->bit_depth == 8)
  200512. {
  200513. png_bytep rp;
  200514. png_uint_32 i;
  200515. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200516. bytes_per_pixel = 3;
  200517. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200518. bytes_per_pixel = 4;
  200519. else
  200520. return;
  200521. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200522. {
  200523. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200524. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200525. }
  200526. }
  200527. else if (row_info->bit_depth == 16)
  200528. {
  200529. png_bytep rp;
  200530. png_uint_32 i;
  200531. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200532. bytes_per_pixel = 6;
  200533. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200534. bytes_per_pixel = 8;
  200535. else
  200536. return;
  200537. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200538. {
  200539. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200540. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200541. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200542. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200543. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200544. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200545. *(rp+1) = (png_byte)(red & 0xff);
  200546. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200547. *(rp+5) = (png_byte)(blue & 0xff);
  200548. }
  200549. }
  200550. }
  200551. }
  200552. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200553. #endif /* PNG_WRITE_SUPPORTED */
  200554. /*** End of inlined file: pngwtran.c ***/
  200555. /*** Start of inlined file: pngwutil.c ***/
  200556. /* pngwutil.c - utilities to write a PNG file
  200557. *
  200558. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200559. * For conditions of distribution and use, see copyright notice in png.h
  200560. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200561. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200562. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200563. */
  200564. #define PNG_INTERNAL
  200565. #ifdef PNG_WRITE_SUPPORTED
  200566. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200567. * with unsigned numbers for convenience, although one supported
  200568. * ancillary chunk uses signed (two's complement) numbers.
  200569. */
  200570. void PNGAPI
  200571. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200572. {
  200573. buf[0] = (png_byte)((i >> 24) & 0xff);
  200574. buf[1] = (png_byte)((i >> 16) & 0xff);
  200575. buf[2] = (png_byte)((i >> 8) & 0xff);
  200576. buf[3] = (png_byte)(i & 0xff);
  200577. }
  200578. /* The png_save_int_32 function assumes integers are stored in two's
  200579. * complement format. If this isn't the case, then this routine needs to
  200580. * be modified to write data in two's complement format.
  200581. */
  200582. void PNGAPI
  200583. png_save_int_32(png_bytep buf, png_int_32 i)
  200584. {
  200585. buf[0] = (png_byte)((i >> 24) & 0xff);
  200586. buf[1] = (png_byte)((i >> 16) & 0xff);
  200587. buf[2] = (png_byte)((i >> 8) & 0xff);
  200588. buf[3] = (png_byte)(i & 0xff);
  200589. }
  200590. /* Place a 16-bit number into a buffer in PNG byte order.
  200591. * The parameter is declared unsigned int, not png_uint_16,
  200592. * just to avoid potential problems on pre-ANSI C compilers.
  200593. */
  200594. void PNGAPI
  200595. png_save_uint_16(png_bytep buf, unsigned int i)
  200596. {
  200597. buf[0] = (png_byte)((i >> 8) & 0xff);
  200598. buf[1] = (png_byte)(i & 0xff);
  200599. }
  200600. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200601. * representing the chunk name. The array must be at least 4 bytes in
  200602. * length, and does not need to be null terminated. To be safe, pass the
  200603. * pre-defined chunk names here, and if you need a new one, define it
  200604. * where the others are defined. The length is the length of the data.
  200605. * All the data must be present. If that is not possible, use the
  200606. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200607. * functions instead.
  200608. */
  200609. void PNGAPI
  200610. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200611. png_bytep data, png_size_t length)
  200612. {
  200613. if(png_ptr == NULL) return;
  200614. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200615. png_write_chunk_data(png_ptr, data, length);
  200616. png_write_chunk_end(png_ptr);
  200617. }
  200618. /* Write the start of a PNG chunk. The type is the chunk type.
  200619. * The total_length is the sum of the lengths of all the data you will be
  200620. * passing in png_write_chunk_data().
  200621. */
  200622. void PNGAPI
  200623. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200624. png_uint_32 length)
  200625. {
  200626. png_byte buf[4];
  200627. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200628. if(png_ptr == NULL) return;
  200629. /* write the length */
  200630. png_save_uint_32(buf, length);
  200631. png_write_data(png_ptr, buf, (png_size_t)4);
  200632. /* write the chunk name */
  200633. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200634. /* reset the crc and run it over the chunk name */
  200635. png_reset_crc(png_ptr);
  200636. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200637. }
  200638. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200639. * Note that multiple calls to this function are allowed, and that the
  200640. * sum of the lengths from these calls *must* add up to the total_length
  200641. * given to png_write_chunk_start().
  200642. */
  200643. void PNGAPI
  200644. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200645. {
  200646. /* write the data, and run the CRC over it */
  200647. if(png_ptr == NULL) return;
  200648. if (data != NULL && length > 0)
  200649. {
  200650. png_calculate_crc(png_ptr, data, length);
  200651. png_write_data(png_ptr, data, length);
  200652. }
  200653. }
  200654. /* Finish a chunk started with png_write_chunk_start(). */
  200655. void PNGAPI
  200656. png_write_chunk_end(png_structp png_ptr)
  200657. {
  200658. png_byte buf[4];
  200659. if(png_ptr == NULL) return;
  200660. /* write the crc */
  200661. png_save_uint_32(buf, png_ptr->crc);
  200662. png_write_data(png_ptr, buf, (png_size_t)4);
  200663. }
  200664. /* Simple function to write the signature. If we have already written
  200665. * the magic bytes of the signature, or more likely, the PNG stream is
  200666. * being embedded into another stream and doesn't need its own signature,
  200667. * we should call png_set_sig_bytes() to tell libpng how many of the
  200668. * bytes have already been written.
  200669. */
  200670. void /* PRIVATE */
  200671. png_write_sig(png_structp png_ptr)
  200672. {
  200673. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200674. /* write the rest of the 8 byte signature */
  200675. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200676. (png_size_t)8 - png_ptr->sig_bytes);
  200677. if(png_ptr->sig_bytes < 3)
  200678. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200679. }
  200680. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200681. /*
  200682. * This pair of functions encapsulates the operation of (a) compressing a
  200683. * text string, and (b) issuing it later as a series of chunk data writes.
  200684. * The compression_state structure is shared context for these functions
  200685. * set up by the caller in order to make the whole mess thread-safe.
  200686. */
  200687. typedef struct
  200688. {
  200689. char *input; /* the uncompressed input data */
  200690. int input_len; /* its length */
  200691. int num_output_ptr; /* number of output pointers used */
  200692. int max_output_ptr; /* size of output_ptr */
  200693. png_charpp output_ptr; /* array of pointers to output */
  200694. } compression_state;
  200695. /* compress given text into storage in the png_ptr structure */
  200696. static int /* PRIVATE */
  200697. png_text_compress(png_structp png_ptr,
  200698. png_charp text, png_size_t text_len, int compression,
  200699. compression_state *comp)
  200700. {
  200701. int ret;
  200702. comp->num_output_ptr = 0;
  200703. comp->max_output_ptr = 0;
  200704. comp->output_ptr = NULL;
  200705. comp->input = NULL;
  200706. comp->input_len = 0;
  200707. /* we may just want to pass the text right through */
  200708. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200709. {
  200710. comp->input = text;
  200711. comp->input_len = text_len;
  200712. return((int)text_len);
  200713. }
  200714. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200715. {
  200716. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200717. char msg[50];
  200718. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200719. png_warning(png_ptr, msg);
  200720. #else
  200721. png_warning(png_ptr, "Unknown compression type");
  200722. #endif
  200723. }
  200724. /* We can't write the chunk until we find out how much data we have,
  200725. * which means we need to run the compressor first and save the
  200726. * output. This shouldn't be a problem, as the vast majority of
  200727. * comments should be reasonable, but we will set up an array of
  200728. * malloc'd pointers to be sure.
  200729. *
  200730. * If we knew the application was well behaved, we could simplify this
  200731. * greatly by assuming we can always malloc an output buffer large
  200732. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200733. * and malloc this directly. The only time this would be a bad idea is
  200734. * if we can't malloc more than 64K and we have 64K of random input
  200735. * data, or if the input string is incredibly large (although this
  200736. * wouldn't cause a failure, just a slowdown due to swapping).
  200737. */
  200738. /* set up the compression buffers */
  200739. png_ptr->zstream.avail_in = (uInt)text_len;
  200740. png_ptr->zstream.next_in = (Bytef *)text;
  200741. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200742. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200743. /* this is the same compression loop as in png_write_row() */
  200744. do
  200745. {
  200746. /* compress the data */
  200747. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200748. if (ret != Z_OK)
  200749. {
  200750. /* error */
  200751. if (png_ptr->zstream.msg != NULL)
  200752. png_error(png_ptr, png_ptr->zstream.msg);
  200753. else
  200754. png_error(png_ptr, "zlib error");
  200755. }
  200756. /* check to see if we need more room */
  200757. if (!(png_ptr->zstream.avail_out))
  200758. {
  200759. /* make sure the output array has room */
  200760. if (comp->num_output_ptr >= comp->max_output_ptr)
  200761. {
  200762. int old_max;
  200763. old_max = comp->max_output_ptr;
  200764. comp->max_output_ptr = comp->num_output_ptr + 4;
  200765. if (comp->output_ptr != NULL)
  200766. {
  200767. png_charpp old_ptr;
  200768. old_ptr = comp->output_ptr;
  200769. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200770. (png_uint_32)(comp->max_output_ptr *
  200771. png_sizeof (png_charpp)));
  200772. png_memcpy(comp->output_ptr, old_ptr, old_max
  200773. * png_sizeof (png_charp));
  200774. png_free(png_ptr, old_ptr);
  200775. }
  200776. else
  200777. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200778. (png_uint_32)(comp->max_output_ptr *
  200779. png_sizeof (png_charp)));
  200780. }
  200781. /* save the data */
  200782. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200783. (png_uint_32)png_ptr->zbuf_size);
  200784. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200785. png_ptr->zbuf_size);
  200786. comp->num_output_ptr++;
  200787. /* and reset the buffer */
  200788. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200789. png_ptr->zstream.next_out = png_ptr->zbuf;
  200790. }
  200791. /* continue until we don't have any more to compress */
  200792. } while (png_ptr->zstream.avail_in);
  200793. /* finish the compression */
  200794. do
  200795. {
  200796. /* tell zlib we are finished */
  200797. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200798. if (ret == Z_OK)
  200799. {
  200800. /* check to see if we need more room */
  200801. if (!(png_ptr->zstream.avail_out))
  200802. {
  200803. /* check to make sure our output array has room */
  200804. if (comp->num_output_ptr >= comp->max_output_ptr)
  200805. {
  200806. int old_max;
  200807. old_max = comp->max_output_ptr;
  200808. comp->max_output_ptr = comp->num_output_ptr + 4;
  200809. if (comp->output_ptr != NULL)
  200810. {
  200811. png_charpp old_ptr;
  200812. old_ptr = comp->output_ptr;
  200813. /* This could be optimized to realloc() */
  200814. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200815. (png_uint_32)(comp->max_output_ptr *
  200816. png_sizeof (png_charpp)));
  200817. png_memcpy(comp->output_ptr, old_ptr,
  200818. old_max * png_sizeof (png_charp));
  200819. png_free(png_ptr, old_ptr);
  200820. }
  200821. else
  200822. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200823. (png_uint_32)(comp->max_output_ptr *
  200824. png_sizeof (png_charp)));
  200825. }
  200826. /* save off the data */
  200827. comp->output_ptr[comp->num_output_ptr] =
  200828. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200829. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200830. png_ptr->zbuf_size);
  200831. comp->num_output_ptr++;
  200832. /* and reset the buffer pointers */
  200833. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200834. png_ptr->zstream.next_out = png_ptr->zbuf;
  200835. }
  200836. }
  200837. else if (ret != Z_STREAM_END)
  200838. {
  200839. /* we got an error */
  200840. if (png_ptr->zstream.msg != NULL)
  200841. png_error(png_ptr, png_ptr->zstream.msg);
  200842. else
  200843. png_error(png_ptr, "zlib error");
  200844. }
  200845. } while (ret != Z_STREAM_END);
  200846. /* text length is number of buffers plus last buffer */
  200847. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200848. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200849. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200850. return((int)text_len);
  200851. }
  200852. /* ship the compressed text out via chunk writes */
  200853. static void /* PRIVATE */
  200854. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200855. {
  200856. int i;
  200857. /* handle the no-compression case */
  200858. if (comp->input)
  200859. {
  200860. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200861. (png_size_t)comp->input_len);
  200862. return;
  200863. }
  200864. /* write saved output buffers, if any */
  200865. for (i = 0; i < comp->num_output_ptr; i++)
  200866. {
  200867. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200868. png_ptr->zbuf_size);
  200869. png_free(png_ptr, comp->output_ptr[i]);
  200870. comp->output_ptr[i]=NULL;
  200871. }
  200872. if (comp->max_output_ptr != 0)
  200873. png_free(png_ptr, comp->output_ptr);
  200874. comp->output_ptr=NULL;
  200875. /* write anything left in zbuf */
  200876. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200877. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200878. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200879. /* reset zlib for another zTXt/iTXt or image data */
  200880. deflateReset(&png_ptr->zstream);
  200881. png_ptr->zstream.data_type = Z_BINARY;
  200882. }
  200883. #endif
  200884. /* Write the IHDR chunk, and update the png_struct with the necessary
  200885. * information. Note that the rest of this code depends upon this
  200886. * information being correct.
  200887. */
  200888. void /* PRIVATE */
  200889. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200890. int bit_depth, int color_type, int compression_type, int filter_type,
  200891. int interlace_type)
  200892. {
  200893. #ifdef PNG_USE_LOCAL_ARRAYS
  200894. PNG_IHDR;
  200895. #endif
  200896. png_byte buf[13]; /* buffer to store the IHDR info */
  200897. png_debug(1, "in png_write_IHDR\n");
  200898. /* Check that we have valid input data from the application info */
  200899. switch (color_type)
  200900. {
  200901. case PNG_COLOR_TYPE_GRAY:
  200902. switch (bit_depth)
  200903. {
  200904. case 1:
  200905. case 2:
  200906. case 4:
  200907. case 8:
  200908. case 16: png_ptr->channels = 1; break;
  200909. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200910. }
  200911. break;
  200912. case PNG_COLOR_TYPE_RGB:
  200913. if (bit_depth != 8 && bit_depth != 16)
  200914. png_error(png_ptr, "Invalid bit depth for RGB image");
  200915. png_ptr->channels = 3;
  200916. break;
  200917. case PNG_COLOR_TYPE_PALETTE:
  200918. switch (bit_depth)
  200919. {
  200920. case 1:
  200921. case 2:
  200922. case 4:
  200923. case 8: png_ptr->channels = 1; break;
  200924. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200925. }
  200926. break;
  200927. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200928. if (bit_depth != 8 && bit_depth != 16)
  200929. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200930. png_ptr->channels = 2;
  200931. break;
  200932. case PNG_COLOR_TYPE_RGB_ALPHA:
  200933. if (bit_depth != 8 && bit_depth != 16)
  200934. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200935. png_ptr->channels = 4;
  200936. break;
  200937. default:
  200938. png_error(png_ptr, "Invalid image color type specified");
  200939. }
  200940. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200941. {
  200942. png_warning(png_ptr, "Invalid compression type specified");
  200943. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200944. }
  200945. /* Write filter_method 64 (intrapixel differencing) only if
  200946. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200947. * 2. Libpng did not write a PNG signature (this filter_method is only
  200948. * used in PNG datastreams that are embedded in MNG datastreams) and
  200949. * 3. The application called png_permit_mng_features with a mask that
  200950. * included PNG_FLAG_MNG_FILTER_64 and
  200951. * 4. The filter_method is 64 and
  200952. * 5. The color_type is RGB or RGBA
  200953. */
  200954. if (
  200955. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200956. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200957. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200958. (color_type == PNG_COLOR_TYPE_RGB ||
  200959. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200960. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200961. #endif
  200962. filter_type != PNG_FILTER_TYPE_BASE)
  200963. {
  200964. png_warning(png_ptr, "Invalid filter type specified");
  200965. filter_type = PNG_FILTER_TYPE_BASE;
  200966. }
  200967. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200968. if (interlace_type != PNG_INTERLACE_NONE &&
  200969. interlace_type != PNG_INTERLACE_ADAM7)
  200970. {
  200971. png_warning(png_ptr, "Invalid interlace type specified");
  200972. interlace_type = PNG_INTERLACE_ADAM7;
  200973. }
  200974. #else
  200975. interlace_type=PNG_INTERLACE_NONE;
  200976. #endif
  200977. /* save off the relevent information */
  200978. png_ptr->bit_depth = (png_byte)bit_depth;
  200979. png_ptr->color_type = (png_byte)color_type;
  200980. png_ptr->interlaced = (png_byte)interlace_type;
  200981. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200982. png_ptr->filter_type = (png_byte)filter_type;
  200983. #endif
  200984. png_ptr->compression_type = (png_byte)compression_type;
  200985. png_ptr->width = width;
  200986. png_ptr->height = height;
  200987. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200988. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200989. /* set the usr info, so any transformations can modify it */
  200990. png_ptr->usr_width = png_ptr->width;
  200991. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200992. png_ptr->usr_channels = png_ptr->channels;
  200993. /* pack the header information into the buffer */
  200994. png_save_uint_32(buf, width);
  200995. png_save_uint_32(buf + 4, height);
  200996. buf[8] = (png_byte)bit_depth;
  200997. buf[9] = (png_byte)color_type;
  200998. buf[10] = (png_byte)compression_type;
  200999. buf[11] = (png_byte)filter_type;
  201000. buf[12] = (png_byte)interlace_type;
  201001. /* write the chunk */
  201002. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201003. /* initialize zlib with PNG info */
  201004. png_ptr->zstream.zalloc = png_zalloc;
  201005. png_ptr->zstream.zfree = png_zfree;
  201006. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201007. if (!(png_ptr->do_filter))
  201008. {
  201009. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201010. png_ptr->bit_depth < 8)
  201011. png_ptr->do_filter = PNG_FILTER_NONE;
  201012. else
  201013. png_ptr->do_filter = PNG_ALL_FILTERS;
  201014. }
  201015. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201016. {
  201017. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201018. png_ptr->zlib_strategy = Z_FILTERED;
  201019. else
  201020. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201021. }
  201022. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201023. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201024. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201025. png_ptr->zlib_mem_level = 8;
  201026. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201027. png_ptr->zlib_window_bits = 15;
  201028. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201029. png_ptr->zlib_method = 8;
  201030. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201031. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201032. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201033. png_error(png_ptr, "zlib failed to initialize compressor");
  201034. png_ptr->zstream.next_out = png_ptr->zbuf;
  201035. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201036. /* libpng is not interested in zstream.data_type */
  201037. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201038. png_ptr->zstream.data_type = Z_BINARY;
  201039. png_ptr->mode = PNG_HAVE_IHDR;
  201040. }
  201041. /* write the palette. We are careful not to trust png_color to be in the
  201042. * correct order for PNG, so people can redefine it to any convenient
  201043. * structure.
  201044. */
  201045. void /* PRIVATE */
  201046. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201047. {
  201048. #ifdef PNG_USE_LOCAL_ARRAYS
  201049. PNG_PLTE;
  201050. #endif
  201051. png_uint_32 i;
  201052. png_colorp pal_ptr;
  201053. png_byte buf[3];
  201054. png_debug(1, "in png_write_PLTE\n");
  201055. if ((
  201056. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201057. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201058. #endif
  201059. num_pal == 0) || num_pal > 256)
  201060. {
  201061. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201062. {
  201063. png_error(png_ptr, "Invalid number of colors in palette");
  201064. }
  201065. else
  201066. {
  201067. png_warning(png_ptr, "Invalid number of colors in palette");
  201068. return;
  201069. }
  201070. }
  201071. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201072. {
  201073. png_warning(png_ptr,
  201074. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201075. return;
  201076. }
  201077. png_ptr->num_palette = (png_uint_16)num_pal;
  201078. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201079. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201080. #ifndef PNG_NO_POINTER_INDEXING
  201081. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201082. {
  201083. buf[0] = pal_ptr->red;
  201084. buf[1] = pal_ptr->green;
  201085. buf[2] = pal_ptr->blue;
  201086. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201087. }
  201088. #else
  201089. /* This is a little slower but some buggy compilers need to do this instead */
  201090. pal_ptr=palette;
  201091. for (i = 0; i < num_pal; i++)
  201092. {
  201093. buf[0] = pal_ptr[i].red;
  201094. buf[1] = pal_ptr[i].green;
  201095. buf[2] = pal_ptr[i].blue;
  201096. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201097. }
  201098. #endif
  201099. png_write_chunk_end(png_ptr);
  201100. png_ptr->mode |= PNG_HAVE_PLTE;
  201101. }
  201102. /* write an IDAT chunk */
  201103. void /* PRIVATE */
  201104. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201105. {
  201106. #ifdef PNG_USE_LOCAL_ARRAYS
  201107. PNG_IDAT;
  201108. #endif
  201109. png_debug(1, "in png_write_IDAT\n");
  201110. /* Optimize the CMF field in the zlib stream. */
  201111. /* This hack of the zlib stream is compliant to the stream specification. */
  201112. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201113. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201114. {
  201115. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201116. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201117. {
  201118. /* Avoid memory underflows and multiplication overflows. */
  201119. /* The conditions below are practically always satisfied;
  201120. however, they still must be checked. */
  201121. if (length >= 2 &&
  201122. png_ptr->height < 16384 && png_ptr->width < 16384)
  201123. {
  201124. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201125. ((png_ptr->width *
  201126. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201127. unsigned int z_cinfo = z_cmf >> 4;
  201128. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201129. while (uncompressed_idat_size <= half_z_window_size &&
  201130. half_z_window_size >= 256)
  201131. {
  201132. z_cinfo--;
  201133. half_z_window_size >>= 1;
  201134. }
  201135. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201136. if (data[0] != (png_byte)z_cmf)
  201137. {
  201138. data[0] = (png_byte)z_cmf;
  201139. data[1] &= 0xe0;
  201140. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201141. }
  201142. }
  201143. }
  201144. else
  201145. png_error(png_ptr,
  201146. "Invalid zlib compression method or flags in IDAT");
  201147. }
  201148. png_write_chunk(png_ptr, png_IDAT, data, length);
  201149. png_ptr->mode |= PNG_HAVE_IDAT;
  201150. }
  201151. /* write an IEND chunk */
  201152. void /* PRIVATE */
  201153. png_write_IEND(png_structp png_ptr)
  201154. {
  201155. #ifdef PNG_USE_LOCAL_ARRAYS
  201156. PNG_IEND;
  201157. #endif
  201158. png_debug(1, "in png_write_IEND\n");
  201159. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201160. (png_size_t)0);
  201161. png_ptr->mode |= PNG_HAVE_IEND;
  201162. }
  201163. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201164. /* write a gAMA chunk */
  201165. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201166. void /* PRIVATE */
  201167. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201168. {
  201169. #ifdef PNG_USE_LOCAL_ARRAYS
  201170. PNG_gAMA;
  201171. #endif
  201172. png_uint_32 igamma;
  201173. png_byte buf[4];
  201174. png_debug(1, "in png_write_gAMA\n");
  201175. /* file_gamma is saved in 1/100,000ths */
  201176. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201177. png_save_uint_32(buf, igamma);
  201178. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201179. }
  201180. #endif
  201181. #ifdef PNG_FIXED_POINT_SUPPORTED
  201182. void /* PRIVATE */
  201183. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201184. {
  201185. #ifdef PNG_USE_LOCAL_ARRAYS
  201186. PNG_gAMA;
  201187. #endif
  201188. png_byte buf[4];
  201189. png_debug(1, "in png_write_gAMA\n");
  201190. /* file_gamma is saved in 1/100,000ths */
  201191. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201192. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201193. }
  201194. #endif
  201195. #endif
  201196. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201197. /* write a sRGB chunk */
  201198. void /* PRIVATE */
  201199. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201200. {
  201201. #ifdef PNG_USE_LOCAL_ARRAYS
  201202. PNG_sRGB;
  201203. #endif
  201204. png_byte buf[1];
  201205. png_debug(1, "in png_write_sRGB\n");
  201206. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201207. png_warning(png_ptr,
  201208. "Invalid sRGB rendering intent specified");
  201209. buf[0]=(png_byte)srgb_intent;
  201210. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201211. }
  201212. #endif
  201213. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201214. /* write an iCCP chunk */
  201215. void /* PRIVATE */
  201216. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201217. png_charp profile, int profile_len)
  201218. {
  201219. #ifdef PNG_USE_LOCAL_ARRAYS
  201220. PNG_iCCP;
  201221. #endif
  201222. png_size_t name_len;
  201223. png_charp new_name;
  201224. compression_state comp;
  201225. int embedded_profile_len = 0;
  201226. png_debug(1, "in png_write_iCCP\n");
  201227. comp.num_output_ptr = 0;
  201228. comp.max_output_ptr = 0;
  201229. comp.output_ptr = NULL;
  201230. comp.input = NULL;
  201231. comp.input_len = 0;
  201232. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201233. &new_name)) == 0)
  201234. {
  201235. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201236. return;
  201237. }
  201238. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201239. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201240. if (profile == NULL)
  201241. profile_len = 0;
  201242. if (profile_len > 3)
  201243. embedded_profile_len =
  201244. ((*( (png_bytep)profile ))<<24) |
  201245. ((*( (png_bytep)profile+1))<<16) |
  201246. ((*( (png_bytep)profile+2))<< 8) |
  201247. ((*( (png_bytep)profile+3)) );
  201248. if (profile_len < embedded_profile_len)
  201249. {
  201250. png_warning(png_ptr,
  201251. "Embedded profile length too large in iCCP chunk");
  201252. return;
  201253. }
  201254. if (profile_len > embedded_profile_len)
  201255. {
  201256. png_warning(png_ptr,
  201257. "Truncating profile to actual length in iCCP chunk");
  201258. profile_len = embedded_profile_len;
  201259. }
  201260. if (profile_len)
  201261. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201262. PNG_COMPRESSION_TYPE_BASE, &comp);
  201263. /* make sure we include the NULL after the name and the compression type */
  201264. png_write_chunk_start(png_ptr, png_iCCP,
  201265. (png_uint_32)name_len+profile_len+2);
  201266. new_name[name_len+1]=0x00;
  201267. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201268. if (profile_len)
  201269. png_write_compressed_data_out(png_ptr, &comp);
  201270. png_write_chunk_end(png_ptr);
  201271. png_free(png_ptr, new_name);
  201272. }
  201273. #endif
  201274. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201275. /* write a sPLT chunk */
  201276. void /* PRIVATE */
  201277. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201278. {
  201279. #ifdef PNG_USE_LOCAL_ARRAYS
  201280. PNG_sPLT;
  201281. #endif
  201282. png_size_t name_len;
  201283. png_charp new_name;
  201284. png_byte entrybuf[10];
  201285. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201286. int palette_size = entry_size * spalette->nentries;
  201287. png_sPLT_entryp ep;
  201288. #ifdef PNG_NO_POINTER_INDEXING
  201289. int i;
  201290. #endif
  201291. png_debug(1, "in png_write_sPLT\n");
  201292. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201293. spalette->name, &new_name))==0)
  201294. {
  201295. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201296. return;
  201297. }
  201298. /* make sure we include the NULL after the name */
  201299. png_write_chunk_start(png_ptr, png_sPLT,
  201300. (png_uint_32)(name_len + 2 + palette_size));
  201301. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201302. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201303. /* loop through each palette entry, writing appropriately */
  201304. #ifndef PNG_NO_POINTER_INDEXING
  201305. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201306. {
  201307. if (spalette->depth == 8)
  201308. {
  201309. entrybuf[0] = (png_byte)ep->red;
  201310. entrybuf[1] = (png_byte)ep->green;
  201311. entrybuf[2] = (png_byte)ep->blue;
  201312. entrybuf[3] = (png_byte)ep->alpha;
  201313. png_save_uint_16(entrybuf + 4, ep->frequency);
  201314. }
  201315. else
  201316. {
  201317. png_save_uint_16(entrybuf + 0, ep->red);
  201318. png_save_uint_16(entrybuf + 2, ep->green);
  201319. png_save_uint_16(entrybuf + 4, ep->blue);
  201320. png_save_uint_16(entrybuf + 6, ep->alpha);
  201321. png_save_uint_16(entrybuf + 8, ep->frequency);
  201322. }
  201323. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201324. }
  201325. #else
  201326. ep=spalette->entries;
  201327. for (i=0; i>spalette->nentries; i++)
  201328. {
  201329. if (spalette->depth == 8)
  201330. {
  201331. entrybuf[0] = (png_byte)ep[i].red;
  201332. entrybuf[1] = (png_byte)ep[i].green;
  201333. entrybuf[2] = (png_byte)ep[i].blue;
  201334. entrybuf[3] = (png_byte)ep[i].alpha;
  201335. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201336. }
  201337. else
  201338. {
  201339. png_save_uint_16(entrybuf + 0, ep[i].red);
  201340. png_save_uint_16(entrybuf + 2, ep[i].green);
  201341. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201342. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201343. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201344. }
  201345. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201346. }
  201347. #endif
  201348. png_write_chunk_end(png_ptr);
  201349. png_free(png_ptr, new_name);
  201350. }
  201351. #endif
  201352. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201353. /* write the sBIT chunk */
  201354. void /* PRIVATE */
  201355. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201356. {
  201357. #ifdef PNG_USE_LOCAL_ARRAYS
  201358. PNG_sBIT;
  201359. #endif
  201360. png_byte buf[4];
  201361. png_size_t size;
  201362. png_debug(1, "in png_write_sBIT\n");
  201363. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201364. if (color_type & PNG_COLOR_MASK_COLOR)
  201365. {
  201366. png_byte maxbits;
  201367. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201368. png_ptr->usr_bit_depth);
  201369. if (sbit->red == 0 || sbit->red > maxbits ||
  201370. sbit->green == 0 || sbit->green > maxbits ||
  201371. sbit->blue == 0 || sbit->blue > maxbits)
  201372. {
  201373. png_warning(png_ptr, "Invalid sBIT depth specified");
  201374. return;
  201375. }
  201376. buf[0] = sbit->red;
  201377. buf[1] = sbit->green;
  201378. buf[2] = sbit->blue;
  201379. size = 3;
  201380. }
  201381. else
  201382. {
  201383. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201384. {
  201385. png_warning(png_ptr, "Invalid sBIT depth specified");
  201386. return;
  201387. }
  201388. buf[0] = sbit->gray;
  201389. size = 1;
  201390. }
  201391. if (color_type & PNG_COLOR_MASK_ALPHA)
  201392. {
  201393. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201394. {
  201395. png_warning(png_ptr, "Invalid sBIT depth specified");
  201396. return;
  201397. }
  201398. buf[size++] = sbit->alpha;
  201399. }
  201400. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201401. }
  201402. #endif
  201403. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201404. /* write the cHRM chunk */
  201405. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201406. void /* PRIVATE */
  201407. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201408. double red_x, double red_y, double green_x, double green_y,
  201409. double blue_x, double blue_y)
  201410. {
  201411. #ifdef PNG_USE_LOCAL_ARRAYS
  201412. PNG_cHRM;
  201413. #endif
  201414. png_byte buf[32];
  201415. png_uint_32 itemp;
  201416. png_debug(1, "in png_write_cHRM\n");
  201417. /* each value is saved in 1/100,000ths */
  201418. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201419. white_x + white_y > 1.0)
  201420. {
  201421. png_warning(png_ptr, "Invalid cHRM white point specified");
  201422. #if !defined(PNG_NO_CONSOLE_IO)
  201423. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201424. #endif
  201425. return;
  201426. }
  201427. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201428. png_save_uint_32(buf, itemp);
  201429. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201430. png_save_uint_32(buf + 4, itemp);
  201431. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201432. {
  201433. png_warning(png_ptr, "Invalid cHRM red point specified");
  201434. return;
  201435. }
  201436. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201437. png_save_uint_32(buf + 8, itemp);
  201438. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201439. png_save_uint_32(buf + 12, itemp);
  201440. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201441. {
  201442. png_warning(png_ptr, "Invalid cHRM green point specified");
  201443. return;
  201444. }
  201445. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201446. png_save_uint_32(buf + 16, itemp);
  201447. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201448. png_save_uint_32(buf + 20, itemp);
  201449. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201450. {
  201451. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201452. return;
  201453. }
  201454. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201455. png_save_uint_32(buf + 24, itemp);
  201456. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201457. png_save_uint_32(buf + 28, itemp);
  201458. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201459. }
  201460. #endif
  201461. #ifdef PNG_FIXED_POINT_SUPPORTED
  201462. void /* PRIVATE */
  201463. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201464. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201465. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201466. png_fixed_point blue_y)
  201467. {
  201468. #ifdef PNG_USE_LOCAL_ARRAYS
  201469. PNG_cHRM;
  201470. #endif
  201471. png_byte buf[32];
  201472. png_debug(1, "in png_write_cHRM\n");
  201473. /* each value is saved in 1/100,000ths */
  201474. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201475. {
  201476. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201477. #if !defined(PNG_NO_CONSOLE_IO)
  201478. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201479. #endif
  201480. return;
  201481. }
  201482. png_save_uint_32(buf, (png_uint_32)white_x);
  201483. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201484. if (red_x + red_y > 100000L)
  201485. {
  201486. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201487. return;
  201488. }
  201489. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201490. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201491. if (green_x + green_y > 100000L)
  201492. {
  201493. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201494. return;
  201495. }
  201496. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201497. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201498. if (blue_x + blue_y > 100000L)
  201499. {
  201500. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201501. return;
  201502. }
  201503. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201504. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201505. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201506. }
  201507. #endif
  201508. #endif
  201509. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201510. /* write the tRNS chunk */
  201511. void /* PRIVATE */
  201512. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201513. int num_trans, int color_type)
  201514. {
  201515. #ifdef PNG_USE_LOCAL_ARRAYS
  201516. PNG_tRNS;
  201517. #endif
  201518. png_byte buf[6];
  201519. png_debug(1, "in png_write_tRNS\n");
  201520. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201521. {
  201522. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201523. {
  201524. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201525. return;
  201526. }
  201527. /* write the chunk out as it is */
  201528. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201529. }
  201530. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201531. {
  201532. /* one 16 bit value */
  201533. if(tran->gray >= (1 << png_ptr->bit_depth))
  201534. {
  201535. png_warning(png_ptr,
  201536. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201537. return;
  201538. }
  201539. png_save_uint_16(buf, tran->gray);
  201540. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201541. }
  201542. else if (color_type == PNG_COLOR_TYPE_RGB)
  201543. {
  201544. /* three 16 bit values */
  201545. png_save_uint_16(buf, tran->red);
  201546. png_save_uint_16(buf + 2, tran->green);
  201547. png_save_uint_16(buf + 4, tran->blue);
  201548. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201549. {
  201550. png_warning(png_ptr,
  201551. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201552. return;
  201553. }
  201554. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201555. }
  201556. else
  201557. {
  201558. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201559. }
  201560. }
  201561. #endif
  201562. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201563. /* write the background chunk */
  201564. void /* PRIVATE */
  201565. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201566. {
  201567. #ifdef PNG_USE_LOCAL_ARRAYS
  201568. PNG_bKGD;
  201569. #endif
  201570. png_byte buf[6];
  201571. png_debug(1, "in png_write_bKGD\n");
  201572. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201573. {
  201574. if (
  201575. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201576. (png_ptr->num_palette ||
  201577. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201578. #endif
  201579. back->index > png_ptr->num_palette)
  201580. {
  201581. png_warning(png_ptr, "Invalid background palette index");
  201582. return;
  201583. }
  201584. buf[0] = back->index;
  201585. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201586. }
  201587. else if (color_type & PNG_COLOR_MASK_COLOR)
  201588. {
  201589. png_save_uint_16(buf, back->red);
  201590. png_save_uint_16(buf + 2, back->green);
  201591. png_save_uint_16(buf + 4, back->blue);
  201592. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201593. {
  201594. png_warning(png_ptr,
  201595. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201596. return;
  201597. }
  201598. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201599. }
  201600. else
  201601. {
  201602. if(back->gray >= (1 << png_ptr->bit_depth))
  201603. {
  201604. png_warning(png_ptr,
  201605. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201606. return;
  201607. }
  201608. png_save_uint_16(buf, back->gray);
  201609. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201610. }
  201611. }
  201612. #endif
  201613. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201614. /* write the histogram */
  201615. void /* PRIVATE */
  201616. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201617. {
  201618. #ifdef PNG_USE_LOCAL_ARRAYS
  201619. PNG_hIST;
  201620. #endif
  201621. int i;
  201622. png_byte buf[3];
  201623. png_debug(1, "in png_write_hIST\n");
  201624. if (num_hist > (int)png_ptr->num_palette)
  201625. {
  201626. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201627. png_ptr->num_palette);
  201628. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201629. return;
  201630. }
  201631. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201632. for (i = 0; i < num_hist; i++)
  201633. {
  201634. png_save_uint_16(buf, hist[i]);
  201635. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201636. }
  201637. png_write_chunk_end(png_ptr);
  201638. }
  201639. #endif
  201640. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201641. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201642. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201643. * and if invalid, correct the keyword rather than discarding the entire
  201644. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201645. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201646. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201647. *
  201648. * The new_key is allocated to hold the corrected keyword and must be freed
  201649. * by the calling routine. This avoids problems with trying to write to
  201650. * static keywords without having to have duplicate copies of the strings.
  201651. */
  201652. png_size_t /* PRIVATE */
  201653. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201654. {
  201655. png_size_t key_len;
  201656. png_charp kp, dp;
  201657. int kflag;
  201658. int kwarn=0;
  201659. png_debug(1, "in png_check_keyword\n");
  201660. *new_key = NULL;
  201661. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201662. {
  201663. png_warning(png_ptr, "zero length keyword");
  201664. return ((png_size_t)0);
  201665. }
  201666. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201667. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201668. if (*new_key == NULL)
  201669. {
  201670. png_warning(png_ptr, "Out of memory while procesing keyword");
  201671. return ((png_size_t)0);
  201672. }
  201673. /* Replace non-printing characters with a blank and print a warning */
  201674. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201675. {
  201676. if ((png_byte)*kp < 0x20 ||
  201677. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201678. {
  201679. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201680. char msg[40];
  201681. png_snprintf(msg, 40,
  201682. "invalid keyword character 0x%02X", (png_byte)*kp);
  201683. png_warning(png_ptr, msg);
  201684. #else
  201685. png_warning(png_ptr, "invalid character in keyword");
  201686. #endif
  201687. *dp = ' ';
  201688. }
  201689. else
  201690. {
  201691. *dp = *kp;
  201692. }
  201693. }
  201694. *dp = '\0';
  201695. /* Remove any trailing white space. */
  201696. kp = *new_key + key_len - 1;
  201697. if (*kp == ' ')
  201698. {
  201699. png_warning(png_ptr, "trailing spaces removed from keyword");
  201700. while (*kp == ' ')
  201701. {
  201702. *(kp--) = '\0';
  201703. key_len--;
  201704. }
  201705. }
  201706. /* Remove any leading white space. */
  201707. kp = *new_key;
  201708. if (*kp == ' ')
  201709. {
  201710. png_warning(png_ptr, "leading spaces removed from keyword");
  201711. while (*kp == ' ')
  201712. {
  201713. kp++;
  201714. key_len--;
  201715. }
  201716. }
  201717. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201718. /* Remove multiple internal spaces. */
  201719. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201720. {
  201721. if (*kp == ' ' && kflag == 0)
  201722. {
  201723. *(dp++) = *kp;
  201724. kflag = 1;
  201725. }
  201726. else if (*kp == ' ')
  201727. {
  201728. key_len--;
  201729. kwarn=1;
  201730. }
  201731. else
  201732. {
  201733. *(dp++) = *kp;
  201734. kflag = 0;
  201735. }
  201736. }
  201737. *dp = '\0';
  201738. if(kwarn)
  201739. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201740. if (key_len == 0)
  201741. {
  201742. png_free(png_ptr, *new_key);
  201743. *new_key=NULL;
  201744. png_warning(png_ptr, "Zero length keyword");
  201745. }
  201746. if (key_len > 79)
  201747. {
  201748. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201749. new_key[79] = '\0';
  201750. key_len = 79;
  201751. }
  201752. return (key_len);
  201753. }
  201754. #endif
  201755. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201756. /* write a tEXt chunk */
  201757. void /* PRIVATE */
  201758. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201759. png_size_t text_len)
  201760. {
  201761. #ifdef PNG_USE_LOCAL_ARRAYS
  201762. PNG_tEXt;
  201763. #endif
  201764. png_size_t key_len;
  201765. png_charp new_key;
  201766. png_debug(1, "in png_write_tEXt\n");
  201767. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201768. {
  201769. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201770. return;
  201771. }
  201772. if (text == NULL || *text == '\0')
  201773. text_len = 0;
  201774. else
  201775. text_len = png_strlen(text);
  201776. /* make sure we include the 0 after the key */
  201777. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201778. /*
  201779. * We leave it to the application to meet PNG-1.0 requirements on the
  201780. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201781. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201782. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201783. */
  201784. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201785. if (text_len)
  201786. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201787. png_write_chunk_end(png_ptr);
  201788. png_free(png_ptr, new_key);
  201789. }
  201790. #endif
  201791. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201792. /* write a compressed text chunk */
  201793. void /* PRIVATE */
  201794. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201795. png_size_t text_len, int compression)
  201796. {
  201797. #ifdef PNG_USE_LOCAL_ARRAYS
  201798. PNG_zTXt;
  201799. #endif
  201800. png_size_t key_len;
  201801. char buf[1];
  201802. png_charp new_key;
  201803. compression_state comp;
  201804. png_debug(1, "in png_write_zTXt\n");
  201805. comp.num_output_ptr = 0;
  201806. comp.max_output_ptr = 0;
  201807. comp.output_ptr = NULL;
  201808. comp.input = NULL;
  201809. comp.input_len = 0;
  201810. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201811. {
  201812. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201813. return;
  201814. }
  201815. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201816. {
  201817. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201818. png_free(png_ptr, new_key);
  201819. return;
  201820. }
  201821. text_len = png_strlen(text);
  201822. /* compute the compressed data; do it now for the length */
  201823. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201824. &comp);
  201825. /* write start of chunk */
  201826. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201827. (key_len+text_len+2));
  201828. /* write key */
  201829. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201830. png_free(png_ptr, new_key);
  201831. buf[0] = (png_byte)compression;
  201832. /* write compression */
  201833. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201834. /* write the compressed data */
  201835. png_write_compressed_data_out(png_ptr, &comp);
  201836. /* close the chunk */
  201837. png_write_chunk_end(png_ptr);
  201838. }
  201839. #endif
  201840. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201841. /* write an iTXt chunk */
  201842. void /* PRIVATE */
  201843. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201844. png_charp lang, png_charp lang_key, png_charp text)
  201845. {
  201846. #ifdef PNG_USE_LOCAL_ARRAYS
  201847. PNG_iTXt;
  201848. #endif
  201849. png_size_t lang_len, key_len, lang_key_len, text_len;
  201850. png_charp new_lang, new_key;
  201851. png_byte cbuf[2];
  201852. compression_state comp;
  201853. png_debug(1, "in png_write_iTXt\n");
  201854. comp.num_output_ptr = 0;
  201855. comp.max_output_ptr = 0;
  201856. comp.output_ptr = NULL;
  201857. comp.input = NULL;
  201858. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201859. {
  201860. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201861. return;
  201862. }
  201863. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201864. {
  201865. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201866. new_lang = NULL;
  201867. lang_len = 0;
  201868. }
  201869. if (lang_key == NULL)
  201870. lang_key_len = 0;
  201871. else
  201872. lang_key_len = png_strlen(lang_key);
  201873. if (text == NULL)
  201874. text_len = 0;
  201875. else
  201876. text_len = png_strlen(text);
  201877. /* compute the compressed data; do it now for the length */
  201878. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201879. &comp);
  201880. /* make sure we include the compression flag, the compression byte,
  201881. * and the NULs after the key, lang, and lang_key parts */
  201882. png_write_chunk_start(png_ptr, png_iTXt,
  201883. (png_uint_32)(
  201884. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201885. + key_len
  201886. + lang_len
  201887. + lang_key_len
  201888. + text_len));
  201889. /*
  201890. * We leave it to the application to meet PNG-1.0 requirements on the
  201891. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201892. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201893. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201894. */
  201895. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201896. /* set the compression flag */
  201897. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201898. compression == PNG_TEXT_COMPRESSION_NONE)
  201899. cbuf[0] = 0;
  201900. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201901. cbuf[0] = 1;
  201902. /* set the compression method */
  201903. cbuf[1] = 0;
  201904. png_write_chunk_data(png_ptr, cbuf, 2);
  201905. cbuf[0] = 0;
  201906. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201907. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201908. png_write_compressed_data_out(png_ptr, &comp);
  201909. png_write_chunk_end(png_ptr);
  201910. png_free(png_ptr, new_key);
  201911. if (new_lang)
  201912. png_free(png_ptr, new_lang);
  201913. }
  201914. #endif
  201915. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201916. /* write the oFFs chunk */
  201917. void /* PRIVATE */
  201918. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201919. int unit_type)
  201920. {
  201921. #ifdef PNG_USE_LOCAL_ARRAYS
  201922. PNG_oFFs;
  201923. #endif
  201924. png_byte buf[9];
  201925. png_debug(1, "in png_write_oFFs\n");
  201926. if (unit_type >= PNG_OFFSET_LAST)
  201927. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201928. png_save_int_32(buf, x_offset);
  201929. png_save_int_32(buf + 4, y_offset);
  201930. buf[8] = (png_byte)unit_type;
  201931. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201932. }
  201933. #endif
  201934. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201935. /* write the pCAL chunk (described in the PNG extensions document) */
  201936. void /* PRIVATE */
  201937. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201938. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201939. {
  201940. #ifdef PNG_USE_LOCAL_ARRAYS
  201941. PNG_pCAL;
  201942. #endif
  201943. png_size_t purpose_len, units_len, total_len;
  201944. png_uint_32p params_len;
  201945. png_byte buf[10];
  201946. png_charp new_purpose;
  201947. int i;
  201948. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201949. if (type >= PNG_EQUATION_LAST)
  201950. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201951. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201952. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201953. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201954. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201955. total_len = purpose_len + units_len + 10;
  201956. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201957. *png_sizeof(png_uint_32)));
  201958. /* Find the length of each parameter, making sure we don't count the
  201959. null terminator for the last parameter. */
  201960. for (i = 0; i < nparams; i++)
  201961. {
  201962. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201963. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201964. total_len += (png_size_t)params_len[i];
  201965. }
  201966. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201967. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201968. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201969. png_save_int_32(buf, X0);
  201970. png_save_int_32(buf + 4, X1);
  201971. buf[8] = (png_byte)type;
  201972. buf[9] = (png_byte)nparams;
  201973. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201974. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201975. png_free(png_ptr, new_purpose);
  201976. for (i = 0; i < nparams; i++)
  201977. {
  201978. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201979. (png_size_t)params_len[i]);
  201980. }
  201981. png_free(png_ptr, params_len);
  201982. png_write_chunk_end(png_ptr);
  201983. }
  201984. #endif
  201985. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201986. /* write the sCAL chunk */
  201987. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201988. void /* PRIVATE */
  201989. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201990. {
  201991. #ifdef PNG_USE_LOCAL_ARRAYS
  201992. PNG_sCAL;
  201993. #endif
  201994. char buf[64];
  201995. png_size_t total_len;
  201996. png_debug(1, "in png_write_sCAL\n");
  201997. buf[0] = (char)unit;
  201998. #if defined(_WIN32_WCE)
  201999. /* sprintf() function is not supported on WindowsCE */
  202000. {
  202001. wchar_t wc_buf[32];
  202002. size_t wc_len;
  202003. swprintf(wc_buf, TEXT("%12.12e"), width);
  202004. wc_len = wcslen(wc_buf);
  202005. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202006. total_len = wc_len + 2;
  202007. swprintf(wc_buf, TEXT("%12.12e"), height);
  202008. wc_len = wcslen(wc_buf);
  202009. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202010. NULL, NULL);
  202011. total_len += wc_len;
  202012. }
  202013. #else
  202014. png_snprintf(buf + 1, 63, "%12.12e", width);
  202015. total_len = 1 + png_strlen(buf + 1) + 1;
  202016. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202017. total_len += png_strlen(buf + total_len);
  202018. #endif
  202019. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202020. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202021. }
  202022. #else
  202023. #ifdef PNG_FIXED_POINT_SUPPORTED
  202024. void /* PRIVATE */
  202025. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202026. png_charp height)
  202027. {
  202028. #ifdef PNG_USE_LOCAL_ARRAYS
  202029. PNG_sCAL;
  202030. #endif
  202031. png_byte buf[64];
  202032. png_size_t wlen, hlen, total_len;
  202033. png_debug(1, "in png_write_sCAL_s\n");
  202034. wlen = png_strlen(width);
  202035. hlen = png_strlen(height);
  202036. total_len = wlen + hlen + 2;
  202037. if (total_len > 64)
  202038. {
  202039. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202040. return;
  202041. }
  202042. buf[0] = (png_byte)unit;
  202043. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202044. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202045. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202046. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202047. }
  202048. #endif
  202049. #endif
  202050. #endif
  202051. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202052. /* write the pHYs chunk */
  202053. void /* PRIVATE */
  202054. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202055. png_uint_32 y_pixels_per_unit,
  202056. int unit_type)
  202057. {
  202058. #ifdef PNG_USE_LOCAL_ARRAYS
  202059. PNG_pHYs;
  202060. #endif
  202061. png_byte buf[9];
  202062. png_debug(1, "in png_write_pHYs\n");
  202063. if (unit_type >= PNG_RESOLUTION_LAST)
  202064. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202065. png_save_uint_32(buf, x_pixels_per_unit);
  202066. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202067. buf[8] = (png_byte)unit_type;
  202068. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202069. }
  202070. #endif
  202071. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202072. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202073. * or png_convert_from_time_t(), or fill in the structure yourself.
  202074. */
  202075. void /* PRIVATE */
  202076. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202077. {
  202078. #ifdef PNG_USE_LOCAL_ARRAYS
  202079. PNG_tIME;
  202080. #endif
  202081. png_byte buf[7];
  202082. png_debug(1, "in png_write_tIME\n");
  202083. if (mod_time->month > 12 || mod_time->month < 1 ||
  202084. mod_time->day > 31 || mod_time->day < 1 ||
  202085. mod_time->hour > 23 || mod_time->second > 60)
  202086. {
  202087. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202088. return;
  202089. }
  202090. png_save_uint_16(buf, mod_time->year);
  202091. buf[2] = mod_time->month;
  202092. buf[3] = mod_time->day;
  202093. buf[4] = mod_time->hour;
  202094. buf[5] = mod_time->minute;
  202095. buf[6] = mod_time->second;
  202096. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202097. }
  202098. #endif
  202099. /* initializes the row writing capability of libpng */
  202100. void /* PRIVATE */
  202101. png_write_start_row(png_structp png_ptr)
  202102. {
  202103. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202104. #ifdef PNG_USE_LOCAL_ARRAYS
  202105. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202106. /* start of interlace block */
  202107. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202108. /* offset to next interlace block */
  202109. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202110. /* start of interlace block in the y direction */
  202111. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202112. /* offset to next interlace block in the y direction */
  202113. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202114. #endif
  202115. #endif
  202116. png_size_t buf_size;
  202117. png_debug(1, "in png_write_start_row\n");
  202118. buf_size = (png_size_t)(PNG_ROWBYTES(
  202119. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202120. /* set up row buffer */
  202121. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202122. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202123. #ifndef PNG_NO_WRITE_FILTERING
  202124. /* set up filtering buffer, if using this filter */
  202125. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202126. {
  202127. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202128. (png_ptr->rowbytes + 1));
  202129. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202130. }
  202131. /* We only need to keep the previous row if we are using one of these. */
  202132. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202133. {
  202134. /* set up previous row buffer */
  202135. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202136. png_memset(png_ptr->prev_row, 0, buf_size);
  202137. if (png_ptr->do_filter & PNG_FILTER_UP)
  202138. {
  202139. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202140. (png_ptr->rowbytes + 1));
  202141. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202142. }
  202143. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202144. {
  202145. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202146. (png_ptr->rowbytes + 1));
  202147. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202148. }
  202149. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202150. {
  202151. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202152. (png_ptr->rowbytes + 1));
  202153. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202154. }
  202155. #endif /* PNG_NO_WRITE_FILTERING */
  202156. }
  202157. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202158. /* if interlaced, we need to set up width and height of pass */
  202159. if (png_ptr->interlaced)
  202160. {
  202161. if (!(png_ptr->transformations & PNG_INTERLACE))
  202162. {
  202163. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202164. png_pass_ystart[0]) / png_pass_yinc[0];
  202165. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202166. png_pass_start[0]) / png_pass_inc[0];
  202167. }
  202168. else
  202169. {
  202170. png_ptr->num_rows = png_ptr->height;
  202171. png_ptr->usr_width = png_ptr->width;
  202172. }
  202173. }
  202174. else
  202175. #endif
  202176. {
  202177. png_ptr->num_rows = png_ptr->height;
  202178. png_ptr->usr_width = png_ptr->width;
  202179. }
  202180. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202181. png_ptr->zstream.next_out = png_ptr->zbuf;
  202182. }
  202183. /* Internal use only. Called when finished processing a row of data. */
  202184. void /* PRIVATE */
  202185. png_write_finish_row(png_structp png_ptr)
  202186. {
  202187. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202188. #ifdef PNG_USE_LOCAL_ARRAYS
  202189. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202190. /* start of interlace block */
  202191. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202192. /* offset to next interlace block */
  202193. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202194. /* start of interlace block in the y direction */
  202195. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202196. /* offset to next interlace block in the y direction */
  202197. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202198. #endif
  202199. #endif
  202200. int ret;
  202201. png_debug(1, "in png_write_finish_row\n");
  202202. /* next row */
  202203. png_ptr->row_number++;
  202204. /* see if we are done */
  202205. if (png_ptr->row_number < png_ptr->num_rows)
  202206. return;
  202207. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202208. /* if interlaced, go to next pass */
  202209. if (png_ptr->interlaced)
  202210. {
  202211. png_ptr->row_number = 0;
  202212. if (png_ptr->transformations & PNG_INTERLACE)
  202213. {
  202214. png_ptr->pass++;
  202215. }
  202216. else
  202217. {
  202218. /* loop until we find a non-zero width or height pass */
  202219. do
  202220. {
  202221. png_ptr->pass++;
  202222. if (png_ptr->pass >= 7)
  202223. break;
  202224. png_ptr->usr_width = (png_ptr->width +
  202225. png_pass_inc[png_ptr->pass] - 1 -
  202226. png_pass_start[png_ptr->pass]) /
  202227. png_pass_inc[png_ptr->pass];
  202228. png_ptr->num_rows = (png_ptr->height +
  202229. png_pass_yinc[png_ptr->pass] - 1 -
  202230. png_pass_ystart[png_ptr->pass]) /
  202231. png_pass_yinc[png_ptr->pass];
  202232. if (png_ptr->transformations & PNG_INTERLACE)
  202233. break;
  202234. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202235. }
  202236. /* reset the row above the image for the next pass */
  202237. if (png_ptr->pass < 7)
  202238. {
  202239. if (png_ptr->prev_row != NULL)
  202240. png_memset(png_ptr->prev_row, 0,
  202241. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202242. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202243. return;
  202244. }
  202245. }
  202246. #endif
  202247. /* if we get here, we've just written the last row, so we need
  202248. to flush the compressor */
  202249. do
  202250. {
  202251. /* tell the compressor we are done */
  202252. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202253. /* check for an error */
  202254. if (ret == Z_OK)
  202255. {
  202256. /* check to see if we need more room */
  202257. if (!(png_ptr->zstream.avail_out))
  202258. {
  202259. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202260. png_ptr->zstream.next_out = png_ptr->zbuf;
  202261. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202262. }
  202263. }
  202264. else if (ret != Z_STREAM_END)
  202265. {
  202266. if (png_ptr->zstream.msg != NULL)
  202267. png_error(png_ptr, png_ptr->zstream.msg);
  202268. else
  202269. png_error(png_ptr, "zlib error");
  202270. }
  202271. } while (ret != Z_STREAM_END);
  202272. /* write any extra space */
  202273. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202274. {
  202275. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202276. png_ptr->zstream.avail_out);
  202277. }
  202278. deflateReset(&png_ptr->zstream);
  202279. png_ptr->zstream.data_type = Z_BINARY;
  202280. }
  202281. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202282. /* Pick out the correct pixels for the interlace pass.
  202283. * The basic idea here is to go through the row with a source
  202284. * pointer and a destination pointer (sp and dp), and copy the
  202285. * correct pixels for the pass. As the row gets compacted,
  202286. * sp will always be >= dp, so we should never overwrite anything.
  202287. * See the default: case for the easiest code to understand.
  202288. */
  202289. void /* PRIVATE */
  202290. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202291. {
  202292. #ifdef PNG_USE_LOCAL_ARRAYS
  202293. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202294. /* start of interlace block */
  202295. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202296. /* offset to next interlace block */
  202297. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202298. #endif
  202299. png_debug(1, "in png_do_write_interlace\n");
  202300. /* we don't have to do anything on the last pass (6) */
  202301. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202302. if (row != NULL && row_info != NULL && pass < 6)
  202303. #else
  202304. if (pass < 6)
  202305. #endif
  202306. {
  202307. /* each pixel depth is handled separately */
  202308. switch (row_info->pixel_depth)
  202309. {
  202310. case 1:
  202311. {
  202312. png_bytep sp;
  202313. png_bytep dp;
  202314. int shift;
  202315. int d;
  202316. int value;
  202317. png_uint_32 i;
  202318. png_uint_32 row_width = row_info->width;
  202319. dp = row;
  202320. d = 0;
  202321. shift = 7;
  202322. for (i = png_pass_start[pass]; i < row_width;
  202323. i += png_pass_inc[pass])
  202324. {
  202325. sp = row + (png_size_t)(i >> 3);
  202326. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202327. d |= (value << shift);
  202328. if (shift == 0)
  202329. {
  202330. shift = 7;
  202331. *dp++ = (png_byte)d;
  202332. d = 0;
  202333. }
  202334. else
  202335. shift--;
  202336. }
  202337. if (shift != 7)
  202338. *dp = (png_byte)d;
  202339. break;
  202340. }
  202341. case 2:
  202342. {
  202343. png_bytep sp;
  202344. png_bytep dp;
  202345. int shift;
  202346. int d;
  202347. int value;
  202348. png_uint_32 i;
  202349. png_uint_32 row_width = row_info->width;
  202350. dp = row;
  202351. shift = 6;
  202352. d = 0;
  202353. for (i = png_pass_start[pass]; i < row_width;
  202354. i += png_pass_inc[pass])
  202355. {
  202356. sp = row + (png_size_t)(i >> 2);
  202357. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202358. d |= (value << shift);
  202359. if (shift == 0)
  202360. {
  202361. shift = 6;
  202362. *dp++ = (png_byte)d;
  202363. d = 0;
  202364. }
  202365. else
  202366. shift -= 2;
  202367. }
  202368. if (shift != 6)
  202369. *dp = (png_byte)d;
  202370. break;
  202371. }
  202372. case 4:
  202373. {
  202374. png_bytep sp;
  202375. png_bytep dp;
  202376. int shift;
  202377. int d;
  202378. int value;
  202379. png_uint_32 i;
  202380. png_uint_32 row_width = row_info->width;
  202381. dp = row;
  202382. shift = 4;
  202383. d = 0;
  202384. for (i = png_pass_start[pass]; i < row_width;
  202385. i += png_pass_inc[pass])
  202386. {
  202387. sp = row + (png_size_t)(i >> 1);
  202388. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202389. d |= (value << shift);
  202390. if (shift == 0)
  202391. {
  202392. shift = 4;
  202393. *dp++ = (png_byte)d;
  202394. d = 0;
  202395. }
  202396. else
  202397. shift -= 4;
  202398. }
  202399. if (shift != 4)
  202400. *dp = (png_byte)d;
  202401. break;
  202402. }
  202403. default:
  202404. {
  202405. png_bytep sp;
  202406. png_bytep dp;
  202407. png_uint_32 i;
  202408. png_uint_32 row_width = row_info->width;
  202409. png_size_t pixel_bytes;
  202410. /* start at the beginning */
  202411. dp = row;
  202412. /* find out how many bytes each pixel takes up */
  202413. pixel_bytes = (row_info->pixel_depth >> 3);
  202414. /* loop through the row, only looking at the pixels that
  202415. matter */
  202416. for (i = png_pass_start[pass]; i < row_width;
  202417. i += png_pass_inc[pass])
  202418. {
  202419. /* find out where the original pixel is */
  202420. sp = row + (png_size_t)i * pixel_bytes;
  202421. /* move the pixel */
  202422. if (dp != sp)
  202423. png_memcpy(dp, sp, pixel_bytes);
  202424. /* next pixel */
  202425. dp += pixel_bytes;
  202426. }
  202427. break;
  202428. }
  202429. }
  202430. /* set new row width */
  202431. row_info->width = (row_info->width +
  202432. png_pass_inc[pass] - 1 -
  202433. png_pass_start[pass]) /
  202434. png_pass_inc[pass];
  202435. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202436. row_info->width);
  202437. }
  202438. }
  202439. #endif
  202440. /* This filters the row, chooses which filter to use, if it has not already
  202441. * been specified by the application, and then writes the row out with the
  202442. * chosen filter.
  202443. */
  202444. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202445. #define PNG_HISHIFT 10
  202446. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202447. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202448. void /* PRIVATE */
  202449. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202450. {
  202451. png_bytep best_row;
  202452. #ifndef PNG_NO_WRITE_FILTER
  202453. png_bytep prev_row, row_buf;
  202454. png_uint_32 mins, bpp;
  202455. png_byte filter_to_do = png_ptr->do_filter;
  202456. png_uint_32 row_bytes = row_info->rowbytes;
  202457. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202458. int num_p_filters = (int)png_ptr->num_prev_filters;
  202459. #endif
  202460. png_debug(1, "in png_write_find_filter\n");
  202461. /* find out how many bytes offset each pixel is */
  202462. bpp = (row_info->pixel_depth + 7) >> 3;
  202463. prev_row = png_ptr->prev_row;
  202464. #endif
  202465. best_row = png_ptr->row_buf;
  202466. #ifndef PNG_NO_WRITE_FILTER
  202467. row_buf = best_row;
  202468. mins = PNG_MAXSUM;
  202469. /* The prediction method we use is to find which method provides the
  202470. * smallest value when summing the absolute values of the distances
  202471. * from zero, using anything >= 128 as negative numbers. This is known
  202472. * as the "minimum sum of absolute differences" heuristic. Other
  202473. * heuristics are the "weighted minimum sum of absolute differences"
  202474. * (experimental and can in theory improve compression), and the "zlib
  202475. * predictive" method (not implemented yet), which does test compressions
  202476. * of lines using different filter methods, and then chooses the
  202477. * (series of) filter(s) that give minimum compressed data size (VERY
  202478. * computationally expensive).
  202479. *
  202480. * GRR 980525: consider also
  202481. * (1) minimum sum of absolute differences from running average (i.e.,
  202482. * keep running sum of non-absolute differences & count of bytes)
  202483. * [track dispersion, too? restart average if dispersion too large?]
  202484. * (1b) minimum sum of absolute differences from sliding average, probably
  202485. * with window size <= deflate window (usually 32K)
  202486. * (2) minimum sum of squared differences from zero or running average
  202487. * (i.e., ~ root-mean-square approach)
  202488. */
  202489. /* We don't need to test the 'no filter' case if this is the only filter
  202490. * that has been chosen, as it doesn't actually do anything to the data.
  202491. */
  202492. if ((filter_to_do & PNG_FILTER_NONE) &&
  202493. filter_to_do != PNG_FILTER_NONE)
  202494. {
  202495. png_bytep rp;
  202496. png_uint_32 sum = 0;
  202497. png_uint_32 i;
  202498. int v;
  202499. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202500. {
  202501. v = *rp;
  202502. sum += (v < 128) ? v : 256 - v;
  202503. }
  202504. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202505. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202506. {
  202507. png_uint_32 sumhi, sumlo;
  202508. int j;
  202509. sumlo = sum & PNG_LOMASK;
  202510. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202511. /* Reduce the sum if we match any of the previous rows */
  202512. for (j = 0; j < num_p_filters; j++)
  202513. {
  202514. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202515. {
  202516. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202517. PNG_WEIGHT_SHIFT;
  202518. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202519. PNG_WEIGHT_SHIFT;
  202520. }
  202521. }
  202522. /* Factor in the cost of this filter (this is here for completeness,
  202523. * but it makes no sense to have a "cost" for the NONE filter, as
  202524. * it has the minimum possible computational cost - none).
  202525. */
  202526. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202527. PNG_COST_SHIFT;
  202528. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202529. PNG_COST_SHIFT;
  202530. if (sumhi > PNG_HIMASK)
  202531. sum = PNG_MAXSUM;
  202532. else
  202533. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202534. }
  202535. #endif
  202536. mins = sum;
  202537. }
  202538. /* sub filter */
  202539. if (filter_to_do == PNG_FILTER_SUB)
  202540. /* it's the only filter so no testing is needed */
  202541. {
  202542. png_bytep rp, lp, dp;
  202543. png_uint_32 i;
  202544. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202545. i++, rp++, dp++)
  202546. {
  202547. *dp = *rp;
  202548. }
  202549. for (lp = row_buf + 1; i < row_bytes;
  202550. i++, rp++, lp++, dp++)
  202551. {
  202552. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202553. }
  202554. best_row = png_ptr->sub_row;
  202555. }
  202556. else if (filter_to_do & PNG_FILTER_SUB)
  202557. {
  202558. png_bytep rp, dp, lp;
  202559. png_uint_32 sum = 0, lmins = mins;
  202560. png_uint_32 i;
  202561. int v;
  202562. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202563. /* We temporarily increase the "minimum sum" by the factor we
  202564. * would reduce the sum of this filter, so that we can do the
  202565. * early exit comparison without scaling the sum each time.
  202566. */
  202567. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202568. {
  202569. int j;
  202570. png_uint_32 lmhi, lmlo;
  202571. lmlo = lmins & PNG_LOMASK;
  202572. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202573. for (j = 0; j < num_p_filters; j++)
  202574. {
  202575. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202576. {
  202577. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202578. PNG_WEIGHT_SHIFT;
  202579. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202580. PNG_WEIGHT_SHIFT;
  202581. }
  202582. }
  202583. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202584. PNG_COST_SHIFT;
  202585. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202586. PNG_COST_SHIFT;
  202587. if (lmhi > PNG_HIMASK)
  202588. lmins = PNG_MAXSUM;
  202589. else
  202590. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202591. }
  202592. #endif
  202593. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202594. i++, rp++, dp++)
  202595. {
  202596. v = *dp = *rp;
  202597. sum += (v < 128) ? v : 256 - v;
  202598. }
  202599. for (lp = row_buf + 1; i < row_bytes;
  202600. i++, rp++, lp++, dp++)
  202601. {
  202602. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202603. sum += (v < 128) ? v : 256 - v;
  202604. if (sum > lmins) /* We are already worse, don't continue. */
  202605. break;
  202606. }
  202607. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202608. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202609. {
  202610. int j;
  202611. png_uint_32 sumhi, sumlo;
  202612. sumlo = sum & PNG_LOMASK;
  202613. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202614. for (j = 0; j < num_p_filters; j++)
  202615. {
  202616. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202617. {
  202618. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202619. PNG_WEIGHT_SHIFT;
  202620. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202621. PNG_WEIGHT_SHIFT;
  202622. }
  202623. }
  202624. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202625. PNG_COST_SHIFT;
  202626. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202627. PNG_COST_SHIFT;
  202628. if (sumhi > PNG_HIMASK)
  202629. sum = PNG_MAXSUM;
  202630. else
  202631. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202632. }
  202633. #endif
  202634. if (sum < mins)
  202635. {
  202636. mins = sum;
  202637. best_row = png_ptr->sub_row;
  202638. }
  202639. }
  202640. /* up filter */
  202641. if (filter_to_do == PNG_FILTER_UP)
  202642. {
  202643. png_bytep rp, dp, pp;
  202644. png_uint_32 i;
  202645. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202646. pp = prev_row + 1; i < row_bytes;
  202647. i++, rp++, pp++, dp++)
  202648. {
  202649. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202650. }
  202651. best_row = png_ptr->up_row;
  202652. }
  202653. else if (filter_to_do & PNG_FILTER_UP)
  202654. {
  202655. png_bytep rp, dp, pp;
  202656. png_uint_32 sum = 0, lmins = mins;
  202657. png_uint_32 i;
  202658. int v;
  202659. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202660. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202661. {
  202662. int j;
  202663. png_uint_32 lmhi, lmlo;
  202664. lmlo = lmins & PNG_LOMASK;
  202665. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202666. for (j = 0; j < num_p_filters; j++)
  202667. {
  202668. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202669. {
  202670. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202671. PNG_WEIGHT_SHIFT;
  202672. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202673. PNG_WEIGHT_SHIFT;
  202674. }
  202675. }
  202676. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202677. PNG_COST_SHIFT;
  202678. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202679. PNG_COST_SHIFT;
  202680. if (lmhi > PNG_HIMASK)
  202681. lmins = PNG_MAXSUM;
  202682. else
  202683. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202684. }
  202685. #endif
  202686. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202687. pp = prev_row + 1; i < row_bytes; i++)
  202688. {
  202689. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202690. sum += (v < 128) ? v : 256 - v;
  202691. if (sum > lmins) /* We are already worse, don't continue. */
  202692. break;
  202693. }
  202694. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202695. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202696. {
  202697. int j;
  202698. png_uint_32 sumhi, sumlo;
  202699. sumlo = sum & PNG_LOMASK;
  202700. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202701. for (j = 0; j < num_p_filters; j++)
  202702. {
  202703. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202704. {
  202705. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202706. PNG_WEIGHT_SHIFT;
  202707. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202708. PNG_WEIGHT_SHIFT;
  202709. }
  202710. }
  202711. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202712. PNG_COST_SHIFT;
  202713. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202714. PNG_COST_SHIFT;
  202715. if (sumhi > PNG_HIMASK)
  202716. sum = PNG_MAXSUM;
  202717. else
  202718. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202719. }
  202720. #endif
  202721. if (sum < mins)
  202722. {
  202723. mins = sum;
  202724. best_row = png_ptr->up_row;
  202725. }
  202726. }
  202727. /* avg filter */
  202728. if (filter_to_do == PNG_FILTER_AVG)
  202729. {
  202730. png_bytep rp, dp, pp, lp;
  202731. png_uint_32 i;
  202732. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202733. pp = prev_row + 1; i < bpp; i++)
  202734. {
  202735. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202736. }
  202737. for (lp = row_buf + 1; i < row_bytes; i++)
  202738. {
  202739. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202740. & 0xff);
  202741. }
  202742. best_row = png_ptr->avg_row;
  202743. }
  202744. else if (filter_to_do & PNG_FILTER_AVG)
  202745. {
  202746. png_bytep rp, dp, pp, lp;
  202747. png_uint_32 sum = 0, lmins = mins;
  202748. png_uint_32 i;
  202749. int v;
  202750. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202751. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202752. {
  202753. int j;
  202754. png_uint_32 lmhi, lmlo;
  202755. lmlo = lmins & PNG_LOMASK;
  202756. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202757. for (j = 0; j < num_p_filters; j++)
  202758. {
  202759. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202760. {
  202761. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202762. PNG_WEIGHT_SHIFT;
  202763. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202764. PNG_WEIGHT_SHIFT;
  202765. }
  202766. }
  202767. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202768. PNG_COST_SHIFT;
  202769. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202770. PNG_COST_SHIFT;
  202771. if (lmhi > PNG_HIMASK)
  202772. lmins = PNG_MAXSUM;
  202773. else
  202774. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202775. }
  202776. #endif
  202777. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202778. pp = prev_row + 1; i < bpp; i++)
  202779. {
  202780. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202781. sum += (v < 128) ? v : 256 - v;
  202782. }
  202783. for (lp = row_buf + 1; i < row_bytes; i++)
  202784. {
  202785. v = *dp++ =
  202786. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202787. sum += (v < 128) ? v : 256 - v;
  202788. if (sum > lmins) /* We are already worse, don't continue. */
  202789. break;
  202790. }
  202791. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202792. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202793. {
  202794. int j;
  202795. png_uint_32 sumhi, sumlo;
  202796. sumlo = sum & PNG_LOMASK;
  202797. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202798. for (j = 0; j < num_p_filters; j++)
  202799. {
  202800. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202801. {
  202802. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202803. PNG_WEIGHT_SHIFT;
  202804. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202805. PNG_WEIGHT_SHIFT;
  202806. }
  202807. }
  202808. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202809. PNG_COST_SHIFT;
  202810. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202811. PNG_COST_SHIFT;
  202812. if (sumhi > PNG_HIMASK)
  202813. sum = PNG_MAXSUM;
  202814. else
  202815. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202816. }
  202817. #endif
  202818. if (sum < mins)
  202819. {
  202820. mins = sum;
  202821. best_row = png_ptr->avg_row;
  202822. }
  202823. }
  202824. /* Paeth filter */
  202825. if (filter_to_do == PNG_FILTER_PAETH)
  202826. {
  202827. png_bytep rp, dp, pp, cp, lp;
  202828. png_uint_32 i;
  202829. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202830. pp = prev_row + 1; i < bpp; i++)
  202831. {
  202832. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202833. }
  202834. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202835. {
  202836. int a, b, c, pa, pb, pc, p;
  202837. b = *pp++;
  202838. c = *cp++;
  202839. a = *lp++;
  202840. p = b - c;
  202841. pc = a - c;
  202842. #ifdef PNG_USE_ABS
  202843. pa = abs(p);
  202844. pb = abs(pc);
  202845. pc = abs(p + pc);
  202846. #else
  202847. pa = p < 0 ? -p : p;
  202848. pb = pc < 0 ? -pc : pc;
  202849. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202850. #endif
  202851. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202852. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202853. }
  202854. best_row = png_ptr->paeth_row;
  202855. }
  202856. else if (filter_to_do & PNG_FILTER_PAETH)
  202857. {
  202858. png_bytep rp, dp, pp, cp, lp;
  202859. png_uint_32 sum = 0, lmins = mins;
  202860. png_uint_32 i;
  202861. int v;
  202862. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202863. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202864. {
  202865. int j;
  202866. png_uint_32 lmhi, lmlo;
  202867. lmlo = lmins & PNG_LOMASK;
  202868. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202869. for (j = 0; j < num_p_filters; j++)
  202870. {
  202871. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202872. {
  202873. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202874. PNG_WEIGHT_SHIFT;
  202875. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202876. PNG_WEIGHT_SHIFT;
  202877. }
  202878. }
  202879. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202880. PNG_COST_SHIFT;
  202881. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202882. PNG_COST_SHIFT;
  202883. if (lmhi > PNG_HIMASK)
  202884. lmins = PNG_MAXSUM;
  202885. else
  202886. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202887. }
  202888. #endif
  202889. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202890. pp = prev_row + 1; i < bpp; i++)
  202891. {
  202892. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202893. sum += (v < 128) ? v : 256 - v;
  202894. }
  202895. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202896. {
  202897. int a, b, c, pa, pb, pc, p;
  202898. b = *pp++;
  202899. c = *cp++;
  202900. a = *lp++;
  202901. #ifndef PNG_SLOW_PAETH
  202902. p = b - c;
  202903. pc = a - c;
  202904. #ifdef PNG_USE_ABS
  202905. pa = abs(p);
  202906. pb = abs(pc);
  202907. pc = abs(p + pc);
  202908. #else
  202909. pa = p < 0 ? -p : p;
  202910. pb = pc < 0 ? -pc : pc;
  202911. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202912. #endif
  202913. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202914. #else /* PNG_SLOW_PAETH */
  202915. p = a + b - c;
  202916. pa = abs(p - a);
  202917. pb = abs(p - b);
  202918. pc = abs(p - c);
  202919. if (pa <= pb && pa <= pc)
  202920. p = a;
  202921. else if (pb <= pc)
  202922. p = b;
  202923. else
  202924. p = c;
  202925. #endif /* PNG_SLOW_PAETH */
  202926. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202927. sum += (v < 128) ? v : 256 - v;
  202928. if (sum > lmins) /* We are already worse, don't continue. */
  202929. break;
  202930. }
  202931. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202932. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202933. {
  202934. int j;
  202935. png_uint_32 sumhi, sumlo;
  202936. sumlo = sum & PNG_LOMASK;
  202937. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202938. for (j = 0; j < num_p_filters; j++)
  202939. {
  202940. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202941. {
  202942. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202943. PNG_WEIGHT_SHIFT;
  202944. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202945. PNG_WEIGHT_SHIFT;
  202946. }
  202947. }
  202948. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202949. PNG_COST_SHIFT;
  202950. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202951. PNG_COST_SHIFT;
  202952. if (sumhi > PNG_HIMASK)
  202953. sum = PNG_MAXSUM;
  202954. else
  202955. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202956. }
  202957. #endif
  202958. if (sum < mins)
  202959. {
  202960. best_row = png_ptr->paeth_row;
  202961. }
  202962. }
  202963. #endif /* PNG_NO_WRITE_FILTER */
  202964. /* Do the actual writing of the filtered row data from the chosen filter. */
  202965. png_write_filtered_row(png_ptr, best_row);
  202966. #ifndef PNG_NO_WRITE_FILTER
  202967. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202968. /* Save the type of filter we picked this time for future calculations */
  202969. if (png_ptr->num_prev_filters > 0)
  202970. {
  202971. int j;
  202972. for (j = 1; j < num_p_filters; j++)
  202973. {
  202974. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202975. }
  202976. png_ptr->prev_filters[j] = best_row[0];
  202977. }
  202978. #endif
  202979. #endif /* PNG_NO_WRITE_FILTER */
  202980. }
  202981. /* Do the actual writing of a previously filtered row. */
  202982. void /* PRIVATE */
  202983. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202984. {
  202985. png_debug(1, "in png_write_filtered_row\n");
  202986. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202987. /* set up the zlib input buffer */
  202988. png_ptr->zstream.next_in = filtered_row;
  202989. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202990. /* repeat until we have compressed all the data */
  202991. do
  202992. {
  202993. int ret; /* return of zlib */
  202994. /* compress the data */
  202995. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202996. /* check for compression errors */
  202997. if (ret != Z_OK)
  202998. {
  202999. if (png_ptr->zstream.msg != NULL)
  203000. png_error(png_ptr, png_ptr->zstream.msg);
  203001. else
  203002. png_error(png_ptr, "zlib error");
  203003. }
  203004. /* see if it is time to write another IDAT */
  203005. if (!(png_ptr->zstream.avail_out))
  203006. {
  203007. /* write the IDAT and reset the zlib output buffer */
  203008. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203009. png_ptr->zstream.next_out = png_ptr->zbuf;
  203010. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203011. }
  203012. /* repeat until all data has been compressed */
  203013. } while (png_ptr->zstream.avail_in);
  203014. /* swap the current and previous rows */
  203015. if (png_ptr->prev_row != NULL)
  203016. {
  203017. png_bytep tptr;
  203018. tptr = png_ptr->prev_row;
  203019. png_ptr->prev_row = png_ptr->row_buf;
  203020. png_ptr->row_buf = tptr;
  203021. }
  203022. /* finish row - updates counters and flushes zlib if last row */
  203023. png_write_finish_row(png_ptr);
  203024. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203025. png_ptr->flush_rows++;
  203026. if (png_ptr->flush_dist > 0 &&
  203027. png_ptr->flush_rows >= png_ptr->flush_dist)
  203028. {
  203029. png_write_flush(png_ptr);
  203030. }
  203031. #endif
  203032. }
  203033. #endif /* PNG_WRITE_SUPPORTED */
  203034. /*** End of inlined file: pngwutil.c ***/
  203035. #else
  203036. extern "C"
  203037. {
  203038. #include <png.h>
  203039. #include <pngconf.h>
  203040. }
  203041. #endif
  203042. }
  203043. #undef max
  203044. #undef min
  203045. #if JUCE_MSVC
  203046. #pragma warning (pop)
  203047. #endif
  203048. BEGIN_JUCE_NAMESPACE
  203049. using ::calloc;
  203050. using ::malloc;
  203051. using ::free;
  203052. namespace PNGHelpers
  203053. {
  203054. using namespace pnglibNamespace;
  203055. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203056. {
  203057. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203058. }
  203059. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203060. {
  203061. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203062. }
  203063. struct PNGErrorStruct {};
  203064. static void errorCallback (png_structp, png_const_charp)
  203065. {
  203066. throw PNGErrorStruct();
  203067. }
  203068. }
  203069. PNGImageFormat::PNGImageFormat() {}
  203070. PNGImageFormat::~PNGImageFormat() {}
  203071. const String PNGImageFormat::getFormatName()
  203072. {
  203073. return "PNG";
  203074. }
  203075. bool PNGImageFormat::canUnderstand (InputStream& in)
  203076. {
  203077. const int bytesNeeded = 4;
  203078. char header [bytesNeeded];
  203079. return in.read (header, bytesNeeded) == bytesNeeded
  203080. && header[1] == 'P'
  203081. && header[2] == 'N'
  203082. && header[3] == 'G';
  203083. }
  203084. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203085. const Image juce_loadWithCoreImage (InputStream& input);
  203086. #endif
  203087. const Image PNGImageFormat::decodeImage (InputStream& in)
  203088. {
  203089. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203090. return juce_loadWithCoreImage (in);
  203091. #else
  203092. using namespace pnglibNamespace;
  203093. Image image;
  203094. png_structp pngReadStruct;
  203095. png_infop pngInfoStruct;
  203096. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203097. if (pngReadStruct != 0)
  203098. {
  203099. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203100. if (pngInfoStruct == 0)
  203101. {
  203102. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203103. return Image::null;
  203104. }
  203105. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203106. // read the header..
  203107. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203108. png_uint_32 width, height;
  203109. int bitDepth, colorType, interlaceType;
  203110. png_read_info (pngReadStruct, pngInfoStruct);
  203111. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203112. &width, &height,
  203113. &bitDepth, &colorType,
  203114. &interlaceType, 0, 0);
  203115. if (bitDepth == 16)
  203116. png_set_strip_16 (pngReadStruct);
  203117. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203118. png_set_expand (pngReadStruct);
  203119. if (bitDepth < 8)
  203120. png_set_expand (pngReadStruct);
  203121. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203122. png_set_expand (pngReadStruct);
  203123. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203124. png_set_gray_to_rgb (pngReadStruct);
  203125. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203126. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203127. || pngInfoStruct->num_trans > 0;
  203128. // Load the image into a temp buffer in the pnglib format..
  203129. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203130. {
  203131. HeapBlock <png_bytep> rows (height);
  203132. for (int y = (int) height; --y >= 0;)
  203133. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203134. png_read_image (pngReadStruct, rows);
  203135. png_read_end (pngReadStruct, pngInfoStruct);
  203136. }
  203137. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203138. // now convert the data to a juce image format..
  203139. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203140. (int) width, (int) height, hasAlphaChan);
  203141. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203142. const Image::BitmapData destData (image, true);
  203143. uint8* srcRow = tempBuffer;
  203144. uint8* destRow = destData.data;
  203145. for (int y = 0; y < (int) height; ++y)
  203146. {
  203147. const uint8* src = srcRow;
  203148. srcRow += (width << 2);
  203149. uint8* dest = destRow;
  203150. destRow += destData.lineStride;
  203151. if (hasAlphaChan)
  203152. {
  203153. for (int i = (int) width; --i >= 0;)
  203154. {
  203155. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203156. ((PixelARGB*) dest)->premultiply();
  203157. dest += destData.pixelStride;
  203158. src += 4;
  203159. }
  203160. }
  203161. else
  203162. {
  203163. for (int i = (int) width; --i >= 0;)
  203164. {
  203165. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203166. dest += destData.pixelStride;
  203167. src += 4;
  203168. }
  203169. }
  203170. }
  203171. }
  203172. return image;
  203173. #endif
  203174. }
  203175. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203176. {
  203177. using namespace pnglibNamespace;
  203178. const int width = image.getWidth();
  203179. const int height = image.getHeight();
  203180. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203181. if (pngWriteStruct == 0)
  203182. return false;
  203183. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203184. if (pngInfoStruct == 0)
  203185. {
  203186. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203187. return false;
  203188. }
  203189. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203190. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203191. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203192. : PNG_COLOR_TYPE_RGB,
  203193. PNG_INTERLACE_NONE,
  203194. PNG_COMPRESSION_TYPE_BASE,
  203195. PNG_FILTER_TYPE_BASE);
  203196. HeapBlock <uint8> rowData (width * 4);
  203197. png_color_8 sig_bit;
  203198. sig_bit.red = 8;
  203199. sig_bit.green = 8;
  203200. sig_bit.blue = 8;
  203201. sig_bit.alpha = 8;
  203202. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203203. png_write_info (pngWriteStruct, pngInfoStruct);
  203204. png_set_shift (pngWriteStruct, &sig_bit);
  203205. png_set_packing (pngWriteStruct);
  203206. const Image::BitmapData srcData (image, false);
  203207. for (int y = 0; y < height; ++y)
  203208. {
  203209. uint8* dst = rowData;
  203210. const uint8* src = srcData.getLinePointer (y);
  203211. if (image.hasAlphaChannel())
  203212. {
  203213. for (int i = width; --i >= 0;)
  203214. {
  203215. PixelARGB p (*(const PixelARGB*) src);
  203216. p.unpremultiply();
  203217. *dst++ = p.getRed();
  203218. *dst++ = p.getGreen();
  203219. *dst++ = p.getBlue();
  203220. *dst++ = p.getAlpha();
  203221. src += srcData.pixelStride;
  203222. }
  203223. }
  203224. else
  203225. {
  203226. for (int i = width; --i >= 0;)
  203227. {
  203228. *dst++ = ((const PixelRGB*) src)->getRed();
  203229. *dst++ = ((const PixelRGB*) src)->getGreen();
  203230. *dst++ = ((const PixelRGB*) src)->getBlue();
  203231. src += srcData.pixelStride;
  203232. }
  203233. }
  203234. png_write_rows (pngWriteStruct, &rowData, 1);
  203235. }
  203236. png_write_end (pngWriteStruct, pngInfoStruct);
  203237. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203238. out.flush();
  203239. return true;
  203240. }
  203241. END_JUCE_NAMESPACE
  203242. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203243. #endif
  203244. //==============================================================================
  203245. #if JUCE_BUILD_NATIVE
  203246. #if JUCE_WINDOWS
  203247. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203248. /*
  203249. This file wraps together all the win32-specific code, so that
  203250. we can include all the native headers just once, and compile all our
  203251. platform-specific stuff in one big lump, keeping it out of the way of
  203252. the rest of the codebase.
  203253. */
  203254. #if JUCE_WINDOWS
  203255. BEGIN_JUCE_NAMESPACE
  203256. #define JUCE_INCLUDED_FILE 1
  203257. // Now include the actual code files..
  203258. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203259. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203260. // compiled on its own).
  203261. #if JUCE_INCLUDED_FILE
  203262. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203263. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203264. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203265. #ifndef DOXYGEN
  203266. // use with DynamicLibraryLoader to simplify importing functions
  203267. //
  203268. // functionName: function to import
  203269. // localFunctionName: name you want to use to actually call it (must be different)
  203270. // returnType: the return type
  203271. // object: the DynamicLibraryLoader to use
  203272. // params: list of params (bracketed)
  203273. //
  203274. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203275. typedef returnType (WINAPI *type##localFunctionName) params; \
  203276. type##localFunctionName localFunctionName \
  203277. = (type##localFunctionName)object.findProcAddress (#functionName);
  203278. // loads and unloads a DLL automatically
  203279. class JUCE_API DynamicLibraryLoader
  203280. {
  203281. public:
  203282. DynamicLibraryLoader (const String& name);
  203283. ~DynamicLibraryLoader();
  203284. void* findProcAddress (const String& functionName);
  203285. private:
  203286. void* libHandle;
  203287. };
  203288. #endif
  203289. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203290. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203291. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203292. {
  203293. libHandle = LoadLibrary (name);
  203294. }
  203295. DynamicLibraryLoader::~DynamicLibraryLoader()
  203296. {
  203297. FreeLibrary ((HMODULE) libHandle);
  203298. }
  203299. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203300. {
  203301. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  203302. }
  203303. #endif
  203304. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203305. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203306. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203307. // compiled on its own).
  203308. #if JUCE_INCLUDED_FILE
  203309. extern void juce_initialiseThreadEvents();
  203310. void Logger::outputDebugString (const String& text)
  203311. {
  203312. OutputDebugString (text + "\n");
  203313. }
  203314. static int64 hiResTicksPerSecond;
  203315. static double hiResTicksScaleFactor;
  203316. #if JUCE_USE_INTRINSICS
  203317. // CPU info functions using intrinsics...
  203318. #pragma intrinsic (__cpuid)
  203319. #pragma intrinsic (__rdtsc)
  203320. const String SystemStats::getCpuVendor()
  203321. {
  203322. int info [4];
  203323. __cpuid (info, 0);
  203324. char v [12];
  203325. memcpy (v, info + 1, 4);
  203326. memcpy (v + 4, info + 3, 4);
  203327. memcpy (v + 8, info + 2, 4);
  203328. return String (v, 12);
  203329. }
  203330. #else
  203331. // CPU info functions using old fashioned inline asm...
  203332. static void juce_getCpuVendor (char* const v)
  203333. {
  203334. int vendor[4];
  203335. zeromem (vendor, 16);
  203336. #ifdef JUCE_64BIT
  203337. #else
  203338. #ifndef __MINGW32__
  203339. __try
  203340. #endif
  203341. {
  203342. #if JUCE_GCC
  203343. unsigned int dummy = 0;
  203344. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203345. #else
  203346. __asm
  203347. {
  203348. mov eax, 0
  203349. cpuid
  203350. mov [vendor], ebx
  203351. mov [vendor + 4], edx
  203352. mov [vendor + 8], ecx
  203353. }
  203354. #endif
  203355. }
  203356. #ifndef __MINGW32__
  203357. __except (EXCEPTION_EXECUTE_HANDLER)
  203358. {
  203359. *v = 0;
  203360. }
  203361. #endif
  203362. #endif
  203363. memcpy (v, vendor, 16);
  203364. }
  203365. const String SystemStats::getCpuVendor()
  203366. {
  203367. char v [16];
  203368. juce_getCpuVendor (v);
  203369. return String (v, 16);
  203370. }
  203371. #endif
  203372. void SystemStats::initialiseStats()
  203373. {
  203374. juce_initialiseThreadEvents();
  203375. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203376. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203377. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203378. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203379. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203380. #else
  203381. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203382. #endif
  203383. {
  203384. SYSTEM_INFO systemInfo;
  203385. GetSystemInfo (&systemInfo);
  203386. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203387. }
  203388. LARGE_INTEGER f;
  203389. QueryPerformanceFrequency (&f);
  203390. hiResTicksPerSecond = f.QuadPart;
  203391. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203392. String s (SystemStats::getJUCEVersion());
  203393. const MMRESULT res = timeBeginPeriod (1);
  203394. (void) res;
  203395. jassert (res == TIMERR_NOERROR);
  203396. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203397. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203398. #endif
  203399. }
  203400. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203401. {
  203402. OSVERSIONINFO info;
  203403. info.dwOSVersionInfoSize = sizeof (info);
  203404. GetVersionEx (&info);
  203405. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203406. {
  203407. switch (info.dwMajorVersion)
  203408. {
  203409. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203410. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203411. default: jassertfalse; break; // !! not a supported OS!
  203412. }
  203413. }
  203414. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203415. {
  203416. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203417. return Win98;
  203418. }
  203419. return UnknownOS;
  203420. }
  203421. const String SystemStats::getOperatingSystemName()
  203422. {
  203423. const char* name = "Unknown OS";
  203424. switch (getOperatingSystemType())
  203425. {
  203426. case Windows7: name = "Windows 7"; break;
  203427. case WinVista: name = "Windows Vista"; break;
  203428. case WinXP: name = "Windows XP"; break;
  203429. case Win2000: name = "Windows 2000"; break;
  203430. case Win98: name = "Windows 98"; break;
  203431. default: jassertfalse; break; // !! new type of OS?
  203432. }
  203433. return name;
  203434. }
  203435. bool SystemStats::isOperatingSystem64Bit()
  203436. {
  203437. #ifdef _WIN64
  203438. return true;
  203439. #else
  203440. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203441. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203442. BOOL isWow64 = FALSE;
  203443. return (fnIsWow64Process != 0)
  203444. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203445. && (isWow64 != FALSE);
  203446. #endif
  203447. }
  203448. int SystemStats::getMemorySizeInMegabytes()
  203449. {
  203450. MEMORYSTATUSEX mem;
  203451. mem.dwLength = sizeof (mem);
  203452. GlobalMemoryStatusEx (&mem);
  203453. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203454. }
  203455. uint32 juce_millisecondsSinceStartup() throw()
  203456. {
  203457. return (uint32) GetTickCount();
  203458. }
  203459. int64 Time::getHighResolutionTicks() throw()
  203460. {
  203461. LARGE_INTEGER ticks;
  203462. QueryPerformanceCounter (&ticks);
  203463. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203464. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203465. // fix for a very obscure PCI hardware bug that can make the counter
  203466. // sometimes jump forwards by a few seconds..
  203467. static int64 hiResTicksOffset = 0;
  203468. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203469. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203470. hiResTicksOffset = newOffset;
  203471. return ticks.QuadPart + hiResTicksOffset;
  203472. }
  203473. double Time::getMillisecondCounterHiRes() throw()
  203474. {
  203475. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203476. }
  203477. int64 Time::getHighResolutionTicksPerSecond() throw()
  203478. {
  203479. return hiResTicksPerSecond;
  203480. }
  203481. static int64 juce_getClockCycleCounter() throw()
  203482. {
  203483. #if JUCE_USE_INTRINSICS
  203484. // MS intrinsics version...
  203485. return __rdtsc();
  203486. #elif JUCE_GCC
  203487. // GNU inline asm version...
  203488. unsigned int hi = 0, lo = 0;
  203489. __asm__ __volatile__ (
  203490. "xor %%eax, %%eax \n\
  203491. xor %%edx, %%edx \n\
  203492. rdtsc \n\
  203493. movl %%eax, %[lo] \n\
  203494. movl %%edx, %[hi]"
  203495. :
  203496. : [hi] "m" (hi),
  203497. [lo] "m" (lo)
  203498. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203499. return (int64) ((((uint64) hi) << 32) | lo);
  203500. #else
  203501. // MSVC inline asm version...
  203502. unsigned int hi = 0, lo = 0;
  203503. __asm
  203504. {
  203505. xor eax, eax
  203506. xor edx, edx
  203507. rdtsc
  203508. mov lo, eax
  203509. mov hi, edx
  203510. }
  203511. return (int64) ((((uint64) hi) << 32) | lo);
  203512. #endif
  203513. }
  203514. int SystemStats::getCpuSpeedInMegaherz()
  203515. {
  203516. const int64 cycles = juce_getClockCycleCounter();
  203517. const uint32 millis = Time::getMillisecondCounter();
  203518. int lastResult = 0;
  203519. for (;;)
  203520. {
  203521. int n = 1000000;
  203522. while (--n > 0) {}
  203523. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203524. const int64 cyclesNow = juce_getClockCycleCounter();
  203525. if (millisElapsed > 80)
  203526. {
  203527. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203528. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203529. return newResult;
  203530. lastResult = newResult;
  203531. }
  203532. }
  203533. }
  203534. bool Time::setSystemTimeToThisTime() const
  203535. {
  203536. SYSTEMTIME st;
  203537. st.wDayOfWeek = 0;
  203538. st.wYear = (WORD) getYear();
  203539. st.wMonth = (WORD) (getMonth() + 1);
  203540. st.wDay = (WORD) getDayOfMonth();
  203541. st.wHour = (WORD) getHours();
  203542. st.wMinute = (WORD) getMinutes();
  203543. st.wSecond = (WORD) getSeconds();
  203544. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203545. // do this twice because of daylight saving conversion problems - the
  203546. // first one sets it up, the second one kicks it in.
  203547. return SetLocalTime (&st) != 0
  203548. && SetLocalTime (&st) != 0;
  203549. }
  203550. int SystemStats::getPageSize()
  203551. {
  203552. SYSTEM_INFO systemInfo;
  203553. GetSystemInfo (&systemInfo);
  203554. return systemInfo.dwPageSize;
  203555. }
  203556. const String SystemStats::getLogonName()
  203557. {
  203558. TCHAR text [256];
  203559. DWORD len = numElementsInArray (text) - 2;
  203560. zerostruct (text);
  203561. GetUserName (text, &len);
  203562. return String (text, len);
  203563. }
  203564. const String SystemStats::getFullUserName()
  203565. {
  203566. return getLogonName();
  203567. }
  203568. #endif
  203569. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203570. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203571. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203572. // compiled on its own).
  203573. #if JUCE_INCLUDED_FILE
  203574. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203575. extern HWND juce_messageWindowHandle;
  203576. #endif
  203577. #if ! JUCE_USE_INTRINSICS
  203578. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203579. // older ones we have to actually call the ops as win32 functions..
  203580. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203581. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203582. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203583. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203584. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203585. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203586. {
  203587. jassertfalse; // This operation isn't available in old MS compiler versions!
  203588. __int64 oldValue = *value;
  203589. if (oldValue == valueToCompare)
  203590. *value = newValue;
  203591. return oldValue;
  203592. }
  203593. #endif
  203594. CriticalSection::CriticalSection() throw()
  203595. {
  203596. // (just to check the MS haven't changed this structure and broken things...)
  203597. #if _MSC_VER >= 1400
  203598. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203599. #else
  203600. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203601. #endif
  203602. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203603. }
  203604. CriticalSection::~CriticalSection() throw()
  203605. {
  203606. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203607. }
  203608. void CriticalSection::enter() const throw()
  203609. {
  203610. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203611. }
  203612. bool CriticalSection::tryEnter() const throw()
  203613. {
  203614. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203615. }
  203616. void CriticalSection::exit() const throw()
  203617. {
  203618. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203619. }
  203620. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203621. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203622. {
  203623. }
  203624. WaitableEvent::~WaitableEvent() throw()
  203625. {
  203626. CloseHandle (internal);
  203627. }
  203628. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203629. {
  203630. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203631. }
  203632. void WaitableEvent::signal() const throw()
  203633. {
  203634. SetEvent (internal);
  203635. }
  203636. void WaitableEvent::reset() const throw()
  203637. {
  203638. ResetEvent (internal);
  203639. }
  203640. void JUCE_API juce_threadEntryPoint (void*);
  203641. static unsigned int __stdcall threadEntryProc (void* userData)
  203642. {
  203643. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203644. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203645. GetCurrentThreadId(), TRUE);
  203646. #endif
  203647. juce_threadEntryPoint (userData);
  203648. _endthreadex (0);
  203649. return 0;
  203650. }
  203651. void juce_CloseThreadHandle (void* handle)
  203652. {
  203653. CloseHandle ((HANDLE) handle);
  203654. }
  203655. void* juce_createThread (void* userData)
  203656. {
  203657. unsigned int threadId;
  203658. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203659. }
  203660. void juce_killThread (void* handle)
  203661. {
  203662. if (handle != 0)
  203663. {
  203664. #if JUCE_DEBUG
  203665. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203666. #endif
  203667. TerminateThread (handle, 0);
  203668. }
  203669. }
  203670. void juce_setCurrentThreadName (const String& name)
  203671. {
  203672. #if JUCE_DEBUG && JUCE_MSVC
  203673. struct
  203674. {
  203675. DWORD dwType;
  203676. LPCSTR szName;
  203677. DWORD dwThreadID;
  203678. DWORD dwFlags;
  203679. } info;
  203680. info.dwType = 0x1000;
  203681. info.szName = name.toCString();
  203682. info.dwThreadID = GetCurrentThreadId();
  203683. info.dwFlags = 0;
  203684. __try
  203685. {
  203686. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203687. }
  203688. __except (EXCEPTION_CONTINUE_EXECUTION)
  203689. {}
  203690. #else
  203691. (void) name;
  203692. #endif
  203693. }
  203694. Thread::ThreadID Thread::getCurrentThreadId()
  203695. {
  203696. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203697. }
  203698. // priority 1 to 10 where 5=normal, 1=low
  203699. bool juce_setThreadPriority (void* threadHandle, int priority)
  203700. {
  203701. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203702. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203703. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203704. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203705. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203706. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203707. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203708. if (threadHandle == 0)
  203709. threadHandle = GetCurrentThread();
  203710. return SetThreadPriority (threadHandle, pri) != FALSE;
  203711. }
  203712. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203713. {
  203714. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203715. }
  203716. static HANDLE sleepEvent = 0;
  203717. void juce_initialiseThreadEvents()
  203718. {
  203719. if (sleepEvent == 0)
  203720. #if JUCE_DEBUG
  203721. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203722. #else
  203723. sleepEvent = CreateEvent (0, 0, 0, 0);
  203724. #endif
  203725. }
  203726. void Thread::yield()
  203727. {
  203728. Sleep (0);
  203729. }
  203730. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203731. {
  203732. if (millisecs >= 10)
  203733. {
  203734. Sleep (millisecs);
  203735. }
  203736. else
  203737. {
  203738. jassert (sleepEvent != 0);
  203739. // unlike Sleep() this is guaranteed to return to the current thread after
  203740. // the time expires, so we'll use this for short waits, which are more likely
  203741. // to need to be accurate
  203742. WaitForSingleObject (sleepEvent, millisecs);
  203743. }
  203744. }
  203745. static int lastProcessPriority = -1;
  203746. // called by WindowDriver because Windows does wierd things to process priority
  203747. // when you swap apps, and this forces an update when the app is brought to the front.
  203748. void juce_repeatLastProcessPriority()
  203749. {
  203750. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203751. {
  203752. DWORD p;
  203753. switch (lastProcessPriority)
  203754. {
  203755. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203756. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203757. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203758. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203759. default: jassertfalse; return; // bad priority value
  203760. }
  203761. SetPriorityClass (GetCurrentProcess(), p);
  203762. }
  203763. }
  203764. void Process::setPriority (ProcessPriority prior)
  203765. {
  203766. if (lastProcessPriority != (int) prior)
  203767. {
  203768. lastProcessPriority = (int) prior;
  203769. juce_repeatLastProcessPriority();
  203770. }
  203771. }
  203772. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203773. {
  203774. return IsDebuggerPresent() != FALSE;
  203775. }
  203776. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203777. {
  203778. return juce_isRunningUnderDebugger();
  203779. }
  203780. void Process::raisePrivilege()
  203781. {
  203782. jassertfalse; // xxx not implemented
  203783. }
  203784. void Process::lowerPrivilege()
  203785. {
  203786. jassertfalse; // xxx not implemented
  203787. }
  203788. void Process::terminate()
  203789. {
  203790. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203791. _CrtDumpMemoryLeaks();
  203792. #endif
  203793. // bullet in the head in case there's a problem shutting down..
  203794. ExitProcess (0);
  203795. }
  203796. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203797. {
  203798. void* result = 0;
  203799. JUCE_TRY
  203800. {
  203801. result = LoadLibrary (name);
  203802. }
  203803. JUCE_CATCH_ALL
  203804. return result;
  203805. }
  203806. void PlatformUtilities::freeDynamicLibrary (void* h)
  203807. {
  203808. JUCE_TRY
  203809. {
  203810. if (h != 0)
  203811. FreeLibrary ((HMODULE) h);
  203812. }
  203813. JUCE_CATCH_ALL
  203814. }
  203815. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203816. {
  203817. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203818. }
  203819. class InterProcessLock::Pimpl
  203820. {
  203821. public:
  203822. Pimpl (const String& name, const int timeOutMillisecs)
  203823. : handle (0), refCount (1)
  203824. {
  203825. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203826. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203827. {
  203828. if (timeOutMillisecs == 0)
  203829. {
  203830. close();
  203831. return;
  203832. }
  203833. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203834. {
  203835. case WAIT_OBJECT_0:
  203836. case WAIT_ABANDONED:
  203837. break;
  203838. case WAIT_TIMEOUT:
  203839. default:
  203840. close();
  203841. break;
  203842. }
  203843. }
  203844. }
  203845. ~Pimpl()
  203846. {
  203847. close();
  203848. }
  203849. void close()
  203850. {
  203851. if (handle != 0)
  203852. {
  203853. ReleaseMutex (handle);
  203854. CloseHandle (handle);
  203855. handle = 0;
  203856. }
  203857. }
  203858. HANDLE handle;
  203859. int refCount;
  203860. };
  203861. InterProcessLock::InterProcessLock (const String& name_)
  203862. : name (name_)
  203863. {
  203864. }
  203865. InterProcessLock::~InterProcessLock()
  203866. {
  203867. }
  203868. bool InterProcessLock::enter (const int timeOutMillisecs)
  203869. {
  203870. const ScopedLock sl (lock);
  203871. if (pimpl == 0)
  203872. {
  203873. pimpl = new Pimpl (name, timeOutMillisecs);
  203874. if (pimpl->handle == 0)
  203875. pimpl = 0;
  203876. }
  203877. else
  203878. {
  203879. pimpl->refCount++;
  203880. }
  203881. return pimpl != 0;
  203882. }
  203883. void InterProcessLock::exit()
  203884. {
  203885. const ScopedLock sl (lock);
  203886. // Trying to release the lock too many times!
  203887. jassert (pimpl != 0);
  203888. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203889. pimpl = 0;
  203890. }
  203891. #endif
  203892. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203893. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203894. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203895. // compiled on its own).
  203896. #if JUCE_INCLUDED_FILE
  203897. #ifndef CSIDL_MYMUSIC
  203898. #define CSIDL_MYMUSIC 0x000d
  203899. #endif
  203900. #ifndef CSIDL_MYVIDEO
  203901. #define CSIDL_MYVIDEO 0x000e
  203902. #endif
  203903. #ifndef INVALID_FILE_ATTRIBUTES
  203904. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203905. #endif
  203906. const juce_wchar File::separator = '\\';
  203907. const String File::separatorString ("\\");
  203908. bool File::exists() const
  203909. {
  203910. return fullPath.isNotEmpty()
  203911. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203912. }
  203913. bool File::existsAsFile() const
  203914. {
  203915. return fullPath.isNotEmpty()
  203916. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203917. }
  203918. bool File::isDirectory() const
  203919. {
  203920. const DWORD attr = GetFileAttributes (fullPath);
  203921. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203922. }
  203923. bool File::hasWriteAccess() const
  203924. {
  203925. if (exists())
  203926. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203927. // on windows, it seems that even read-only directories can still be written into,
  203928. // so checking the parent directory's permissions would return the wrong result..
  203929. return true;
  203930. }
  203931. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203932. {
  203933. DWORD attr = GetFileAttributes (fullPath);
  203934. if (attr == INVALID_FILE_ATTRIBUTES)
  203935. return false;
  203936. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203937. return true;
  203938. if (shouldBeReadOnly)
  203939. attr |= FILE_ATTRIBUTE_READONLY;
  203940. else
  203941. attr &= ~FILE_ATTRIBUTE_READONLY;
  203942. return SetFileAttributes (fullPath, attr) != FALSE;
  203943. }
  203944. bool File::isHidden() const
  203945. {
  203946. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203947. }
  203948. bool File::deleteFile() const
  203949. {
  203950. if (! exists())
  203951. return true;
  203952. else if (isDirectory())
  203953. return RemoveDirectory (fullPath) != 0;
  203954. else
  203955. return DeleteFile (fullPath) != 0;
  203956. }
  203957. bool File::moveToTrash() const
  203958. {
  203959. if (! exists())
  203960. return true;
  203961. SHFILEOPSTRUCT fos;
  203962. zerostruct (fos);
  203963. // The string we pass in must be double null terminated..
  203964. String doubleNullTermPath (getFullPathName() + " ");
  203965. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203966. p [getFullPathName().length()] = 0;
  203967. fos.wFunc = FO_DELETE;
  203968. fos.pFrom = p;
  203969. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203970. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203971. return SHFileOperation (&fos) == 0;
  203972. }
  203973. bool File::copyInternal (const File& dest) const
  203974. {
  203975. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203976. }
  203977. bool File::moveInternal (const File& dest) const
  203978. {
  203979. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203980. }
  203981. void File::createDirectoryInternal (const String& fileName) const
  203982. {
  203983. CreateDirectory (fileName, 0);
  203984. }
  203985. int64 juce_fileSetPosition (void* handle, int64 pos)
  203986. {
  203987. LARGE_INTEGER li;
  203988. li.QuadPart = pos;
  203989. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203990. return li.QuadPart;
  203991. }
  203992. void FileInputStream::openHandle()
  203993. {
  203994. totalSize = file.getSize();
  203995. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203996. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203997. if (h != INVALID_HANDLE_VALUE)
  203998. fileHandle = (void*) h;
  203999. }
  204000. void FileInputStream::closeHandle()
  204001. {
  204002. CloseHandle ((HANDLE) fileHandle);
  204003. }
  204004. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204005. {
  204006. if (fileHandle != 0)
  204007. {
  204008. DWORD actualNum = 0;
  204009. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204010. return (size_t) actualNum;
  204011. }
  204012. return 0;
  204013. }
  204014. void FileOutputStream::openHandle()
  204015. {
  204016. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204017. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204018. if (h != INVALID_HANDLE_VALUE)
  204019. {
  204020. LARGE_INTEGER li;
  204021. li.QuadPart = 0;
  204022. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204023. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204024. {
  204025. fileHandle = (void*) h;
  204026. currentPosition = li.QuadPart;
  204027. }
  204028. }
  204029. }
  204030. void FileOutputStream::closeHandle()
  204031. {
  204032. CloseHandle ((HANDLE) fileHandle);
  204033. }
  204034. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204035. {
  204036. if (fileHandle != 0)
  204037. {
  204038. DWORD actualNum = 0;
  204039. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204040. return (int) actualNum;
  204041. }
  204042. return 0;
  204043. }
  204044. void FileOutputStream::flushInternal()
  204045. {
  204046. if (fileHandle != 0)
  204047. FlushFileBuffers ((HANDLE) fileHandle);
  204048. }
  204049. int64 File::getSize() const
  204050. {
  204051. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204052. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204053. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204054. return 0;
  204055. }
  204056. static int64 fileTimeToTime (const FILETIME* const ft)
  204057. {
  204058. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204059. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204060. }
  204061. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204062. {
  204063. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204064. }
  204065. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204066. {
  204067. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204068. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204069. {
  204070. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204071. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204072. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204073. }
  204074. else
  204075. {
  204076. creationTime = accessTime = modificationTime = 0;
  204077. }
  204078. }
  204079. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204080. {
  204081. bool ok = false;
  204082. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204083. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204084. if (h != INVALID_HANDLE_VALUE)
  204085. {
  204086. FILETIME m, a, c;
  204087. timeToFileTime (modificationTime, &m);
  204088. timeToFileTime (accessTime, &a);
  204089. timeToFileTime (creationTime, &c);
  204090. ok = SetFileTime (h,
  204091. creationTime > 0 ? &c : 0,
  204092. accessTime > 0 ? &a : 0,
  204093. modificationTime > 0 ? &m : 0) != 0;
  204094. CloseHandle (h);
  204095. }
  204096. return ok;
  204097. }
  204098. void File::findFileSystemRoots (Array<File>& destArray)
  204099. {
  204100. TCHAR buffer [2048];
  204101. buffer[0] = 0;
  204102. buffer[1] = 0;
  204103. GetLogicalDriveStrings (2048, buffer);
  204104. const TCHAR* n = buffer;
  204105. StringArray roots;
  204106. while (*n != 0)
  204107. {
  204108. roots.add (String (n));
  204109. while (*n++ != 0)
  204110. {}
  204111. }
  204112. roots.sort (true);
  204113. for (int i = 0; i < roots.size(); ++i)
  204114. destArray.add (roots [i]);
  204115. }
  204116. static const String getDriveFromPath (const String& path)
  204117. {
  204118. if (path.isNotEmpty() && path[1] == ':')
  204119. return path.substring (0, 2) + '\\';
  204120. return path;
  204121. }
  204122. const String File::getVolumeLabel() const
  204123. {
  204124. TCHAR dest[64];
  204125. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204126. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204127. dest[0] = 0;
  204128. return dest;
  204129. }
  204130. int File::getVolumeSerialNumber() const
  204131. {
  204132. TCHAR dest[64];
  204133. DWORD serialNum;
  204134. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204135. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204136. return 0;
  204137. return (int) serialNum;
  204138. }
  204139. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204140. {
  204141. ULARGE_INTEGER spc, tot, totFree;
  204142. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204143. return total ? (int64) tot.QuadPart
  204144. : (int64) spc.QuadPart;
  204145. return 0;
  204146. }
  204147. int64 File::getBytesFreeOnVolume() const
  204148. {
  204149. return getDiskSpaceInfo (getFullPathName(), false);
  204150. }
  204151. int64 File::getVolumeTotalSize() const
  204152. {
  204153. return getDiskSpaceInfo (getFullPathName(), true);
  204154. }
  204155. static unsigned int getWindowsDriveType (const String& path)
  204156. {
  204157. return GetDriveType (getDriveFromPath (path));
  204158. }
  204159. bool File::isOnCDRomDrive() const
  204160. {
  204161. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204162. }
  204163. bool File::isOnHardDisk() const
  204164. {
  204165. if (fullPath.isEmpty())
  204166. return false;
  204167. const unsigned int n = getWindowsDriveType (getFullPathName());
  204168. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204169. return n != DRIVE_REMOVABLE;
  204170. else
  204171. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204172. }
  204173. bool File::isOnRemovableDrive() const
  204174. {
  204175. if (fullPath.isEmpty())
  204176. return false;
  204177. const unsigned int n = getWindowsDriveType (getFullPathName());
  204178. return n == DRIVE_CDROM
  204179. || n == DRIVE_REMOTE
  204180. || n == DRIVE_REMOVABLE
  204181. || n == DRIVE_RAMDISK;
  204182. }
  204183. static const File juce_getSpecialFolderPath (int type)
  204184. {
  204185. WCHAR path [MAX_PATH + 256];
  204186. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204187. return File (String (path));
  204188. return File::nonexistent;
  204189. }
  204190. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204191. {
  204192. int csidlType = 0;
  204193. switch (type)
  204194. {
  204195. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204196. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204197. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204198. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204199. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204200. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204201. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204202. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204203. case tempDirectory:
  204204. {
  204205. WCHAR dest [2048];
  204206. dest[0] = 0;
  204207. GetTempPath (numElementsInArray (dest), dest);
  204208. return File (String (dest));
  204209. }
  204210. case invokedExecutableFile:
  204211. case currentExecutableFile:
  204212. case currentApplicationFile:
  204213. {
  204214. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204215. WCHAR dest [MAX_PATH + 256];
  204216. dest[0] = 0;
  204217. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204218. return File (String (dest));
  204219. }
  204220. case hostApplicationPath:
  204221. {
  204222. WCHAR dest [MAX_PATH + 256];
  204223. dest[0] = 0;
  204224. GetModuleFileName (0, dest, numElementsInArray (dest));
  204225. return File (String (dest));
  204226. }
  204227. default:
  204228. jassertfalse; // unknown type?
  204229. return File::nonexistent;
  204230. }
  204231. return juce_getSpecialFolderPath (csidlType);
  204232. }
  204233. const File File::getCurrentWorkingDirectory()
  204234. {
  204235. WCHAR dest [MAX_PATH + 256];
  204236. dest[0] = 0;
  204237. GetCurrentDirectory (numElementsInArray (dest), dest);
  204238. return File (String (dest));
  204239. }
  204240. bool File::setAsCurrentWorkingDirectory() const
  204241. {
  204242. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204243. }
  204244. const String File::getVersion() const
  204245. {
  204246. String result;
  204247. DWORD handle = 0;
  204248. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204249. HeapBlock<char> buffer;
  204250. buffer.calloc (bufferSize);
  204251. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204252. {
  204253. VS_FIXEDFILEINFO* vffi;
  204254. UINT len = 0;
  204255. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204256. {
  204257. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204258. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204259. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204260. << (int) LOWORD (vffi->dwFileVersionLS);
  204261. }
  204262. }
  204263. return result;
  204264. }
  204265. const File File::getLinkedTarget() const
  204266. {
  204267. File result (*this);
  204268. String p (getFullPathName());
  204269. if (! exists())
  204270. p += ".lnk";
  204271. else if (getFileExtension() != ".lnk")
  204272. return result;
  204273. ComSmartPtr <IShellLink> shellLink;
  204274. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204275. {
  204276. ComSmartPtr <IPersistFile> persistFile;
  204277. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  204278. {
  204279. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204280. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204281. {
  204282. WIN32_FIND_DATA winFindData;
  204283. WCHAR resolvedPath [MAX_PATH];
  204284. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204285. result = File (resolvedPath);
  204286. }
  204287. }
  204288. }
  204289. return result;
  204290. }
  204291. class DirectoryIterator::NativeIterator::Pimpl
  204292. {
  204293. public:
  204294. Pimpl (const File& directory, const String& wildCard)
  204295. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204296. handle (INVALID_HANDLE_VALUE)
  204297. {
  204298. }
  204299. ~Pimpl()
  204300. {
  204301. if (handle != INVALID_HANDLE_VALUE)
  204302. FindClose (handle);
  204303. }
  204304. bool next (String& filenameFound,
  204305. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204306. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204307. {
  204308. WIN32_FIND_DATA findData;
  204309. if (handle == INVALID_HANDLE_VALUE)
  204310. {
  204311. handle = FindFirstFile (directoryWithWildCard, &findData);
  204312. if (handle == INVALID_HANDLE_VALUE)
  204313. return false;
  204314. }
  204315. else
  204316. {
  204317. if (FindNextFile (handle, &findData) == 0)
  204318. return false;
  204319. }
  204320. filenameFound = findData.cFileName;
  204321. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204322. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204323. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204324. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204325. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204326. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204327. return true;
  204328. }
  204329. juce_UseDebuggingNewOperator
  204330. private:
  204331. const String directoryWithWildCard;
  204332. HANDLE handle;
  204333. Pimpl (const Pimpl&);
  204334. Pimpl& operator= (const Pimpl&);
  204335. };
  204336. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204337. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204338. {
  204339. }
  204340. DirectoryIterator::NativeIterator::~NativeIterator()
  204341. {
  204342. }
  204343. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204344. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204345. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204346. {
  204347. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204348. }
  204349. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204350. {
  204351. HINSTANCE hInstance = 0;
  204352. JUCE_TRY
  204353. {
  204354. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204355. }
  204356. JUCE_CATCH_ALL
  204357. return hInstance > (HINSTANCE) 32;
  204358. }
  204359. void File::revealToUser() const
  204360. {
  204361. if (isDirectory())
  204362. startAsProcess();
  204363. else if (getParentDirectory().exists())
  204364. getParentDirectory().startAsProcess();
  204365. }
  204366. class NamedPipeInternal
  204367. {
  204368. public:
  204369. NamedPipeInternal (const String& file, const bool isPipe_)
  204370. : pipeH (0),
  204371. cancelEvent (0),
  204372. connected (false),
  204373. isPipe (isPipe_)
  204374. {
  204375. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204376. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204377. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204378. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204379. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204380. }
  204381. ~NamedPipeInternal()
  204382. {
  204383. disconnectPipe();
  204384. if (pipeH != 0)
  204385. CloseHandle (pipeH);
  204386. CloseHandle (cancelEvent);
  204387. }
  204388. bool connect (const int timeOutMs)
  204389. {
  204390. if (! isPipe)
  204391. return true;
  204392. if (! connected)
  204393. {
  204394. OVERLAPPED over;
  204395. zerostruct (over);
  204396. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204397. if (ConnectNamedPipe (pipeH, &over))
  204398. {
  204399. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204400. }
  204401. else
  204402. {
  204403. const int err = GetLastError();
  204404. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204405. {
  204406. HANDLE handles[] = { over.hEvent, cancelEvent };
  204407. if (WaitForMultipleObjects (2, handles, FALSE,
  204408. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204409. connected = true;
  204410. }
  204411. else if (err == ERROR_PIPE_CONNECTED)
  204412. {
  204413. connected = true;
  204414. }
  204415. }
  204416. CloseHandle (over.hEvent);
  204417. }
  204418. return connected;
  204419. }
  204420. void disconnectPipe()
  204421. {
  204422. if (connected)
  204423. {
  204424. DisconnectNamedPipe (pipeH);
  204425. connected = false;
  204426. }
  204427. }
  204428. HANDLE pipeH;
  204429. HANDLE cancelEvent;
  204430. bool connected, isPipe;
  204431. };
  204432. void NamedPipe::close()
  204433. {
  204434. cancelPendingReads();
  204435. const ScopedLock sl (lock);
  204436. delete static_cast<NamedPipeInternal*> (internal);
  204437. internal = 0;
  204438. }
  204439. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204440. {
  204441. close();
  204442. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204443. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204444. {
  204445. internal = intern.release();
  204446. return true;
  204447. }
  204448. return false;
  204449. }
  204450. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204451. {
  204452. const ScopedLock sl (lock);
  204453. int bytesRead = -1;
  204454. bool waitAgain = true;
  204455. while (waitAgain && internal != 0)
  204456. {
  204457. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204458. waitAgain = false;
  204459. if (! intern->connect (timeOutMilliseconds))
  204460. break;
  204461. if (maxBytesToRead <= 0)
  204462. return 0;
  204463. OVERLAPPED over;
  204464. zerostruct (over);
  204465. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204466. unsigned long numRead;
  204467. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204468. {
  204469. bytesRead = (int) numRead;
  204470. }
  204471. else if (GetLastError() == ERROR_IO_PENDING)
  204472. {
  204473. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204474. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204475. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204476. : INFINITE);
  204477. if (waitResult != WAIT_OBJECT_0)
  204478. {
  204479. // if the operation timed out, let's cancel it...
  204480. CancelIo (intern->pipeH);
  204481. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204482. }
  204483. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204484. {
  204485. bytesRead = (int) numRead;
  204486. }
  204487. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204488. {
  204489. intern->disconnectPipe();
  204490. waitAgain = true;
  204491. }
  204492. }
  204493. else
  204494. {
  204495. waitAgain = internal != 0;
  204496. Sleep (5);
  204497. }
  204498. CloseHandle (over.hEvent);
  204499. }
  204500. return bytesRead;
  204501. }
  204502. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204503. {
  204504. int bytesWritten = -1;
  204505. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204506. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204507. {
  204508. if (numBytesToWrite <= 0)
  204509. return 0;
  204510. OVERLAPPED over;
  204511. zerostruct (over);
  204512. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204513. unsigned long numWritten;
  204514. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204515. {
  204516. bytesWritten = (int) numWritten;
  204517. }
  204518. else if (GetLastError() == ERROR_IO_PENDING)
  204519. {
  204520. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204521. DWORD waitResult;
  204522. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204523. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204524. : INFINITE);
  204525. if (waitResult != WAIT_OBJECT_0)
  204526. {
  204527. CancelIo (intern->pipeH);
  204528. WaitForSingleObject (over.hEvent, INFINITE);
  204529. }
  204530. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204531. {
  204532. bytesWritten = (int) numWritten;
  204533. }
  204534. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204535. {
  204536. intern->disconnectPipe();
  204537. }
  204538. }
  204539. CloseHandle (over.hEvent);
  204540. }
  204541. return bytesWritten;
  204542. }
  204543. void NamedPipe::cancelPendingReads()
  204544. {
  204545. if (internal != 0)
  204546. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204547. }
  204548. #endif
  204549. /*** End of inlined file: juce_win32_Files.cpp ***/
  204550. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204551. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204552. // compiled on its own).
  204553. #if JUCE_INCLUDED_FILE
  204554. #ifndef INTERNET_FLAG_NEED_FILE
  204555. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204556. #endif
  204557. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204558. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204559. #endif
  204560. struct ConnectionAndRequestStruct
  204561. {
  204562. HINTERNET connection, request;
  204563. };
  204564. static HINTERNET sessionHandle = 0;
  204565. #ifndef WORKAROUND_TIMEOUT_BUG
  204566. //#define WORKAROUND_TIMEOUT_BUG 1
  204567. #endif
  204568. #if WORKAROUND_TIMEOUT_BUG
  204569. // Required because of a Microsoft bug in setting a timeout
  204570. class InternetConnectThread : public Thread
  204571. {
  204572. public:
  204573. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204574. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204575. {
  204576. startThread();
  204577. }
  204578. ~InternetConnectThread()
  204579. {
  204580. stopThread (60000);
  204581. }
  204582. void run()
  204583. {
  204584. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204585. uc.nPort, _T(""), _T(""),
  204586. isFtp ? INTERNET_SERVICE_FTP
  204587. : INTERNET_SERVICE_HTTP,
  204588. 0, 0);
  204589. notify();
  204590. }
  204591. juce_UseDebuggingNewOperator
  204592. private:
  204593. URL_COMPONENTS& uc;
  204594. HINTERNET& connection;
  204595. const bool isFtp;
  204596. InternetConnectThread (const InternetConnectThread&);
  204597. InternetConnectThread& operator= (const InternetConnectThread&);
  204598. };
  204599. #endif
  204600. void* juce_openInternetFile (const String& url,
  204601. const String& headers,
  204602. const MemoryBlock& postData,
  204603. const bool isPost,
  204604. URL::OpenStreamProgressCallback* callback,
  204605. void* callbackContext,
  204606. int timeOutMs)
  204607. {
  204608. if (sessionHandle == 0)
  204609. sessionHandle = InternetOpen (_T("juce"),
  204610. INTERNET_OPEN_TYPE_PRECONFIG,
  204611. 0, 0, 0);
  204612. if (sessionHandle != 0)
  204613. {
  204614. // break up the url..
  204615. TCHAR file[1024], server[1024];
  204616. URL_COMPONENTS uc;
  204617. zerostruct (uc);
  204618. uc.dwStructSize = sizeof (uc);
  204619. uc.dwUrlPathLength = sizeof (file);
  204620. uc.dwHostNameLength = sizeof (server);
  204621. uc.lpszUrlPath = file;
  204622. uc.lpszHostName = server;
  204623. if (InternetCrackUrl (url, 0, 0, &uc))
  204624. {
  204625. int disable = 1;
  204626. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204627. if (timeOutMs == 0)
  204628. timeOutMs = 30000;
  204629. else if (timeOutMs < 0)
  204630. timeOutMs = -1;
  204631. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204632. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204633. #if WORKAROUND_TIMEOUT_BUG
  204634. HINTERNET connection = 0;
  204635. {
  204636. InternetConnectThread connectThread (uc, connection, isFtp);
  204637. connectThread.wait (timeOutMs);
  204638. if (connection == 0)
  204639. {
  204640. InternetCloseHandle (sessionHandle);
  204641. sessionHandle = 0;
  204642. }
  204643. }
  204644. #else
  204645. HINTERNET connection = InternetConnect (sessionHandle,
  204646. uc.lpszHostName,
  204647. uc.nPort,
  204648. _T(""), _T(""),
  204649. isFtp ? INTERNET_SERVICE_FTP
  204650. : INTERNET_SERVICE_HTTP,
  204651. 0, 0);
  204652. #endif
  204653. if (connection != 0)
  204654. {
  204655. if (isFtp)
  204656. {
  204657. HINTERNET request = FtpOpenFile (connection,
  204658. uc.lpszUrlPath,
  204659. GENERIC_READ,
  204660. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204661. 0);
  204662. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204663. result->connection = connection;
  204664. result->request = request;
  204665. return result;
  204666. }
  204667. else
  204668. {
  204669. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204670. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204671. if (url.startsWithIgnoreCase ("https:"))
  204672. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204673. // IE7 seems to automatically work out when it's https)
  204674. HINTERNET request = HttpOpenRequest (connection,
  204675. isPost ? _T("POST")
  204676. : _T("GET"),
  204677. uc.lpszUrlPath,
  204678. 0, 0, mimeTypes, flags, 0);
  204679. if (request != 0)
  204680. {
  204681. INTERNET_BUFFERS buffers;
  204682. zerostruct (buffers);
  204683. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204684. buffers.lpcszHeader = (LPCTSTR) headers;
  204685. buffers.dwHeadersLength = headers.length();
  204686. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204687. ConnectionAndRequestStruct* result = 0;
  204688. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204689. {
  204690. int bytesSent = 0;
  204691. for (;;)
  204692. {
  204693. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204694. DWORD bytesDone = 0;
  204695. if (bytesToDo > 0
  204696. && ! InternetWriteFile (request,
  204697. static_cast <const char*> (postData.getData()) + bytesSent,
  204698. bytesToDo, &bytesDone))
  204699. {
  204700. break;
  204701. }
  204702. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204703. {
  204704. result = new ConnectionAndRequestStruct();
  204705. result->connection = connection;
  204706. result->request = request;
  204707. if (! HttpEndRequest (request, 0, 0, 0))
  204708. break;
  204709. return result;
  204710. }
  204711. bytesSent += bytesDone;
  204712. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204713. break;
  204714. }
  204715. }
  204716. InternetCloseHandle (request);
  204717. }
  204718. InternetCloseHandle (connection);
  204719. }
  204720. }
  204721. }
  204722. }
  204723. return 0;
  204724. }
  204725. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204726. {
  204727. DWORD bytesRead = 0;
  204728. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204729. if (crs != 0)
  204730. InternetReadFile (crs->request,
  204731. buffer, bytesToRead,
  204732. &bytesRead);
  204733. return bytesRead;
  204734. }
  204735. int juce_seekInInternetFile (void* handle, int newPosition)
  204736. {
  204737. if (handle != 0)
  204738. {
  204739. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204740. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204741. }
  204742. return -1;
  204743. }
  204744. int64 juce_getInternetFileContentLength (void* handle)
  204745. {
  204746. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204747. if (crs != 0)
  204748. {
  204749. DWORD index = 0, result = 0, size = sizeof (result);
  204750. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204751. return (int64) result;
  204752. }
  204753. return -1;
  204754. }
  204755. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204756. {
  204757. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204758. if (crs != 0)
  204759. {
  204760. DWORD bufferSizeBytes = 4096;
  204761. for (;;)
  204762. {
  204763. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204764. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204765. {
  204766. StringArray headersArray;
  204767. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204768. for (int i = 0; i < headersArray.size(); ++i)
  204769. {
  204770. const String& header = headersArray[i];
  204771. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204772. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204773. const String previousValue (headers [key]);
  204774. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204775. }
  204776. break;
  204777. }
  204778. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204779. break;
  204780. }
  204781. }
  204782. }
  204783. void juce_closeInternetFile (void* handle)
  204784. {
  204785. if (handle != 0)
  204786. {
  204787. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204788. InternetCloseHandle (crs->request);
  204789. InternetCloseHandle (crs->connection);
  204790. }
  204791. }
  204792. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204793. {
  204794. int numFound = 0;
  204795. DynamicLibraryLoader dll ("iphlpapi.dll");
  204796. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204797. if (getAdaptersInfo != 0)
  204798. {
  204799. ULONG len = sizeof (IP_ADAPTER_INFO);
  204800. MemoryBlock mb;
  204801. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204802. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204803. {
  204804. mb.setSize (len);
  204805. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204806. }
  204807. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204808. {
  204809. PIP_ADAPTER_INFO adapter = adapterInfo;
  204810. while (adapter != 0)
  204811. {
  204812. int64 mac = 0;
  204813. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204814. mac = (mac << 8) | adapter->Address[i];
  204815. if (littleEndian)
  204816. mac = (int64) ByteOrder::swap ((uint64) mac);
  204817. if (numFound < maxNum && mac != 0)
  204818. addresses [numFound++] = mac;
  204819. adapter = adapter->Next;
  204820. }
  204821. }
  204822. }
  204823. return numFound;
  204824. }
  204825. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204826. {
  204827. int numFound = 0;
  204828. DynamicLibraryLoader dll ("netapi32.dll");
  204829. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204830. if (NetbiosCall != 0)
  204831. {
  204832. NCB ncb;
  204833. zerostruct (ncb);
  204834. struct ASTAT
  204835. {
  204836. ADAPTER_STATUS adapt;
  204837. NAME_BUFFER NameBuff [30];
  204838. };
  204839. ASTAT astat;
  204840. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204841. LANA_ENUM enums;
  204842. zerostruct (enums);
  204843. ncb.ncb_command = NCBENUM;
  204844. ncb.ncb_buffer = (unsigned char*) &enums;
  204845. ncb.ncb_length = sizeof (LANA_ENUM);
  204846. NetbiosCall (&ncb);
  204847. for (int i = 0; i < enums.length; ++i)
  204848. {
  204849. zerostruct (ncb);
  204850. ncb.ncb_command = NCBRESET;
  204851. ncb.ncb_lana_num = enums.lana[i];
  204852. if (NetbiosCall (&ncb) == 0)
  204853. {
  204854. zerostruct (ncb);
  204855. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204856. ncb.ncb_command = NCBASTAT;
  204857. ncb.ncb_lana_num = enums.lana[i];
  204858. ncb.ncb_buffer = (unsigned char*) &astat;
  204859. ncb.ncb_length = sizeof (ASTAT);
  204860. if (NetbiosCall (&ncb) == 0)
  204861. {
  204862. if (astat.adapt.adapter_type == 0xfe)
  204863. {
  204864. uint64 mac = 0;
  204865. for (int i = 6; --i >= 0;)
  204866. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204867. if (numFound < maxNum && mac != 0)
  204868. addresses [numFound++] = mac;
  204869. }
  204870. }
  204871. }
  204872. }
  204873. }
  204874. return numFound;
  204875. }
  204876. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204877. {
  204878. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204879. if (numFound == 0)
  204880. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204881. return numFound;
  204882. }
  204883. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204884. const String& emailSubject,
  204885. const String& bodyText,
  204886. const StringArray& filesToAttach)
  204887. {
  204888. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204889. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204890. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204891. bool ok = false;
  204892. if (mapiSendMail != 0)
  204893. {
  204894. MapiMessage message;
  204895. zerostruct (message);
  204896. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204897. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204898. MapiRecipDesc recip;
  204899. zerostruct (recip);
  204900. recip.ulRecipClass = MAPI_TO;
  204901. String targetEmailAddress_ (targetEmailAddress);
  204902. if (targetEmailAddress_.isEmpty())
  204903. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204904. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204905. message.nRecipCount = 1;
  204906. message.lpRecips = &recip;
  204907. HeapBlock <MapiFileDesc> files;
  204908. files.calloc (filesToAttach.size());
  204909. message.nFileCount = filesToAttach.size();
  204910. message.lpFiles = files;
  204911. for (int i = 0; i < filesToAttach.size(); ++i)
  204912. {
  204913. files[i].nPosition = (ULONG) -1;
  204914. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204915. }
  204916. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204917. }
  204918. FreeLibrary (h);
  204919. return ok;
  204920. }
  204921. #endif
  204922. /*** End of inlined file: juce_win32_Network.cpp ***/
  204923. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204924. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204925. // compiled on its own).
  204926. #if JUCE_INCLUDED_FILE
  204927. static HKEY findKeyForPath (String name,
  204928. const bool createForWriting,
  204929. String& valueName)
  204930. {
  204931. HKEY rootKey = 0;
  204932. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204933. rootKey = HKEY_CURRENT_USER;
  204934. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204935. rootKey = HKEY_LOCAL_MACHINE;
  204936. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204937. rootKey = HKEY_CLASSES_ROOT;
  204938. if (rootKey != 0)
  204939. {
  204940. name = name.substring (name.indexOfChar ('\\') + 1);
  204941. const int lastSlash = name.lastIndexOfChar ('\\');
  204942. valueName = name.substring (lastSlash + 1);
  204943. name = name.substring (0, lastSlash);
  204944. HKEY key;
  204945. DWORD result;
  204946. if (createForWriting)
  204947. {
  204948. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204949. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204950. return key;
  204951. }
  204952. else
  204953. {
  204954. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204955. return key;
  204956. }
  204957. }
  204958. return 0;
  204959. }
  204960. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204961. const String& defaultValue)
  204962. {
  204963. String valueName, result (defaultValue);
  204964. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204965. if (k != 0)
  204966. {
  204967. WCHAR buffer [2048];
  204968. unsigned long bufferSize = sizeof (buffer);
  204969. DWORD type = REG_SZ;
  204970. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204971. {
  204972. if (type == REG_SZ)
  204973. result = buffer;
  204974. else if (type == REG_DWORD)
  204975. result = String ((int) *(DWORD*) buffer);
  204976. }
  204977. RegCloseKey (k);
  204978. }
  204979. return result;
  204980. }
  204981. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204982. const String& value)
  204983. {
  204984. String valueName;
  204985. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204986. if (k != 0)
  204987. {
  204988. RegSetValueEx (k, valueName, 0, REG_SZ,
  204989. (const BYTE*) (const WCHAR*) value,
  204990. sizeof (WCHAR) * (value.length() + 1));
  204991. RegCloseKey (k);
  204992. }
  204993. }
  204994. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204995. {
  204996. bool exists = false;
  204997. String valueName;
  204998. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204999. if (k != 0)
  205000. {
  205001. unsigned char buffer [2048];
  205002. unsigned long bufferSize = sizeof (buffer);
  205003. DWORD type = 0;
  205004. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205005. exists = true;
  205006. RegCloseKey (k);
  205007. }
  205008. return exists;
  205009. }
  205010. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205011. {
  205012. String valueName;
  205013. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205014. if (k != 0)
  205015. {
  205016. RegDeleteValue (k, valueName);
  205017. RegCloseKey (k);
  205018. }
  205019. }
  205020. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205021. {
  205022. String valueName;
  205023. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205024. if (k != 0)
  205025. {
  205026. RegDeleteKey (k, valueName);
  205027. RegCloseKey (k);
  205028. }
  205029. }
  205030. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205031. const String& symbolicDescription,
  205032. const String& fullDescription,
  205033. const File& targetExecutable,
  205034. int iconResourceNumber)
  205035. {
  205036. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205037. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205038. if (iconResourceNumber != 0)
  205039. setRegistryValue (key + "\\DefaultIcon\\",
  205040. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205041. setRegistryValue (key + "\\", fullDescription);
  205042. setRegistryValue (key + "\\shell\\open\\command\\",
  205043. targetExecutable.getFullPathName() + " %1");
  205044. }
  205045. bool juce_IsRunningInWine()
  205046. {
  205047. HKEY key;
  205048. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205049. {
  205050. RegCloseKey (key);
  205051. return true;
  205052. }
  205053. return false;
  205054. }
  205055. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205056. {
  205057. String s (::GetCommandLineW());
  205058. StringArray tokens;
  205059. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205060. return tokens.joinIntoString (" ", 1);
  205061. }
  205062. static void* currentModuleHandle = 0;
  205063. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205064. {
  205065. if (currentModuleHandle == 0)
  205066. currentModuleHandle = GetModuleHandle (0);
  205067. return currentModuleHandle;
  205068. }
  205069. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205070. {
  205071. currentModuleHandle = newHandle;
  205072. }
  205073. void PlatformUtilities::fpuReset()
  205074. {
  205075. #if JUCE_MSVC
  205076. _clearfp();
  205077. #endif
  205078. }
  205079. void PlatformUtilities::beep()
  205080. {
  205081. MessageBeep (MB_OK);
  205082. }
  205083. #endif
  205084. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205085. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205086. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205087. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205088. // compiled on its own).
  205089. #if JUCE_INCLUDED_FILE
  205090. static const unsigned int specialId = WM_APP + 0x4400;
  205091. static const unsigned int broadcastId = WM_APP + 0x4403;
  205092. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205093. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205094. HWND juce_messageWindowHandle = 0;
  205095. extern long improbableWindowNumber; // defined in windowing.cpp
  205096. #ifndef WM_APPCOMMAND
  205097. #define WM_APPCOMMAND 0x0319
  205098. #endif
  205099. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205100. const UINT message,
  205101. const WPARAM wParam,
  205102. const LPARAM lParam) throw()
  205103. {
  205104. JUCE_TRY
  205105. {
  205106. if (h == juce_messageWindowHandle)
  205107. {
  205108. if (message == specialCallbackId)
  205109. {
  205110. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205111. return (LRESULT) (*func) ((void*) lParam);
  205112. }
  205113. else if (message == specialId)
  205114. {
  205115. // these are trapped early in the dispatch call, but must also be checked
  205116. // here in case there are windows modal dialog boxes doing their own
  205117. // dispatch loop and not calling our version
  205118. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205119. return 0;
  205120. }
  205121. else if (message == broadcastId)
  205122. {
  205123. const ScopedPointer <String> messageString ((String*) lParam);
  205124. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205125. return 0;
  205126. }
  205127. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205128. {
  205129. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205130. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205131. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205132. return 0;
  205133. }
  205134. }
  205135. }
  205136. JUCE_CATCH_EXCEPTION
  205137. return DefWindowProc (h, message, wParam, lParam);
  205138. }
  205139. static bool isEventBlockedByModalComps (MSG& m)
  205140. {
  205141. if (Component::getNumCurrentlyModalComponents() == 0
  205142. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205143. return false;
  205144. switch (m.message)
  205145. {
  205146. case WM_MOUSEMOVE:
  205147. case WM_NCMOUSEMOVE:
  205148. case 0x020A: /* WM_MOUSEWHEEL */
  205149. case 0x020E: /* WM_MOUSEHWHEEL */
  205150. case WM_KEYUP:
  205151. case WM_SYSKEYUP:
  205152. case WM_CHAR:
  205153. case WM_APPCOMMAND:
  205154. case WM_LBUTTONUP:
  205155. case WM_MBUTTONUP:
  205156. case WM_RBUTTONUP:
  205157. case WM_MOUSEACTIVATE:
  205158. case WM_NCMOUSEHOVER:
  205159. case WM_MOUSEHOVER:
  205160. return true;
  205161. case WM_NCLBUTTONDOWN:
  205162. case WM_NCLBUTTONDBLCLK:
  205163. case WM_NCRBUTTONDOWN:
  205164. case WM_NCRBUTTONDBLCLK:
  205165. case WM_NCMBUTTONDOWN:
  205166. case WM_NCMBUTTONDBLCLK:
  205167. case WM_LBUTTONDOWN:
  205168. case WM_LBUTTONDBLCLK:
  205169. case WM_MBUTTONDOWN:
  205170. case WM_MBUTTONDBLCLK:
  205171. case WM_RBUTTONDOWN:
  205172. case WM_RBUTTONDBLCLK:
  205173. case WM_KEYDOWN:
  205174. case WM_SYSKEYDOWN:
  205175. {
  205176. Component* const modal = Component::getCurrentlyModalComponent (0);
  205177. if (modal != 0)
  205178. modal->inputAttemptWhenModal();
  205179. return true;
  205180. }
  205181. default:
  205182. break;
  205183. }
  205184. return false;
  205185. }
  205186. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205187. {
  205188. MSG m;
  205189. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205190. return false;
  205191. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205192. {
  205193. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205194. {
  205195. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205196. }
  205197. else if (m.message == WM_QUIT)
  205198. {
  205199. if (JUCEApplication::getInstance() != 0)
  205200. JUCEApplication::getInstance()->systemRequestedQuit();
  205201. }
  205202. else if (! isEventBlockedByModalComps (m))
  205203. {
  205204. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205205. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205206. {
  205207. // if it's someone else's window being clicked on, and the focus is
  205208. // currently on a juce window, pass the kb focus over..
  205209. HWND currentFocus = GetFocus();
  205210. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205211. SetFocus (m.hwnd);
  205212. }
  205213. TranslateMessage (&m);
  205214. DispatchMessage (&m);
  205215. }
  205216. }
  205217. return true;
  205218. }
  205219. bool juce_postMessageToSystemQueue (Message* message)
  205220. {
  205221. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205222. }
  205223. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205224. void* userData)
  205225. {
  205226. if (MessageManager::getInstance()->isThisTheMessageThread())
  205227. {
  205228. return (*callback) (userData);
  205229. }
  205230. else
  205231. {
  205232. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205233. // deadlock because the message manager is blocked from running, and can't
  205234. // call your function..
  205235. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205236. return (void*) SendMessage (juce_messageWindowHandle,
  205237. specialCallbackId,
  205238. (WPARAM) callback,
  205239. (LPARAM) userData);
  205240. }
  205241. }
  205242. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205243. {
  205244. if (hwnd != juce_messageWindowHandle)
  205245. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205246. return TRUE;
  205247. }
  205248. void MessageManager::broadcastMessage (const String& value)
  205249. {
  205250. Array<void*> windows;
  205251. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205252. const String localCopy (value);
  205253. COPYDATASTRUCT data;
  205254. data.dwData = broadcastId;
  205255. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205256. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205257. for (int i = windows.size(); --i >= 0;)
  205258. {
  205259. HWND hwnd = (HWND) windows.getUnchecked(i);
  205260. TCHAR windowName [64]; // no need to read longer strings than this
  205261. GetWindowText (hwnd, windowName, 64);
  205262. windowName [63] = 0;
  205263. if (String (windowName) == messageWindowName)
  205264. {
  205265. DWORD_PTR result;
  205266. SendMessageTimeout (hwnd, WM_COPYDATA,
  205267. (WPARAM) juce_messageWindowHandle,
  205268. (LPARAM) &data,
  205269. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205270. 8000,
  205271. &result);
  205272. }
  205273. }
  205274. }
  205275. static const String getMessageWindowClassName()
  205276. {
  205277. // this name has to be different for each app/dll instance because otherwise
  205278. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205279. // window class).
  205280. static int number = 0;
  205281. if (number == 0)
  205282. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205283. return "JUCEcs_" + String (number);
  205284. }
  205285. void MessageManager::doPlatformSpecificInitialisation()
  205286. {
  205287. OleInitialize (0);
  205288. const String className (getMessageWindowClassName());
  205289. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205290. WNDCLASSEX wc;
  205291. zerostruct (wc);
  205292. wc.cbSize = sizeof (wc);
  205293. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205294. wc.cbWndExtra = 4;
  205295. wc.hInstance = hmod;
  205296. wc.lpszClassName = className;
  205297. RegisterClassEx (&wc);
  205298. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205299. messageWindowName,
  205300. 0, 0, 0, 0, 0, 0, 0,
  205301. hmod, 0);
  205302. }
  205303. void MessageManager::doPlatformSpecificShutdown()
  205304. {
  205305. DestroyWindow (juce_messageWindowHandle);
  205306. UnregisterClass (getMessageWindowClassName(), 0);
  205307. OleUninitialize();
  205308. }
  205309. #endif
  205310. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205311. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205312. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205313. // compiled on its own).
  205314. #if JUCE_INCLUDED_FILE
  205315. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205316. NEWTEXTMETRICEXW*,
  205317. int type,
  205318. LPARAM lParam)
  205319. {
  205320. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205321. {
  205322. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205323. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205324. }
  205325. return 1;
  205326. }
  205327. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205328. NEWTEXTMETRICEXW*,
  205329. int type,
  205330. LPARAM lParam)
  205331. {
  205332. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205333. {
  205334. LOGFONTW lf;
  205335. zerostruct (lf);
  205336. lf.lfWeight = FW_DONTCARE;
  205337. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205338. lf.lfQuality = DEFAULT_QUALITY;
  205339. lf.lfCharSet = DEFAULT_CHARSET;
  205340. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205341. lf.lfPitchAndFamily = FF_DONTCARE;
  205342. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205343. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205344. HDC dc = CreateCompatibleDC (0);
  205345. EnumFontFamiliesEx (dc, &lf,
  205346. (FONTENUMPROCW) &wfontEnum2,
  205347. lParam, 0);
  205348. DeleteDC (dc);
  205349. }
  205350. return 1;
  205351. }
  205352. const StringArray Font::findAllTypefaceNames()
  205353. {
  205354. StringArray results;
  205355. HDC dc = CreateCompatibleDC (0);
  205356. {
  205357. LOGFONTW lf;
  205358. zerostruct (lf);
  205359. lf.lfWeight = FW_DONTCARE;
  205360. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205361. lf.lfQuality = DEFAULT_QUALITY;
  205362. lf.lfCharSet = DEFAULT_CHARSET;
  205363. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205364. lf.lfPitchAndFamily = FF_DONTCARE;
  205365. lf.lfFaceName[0] = 0;
  205366. EnumFontFamiliesEx (dc, &lf,
  205367. (FONTENUMPROCW) &wfontEnum1,
  205368. (LPARAM) &results, 0);
  205369. }
  205370. DeleteDC (dc);
  205371. results.sort (true);
  205372. return results;
  205373. }
  205374. extern bool juce_IsRunningInWine();
  205375. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205376. {
  205377. if (juce_IsRunningInWine())
  205378. {
  205379. // If we're running in Wine, then use fonts that might be available on Linux..
  205380. defaultSans = "Bitstream Vera Sans";
  205381. defaultSerif = "Bitstream Vera Serif";
  205382. defaultFixed = "Bitstream Vera Sans Mono";
  205383. }
  205384. else
  205385. {
  205386. defaultSans = "Verdana";
  205387. defaultSerif = "Times";
  205388. defaultFixed = "Lucida Console";
  205389. }
  205390. }
  205391. class FontDCHolder : private DeletedAtShutdown
  205392. {
  205393. public:
  205394. FontDCHolder()
  205395. : dc (0), numKPs (0), size (0),
  205396. bold (false), italic (false)
  205397. {
  205398. }
  205399. ~FontDCHolder()
  205400. {
  205401. if (dc != 0)
  205402. {
  205403. DeleteDC (dc);
  205404. DeleteObject (fontH);
  205405. }
  205406. clearSingletonInstance();
  205407. }
  205408. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205409. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205410. {
  205411. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205412. {
  205413. fontName = fontName_;
  205414. bold = bold_;
  205415. italic = italic_;
  205416. size = size_;
  205417. if (dc != 0)
  205418. {
  205419. DeleteDC (dc);
  205420. DeleteObject (fontH);
  205421. kps.free();
  205422. }
  205423. fontH = 0;
  205424. dc = CreateCompatibleDC (0);
  205425. SetMapperFlags (dc, 0);
  205426. SetMapMode (dc, MM_TEXT);
  205427. LOGFONTW lfw;
  205428. zerostruct (lfw);
  205429. lfw.lfCharSet = DEFAULT_CHARSET;
  205430. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205431. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205432. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205433. lfw.lfQuality = PROOF_QUALITY;
  205434. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205435. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205436. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205437. lfw.lfHeight = size > 0 ? size : -256;
  205438. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205439. if (standardSizedFont != 0)
  205440. {
  205441. if (SelectObject (dc, standardSizedFont) != 0)
  205442. {
  205443. fontH = standardSizedFont;
  205444. if (size == 0)
  205445. {
  205446. OUTLINETEXTMETRIC otm;
  205447. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205448. {
  205449. lfw.lfHeight = -(int) otm.otmEMSquare;
  205450. fontH = CreateFontIndirect (&lfw);
  205451. SelectObject (dc, fontH);
  205452. DeleteObject (standardSizedFont);
  205453. }
  205454. }
  205455. }
  205456. else
  205457. {
  205458. jassertfalse;
  205459. }
  205460. }
  205461. else
  205462. {
  205463. jassertfalse;
  205464. }
  205465. }
  205466. return dc;
  205467. }
  205468. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205469. {
  205470. if (kps == 0)
  205471. {
  205472. numKPs = GetKerningPairs (dc, 0, 0);
  205473. kps.calloc (numKPs);
  205474. GetKerningPairs (dc, numKPs, kps);
  205475. }
  205476. numKPs_ = numKPs;
  205477. return kps;
  205478. }
  205479. private:
  205480. HFONT fontH;
  205481. HDC dc;
  205482. String fontName;
  205483. HeapBlock <KERNINGPAIR> kps;
  205484. int numKPs, size;
  205485. bool bold, italic;
  205486. FontDCHolder (const FontDCHolder&);
  205487. FontDCHolder& operator= (const FontDCHolder&);
  205488. };
  205489. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205490. class WindowsTypeface : public CustomTypeface
  205491. {
  205492. public:
  205493. WindowsTypeface (const Font& font)
  205494. {
  205495. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205496. font.isBold(), font.isItalic(), 0);
  205497. TEXTMETRIC tm;
  205498. tm.tmAscent = tm.tmHeight = 1;
  205499. tm.tmDefaultChar = 0;
  205500. GetTextMetrics (dc, &tm);
  205501. setCharacteristics (font.getTypefaceName(),
  205502. tm.tmAscent / (float) tm.tmHeight,
  205503. font.isBold(), font.isItalic(),
  205504. tm.tmDefaultChar);
  205505. }
  205506. bool loadGlyphIfPossible (juce_wchar character)
  205507. {
  205508. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205509. GLYPHMETRICS gm;
  205510. {
  205511. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205512. WORD index = 0;
  205513. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205514. && index == 0xffff)
  205515. {
  205516. return false;
  205517. }
  205518. }
  205519. Path glyphPath;
  205520. TEXTMETRIC tm;
  205521. if (! GetTextMetrics (dc, &tm))
  205522. {
  205523. addGlyph (character, glyphPath, 0);
  205524. return true;
  205525. }
  205526. const float height = (float) tm.tmHeight;
  205527. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205528. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205529. &gm, 0, 0, &identityMatrix);
  205530. if (bufSize > 0)
  205531. {
  205532. HeapBlock<char> data (bufSize);
  205533. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205534. bufSize, data, &identityMatrix);
  205535. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205536. const float scaleX = 1.0f / height;
  205537. const float scaleY = -1.0f / height;
  205538. while ((char*) pheader < data + bufSize)
  205539. {
  205540. float x = scaleX * pheader->pfxStart.x.value;
  205541. float y = scaleY * pheader->pfxStart.y.value;
  205542. glyphPath.startNewSubPath (x, y);
  205543. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205544. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205545. while ((const char*) curve < curveEnd)
  205546. {
  205547. if (curve->wType == TT_PRIM_LINE)
  205548. {
  205549. for (int i = 0; i < curve->cpfx; ++i)
  205550. {
  205551. x = scaleX * curve->apfx[i].x.value;
  205552. y = scaleY * curve->apfx[i].y.value;
  205553. glyphPath.lineTo (x, y);
  205554. }
  205555. }
  205556. else if (curve->wType == TT_PRIM_QSPLINE)
  205557. {
  205558. for (int i = 0; i < curve->cpfx - 1; ++i)
  205559. {
  205560. const float x2 = scaleX * curve->apfx[i].x.value;
  205561. const float y2 = scaleY * curve->apfx[i].y.value;
  205562. float x3, y3;
  205563. if (i < curve->cpfx - 2)
  205564. {
  205565. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205566. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205567. }
  205568. else
  205569. {
  205570. x3 = scaleX * curve->apfx[i + 1].x.value;
  205571. y3 = scaleY * curve->apfx[i + 1].y.value;
  205572. }
  205573. glyphPath.quadraticTo (x2, y2, x3, y3);
  205574. x = x3;
  205575. y = y3;
  205576. }
  205577. }
  205578. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205579. }
  205580. pheader = (const TTPOLYGONHEADER*) curve;
  205581. glyphPath.closeSubPath();
  205582. }
  205583. }
  205584. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205585. int numKPs;
  205586. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205587. for (int i = 0; i < numKPs; ++i)
  205588. {
  205589. if (kps[i].wFirst == character)
  205590. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205591. kps[i].iKernAmount / height);
  205592. }
  205593. return true;
  205594. }
  205595. juce_UseDebuggingNewOperator
  205596. };
  205597. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205598. {
  205599. return new WindowsTypeface (font);
  205600. }
  205601. #endif
  205602. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205603. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205604. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205605. // compiled on its own).
  205606. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205607. class SharedD2DFactory : public DeletedAtShutdown
  205608. {
  205609. public:
  205610. SharedD2DFactory()
  205611. {
  205612. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205613. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205614. if (directWriteFactory != 0)
  205615. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205616. }
  205617. ~SharedD2DFactory()
  205618. {
  205619. clearSingletonInstance();
  205620. }
  205621. juce_DeclareSingleton (SharedD2DFactory, false);
  205622. ComSmartPtr <ID2D1Factory> d2dFactory;
  205623. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205624. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205625. };
  205626. juce_ImplementSingleton (SharedD2DFactory)
  205627. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205628. {
  205629. public:
  205630. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205631. : hwnd (hwnd_),
  205632. currentState (0)
  205633. {
  205634. RECT windowRect;
  205635. GetClientRect (hwnd, &windowRect);
  205636. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205637. bounds.setSize (size.width, size.height);
  205638. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205639. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205640. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205641. // xxx check for error
  205642. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205643. }
  205644. ~Direct2DLowLevelGraphicsContext()
  205645. {
  205646. states.clear();
  205647. }
  205648. void resized()
  205649. {
  205650. RECT windowRect;
  205651. GetClientRect (hwnd, &windowRect);
  205652. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205653. renderingTarget->Resize (size);
  205654. bounds.setSize (size.width, size.height);
  205655. }
  205656. void clear()
  205657. {
  205658. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205659. }
  205660. void start()
  205661. {
  205662. renderingTarget->BeginDraw();
  205663. saveState();
  205664. }
  205665. void end()
  205666. {
  205667. states.clear();
  205668. currentState = 0;
  205669. renderingTarget->EndDraw();
  205670. renderingTarget->CheckWindowState();
  205671. }
  205672. bool isVectorDevice() const { return false; }
  205673. void setOrigin (int x, int y)
  205674. {
  205675. currentState->origin.addXY (x, y);
  205676. }
  205677. bool clipToRectangle (const Rectangle<int>& r)
  205678. {
  205679. currentState->clipToRectangle (r);
  205680. return ! isClipEmpty();
  205681. }
  205682. bool clipToRectangleList (const RectangleList& clipRegion)
  205683. {
  205684. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205685. return ! isClipEmpty();
  205686. }
  205687. void excludeClipRectangle (const Rectangle<int>&)
  205688. {
  205689. //xxx
  205690. }
  205691. void clipToPath (const Path& path, const AffineTransform& transform)
  205692. {
  205693. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205694. }
  205695. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205696. {
  205697. currentState->clipToImage (sourceImage,transform);
  205698. }
  205699. bool clipRegionIntersects (const Rectangle<int>& r)
  205700. {
  205701. const Rectangle<int> r2 (r + currentState->origin);
  205702. return currentState->clipRect.intersects (r2);
  205703. }
  205704. const Rectangle<int> getClipBounds() const
  205705. {
  205706. // xxx could this take into account complex clip regions?
  205707. return currentState->clipRect - currentState->origin;
  205708. }
  205709. bool isClipEmpty() const
  205710. {
  205711. return currentState->clipRect.isEmpty();
  205712. }
  205713. void saveState()
  205714. {
  205715. states.add (new SavedState (*this));
  205716. currentState = states.getLast();
  205717. }
  205718. void restoreState()
  205719. {
  205720. jassert (states.size() > 1) //you should never pop the last state!
  205721. states.removeLast (1);
  205722. currentState = states.getLast();
  205723. }
  205724. void setFill (const FillType& fillType)
  205725. {
  205726. currentState->setFill (fillType);
  205727. }
  205728. void setOpacity (float newOpacity)
  205729. {
  205730. currentState->setOpacity (newOpacity);
  205731. }
  205732. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205733. {
  205734. }
  205735. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205736. {
  205737. currentState->createBrush();
  205738. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205739. }
  205740. void fillPath (const Path& p, const AffineTransform& transform)
  205741. {
  205742. currentState->createBrush();
  205743. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205744. if (renderingTarget != 0)
  205745. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205746. }
  205747. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205748. {
  205749. const int x = currentState->origin.getX();
  205750. const int y = currentState->origin.getY();
  205751. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205752. D2D1_SIZE_U size;
  205753. size.width = image.getWidth();
  205754. size.height = image.getHeight();
  205755. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205756. Image img (image.convertedToFormat (Image::ARGB));
  205757. Image::BitmapData bd (img, false);
  205758. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205759. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205760. {
  205761. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205762. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205763. if (tempBitmap != 0)
  205764. renderingTarget->DrawBitmap (tempBitmap);
  205765. }
  205766. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205767. }
  205768. void drawLine (const Line <float>& line)
  205769. {
  205770. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205771. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205772. line.getEnd() + currentState->origin.toFloat());
  205773. currentState->createBrush();
  205774. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205775. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205776. currentState->currentBrush);
  205777. }
  205778. void drawVerticalLine (int x, float top, float bottom)
  205779. {
  205780. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205781. currentState->createBrush();
  205782. x += currentState->origin.getX();
  205783. const int y = currentState->origin.getY();
  205784. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205785. D2D1::Point2F (x, y + bottom),
  205786. currentState->currentBrush);
  205787. }
  205788. void drawHorizontalLine (int y, float left, float right)
  205789. {
  205790. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205791. currentState->createBrush();
  205792. y += currentState->origin.getY();
  205793. const int x = currentState->origin.getX();
  205794. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205795. D2D1::Point2F (x + right, y),
  205796. currentState->currentBrush);
  205797. }
  205798. void setFont (const Font& newFont)
  205799. {
  205800. currentState->setFont (newFont);
  205801. }
  205802. const Font getFont()
  205803. {
  205804. return currentState->font;
  205805. }
  205806. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205807. {
  205808. const float x = currentState->origin.getX();
  205809. const float y = currentState->origin.getY();
  205810. currentState->createBrush();
  205811. currentState->createFont();
  205812. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205813. float hScale = currentState->font.getHorizontalScale();
  205814. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205815. float dpiX = 0, dpiY = 0;
  205816. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205817. UINT32 glyphNum = glyphNumber;
  205818. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205819. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205820. DWRITE_GLYPH_OFFSET offset;
  205821. offset.advanceOffset = 0;
  205822. offset.ascenderOffset = 0;
  205823. float glyphAdvances = 0;
  205824. DWRITE_GLYPH_RUN glyph;
  205825. glyph.fontFace = currentState->currentFontFace;
  205826. glyph.glyphCount = 1;
  205827. glyph.glyphIndices = &glyphNum1;
  205828. glyph.isSideways = FALSE;
  205829. glyph.glyphAdvances = &glyphAdvances;
  205830. glyph.glyphOffsets = &offset;
  205831. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205832. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205833. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205834. }
  205835. class SavedState
  205836. {
  205837. public:
  205838. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205839. : owner (owner_), currentBrush (0),
  205840. fontScaling (1.0f), currentFontFace (0),
  205841. clipsRect (false), shouldClipRect (false),
  205842. clipsRectList (false), shouldClipRectList (false),
  205843. clipsComplex (false), shouldClipComplex (false),
  205844. clipsBitmap (false), shouldClipBitmap (false)
  205845. {
  205846. if (owner.currentState != 0)
  205847. {
  205848. // xxx seems like a very slow way to create one of these, and this is a performance
  205849. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205850. setFill (owner.currentState->fillType);
  205851. currentBrush = owner.currentState->currentBrush;
  205852. origin = owner.currentState->origin;
  205853. clipRect = owner.currentState->clipRect;
  205854. font = owner.currentState->font;
  205855. currentFontFace = owner.currentState->currentFontFace;
  205856. }
  205857. else
  205858. {
  205859. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205860. clipRect.setSize (size.width, size.height);
  205861. setFill (FillType (Colours::black));
  205862. }
  205863. }
  205864. ~SavedState()
  205865. {
  205866. clearClip();
  205867. clearFont();
  205868. clearFill();
  205869. clearPathClip();
  205870. clearImageClip();
  205871. complexClipLayer = 0;
  205872. bitmapMaskLayer = 0;
  205873. }
  205874. void clearClip()
  205875. {
  205876. popClips();
  205877. shouldClipRect = false;
  205878. }
  205879. void clipToRectangle (const Rectangle<int>& r)
  205880. {
  205881. clearClip();
  205882. clipRect = r + origin;
  205883. shouldClipRect = true;
  205884. pushClips();
  205885. }
  205886. void clearPathClip()
  205887. {
  205888. popClips();
  205889. if (shouldClipComplex)
  205890. {
  205891. complexClipGeometry = 0;
  205892. shouldClipComplex = false;
  205893. }
  205894. }
  205895. void clipToPath (ID2D1Geometry* geometry)
  205896. {
  205897. clearPathClip();
  205898. if (complexClipLayer == 0)
  205899. owner.renderingTarget->CreateLayer (&complexClipLayer);
  205900. complexClipGeometry = geometry;
  205901. shouldClipComplex = true;
  205902. pushClips();
  205903. }
  205904. void clearRectListClip()
  205905. {
  205906. popClips();
  205907. if (shouldClipRectList)
  205908. {
  205909. rectListGeometry = 0;
  205910. shouldClipRectList = false;
  205911. }
  205912. }
  205913. void clipToRectList (ID2D1Geometry* geometry)
  205914. {
  205915. clearRectListClip();
  205916. if (rectListLayer == 0)
  205917. owner.renderingTarget->CreateLayer (&rectListLayer);
  205918. rectListGeometry = geometry;
  205919. shouldClipRectList = true;
  205920. pushClips();
  205921. }
  205922. void clearImageClip()
  205923. {
  205924. popClips();
  205925. if (shouldClipBitmap)
  205926. {
  205927. maskBitmap = 0;
  205928. bitmapMaskBrush = 0;
  205929. shouldClipBitmap = false;
  205930. }
  205931. }
  205932. void clipToImage (const Image& image, const AffineTransform& transform)
  205933. {
  205934. clearImageClip();
  205935. if (bitmapMaskLayer == 0)
  205936. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  205937. D2D1_BRUSH_PROPERTIES brushProps;
  205938. brushProps.opacity = 1;
  205939. brushProps.transform = transfromToMatrix (transform);
  205940. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205941. D2D1_SIZE_U size;
  205942. size.width = image.getWidth();
  205943. size.height = image.getHeight();
  205944. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205945. maskImage = image.convertedToFormat (Image::ARGB);
  205946. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205947. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205948. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205949. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  205950. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  205951. imageMaskLayerParams = D2D1::LayerParameters();
  205952. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205953. shouldClipBitmap = true;
  205954. pushClips();
  205955. }
  205956. void popClips()
  205957. {
  205958. if (clipsBitmap)
  205959. {
  205960. owner.renderingTarget->PopLayer();
  205961. clipsBitmap = false;
  205962. }
  205963. if (clipsComplex)
  205964. {
  205965. owner.renderingTarget->PopLayer();
  205966. clipsComplex = false;
  205967. }
  205968. if (clipsRectList)
  205969. {
  205970. owner.renderingTarget->PopLayer();
  205971. clipsRectList = false;
  205972. }
  205973. if (clipsRect)
  205974. {
  205975. owner.renderingTarget->PopAxisAlignedClip();
  205976. clipsRect = false;
  205977. }
  205978. }
  205979. void pushClips()
  205980. {
  205981. if (shouldClipRect && ! clipsRect)
  205982. {
  205983. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  205984. clipsRect = true;
  205985. }
  205986. if (shouldClipRectList && ! clipsRectList)
  205987. {
  205988. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205989. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205990. layerParams.geometricMask = rectListGeometry;
  205991. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  205992. clipsRectList = true;
  205993. }
  205994. if (shouldClipComplex && ! clipsComplex)
  205995. {
  205996. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205997. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205998. layerParams.geometricMask = complexClipGeometry;
  205999. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206000. clipsComplex = true;
  206001. }
  206002. if (shouldClipBitmap && ! clipsBitmap)
  206003. {
  206004. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206005. clipsBitmap = true;
  206006. }
  206007. }
  206008. void setFill (const FillType& newFillType)
  206009. {
  206010. if (fillType != newFillType)
  206011. {
  206012. fillType = newFillType;
  206013. clearFill();
  206014. }
  206015. }
  206016. void clearFont()
  206017. {
  206018. currentFontFace = localFontFace = 0;
  206019. }
  206020. void setFont (const Font& newFont)
  206021. {
  206022. if (font != newFont)
  206023. {
  206024. font = newFont;
  206025. clearFont();
  206026. }
  206027. }
  206028. void createFont()
  206029. {
  206030. // xxx The font shouldn't be managed by the graphics context.
  206031. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206032. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206033. // WindowsTypeface class.
  206034. if (currentFontFace == 0)
  206035. {
  206036. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206037. fontScaling = systemType->getAscent();
  206038. BOOL fontFound;
  206039. uint32 fontIndex;
  206040. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206041. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206042. if (! fontFound)
  206043. fontIndex = 0;
  206044. ComSmartPtr <IDWriteFontFamily> fontFam;
  206045. fonts->GetFontFamily (fontIndex, &fontFam);
  206046. ComSmartPtr <IDWriteFont> font;
  206047. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206048. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206049. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206050. font->CreateFontFace (&localFontFace);
  206051. currentFontFace = localFontFace;
  206052. }
  206053. }
  206054. void setOpacity (float newOpacity)
  206055. {
  206056. fillType.setOpacity (newOpacity);
  206057. if (currentBrush != 0)
  206058. currentBrush->SetOpacity (newOpacity);
  206059. }
  206060. void clearFill()
  206061. {
  206062. gradientStops = 0;
  206063. linearGradient = 0;
  206064. radialGradient = 0;
  206065. bitmap = 0;
  206066. bitmapBrush = 0;
  206067. currentBrush = 0;
  206068. }
  206069. void createBrush()
  206070. {
  206071. if (currentBrush == 0)
  206072. {
  206073. const int x = origin.getX();
  206074. const int y = origin.getY();
  206075. if (fillType.isColour())
  206076. {
  206077. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206078. owner.colourBrush->SetColor (colour);
  206079. currentBrush = owner.colourBrush;
  206080. }
  206081. else if (fillType.isTiledImage())
  206082. {
  206083. D2D1_BRUSH_PROPERTIES brushProps;
  206084. brushProps.opacity = fillType.getOpacity();
  206085. brushProps.transform = transfromToMatrix (fillType.transform);
  206086. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206087. image = fillType.image;
  206088. D2D1_SIZE_U size;
  206089. size.width = image.getWidth();
  206090. size.height = image.getHeight();
  206091. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206092. this->image = image.convertedToFormat (Image::ARGB);
  206093. Image::BitmapData bd (this->image, false);
  206094. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206095. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206096. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206097. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206098. currentBrush = bitmapBrush;
  206099. }
  206100. else if (fillType.isGradient())
  206101. {
  206102. gradientStops = 0;
  206103. D2D1_BRUSH_PROPERTIES brushProps;
  206104. brushProps.opacity = fillType.getOpacity();
  206105. brushProps.transform = transfromToMatrix (fillType.transform);
  206106. const int numColors = fillType.gradient->getNumColours();
  206107. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206108. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206109. {
  206110. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206111. stops[i].position = fillType.gradient->getColourPosition(i);
  206112. }
  206113. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206114. if (fillType.gradient->isRadial)
  206115. {
  206116. radialGradient = 0;
  206117. const Point<float>& p1 = fillType.gradient->point1;
  206118. const Point<float>& p2 = fillType.gradient->point2;
  206119. float r = p1.getDistanceFrom (p2);
  206120. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206121. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206122. D2D1::Point2F (0, 0),
  206123. r, r);
  206124. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206125. currentBrush = radialGradient;
  206126. }
  206127. else
  206128. {
  206129. linearGradient = 0;
  206130. const Point<float>& p1 = fillType.gradient->point1;
  206131. const Point<float>& p2 = fillType.gradient->point2;
  206132. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206133. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206134. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206135. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206136. currentBrush = linearGradient;
  206137. }
  206138. }
  206139. }
  206140. }
  206141. juce_UseDebuggingNewOperator
  206142. //xxx most of these members should probably be private...
  206143. Direct2DLowLevelGraphicsContext& owner;
  206144. Point<int> origin;
  206145. Font font;
  206146. float fontScaling;
  206147. IDWriteFontFace* currentFontFace;
  206148. ComSmartPtr <IDWriteFontFace> localFontFace;
  206149. FillType fillType;
  206150. Image image;
  206151. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206152. Rectangle<int> clipRect;
  206153. bool clipsRect, shouldClipRect;
  206154. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206155. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206156. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206157. bool clipsComplex, shouldClipComplex;
  206158. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206159. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206160. ComSmartPtr <ID2D1Layer> rectListLayer;
  206161. bool clipsRectList, shouldClipRectList;
  206162. Image maskImage;
  206163. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206164. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206165. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206166. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206167. bool clipsBitmap, shouldClipBitmap;
  206168. ID2D1Brush* currentBrush;
  206169. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206170. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206171. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206172. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206173. private:
  206174. SavedState (const SavedState&);
  206175. SavedState& operator= (const SavedState& other);
  206176. };
  206177. juce_UseDebuggingNewOperator
  206178. private:
  206179. HWND hwnd;
  206180. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206181. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206182. Rectangle<int> bounds;
  206183. SavedState* currentState;
  206184. OwnedArray<SavedState> states;
  206185. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206186. {
  206187. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206188. }
  206189. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206190. {
  206191. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206192. }
  206193. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206194. {
  206195. transform.transformPoint (x, y);
  206196. return D2D1::Point2F (x, y);
  206197. }
  206198. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206199. {
  206200. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206201. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206202. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206203. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206204. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206205. }
  206206. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206207. {
  206208. ID2D1PathGeometry* p = 0;
  206209. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206210. ComSmartPtr <ID2D1GeometrySink> sink;
  206211. HRESULT hr = p->Open (&sink); // xxx handle error
  206212. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206213. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206214. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206215. hr = sink->Close();
  206216. return p;
  206217. }
  206218. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206219. {
  206220. Path::Iterator it (path);
  206221. while (it.next())
  206222. {
  206223. switch (it.elementType)
  206224. {
  206225. case Path::Iterator::cubicTo:
  206226. {
  206227. D2D1_BEZIER_SEGMENT seg;
  206228. transform.transformPoint (it.x1, it.y1);
  206229. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206230. transform.transformPoint (it.x2, it.y2);
  206231. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206232. transform.transformPoint(it.x3, it.y3);
  206233. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206234. sink->AddBezier (seg);
  206235. break;
  206236. }
  206237. case Path::Iterator::lineTo:
  206238. {
  206239. transform.transformPoint (it.x1, it.y1);
  206240. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206241. break;
  206242. }
  206243. case Path::Iterator::quadraticTo:
  206244. {
  206245. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206246. transform.transformPoint (it.x1, it.y1);
  206247. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206248. transform.transformPoint (it.x2, it.y2);
  206249. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206250. sink->AddQuadraticBezier (seg);
  206251. break;
  206252. }
  206253. case Path::Iterator::closePath:
  206254. {
  206255. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206256. break;
  206257. }
  206258. case Path::Iterator::startNewSubPath:
  206259. {
  206260. transform.transformPoint (it.x1, it.y1);
  206261. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206262. break;
  206263. }
  206264. }
  206265. }
  206266. }
  206267. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206268. {
  206269. ID2D1PathGeometry* p = 0;
  206270. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206271. ComSmartPtr <ID2D1GeometrySink> sink;
  206272. HRESULT hr = p->Open (&sink);
  206273. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206274. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206275. hr = sink->Close();
  206276. return p;
  206277. }
  206278. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206279. {
  206280. D2D1::Matrix3x2F matrix;
  206281. matrix._11 = transform.mat00;
  206282. matrix._12 = transform.mat10;
  206283. matrix._21 = transform.mat01;
  206284. matrix._22 = transform.mat11;
  206285. matrix._31 = transform.mat02;
  206286. matrix._32 = transform.mat12;
  206287. return matrix;
  206288. }
  206289. };
  206290. #endif
  206291. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206292. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206293. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206294. // compiled on its own).
  206295. #if JUCE_INCLUDED_FILE
  206296. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206297. // these are in the windows SDK, but need to be repeated here for GCC..
  206298. #ifndef GET_APPCOMMAND_LPARAM
  206299. #define FAPPCOMMAND_MASK 0xF000
  206300. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206301. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206302. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206303. #define APPCOMMAND_MEDIA_STOP 13
  206304. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206305. #define WM_APPCOMMAND 0x0319
  206306. #endif
  206307. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206308. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206309. extern bool juce_IsRunningInWine();
  206310. #ifndef ULW_ALPHA
  206311. #define ULW_ALPHA 0x00000002
  206312. #endif
  206313. #ifndef AC_SRC_ALPHA
  206314. #define AC_SRC_ALPHA 0x01
  206315. #endif
  206316. static HPALETTE palette = 0;
  206317. static bool createPaletteIfNeeded = true;
  206318. static bool shouldDeactivateTitleBar = true;
  206319. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206320. #define WM_TRAYNOTIFY WM_USER + 100
  206321. using ::abs;
  206322. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206323. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206324. bool Desktop::canUseSemiTransparentWindows() throw()
  206325. {
  206326. if (updateLayeredWindow == 0)
  206327. {
  206328. if (! juce_IsRunningInWine())
  206329. {
  206330. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206331. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206332. }
  206333. }
  206334. return updateLayeredWindow != 0;
  206335. }
  206336. const int extendedKeyModifier = 0x10000;
  206337. const int KeyPress::spaceKey = VK_SPACE;
  206338. const int KeyPress::returnKey = VK_RETURN;
  206339. const int KeyPress::escapeKey = VK_ESCAPE;
  206340. const int KeyPress::backspaceKey = VK_BACK;
  206341. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206342. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206343. const int KeyPress::tabKey = VK_TAB;
  206344. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206345. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206346. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206347. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206348. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206349. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206350. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206351. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206352. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206353. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206354. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206355. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206356. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206357. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206358. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206359. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206360. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206361. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206362. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206363. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206364. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206365. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206366. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206367. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206368. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206369. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206370. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206371. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206372. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206373. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206374. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206375. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206376. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206377. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206378. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206379. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206380. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206381. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206382. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206383. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206384. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206385. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206386. const int KeyPress::playKey = 0x30000;
  206387. const int KeyPress::stopKey = 0x30001;
  206388. const int KeyPress::fastForwardKey = 0x30002;
  206389. const int KeyPress::rewindKey = 0x30003;
  206390. class WindowsBitmapImage : public Image::SharedImage
  206391. {
  206392. public:
  206393. HBITMAP hBitmap;
  206394. BITMAPV4HEADER bitmapInfo;
  206395. HDC hdc;
  206396. unsigned char* bitmapData;
  206397. WindowsBitmapImage (const Image::PixelFormat format_,
  206398. const int w, const int h, const bool clearImage)
  206399. : Image::SharedImage (format_, w, h)
  206400. {
  206401. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206402. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206403. zerostruct (bitmapInfo);
  206404. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206405. bitmapInfo.bV4Width = w;
  206406. bitmapInfo.bV4Height = h;
  206407. bitmapInfo.bV4Planes = 1;
  206408. bitmapInfo.bV4CSType = 1;
  206409. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206410. if (format_ == Image::ARGB)
  206411. {
  206412. bitmapInfo.bV4AlphaMask = 0xff000000;
  206413. bitmapInfo.bV4RedMask = 0xff0000;
  206414. bitmapInfo.bV4GreenMask = 0xff00;
  206415. bitmapInfo.bV4BlueMask = 0xff;
  206416. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206417. }
  206418. else
  206419. {
  206420. bitmapInfo.bV4V4Compression = BI_RGB;
  206421. }
  206422. lineStride = -((w * pixelStride + 3) & ~3);
  206423. HDC dc = GetDC (0);
  206424. hdc = CreateCompatibleDC (dc);
  206425. ReleaseDC (0, dc);
  206426. SetMapMode (hdc, MM_TEXT);
  206427. hBitmap = CreateDIBSection (hdc,
  206428. (BITMAPINFO*) &(bitmapInfo),
  206429. DIB_RGB_COLORS,
  206430. (void**) &bitmapData,
  206431. 0, 0);
  206432. SelectObject (hdc, hBitmap);
  206433. if (format_ == Image::ARGB && clearImage)
  206434. zeromem (bitmapData, abs (h * lineStride));
  206435. imageData = bitmapData - (lineStride * (h - 1));
  206436. }
  206437. ~WindowsBitmapImage()
  206438. {
  206439. DeleteDC (hdc);
  206440. DeleteObject (hBitmap);
  206441. }
  206442. Image::ImageType getType() const { return Image::NativeImage; }
  206443. LowLevelGraphicsContext* createLowLevelContext()
  206444. {
  206445. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206446. }
  206447. SharedImage* clone()
  206448. {
  206449. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206450. for (int i = 0; i < height; ++i)
  206451. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206452. return im;
  206453. }
  206454. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206455. const int x, const int y,
  206456. const RectangleList& maskedRegion) throw()
  206457. {
  206458. static HDRAWDIB hdd = 0;
  206459. static bool needToCreateDrawDib = true;
  206460. if (needToCreateDrawDib)
  206461. {
  206462. needToCreateDrawDib = false;
  206463. HDC dc = GetDC (0);
  206464. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206465. ReleaseDC (0, dc);
  206466. // only open if we're not palettised
  206467. if (n > 8)
  206468. hdd = DrawDibOpen();
  206469. }
  206470. if (createPaletteIfNeeded)
  206471. {
  206472. HDC dc = GetDC (0);
  206473. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206474. ReleaseDC (0, dc);
  206475. if (n <= 8)
  206476. palette = CreateHalftonePalette (dc);
  206477. createPaletteIfNeeded = false;
  206478. }
  206479. if (palette != 0)
  206480. {
  206481. SelectPalette (dc, palette, FALSE);
  206482. RealizePalette (dc);
  206483. SetStretchBltMode (dc, HALFTONE);
  206484. }
  206485. SetMapMode (dc, MM_TEXT);
  206486. if (transparent)
  206487. {
  206488. POINT p, pos;
  206489. SIZE size;
  206490. RECT windowBounds;
  206491. GetWindowRect (hwnd, &windowBounds);
  206492. p.x = -x;
  206493. p.y = -y;
  206494. pos.x = windowBounds.left;
  206495. pos.y = windowBounds.top;
  206496. size.cx = windowBounds.right - windowBounds.left;
  206497. size.cy = windowBounds.bottom - windowBounds.top;
  206498. BLENDFUNCTION bf;
  206499. bf.AlphaFormat = AC_SRC_ALPHA;
  206500. bf.BlendFlags = 0;
  206501. bf.BlendOp = AC_SRC_OVER;
  206502. bf.SourceConstantAlpha = 0xff;
  206503. if (! maskedRegion.isEmpty())
  206504. {
  206505. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206506. {
  206507. const Rectangle<int>& r = *i.getRectangle();
  206508. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206509. }
  206510. }
  206511. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206512. }
  206513. else
  206514. {
  206515. int savedDC = 0;
  206516. if (! maskedRegion.isEmpty())
  206517. {
  206518. savedDC = SaveDC (dc);
  206519. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206520. {
  206521. const Rectangle<int>& r = *i.getRectangle();
  206522. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206523. }
  206524. }
  206525. if (hdd == 0)
  206526. {
  206527. StretchDIBits (dc,
  206528. x, y, width, height,
  206529. 0, 0, width, height,
  206530. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206531. DIB_RGB_COLORS, SRCCOPY);
  206532. }
  206533. else
  206534. {
  206535. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206536. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206537. 0, 0, width, height, 0);
  206538. }
  206539. if (! maskedRegion.isEmpty())
  206540. RestoreDC (dc, savedDC);
  206541. }
  206542. }
  206543. juce_UseDebuggingNewOperator
  206544. private:
  206545. WindowsBitmapImage (const WindowsBitmapImage&);
  206546. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206547. };
  206548. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206549. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206550. {
  206551. SHORT k = (SHORT) keyCode;
  206552. if ((keyCode & extendedKeyModifier) == 0
  206553. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206554. k += (SHORT) 'A' - (SHORT) 'a';
  206555. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206556. (SHORT) '+', VK_OEM_PLUS,
  206557. (SHORT) '-', VK_OEM_MINUS,
  206558. (SHORT) '.', VK_OEM_PERIOD,
  206559. (SHORT) ';', VK_OEM_1,
  206560. (SHORT) ':', VK_OEM_1,
  206561. (SHORT) '/', VK_OEM_2,
  206562. (SHORT) '?', VK_OEM_2,
  206563. (SHORT) '[', VK_OEM_4,
  206564. (SHORT) ']', VK_OEM_6 };
  206565. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206566. if (k == translatedValues [i])
  206567. k = translatedValues [i + 1];
  206568. return (GetKeyState (k) & 0x8000) != 0;
  206569. }
  206570. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206571. {
  206572. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206573. return callback (userData);
  206574. else
  206575. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206576. }
  206577. class Win32ComponentPeer : public ComponentPeer
  206578. {
  206579. public:
  206580. enum RenderingEngineType
  206581. {
  206582. softwareRenderingEngine = 0,
  206583. direct2DRenderingEngine
  206584. };
  206585. Win32ComponentPeer (Component* const component,
  206586. const int windowStyleFlags)
  206587. : ComponentPeer (component, windowStyleFlags),
  206588. dontRepaint (false),
  206589. #if JUCE_DIRECT2D
  206590. currentRenderingEngine (direct2DRenderingEngine),
  206591. #else
  206592. currentRenderingEngine (softwareRenderingEngine),
  206593. #endif
  206594. fullScreen (false),
  206595. isDragging (false),
  206596. isMouseOver (false),
  206597. hasCreatedCaret (false),
  206598. currentWindowIcon (0),
  206599. dropTarget (0)
  206600. {
  206601. callFunctionIfNotLocked (&createWindowCallback, this);
  206602. setTitle (component->getName());
  206603. if ((windowStyleFlags & windowHasDropShadow) != 0
  206604. && Desktop::canUseSemiTransparentWindows())
  206605. {
  206606. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206607. if (shadower != 0)
  206608. shadower->setOwner (component);
  206609. }
  206610. }
  206611. ~Win32ComponentPeer()
  206612. {
  206613. setTaskBarIcon (Image());
  206614. shadower = 0;
  206615. // do this before the next bit to avoid messages arriving for this window
  206616. // before it's destroyed
  206617. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206618. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206619. if (currentWindowIcon != 0)
  206620. DestroyIcon (currentWindowIcon);
  206621. if (dropTarget != 0)
  206622. {
  206623. dropTarget->Release();
  206624. dropTarget = 0;
  206625. }
  206626. #if JUCE_DIRECT2D
  206627. direct2DContext = 0;
  206628. #endif
  206629. }
  206630. void* getNativeHandle() const
  206631. {
  206632. return hwnd;
  206633. }
  206634. void setVisible (bool shouldBeVisible)
  206635. {
  206636. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206637. if (shouldBeVisible)
  206638. InvalidateRect (hwnd, 0, 0);
  206639. else
  206640. lastPaintTime = 0;
  206641. }
  206642. void setTitle (const String& title)
  206643. {
  206644. SetWindowText (hwnd, title);
  206645. }
  206646. void setPosition (int x, int y)
  206647. {
  206648. offsetWithinParent (x, y);
  206649. SetWindowPos (hwnd, 0,
  206650. x - windowBorder.getLeft(),
  206651. y - windowBorder.getTop(),
  206652. 0, 0,
  206653. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206654. }
  206655. void repaintNowIfTransparent()
  206656. {
  206657. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206658. handlePaintMessage();
  206659. }
  206660. void updateBorderSize()
  206661. {
  206662. WINDOWINFO info;
  206663. info.cbSize = sizeof (info);
  206664. if (GetWindowInfo (hwnd, &info))
  206665. {
  206666. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206667. info.rcClient.left - info.rcWindow.left,
  206668. info.rcWindow.bottom - info.rcClient.bottom,
  206669. info.rcWindow.right - info.rcClient.right);
  206670. }
  206671. #if JUCE_DIRECT2D
  206672. if (direct2DContext != 0)
  206673. direct2DContext->resized();
  206674. #endif
  206675. }
  206676. void setSize (int w, int h)
  206677. {
  206678. SetWindowPos (hwnd, 0, 0, 0,
  206679. w + windowBorder.getLeftAndRight(),
  206680. h + windowBorder.getTopAndBottom(),
  206681. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206682. updateBorderSize();
  206683. repaintNowIfTransparent();
  206684. }
  206685. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206686. {
  206687. fullScreen = isNowFullScreen;
  206688. offsetWithinParent (x, y);
  206689. SetWindowPos (hwnd, 0,
  206690. x - windowBorder.getLeft(),
  206691. y - windowBorder.getTop(),
  206692. w + windowBorder.getLeftAndRight(),
  206693. h + windowBorder.getTopAndBottom(),
  206694. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206695. updateBorderSize();
  206696. repaintNowIfTransparent();
  206697. }
  206698. const Rectangle<int> getBounds() const
  206699. {
  206700. RECT r;
  206701. GetWindowRect (hwnd, &r);
  206702. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206703. HWND parentH = GetParent (hwnd);
  206704. if (parentH != 0)
  206705. {
  206706. GetWindowRect (parentH, &r);
  206707. bounds.translate (-r.left, -r.top);
  206708. }
  206709. return windowBorder.subtractedFrom (bounds);
  206710. }
  206711. const Point<int> getScreenPosition() const
  206712. {
  206713. RECT r;
  206714. GetWindowRect (hwnd, &r);
  206715. return Point<int> (r.left + windowBorder.getLeft(),
  206716. r.top + windowBorder.getTop());
  206717. }
  206718. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  206719. {
  206720. return relativePosition + getScreenPosition();
  206721. }
  206722. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  206723. {
  206724. return screenPosition - getScreenPosition();
  206725. }
  206726. void setMinimised (bool shouldBeMinimised)
  206727. {
  206728. if (shouldBeMinimised != isMinimised())
  206729. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206730. }
  206731. bool isMinimised() const
  206732. {
  206733. WINDOWPLACEMENT wp;
  206734. wp.length = sizeof (WINDOWPLACEMENT);
  206735. GetWindowPlacement (hwnd, &wp);
  206736. return wp.showCmd == SW_SHOWMINIMIZED;
  206737. }
  206738. void setFullScreen (bool shouldBeFullScreen)
  206739. {
  206740. setMinimised (false);
  206741. if (fullScreen != shouldBeFullScreen)
  206742. {
  206743. fullScreen = shouldBeFullScreen;
  206744. const Component::SafePointer<Component> deletionChecker (component);
  206745. if (! fullScreen)
  206746. {
  206747. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206748. if (hasTitleBar())
  206749. ShowWindow (hwnd, SW_SHOWNORMAL);
  206750. if (! boundsCopy.isEmpty())
  206751. {
  206752. setBounds (boundsCopy.getX(),
  206753. boundsCopy.getY(),
  206754. boundsCopy.getWidth(),
  206755. boundsCopy.getHeight(),
  206756. false);
  206757. }
  206758. }
  206759. else
  206760. {
  206761. if (hasTitleBar())
  206762. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206763. else
  206764. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206765. }
  206766. if (deletionChecker != 0)
  206767. handleMovedOrResized();
  206768. }
  206769. }
  206770. bool isFullScreen() const
  206771. {
  206772. if (! hasTitleBar())
  206773. return fullScreen;
  206774. WINDOWPLACEMENT wp;
  206775. wp.length = sizeof (wp);
  206776. GetWindowPlacement (hwnd, &wp);
  206777. return wp.showCmd == SW_SHOWMAXIMIZED;
  206778. }
  206779. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206780. {
  206781. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  206782. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  206783. return false;
  206784. RECT r;
  206785. GetWindowRect (hwnd, &r);
  206786. POINT p;
  206787. p.x = position.getX() + r.left + windowBorder.getLeft();
  206788. p.y = position.getY() + r.top + windowBorder.getTop();
  206789. HWND w = WindowFromPoint (p);
  206790. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206791. }
  206792. const BorderSize getFrameSize() const
  206793. {
  206794. return windowBorder;
  206795. }
  206796. bool setAlwaysOnTop (bool alwaysOnTop)
  206797. {
  206798. const bool oldDeactivate = shouldDeactivateTitleBar;
  206799. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206800. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206801. 0, 0, 0, 0,
  206802. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206803. shouldDeactivateTitleBar = oldDeactivate;
  206804. if (shadower != 0)
  206805. shadower->componentBroughtToFront (*component);
  206806. return true;
  206807. }
  206808. void toFront (bool makeActive)
  206809. {
  206810. setMinimised (false);
  206811. const bool oldDeactivate = shouldDeactivateTitleBar;
  206812. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206813. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206814. shouldDeactivateTitleBar = oldDeactivate;
  206815. if (! makeActive)
  206816. {
  206817. // in this case a broughttofront call won't have occured, so do it now..
  206818. handleBroughtToFront();
  206819. }
  206820. }
  206821. void toBehind (ComponentPeer* other)
  206822. {
  206823. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206824. jassert (otherPeer != 0); // wrong type of window?
  206825. if (otherPeer != 0)
  206826. {
  206827. setMinimised (false);
  206828. // must be careful not to try to put a topmost window behind a normal one, or win32
  206829. // promotes the normal one to be topmost!
  206830. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206831. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206832. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206833. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206834. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206835. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206836. }
  206837. }
  206838. bool isFocused() const
  206839. {
  206840. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206841. }
  206842. void grabFocus()
  206843. {
  206844. const bool oldDeactivate = shouldDeactivateTitleBar;
  206845. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206846. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206847. shouldDeactivateTitleBar = oldDeactivate;
  206848. }
  206849. void textInputRequired (const Point<int>&)
  206850. {
  206851. if (! hasCreatedCaret)
  206852. {
  206853. hasCreatedCaret = true;
  206854. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206855. }
  206856. ShowCaret (hwnd);
  206857. SetCaretPos (0, 0);
  206858. }
  206859. void repaint (const Rectangle<int>& area)
  206860. {
  206861. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206862. InvalidateRect (hwnd, &r, FALSE);
  206863. }
  206864. void performAnyPendingRepaintsNow()
  206865. {
  206866. MSG m;
  206867. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206868. DispatchMessage (&m);
  206869. }
  206870. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206871. {
  206872. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206873. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206874. return 0;
  206875. }
  206876. void setTaskBarIcon (const Image& image)
  206877. {
  206878. if (image.isValid())
  206879. {
  206880. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  206881. if (taskBarIcon == 0)
  206882. {
  206883. taskBarIcon = new NOTIFYICONDATA();
  206884. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206885. taskBarIcon->hWnd = (HWND) hwnd;
  206886. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206887. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206888. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206889. taskBarIcon->hIcon = hicon;
  206890. taskBarIcon->szTip[0] = 0;
  206891. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206892. }
  206893. else
  206894. {
  206895. HICON oldIcon = taskBarIcon->hIcon;
  206896. taskBarIcon->hIcon = hicon;
  206897. taskBarIcon->uFlags = NIF_ICON;
  206898. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206899. DestroyIcon (oldIcon);
  206900. }
  206901. DestroyIcon (hicon);
  206902. }
  206903. else if (taskBarIcon != 0)
  206904. {
  206905. taskBarIcon->uFlags = 0;
  206906. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206907. DestroyIcon (taskBarIcon->hIcon);
  206908. taskBarIcon = 0;
  206909. }
  206910. }
  206911. void setTaskBarIconToolTip (const String& toolTip) const
  206912. {
  206913. if (taskBarIcon != 0)
  206914. {
  206915. taskBarIcon->uFlags = NIF_TIP;
  206916. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206917. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206918. }
  206919. }
  206920. bool isInside (HWND h) const
  206921. {
  206922. return GetAncestor (hwnd, GA_ROOT) == h;
  206923. }
  206924. static void updateKeyModifiers() throw()
  206925. {
  206926. int keyMods = 0;
  206927. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  206928. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  206929. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  206930. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206931. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206932. }
  206933. static void updateModifiersFromWParam (const WPARAM wParam)
  206934. {
  206935. int mouseMods = 0;
  206936. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  206937. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  206938. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  206939. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  206940. updateKeyModifiers();
  206941. }
  206942. static int64 getMouseEventTime()
  206943. {
  206944. static int64 eventTimeOffset = 0;
  206945. static DWORD lastMessageTime = 0;
  206946. const DWORD thisMessageTime = GetMessageTime();
  206947. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206948. {
  206949. lastMessageTime = thisMessageTime;
  206950. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  206951. }
  206952. return eventTimeOffset + thisMessageTime;
  206953. }
  206954. juce_UseDebuggingNewOperator
  206955. bool dontRepaint;
  206956. static ModifierKeys currentModifiers;
  206957. static ModifierKeys modifiersAtLastCallback;
  206958. private:
  206959. HWND hwnd;
  206960. ScopedPointer<DropShadower> shadower;
  206961. RenderingEngineType currentRenderingEngine;
  206962. #if JUCE_DIRECT2D
  206963. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  206964. #endif
  206965. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  206966. BorderSize windowBorder;
  206967. HICON currentWindowIcon;
  206968. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  206969. IDropTarget* dropTarget;
  206970. class TemporaryImage : public Timer
  206971. {
  206972. public:
  206973. TemporaryImage() {}
  206974. ~TemporaryImage() {}
  206975. const Image& getImage (const bool transparent, const int w, const int h)
  206976. {
  206977. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206978. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  206979. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  206980. startTimer (3000);
  206981. return image;
  206982. }
  206983. void timerCallback()
  206984. {
  206985. stopTimer();
  206986. image = Image::null;
  206987. }
  206988. private:
  206989. Image image;
  206990. TemporaryImage (const TemporaryImage&);
  206991. TemporaryImage& operator= (const TemporaryImage&);
  206992. };
  206993. TemporaryImage offscreenImageGenerator;
  206994. class WindowClassHolder : public DeletedAtShutdown
  206995. {
  206996. public:
  206997. WindowClassHolder()
  206998. : windowClassName ("JUCE_")
  206999. {
  207000. // this name has to be different for each app/dll instance because otherwise
  207001. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207002. // window class).
  207003. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207004. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207005. TCHAR moduleFile [1024];
  207006. moduleFile[0] = 0;
  207007. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207008. WORD iconNum = 0;
  207009. WNDCLASSEX wcex;
  207010. wcex.cbSize = sizeof (wcex);
  207011. wcex.style = CS_OWNDC;
  207012. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207013. wcex.lpszClassName = windowClassName;
  207014. wcex.cbClsExtra = 0;
  207015. wcex.cbWndExtra = 32;
  207016. wcex.hInstance = moduleHandle;
  207017. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207018. iconNum = 1;
  207019. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207020. wcex.hCursor = 0;
  207021. wcex.hbrBackground = 0;
  207022. wcex.lpszMenuName = 0;
  207023. RegisterClassEx (&wcex);
  207024. }
  207025. ~WindowClassHolder()
  207026. {
  207027. if (ComponentPeer::getNumPeers() == 0)
  207028. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207029. clearSingletonInstance();
  207030. }
  207031. String windowClassName;
  207032. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207033. };
  207034. static void* createWindowCallback (void* userData)
  207035. {
  207036. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207037. return 0;
  207038. }
  207039. void createWindow()
  207040. {
  207041. DWORD exstyle = WS_EX_ACCEPTFILES;
  207042. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207043. if (hasTitleBar())
  207044. {
  207045. type |= WS_OVERLAPPED;
  207046. if ((styleFlags & windowHasCloseButton) != 0)
  207047. {
  207048. type |= WS_SYSMENU;
  207049. }
  207050. else
  207051. {
  207052. // annoyingly, windows won't let you have a min/max button without a close button
  207053. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207054. }
  207055. if ((styleFlags & windowIsResizable) != 0)
  207056. type |= WS_THICKFRAME;
  207057. }
  207058. else
  207059. {
  207060. type |= WS_POPUP | WS_SYSMENU;
  207061. }
  207062. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207063. exstyle |= WS_EX_TOOLWINDOW;
  207064. else
  207065. exstyle |= WS_EX_APPWINDOW;
  207066. if ((styleFlags & windowHasMinimiseButton) != 0)
  207067. type |= WS_MINIMIZEBOX;
  207068. if ((styleFlags & windowHasMaximiseButton) != 0)
  207069. type |= WS_MAXIMIZEBOX;
  207070. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207071. exstyle |= WS_EX_TRANSPARENT;
  207072. if ((styleFlags & windowIsSemiTransparent) != 0
  207073. && Desktop::canUseSemiTransparentWindows())
  207074. exstyle |= WS_EX_LAYERED;
  207075. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  207076. #if JUCE_DIRECT2D
  207077. updateDirect2DContext();
  207078. #endif
  207079. if (hwnd != 0)
  207080. {
  207081. SetWindowLongPtr (hwnd, 0, 0);
  207082. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207083. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207084. if (dropTarget == 0)
  207085. dropTarget = new JuceDropTarget (this);
  207086. RegisterDragDrop (hwnd, dropTarget);
  207087. updateBorderSize();
  207088. // Calling this function here is (for some reason) necessary to make Windows
  207089. // correctly enable the menu items that we specify in the wm_initmenu message.
  207090. GetSystemMenu (hwnd, false);
  207091. }
  207092. else
  207093. {
  207094. jassertfalse;
  207095. }
  207096. }
  207097. static void* destroyWindowCallback (void* handle)
  207098. {
  207099. RevokeDragDrop ((HWND) handle);
  207100. DestroyWindow ((HWND) handle);
  207101. return 0;
  207102. }
  207103. static void* toFrontCallback1 (void* h)
  207104. {
  207105. SetForegroundWindow ((HWND) h);
  207106. return 0;
  207107. }
  207108. static void* toFrontCallback2 (void* h)
  207109. {
  207110. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207111. return 0;
  207112. }
  207113. static void* setFocusCallback (void* h)
  207114. {
  207115. SetFocus ((HWND) h);
  207116. return 0;
  207117. }
  207118. static void* getFocusCallback (void*)
  207119. {
  207120. return GetFocus();
  207121. }
  207122. void offsetWithinParent (int& x, int& y) const
  207123. {
  207124. if (isTransparent())
  207125. {
  207126. HWND parentHwnd = GetParent (hwnd);
  207127. if (parentHwnd != 0)
  207128. {
  207129. RECT parentRect;
  207130. GetWindowRect (parentHwnd, &parentRect);
  207131. x += parentRect.left;
  207132. y += parentRect.top;
  207133. }
  207134. }
  207135. }
  207136. bool isTransparent() const
  207137. {
  207138. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207139. }
  207140. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207141. void setIcon (const Image& newIcon)
  207142. {
  207143. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207144. if (hicon != 0)
  207145. {
  207146. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207147. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207148. if (currentWindowIcon != 0)
  207149. DestroyIcon (currentWindowIcon);
  207150. currentWindowIcon = hicon;
  207151. }
  207152. }
  207153. void handlePaintMessage()
  207154. {
  207155. #if JUCE_DIRECT2D
  207156. if (direct2DContext != 0)
  207157. {
  207158. RECT r;
  207159. if (GetUpdateRect (hwnd, &r, false))
  207160. {
  207161. direct2DContext->start();
  207162. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207163. handlePaint (*direct2DContext);
  207164. direct2DContext->end();
  207165. }
  207166. }
  207167. else
  207168. #endif
  207169. {
  207170. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207171. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207172. PAINTSTRUCT paintStruct;
  207173. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207174. // message and become re-entrant, but that's OK
  207175. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207176. // corrupt the image it's using to paint into, so do a check here.
  207177. static bool reentrant = false;
  207178. if (reentrant)
  207179. {
  207180. DeleteObject (rgn);
  207181. EndPaint (hwnd, &paintStruct);
  207182. return;
  207183. }
  207184. reentrant = true;
  207185. // this is the rectangle to update..
  207186. int x = paintStruct.rcPaint.left;
  207187. int y = paintStruct.rcPaint.top;
  207188. int w = paintStruct.rcPaint.right - x;
  207189. int h = paintStruct.rcPaint.bottom - y;
  207190. const bool transparent = isTransparent();
  207191. if (transparent)
  207192. {
  207193. // it's not possible to have a transparent window with a title bar at the moment!
  207194. jassert (! hasTitleBar());
  207195. RECT r;
  207196. GetWindowRect (hwnd, &r);
  207197. x = y = 0;
  207198. w = r.right - r.left;
  207199. h = r.bottom - r.top;
  207200. }
  207201. if (w > 0 && h > 0)
  207202. {
  207203. clearMaskedRegion();
  207204. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207205. RectangleList contextClip;
  207206. const Rectangle<int> clipBounds (0, 0, w, h);
  207207. bool needToPaintAll = true;
  207208. if (regionType == COMPLEXREGION && ! transparent)
  207209. {
  207210. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207211. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207212. DeleteObject (clipRgn);
  207213. char rgnData [8192];
  207214. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207215. if (res > 0 && res <= sizeof (rgnData))
  207216. {
  207217. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207218. if (hdr->iType == RDH_RECTANGLES
  207219. && hdr->rcBound.right - hdr->rcBound.left >= w
  207220. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207221. {
  207222. needToPaintAll = false;
  207223. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207224. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207225. while (--num >= 0)
  207226. {
  207227. if (rects->right <= x + w && rects->bottom <= y + h)
  207228. {
  207229. // (need to move this one pixel to the left because of a win32 bug)
  207230. const int cx = jmax (x, (int) rects->left - 1);
  207231. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207232. .getIntersection (clipBounds));
  207233. }
  207234. else
  207235. {
  207236. needToPaintAll = true;
  207237. break;
  207238. }
  207239. ++rects;
  207240. }
  207241. }
  207242. }
  207243. }
  207244. if (needToPaintAll)
  207245. {
  207246. contextClip.clear();
  207247. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207248. }
  207249. if (transparent)
  207250. {
  207251. RectangleList::Iterator i (contextClip);
  207252. while (i.next())
  207253. offscreenImage.clear (*i.getRectangle());
  207254. }
  207255. // if the component's not opaque, this won't draw properly unless the platform can support this
  207256. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207257. updateCurrentModifiers();
  207258. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207259. handlePaint (context);
  207260. if (! dontRepaint)
  207261. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207262. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207263. }
  207264. DeleteObject (rgn);
  207265. EndPaint (hwnd, &paintStruct);
  207266. reentrant = false;
  207267. }
  207268. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207269. _fpreset(); // because some graphics cards can unmask FP exceptions
  207270. #endif
  207271. lastPaintTime = Time::getMillisecondCounter();
  207272. }
  207273. void doMouseEvent (const Point<int>& position)
  207274. {
  207275. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207276. }
  207277. const StringArray getAvailableRenderingEngines()
  207278. {
  207279. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207280. #if JUCE_DIRECT2D
  207281. // xxx is this correct? Seems to enable it on Vista too??
  207282. OSVERSIONINFO info;
  207283. zerostruct (info);
  207284. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207285. GetVersionEx (&info);
  207286. if (info.dwMajorVersion >= 6)
  207287. s.add ("Direct2D");
  207288. #endif
  207289. return s;
  207290. }
  207291. int getCurrentRenderingEngine() throw()
  207292. {
  207293. return currentRenderingEngine;
  207294. }
  207295. #if JUCE_DIRECT2D
  207296. void updateDirect2DContext()
  207297. {
  207298. if (currentRenderingEngine != direct2DRenderingEngine)
  207299. direct2DContext = 0;
  207300. else if (direct2DContext == 0)
  207301. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207302. }
  207303. #endif
  207304. void setCurrentRenderingEngine (int index)
  207305. {
  207306. (void) index;
  207307. #if JUCE_DIRECT2D
  207308. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207309. updateDirect2DContext();
  207310. repaint (component->getLocalBounds());
  207311. #endif
  207312. }
  207313. void doMouseMove (const Point<int>& position)
  207314. {
  207315. if (! isMouseOver)
  207316. {
  207317. isMouseOver = true;
  207318. updateKeyModifiers();
  207319. TRACKMOUSEEVENT tme;
  207320. tme.cbSize = sizeof (tme);
  207321. tme.dwFlags = TME_LEAVE;
  207322. tme.hwndTrack = hwnd;
  207323. tme.dwHoverTime = 0;
  207324. if (! TrackMouseEvent (&tme))
  207325. jassertfalse;
  207326. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207327. }
  207328. else if (! isDragging)
  207329. {
  207330. if (! contains (position, false))
  207331. return;
  207332. }
  207333. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207334. static uint32 lastMouseTime = 0;
  207335. const uint32 now = Time::getMillisecondCounter();
  207336. const int maxMouseMovesPerSecond = 60;
  207337. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207338. {
  207339. lastMouseTime = now;
  207340. doMouseEvent (position);
  207341. }
  207342. }
  207343. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207344. {
  207345. if (GetCapture() != hwnd)
  207346. SetCapture (hwnd);
  207347. doMouseMove (position);
  207348. updateModifiersFromWParam (wParam);
  207349. isDragging = true;
  207350. doMouseEvent (position);
  207351. }
  207352. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207353. {
  207354. updateModifiersFromWParam (wParam);
  207355. isDragging = false;
  207356. // release the mouse capture if the user has released all buttons
  207357. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207358. ReleaseCapture();
  207359. doMouseEvent (position);
  207360. }
  207361. void doCaptureChanged()
  207362. {
  207363. if (isDragging)
  207364. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207365. }
  207366. void doMouseExit()
  207367. {
  207368. isMouseOver = false;
  207369. doMouseEvent (getCurrentMousePos());
  207370. }
  207371. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207372. {
  207373. updateKeyModifiers();
  207374. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207375. handleMouseWheel (0, position, getMouseEventTime(),
  207376. isVertical ? 0.0f : amount,
  207377. isVertical ? amount : 0.0f);
  207378. }
  207379. void sendModifierKeyChangeIfNeeded()
  207380. {
  207381. if (modifiersAtLastCallback != currentModifiers)
  207382. {
  207383. modifiersAtLastCallback = currentModifiers;
  207384. handleModifierKeysChange();
  207385. }
  207386. }
  207387. bool doKeyUp (const WPARAM key)
  207388. {
  207389. updateKeyModifiers();
  207390. switch (key)
  207391. {
  207392. case VK_SHIFT:
  207393. case VK_CONTROL:
  207394. case VK_MENU:
  207395. case VK_CAPITAL:
  207396. case VK_LWIN:
  207397. case VK_RWIN:
  207398. case VK_APPS:
  207399. case VK_NUMLOCK:
  207400. case VK_SCROLL:
  207401. case VK_LSHIFT:
  207402. case VK_RSHIFT:
  207403. case VK_LCONTROL:
  207404. case VK_LMENU:
  207405. case VK_RCONTROL:
  207406. case VK_RMENU:
  207407. sendModifierKeyChangeIfNeeded();
  207408. }
  207409. return handleKeyUpOrDown (false)
  207410. || Component::getCurrentlyModalComponent() != 0;
  207411. }
  207412. bool doKeyDown (const WPARAM key)
  207413. {
  207414. updateKeyModifiers();
  207415. bool used = false;
  207416. switch (key)
  207417. {
  207418. case VK_SHIFT:
  207419. case VK_LSHIFT:
  207420. case VK_RSHIFT:
  207421. case VK_CONTROL:
  207422. case VK_LCONTROL:
  207423. case VK_RCONTROL:
  207424. case VK_MENU:
  207425. case VK_LMENU:
  207426. case VK_RMENU:
  207427. case VK_LWIN:
  207428. case VK_RWIN:
  207429. case VK_CAPITAL:
  207430. case VK_NUMLOCK:
  207431. case VK_SCROLL:
  207432. case VK_APPS:
  207433. sendModifierKeyChangeIfNeeded();
  207434. break;
  207435. case VK_LEFT:
  207436. case VK_RIGHT:
  207437. case VK_UP:
  207438. case VK_DOWN:
  207439. case VK_PRIOR:
  207440. case VK_NEXT:
  207441. case VK_HOME:
  207442. case VK_END:
  207443. case VK_DELETE:
  207444. case VK_INSERT:
  207445. case VK_F1:
  207446. case VK_F2:
  207447. case VK_F3:
  207448. case VK_F4:
  207449. case VK_F5:
  207450. case VK_F6:
  207451. case VK_F7:
  207452. case VK_F8:
  207453. case VK_F9:
  207454. case VK_F10:
  207455. case VK_F11:
  207456. case VK_F12:
  207457. case VK_F13:
  207458. case VK_F14:
  207459. case VK_F15:
  207460. case VK_F16:
  207461. used = handleKeyUpOrDown (true);
  207462. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207463. break;
  207464. case VK_ADD:
  207465. case VK_SUBTRACT:
  207466. case VK_MULTIPLY:
  207467. case VK_DIVIDE:
  207468. case VK_SEPARATOR:
  207469. case VK_DECIMAL:
  207470. used = handleKeyUpOrDown (true);
  207471. break;
  207472. default:
  207473. used = handleKeyUpOrDown (true);
  207474. {
  207475. MSG msg;
  207476. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207477. {
  207478. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207479. // manually generate the key-press event that matches this key-down.
  207480. const UINT keyChar = MapVirtualKey (key, 2);
  207481. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207482. }
  207483. }
  207484. break;
  207485. }
  207486. if (Component::getCurrentlyModalComponent() != 0)
  207487. used = true;
  207488. return used;
  207489. }
  207490. bool doKeyChar (int key, const LPARAM flags)
  207491. {
  207492. updateKeyModifiers();
  207493. juce_wchar textChar = (juce_wchar) key;
  207494. const int virtualScanCode = (flags >> 16) & 0xff;
  207495. if (key >= '0' && key <= '9')
  207496. {
  207497. switch (virtualScanCode) // check for a numeric keypad scan-code
  207498. {
  207499. case 0x52:
  207500. case 0x4f:
  207501. case 0x50:
  207502. case 0x51:
  207503. case 0x4b:
  207504. case 0x4c:
  207505. case 0x4d:
  207506. case 0x47:
  207507. case 0x48:
  207508. case 0x49:
  207509. key = (key - '0') + KeyPress::numberPad0;
  207510. break;
  207511. default:
  207512. break;
  207513. }
  207514. }
  207515. else
  207516. {
  207517. // convert the scan code to an unmodified character code..
  207518. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207519. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207520. keyChar = LOWORD (keyChar);
  207521. if (keyChar != 0)
  207522. key = (int) keyChar;
  207523. // avoid sending junk text characters for some control-key combinations
  207524. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207525. textChar = 0;
  207526. }
  207527. return handleKeyPress (key, textChar);
  207528. }
  207529. bool doAppCommand (const LPARAM lParam)
  207530. {
  207531. int key = 0;
  207532. switch (GET_APPCOMMAND_LPARAM (lParam))
  207533. {
  207534. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207535. key = KeyPress::playKey;
  207536. break;
  207537. case APPCOMMAND_MEDIA_STOP:
  207538. key = KeyPress::stopKey;
  207539. break;
  207540. case APPCOMMAND_MEDIA_NEXTTRACK:
  207541. key = KeyPress::fastForwardKey;
  207542. break;
  207543. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207544. key = KeyPress::rewindKey;
  207545. break;
  207546. }
  207547. if (key != 0)
  207548. {
  207549. updateKeyModifiers();
  207550. if (hwnd == GetActiveWindow())
  207551. {
  207552. handleKeyPress (key, 0);
  207553. return true;
  207554. }
  207555. }
  207556. return false;
  207557. }
  207558. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207559. {
  207560. public:
  207561. JuceDropTarget (Win32ComponentPeer* const owner_)
  207562. : owner (owner_)
  207563. {
  207564. }
  207565. ~JuceDropTarget() {}
  207566. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207567. {
  207568. updateFileList (pDataObject);
  207569. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207570. *pdwEffect = DROPEFFECT_COPY;
  207571. return S_OK;
  207572. }
  207573. HRESULT __stdcall DragLeave()
  207574. {
  207575. owner->handleFileDragExit (files);
  207576. return S_OK;
  207577. }
  207578. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207579. {
  207580. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207581. *pdwEffect = DROPEFFECT_COPY;
  207582. return S_OK;
  207583. }
  207584. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207585. {
  207586. updateFileList (pDataObject);
  207587. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207588. *pdwEffect = DROPEFFECT_COPY;
  207589. return S_OK;
  207590. }
  207591. private:
  207592. Win32ComponentPeer* const owner;
  207593. StringArray files;
  207594. void updateFileList (IDataObject* const pDataObject)
  207595. {
  207596. files.clear();
  207597. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207598. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207599. if (pDataObject->GetData (&format, &medium) == S_OK)
  207600. {
  207601. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207602. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207603. unsigned int i = 0;
  207604. if (pDropFiles->fWide)
  207605. {
  207606. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207607. for (;;)
  207608. {
  207609. unsigned int len = 0;
  207610. while (i + len < totalLen && fname [i + len] != 0)
  207611. ++len;
  207612. if (len == 0)
  207613. break;
  207614. files.add (String (fname + i, len));
  207615. i += len + 1;
  207616. }
  207617. }
  207618. else
  207619. {
  207620. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207621. for (;;)
  207622. {
  207623. unsigned int len = 0;
  207624. while (i + len < totalLen && fname [i + len] != 0)
  207625. ++len;
  207626. if (len == 0)
  207627. break;
  207628. files.add (String (fname + i, len));
  207629. i += len + 1;
  207630. }
  207631. }
  207632. GlobalUnlock (medium.hGlobal);
  207633. }
  207634. }
  207635. JuceDropTarget (const JuceDropTarget&);
  207636. JuceDropTarget& operator= (const JuceDropTarget&);
  207637. };
  207638. void doSettingChange()
  207639. {
  207640. Desktop::getInstance().refreshMonitorSizes();
  207641. if (fullScreen && ! isMinimised())
  207642. {
  207643. const Rectangle<int> r (component->getParentMonitorArea());
  207644. SetWindowPos (hwnd, 0,
  207645. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207646. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207647. }
  207648. }
  207649. public:
  207650. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207651. {
  207652. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207653. if (peer != 0)
  207654. return peer->peerWindowProc (h, message, wParam, lParam);
  207655. return DefWindowProcW (h, message, wParam, lParam);
  207656. }
  207657. private:
  207658. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207659. {
  207660. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207661. }
  207662. const Point<int> getCurrentMousePos() throw()
  207663. {
  207664. RECT wr;
  207665. GetWindowRect (hwnd, &wr);
  207666. const DWORD mp = GetMessagePos();
  207667. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207668. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207669. }
  207670. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207671. {
  207672. if (isValidPeer (this))
  207673. {
  207674. switch (message)
  207675. {
  207676. case WM_NCHITTEST:
  207677. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207678. return HTTRANSPARENT;
  207679. if (hasTitleBar())
  207680. break;
  207681. return HTCLIENT;
  207682. case WM_PAINT:
  207683. handlePaintMessage();
  207684. return 0;
  207685. case WM_NCPAINT:
  207686. if (wParam != 1)
  207687. handlePaintMessage();
  207688. if (hasTitleBar())
  207689. break;
  207690. return 0;
  207691. case WM_ERASEBKGND:
  207692. case WM_NCCALCSIZE:
  207693. if (hasTitleBar())
  207694. break;
  207695. return 1;
  207696. case WM_MOUSEMOVE:
  207697. doMouseMove (getPointFromLParam (lParam));
  207698. return 0;
  207699. case WM_MOUSELEAVE:
  207700. doMouseExit();
  207701. return 0;
  207702. case WM_LBUTTONDOWN:
  207703. case WM_MBUTTONDOWN:
  207704. case WM_RBUTTONDOWN:
  207705. doMouseDown (getPointFromLParam (lParam), wParam);
  207706. return 0;
  207707. case WM_LBUTTONUP:
  207708. case WM_MBUTTONUP:
  207709. case WM_RBUTTONUP:
  207710. doMouseUp (getPointFromLParam (lParam), wParam);
  207711. return 0;
  207712. case WM_CAPTURECHANGED:
  207713. doCaptureChanged();
  207714. return 0;
  207715. case WM_NCMOUSEMOVE:
  207716. if (hasTitleBar())
  207717. break;
  207718. return 0;
  207719. case 0x020A: /* WM_MOUSEWHEEL */
  207720. doMouseWheel (getCurrentMousePos(), wParam, true);
  207721. return 0;
  207722. case 0x020E: /* WM_MOUSEHWHEEL */
  207723. doMouseWheel (getCurrentMousePos(), wParam, false);
  207724. return 0;
  207725. case WM_WINDOWPOSCHANGING:
  207726. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207727. {
  207728. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207729. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207730. {
  207731. if (constrainer != 0)
  207732. {
  207733. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  207734. component->getY() - windowBorder.getTop(),
  207735. component->getWidth() + windowBorder.getLeftAndRight(),
  207736. component->getHeight() + windowBorder.getTopAndBottom());
  207737. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207738. constrainer->checkBounds (pos, current,
  207739. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207740. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207741. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207742. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207743. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207744. wp->x = pos.getX();
  207745. wp->y = pos.getY();
  207746. wp->cx = pos.getWidth();
  207747. wp->cy = pos.getHeight();
  207748. }
  207749. }
  207750. }
  207751. return 0;
  207752. case WM_WINDOWPOSCHANGED:
  207753. handleMovedOrResized();
  207754. if (dontRepaint)
  207755. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207756. return 0;
  207757. case WM_KEYDOWN:
  207758. case WM_SYSKEYDOWN:
  207759. if (doKeyDown (wParam))
  207760. return 0;
  207761. break;
  207762. case WM_KEYUP:
  207763. case WM_SYSKEYUP:
  207764. if (doKeyUp (wParam))
  207765. return 0;
  207766. break;
  207767. case WM_CHAR:
  207768. if (doKeyChar ((int) wParam, lParam))
  207769. return 0;
  207770. break;
  207771. case WM_APPCOMMAND:
  207772. if (doAppCommand (lParam))
  207773. return TRUE;
  207774. break;
  207775. case WM_SETFOCUS:
  207776. updateKeyModifiers();
  207777. handleFocusGain();
  207778. break;
  207779. case WM_KILLFOCUS:
  207780. if (hasCreatedCaret)
  207781. {
  207782. hasCreatedCaret = false;
  207783. DestroyCaret();
  207784. }
  207785. handleFocusLoss();
  207786. break;
  207787. case WM_ACTIVATEAPP:
  207788. // Windows does weird things to process priority when you swap apps,
  207789. // so this forces an update when the app is brought to the front
  207790. if (wParam != FALSE)
  207791. juce_repeatLastProcessPriority();
  207792. else
  207793. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207794. juce_CheckCurrentlyFocusedTopLevelWindow();
  207795. modifiersAtLastCallback = -1;
  207796. return 0;
  207797. case WM_ACTIVATE:
  207798. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207799. {
  207800. modifiersAtLastCallback = -1;
  207801. updateKeyModifiers();
  207802. if (isMinimised())
  207803. {
  207804. component->repaint();
  207805. handleMovedOrResized();
  207806. if (! ComponentPeer::isValidPeer (this))
  207807. return 0;
  207808. }
  207809. if (LOWORD (wParam) == WA_CLICKACTIVE
  207810. && component->isCurrentlyBlockedByAnotherModalComponent())
  207811. {
  207812. const Point<int> mousePos (component->getMouseXYRelative());
  207813. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  207814. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207815. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207816. return 0;
  207817. }
  207818. handleBroughtToFront();
  207819. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207820. Component::getCurrentlyModalComponent()->toFront (true);
  207821. return 0;
  207822. }
  207823. break;
  207824. case WM_NCACTIVATE:
  207825. // while a temporary window is being shown, prevent Windows from deactivating the
  207826. // title bars of our main windows.
  207827. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207828. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207829. break;
  207830. case WM_MOUSEACTIVATE:
  207831. if (! component->getMouseClickGrabsKeyboardFocus())
  207832. return MA_NOACTIVATE;
  207833. break;
  207834. case WM_SHOWWINDOW:
  207835. if (wParam != 0)
  207836. handleBroughtToFront();
  207837. break;
  207838. case WM_CLOSE:
  207839. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  207840. handleUserClosingWindow();
  207841. return 0;
  207842. case WM_QUERYENDSESSION:
  207843. if (JUCEApplication::getInstance() != 0)
  207844. {
  207845. JUCEApplication::getInstance()->systemRequestedQuit();
  207846. return MessageManager::getInstance()->hasStopMessageBeenSent();
  207847. }
  207848. return TRUE;
  207849. case WM_TRAYNOTIFY:
  207850. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207851. {
  207852. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207853. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207854. {
  207855. Component* const current = Component::getCurrentlyModalComponent();
  207856. if (current != 0)
  207857. current->inputAttemptWhenModal();
  207858. }
  207859. }
  207860. else
  207861. {
  207862. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207863. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207864. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207865. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207866. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207867. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207868. eventMods = eventMods.withoutMouseButtons();
  207869. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207870. Point<int>(), eventMods, component, component, getMouseEventTime(),
  207871. Point<int>(), getMouseEventTime(), 1, false);
  207872. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207873. {
  207874. SetFocus (hwnd);
  207875. SetForegroundWindow (hwnd);
  207876. component->mouseDown (e);
  207877. }
  207878. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207879. {
  207880. component->mouseUp (e);
  207881. }
  207882. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207883. {
  207884. component->mouseDoubleClick (e);
  207885. }
  207886. else if (lParam == WM_MOUSEMOVE)
  207887. {
  207888. component->mouseMove (e);
  207889. }
  207890. }
  207891. break;
  207892. case WM_SYNCPAINT:
  207893. return 0;
  207894. case WM_PALETTECHANGED:
  207895. InvalidateRect (h, 0, 0);
  207896. break;
  207897. case WM_DISPLAYCHANGE:
  207898. InvalidateRect (h, 0, 0);
  207899. createPaletteIfNeeded = true;
  207900. // intentional fall-through...
  207901. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207902. doSettingChange();
  207903. break;
  207904. case WM_INITMENU:
  207905. if (! hasTitleBar())
  207906. {
  207907. if (isFullScreen())
  207908. {
  207909. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207910. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207911. }
  207912. else if (! isMinimised())
  207913. {
  207914. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207915. }
  207916. }
  207917. break;
  207918. case WM_SYSCOMMAND:
  207919. switch (wParam & 0xfff0)
  207920. {
  207921. case SC_CLOSE:
  207922. if (sendInputAttemptWhenModalMessage())
  207923. return 0;
  207924. if (hasTitleBar())
  207925. {
  207926. PostMessage (h, WM_CLOSE, 0, 0);
  207927. return 0;
  207928. }
  207929. break;
  207930. case SC_KEYMENU:
  207931. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  207932. // obscure situations that can arise if a modal loop is started from an alt-key
  207933. // keypress).
  207934. if (hasTitleBar() && h == GetCapture())
  207935. ReleaseCapture();
  207936. break;
  207937. case SC_MAXIMIZE:
  207938. if (sendInputAttemptWhenModalMessage())
  207939. return 0;
  207940. setFullScreen (true);
  207941. return 0;
  207942. case SC_MINIMIZE:
  207943. if (sendInputAttemptWhenModalMessage())
  207944. return 0;
  207945. if (! hasTitleBar())
  207946. {
  207947. setMinimised (true);
  207948. return 0;
  207949. }
  207950. break;
  207951. case SC_RESTORE:
  207952. if (sendInputAttemptWhenModalMessage())
  207953. return 0;
  207954. if (hasTitleBar())
  207955. {
  207956. if (isFullScreen())
  207957. {
  207958. setFullScreen (false);
  207959. return 0;
  207960. }
  207961. }
  207962. else
  207963. {
  207964. if (isMinimised())
  207965. setMinimised (false);
  207966. else if (isFullScreen())
  207967. setFullScreen (false);
  207968. return 0;
  207969. }
  207970. break;
  207971. }
  207972. break;
  207973. case WM_NCLBUTTONDOWN:
  207974. case WM_NCRBUTTONDOWN:
  207975. case WM_NCMBUTTONDOWN:
  207976. sendInputAttemptWhenModalMessage();
  207977. break;
  207978. //case WM_IME_STARTCOMPOSITION;
  207979. // return 0;
  207980. case WM_GETDLGCODE:
  207981. return DLGC_WANTALLKEYS;
  207982. default:
  207983. break;
  207984. }
  207985. }
  207986. return DefWindowProcW (h, message, wParam, lParam);
  207987. }
  207988. bool sendInputAttemptWhenModalMessage()
  207989. {
  207990. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207991. {
  207992. Component* const current = Component::getCurrentlyModalComponent();
  207993. if (current != 0)
  207994. current->inputAttemptWhenModal();
  207995. return true;
  207996. }
  207997. return false;
  207998. }
  207999. Win32ComponentPeer (const Win32ComponentPeer&);
  208000. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208001. };
  208002. ModifierKeys Win32ComponentPeer::currentModifiers;
  208003. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208004. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  208005. {
  208006. return new Win32ComponentPeer (this, styleFlags);
  208007. }
  208008. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208009. void ModifierKeys::updateCurrentModifiers() throw()
  208010. {
  208011. currentModifiers = Win32ComponentPeer::currentModifiers;
  208012. }
  208013. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208014. {
  208015. Win32ComponentPeer::updateKeyModifiers();
  208016. int keyMods = 0;
  208017. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208018. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208019. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208020. Win32ComponentPeer::currentModifiers
  208021. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208022. return Win32ComponentPeer::currentModifiers;
  208023. }
  208024. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208025. {
  208026. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208027. if (wp != 0)
  208028. wp->setTaskBarIcon (newImage);
  208029. }
  208030. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208031. {
  208032. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208033. if (wp != 0)
  208034. wp->setTaskBarIconToolTip (tooltip);
  208035. }
  208036. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208037. {
  208038. DWORD val = GetWindowLong (h, styleType);
  208039. if (bitIsSet)
  208040. val |= feature;
  208041. else
  208042. val &= ~feature;
  208043. SetWindowLongPtr (h, styleType, val);
  208044. SetWindowPos (h, 0, 0, 0, 0, 0,
  208045. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208046. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208047. }
  208048. bool Process::isForegroundProcess()
  208049. {
  208050. HWND fg = GetForegroundWindow();
  208051. if (fg == 0)
  208052. return true;
  208053. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208054. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208055. // have to see if any of our windows are children of the foreground window
  208056. fg = GetAncestor (fg, GA_ROOT);
  208057. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208058. {
  208059. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208060. if (wp != 0 && wp->isInside (fg))
  208061. return true;
  208062. }
  208063. return false;
  208064. }
  208065. bool AlertWindow::showNativeDialogBox (const String& title,
  208066. const String& bodyText,
  208067. bool isOkCancel)
  208068. {
  208069. return MessageBox (0, bodyText, title,
  208070. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208071. : MB_OK)) == IDOK;
  208072. }
  208073. void Desktop::createMouseInputSources()
  208074. {
  208075. mouseSources.add (new MouseInputSource (0, true));
  208076. }
  208077. const Point<int> Desktop::getMousePosition()
  208078. {
  208079. POINT mousePos;
  208080. GetCursorPos (&mousePos);
  208081. return Point<int> (mousePos.x, mousePos.y);
  208082. }
  208083. void Desktop::setMousePosition (const Point<int>& newPosition)
  208084. {
  208085. SetCursorPos (newPosition.getX(), newPosition.getY());
  208086. }
  208087. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208088. {
  208089. return createSoftwareImage (format, width, height, clearImage);
  208090. }
  208091. class ScreenSaverDefeater : public Timer,
  208092. public DeletedAtShutdown
  208093. {
  208094. public:
  208095. ScreenSaverDefeater()
  208096. {
  208097. startTimer (10000);
  208098. timerCallback();
  208099. }
  208100. ~ScreenSaverDefeater() {}
  208101. void timerCallback()
  208102. {
  208103. if (Process::isForegroundProcess())
  208104. {
  208105. // simulate a shift key getting pressed..
  208106. INPUT input[2];
  208107. input[0].type = INPUT_KEYBOARD;
  208108. input[0].ki.wVk = VK_SHIFT;
  208109. input[0].ki.dwFlags = 0;
  208110. input[0].ki.dwExtraInfo = 0;
  208111. input[1].type = INPUT_KEYBOARD;
  208112. input[1].ki.wVk = VK_SHIFT;
  208113. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208114. input[1].ki.dwExtraInfo = 0;
  208115. SendInput (2, input, sizeof (INPUT));
  208116. }
  208117. }
  208118. };
  208119. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208120. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208121. {
  208122. if (isEnabled)
  208123. deleteAndZero (screenSaverDefeater);
  208124. else if (screenSaverDefeater == 0)
  208125. screenSaverDefeater = new ScreenSaverDefeater();
  208126. }
  208127. bool Desktop::isScreenSaverEnabled()
  208128. {
  208129. return screenSaverDefeater == 0;
  208130. }
  208131. /* (The code below is the "correct" way to disable the screen saver, but it
  208132. completely fails on winXP when the saver is password-protected...)
  208133. static bool juce_screenSaverEnabled = true;
  208134. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208135. {
  208136. juce_screenSaverEnabled = isEnabled;
  208137. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208138. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208139. }
  208140. bool Desktop::isScreenSaverEnabled() throw()
  208141. {
  208142. return juce_screenSaverEnabled;
  208143. }
  208144. */
  208145. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208146. {
  208147. if (enableOrDisable)
  208148. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208149. }
  208150. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208151. {
  208152. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208153. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208154. return TRUE;
  208155. }
  208156. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208157. {
  208158. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208159. // make sure the first in the list is the main monitor
  208160. for (int i = 1; i < monitorCoords.size(); ++i)
  208161. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208162. monitorCoords.swap (i, 0);
  208163. if (monitorCoords.size() == 0)
  208164. {
  208165. RECT r;
  208166. GetWindowRect (GetDesktopWindow(), &r);
  208167. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208168. }
  208169. if (clipToWorkArea)
  208170. {
  208171. // clip the main monitor to the active non-taskbar area
  208172. RECT r;
  208173. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208174. Rectangle<int>& screen = monitorCoords.getReference (0);
  208175. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208176. jmax (screen.getY(), (int) r.top));
  208177. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208178. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208179. }
  208180. }
  208181. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208182. {
  208183. Image im;
  208184. if (bitmap != 0)
  208185. {
  208186. BITMAP bm;
  208187. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208188. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208189. {
  208190. HDC tempDC = GetDC (0);
  208191. HDC dc = CreateCompatibleDC (tempDC);
  208192. ReleaseDC (0, tempDC);
  208193. SelectObject (dc, bitmap);
  208194. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208195. Image::BitmapData imageData (im, true);
  208196. for (int y = bm.bmHeight; --y >= 0;)
  208197. {
  208198. for (int x = bm.bmWidth; --x >= 0;)
  208199. {
  208200. COLORREF col = GetPixel (dc, x, y);
  208201. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208202. (uint8) GetGValue (col),
  208203. (uint8) GetBValue (col)));
  208204. }
  208205. }
  208206. DeleteDC (dc);
  208207. }
  208208. }
  208209. return im;
  208210. }
  208211. static const Image createImageFromHICON (HICON icon)
  208212. {
  208213. ICONINFO info;
  208214. if (GetIconInfo (icon, &info))
  208215. {
  208216. Image mask (createImageFromHBITMAP (info.hbmMask));
  208217. Image image (createImageFromHBITMAP (info.hbmColor));
  208218. if (mask.isValid() && image.isValid())
  208219. {
  208220. for (int y = image.getHeight(); --y >= 0;)
  208221. {
  208222. for (int x = image.getWidth(); --x >= 0;)
  208223. {
  208224. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208225. if (brightness > 0.0f)
  208226. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208227. }
  208228. }
  208229. return image;
  208230. }
  208231. }
  208232. return Image::null;
  208233. }
  208234. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208235. {
  208236. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208237. Image bitmap (nativeBitmap);
  208238. {
  208239. Graphics g (bitmap);
  208240. g.drawImageAt (image, 0, 0);
  208241. }
  208242. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208243. ICONINFO info;
  208244. info.fIcon = isIcon;
  208245. info.xHotspot = hotspotX;
  208246. info.yHotspot = hotspotY;
  208247. info.hbmMask = mask;
  208248. info.hbmColor = nativeBitmap->hBitmap;
  208249. HICON hi = CreateIconIndirect (&info);
  208250. DeleteObject (mask);
  208251. return hi;
  208252. }
  208253. const Image juce_createIconForFile (const File& file)
  208254. {
  208255. Image image;
  208256. WCHAR filename [1024];
  208257. file.getFullPathName().copyToUnicode (filename, 1023);
  208258. WORD iconNum = 0;
  208259. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208260. filename, &iconNum);
  208261. if (icon != 0)
  208262. {
  208263. image = createImageFromHICON (icon);
  208264. DestroyIcon (icon);
  208265. }
  208266. return image;
  208267. }
  208268. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208269. {
  208270. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208271. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208272. Image im (image);
  208273. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208274. {
  208275. im = im.rescaled (maxW, maxH);
  208276. hotspotX = (hotspotX * maxW) / image.getWidth();
  208277. hotspotY = (hotspotY * maxH) / image.getHeight();
  208278. }
  208279. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208280. }
  208281. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208282. {
  208283. if (cursorHandle != 0 && ! isStandard)
  208284. DestroyCursor ((HCURSOR) cursorHandle);
  208285. }
  208286. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208287. {
  208288. LPCTSTR cursorName = IDC_ARROW;
  208289. switch (type)
  208290. {
  208291. case NormalCursor: break;
  208292. case NoCursor: return 0;
  208293. case WaitCursor: cursorName = IDC_WAIT; break;
  208294. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208295. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208296. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208297. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208298. case LeftRightResizeCursor:
  208299. case LeftEdgeResizeCursor:
  208300. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208301. case UpDownResizeCursor:
  208302. case TopEdgeResizeCursor:
  208303. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208304. case TopLeftCornerResizeCursor:
  208305. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208306. case TopRightCornerResizeCursor:
  208307. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208308. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208309. case DraggingHandCursor:
  208310. {
  208311. static void* dragHandCursor = 0;
  208312. if (dragHandCursor == 0)
  208313. {
  208314. static const unsigned char dragHandData[] =
  208315. { 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,
  208316. 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,
  208317. 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 };
  208318. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208319. }
  208320. return dragHandCursor;
  208321. }
  208322. default:
  208323. jassertfalse; break;
  208324. }
  208325. HCURSOR cursorH = LoadCursor (0, cursorName);
  208326. if (cursorH == 0)
  208327. cursorH = LoadCursor (0, IDC_ARROW);
  208328. return cursorH;
  208329. }
  208330. void MouseCursor::showInWindow (ComponentPeer*) const
  208331. {
  208332. SetCursor ((HCURSOR) getHandle());
  208333. }
  208334. void MouseCursor::showInAllWindows() const
  208335. {
  208336. showInWindow (0);
  208337. }
  208338. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208339. {
  208340. public:
  208341. JuceDropSource() {}
  208342. ~JuceDropSource() {}
  208343. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208344. {
  208345. if (escapePressed)
  208346. return DRAGDROP_S_CANCEL;
  208347. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208348. return DRAGDROP_S_DROP;
  208349. return S_OK;
  208350. }
  208351. HRESULT __stdcall GiveFeedback (DWORD)
  208352. {
  208353. return DRAGDROP_S_USEDEFAULTCURSORS;
  208354. }
  208355. };
  208356. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208357. {
  208358. public:
  208359. JuceEnumFormatEtc (const FORMATETC* const format_)
  208360. : format (format_),
  208361. index (0)
  208362. {
  208363. }
  208364. ~JuceEnumFormatEtc() {}
  208365. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208366. {
  208367. if (result == 0)
  208368. return E_POINTER;
  208369. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208370. newOne->index = index;
  208371. *result = newOne;
  208372. return S_OK;
  208373. }
  208374. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208375. {
  208376. if (pceltFetched != 0)
  208377. *pceltFetched = 0;
  208378. else if (celt != 1)
  208379. return S_FALSE;
  208380. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208381. {
  208382. copyFormatEtc (lpFormatEtc [0], *format);
  208383. ++index;
  208384. if (pceltFetched != 0)
  208385. *pceltFetched = 1;
  208386. return S_OK;
  208387. }
  208388. return S_FALSE;
  208389. }
  208390. HRESULT __stdcall Skip (ULONG celt)
  208391. {
  208392. if (index + (int) celt >= 1)
  208393. return S_FALSE;
  208394. index += celt;
  208395. return S_OK;
  208396. }
  208397. HRESULT __stdcall Reset()
  208398. {
  208399. index = 0;
  208400. return S_OK;
  208401. }
  208402. private:
  208403. const FORMATETC* const format;
  208404. int index;
  208405. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208406. {
  208407. dest = source;
  208408. if (source.ptd != 0)
  208409. {
  208410. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208411. *(dest.ptd) = *(source.ptd);
  208412. }
  208413. }
  208414. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208415. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208416. };
  208417. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208418. {
  208419. public:
  208420. JuceDataObject (JuceDropSource* const dropSource_,
  208421. const FORMATETC* const format_,
  208422. const STGMEDIUM* const medium_)
  208423. : dropSource (dropSource_),
  208424. format (format_),
  208425. medium (medium_)
  208426. {
  208427. }
  208428. virtual ~JuceDataObject()
  208429. {
  208430. jassert (refCount == 0);
  208431. }
  208432. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208433. {
  208434. if ((pFormatEtc->tymed & format->tymed) != 0
  208435. && pFormatEtc->cfFormat == format->cfFormat
  208436. && pFormatEtc->dwAspect == format->dwAspect)
  208437. {
  208438. pMedium->tymed = format->tymed;
  208439. pMedium->pUnkForRelease = 0;
  208440. if (format->tymed == TYMED_HGLOBAL)
  208441. {
  208442. const SIZE_T len = GlobalSize (medium->hGlobal);
  208443. void* const src = GlobalLock (medium->hGlobal);
  208444. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208445. memcpy (dst, src, len);
  208446. GlobalUnlock (medium->hGlobal);
  208447. pMedium->hGlobal = dst;
  208448. return S_OK;
  208449. }
  208450. }
  208451. return DV_E_FORMATETC;
  208452. }
  208453. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208454. {
  208455. if (f == 0)
  208456. return E_INVALIDARG;
  208457. if (f->tymed == format->tymed
  208458. && f->cfFormat == format->cfFormat
  208459. && f->dwAspect == format->dwAspect)
  208460. return S_OK;
  208461. return DV_E_FORMATETC;
  208462. }
  208463. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208464. {
  208465. pFormatEtcOut->ptd = 0;
  208466. return E_NOTIMPL;
  208467. }
  208468. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208469. {
  208470. if (result == 0)
  208471. return E_POINTER;
  208472. if (direction == DATADIR_GET)
  208473. {
  208474. *result = new JuceEnumFormatEtc (format);
  208475. return S_OK;
  208476. }
  208477. *result = 0;
  208478. return E_NOTIMPL;
  208479. }
  208480. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208481. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208482. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208483. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208484. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208485. private:
  208486. JuceDropSource* const dropSource;
  208487. const FORMATETC* const format;
  208488. const STGMEDIUM* const medium;
  208489. JuceDataObject (const JuceDataObject&);
  208490. JuceDataObject& operator= (const JuceDataObject&);
  208491. };
  208492. static HDROP createHDrop (const StringArray& fileNames)
  208493. {
  208494. int totalChars = 0;
  208495. for (int i = fileNames.size(); --i >= 0;)
  208496. totalChars += fileNames[i].length() + 1;
  208497. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208498. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208499. if (hDrop != 0)
  208500. {
  208501. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208502. pDropFiles->pFiles = sizeof (DROPFILES);
  208503. pDropFiles->fWide = true;
  208504. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  208505. for (int i = 0; i < fileNames.size(); ++i)
  208506. {
  208507. fileNames[i].copyToUnicode (fname, 2048);
  208508. fname += fileNames[i].length() + 1;
  208509. }
  208510. *fname = 0;
  208511. GlobalUnlock (hDrop);
  208512. }
  208513. return hDrop;
  208514. }
  208515. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208516. {
  208517. JuceDropSource* const source = new JuceDropSource();
  208518. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208519. DWORD effect;
  208520. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208521. data->Release();
  208522. source->Release();
  208523. return res == DRAGDROP_S_DROP;
  208524. }
  208525. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208526. {
  208527. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208528. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208529. medium.hGlobal = createHDrop (files);
  208530. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208531. : DROPEFFECT_COPY);
  208532. }
  208533. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208534. {
  208535. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208536. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208537. const int numChars = text.length();
  208538. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208539. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208540. text.copyToUnicode (data, numChars + 1);
  208541. format.cfFormat = CF_UNICODETEXT;
  208542. GlobalUnlock (medium.hGlobal);
  208543. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208544. }
  208545. #endif
  208546. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208547. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208548. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208549. // compiled on its own).
  208550. #if JUCE_INCLUDED_FILE
  208551. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  208552. namespace FileChooserHelpers
  208553. {
  208554. static const void* defaultDirPath = 0;
  208555. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  208556. static Component* currentExtraFileWin = 0;
  208557. static bool areThereAnyAlwaysOnTopWindows()
  208558. {
  208559. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208560. {
  208561. Component* c = Desktop::getInstance().getComponent (i);
  208562. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208563. return true;
  208564. }
  208565. return false;
  208566. }
  208567. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  208568. {
  208569. if (msg == BFFM_INITIALIZED)
  208570. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  208571. else if (msg == BFFM_VALIDATEFAILEDW)
  208572. returnedString = (LPCWSTR) lParam;
  208573. else if (msg == BFFM_VALIDATEFAILEDA)
  208574. returnedString = (const char*) lParam;
  208575. return 0;
  208576. }
  208577. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208578. {
  208579. if (currentExtraFileWin != 0)
  208580. {
  208581. if (uiMsg == WM_INITDIALOG)
  208582. {
  208583. HWND dialogH = GetParent (hdlg);
  208584. jassert (dialogH != 0);
  208585. if (dialogH == 0)
  208586. dialogH = hdlg;
  208587. RECT r, cr;
  208588. GetWindowRect (dialogH, &r);
  208589. GetClientRect (dialogH, &cr);
  208590. SetWindowPos (dialogH, 0,
  208591. r.left, r.top,
  208592. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  208593. jmax (150, (int) (r.bottom - r.top)),
  208594. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208595. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  208596. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  208597. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  208598. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  208599. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  208600. }
  208601. else if (uiMsg == WM_NOTIFY)
  208602. {
  208603. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208604. if (ofn->hdr.code == CDN_SELCHANGE)
  208605. {
  208606. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  208607. if (comp != 0)
  208608. {
  208609. TCHAR path [MAX_PATH * 2];
  208610. path[0] = 0;
  208611. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208612. const String fn ((const WCHAR*) path);
  208613. comp->selectedFileChanged (File (fn));
  208614. }
  208615. }
  208616. }
  208617. }
  208618. return 0;
  208619. }
  208620. class FPComponentHolder : public Component
  208621. {
  208622. public:
  208623. FPComponentHolder()
  208624. {
  208625. setVisible (true);
  208626. setOpaque (true);
  208627. }
  208628. ~FPComponentHolder()
  208629. {
  208630. }
  208631. void paint (Graphics& g)
  208632. {
  208633. g.fillAll (Colours::lightgrey);
  208634. }
  208635. private:
  208636. FPComponentHolder (const FPComponentHolder&);
  208637. FPComponentHolder& operator= (const FPComponentHolder&);
  208638. };
  208639. }
  208640. void FileChooser::showPlatformDialog (Array<File>& results,
  208641. const String& title,
  208642. const File& currentFileOrDirectory,
  208643. const String& filter,
  208644. bool selectsDirectory,
  208645. bool /*selectsFiles*/,
  208646. bool isSaveDialogue,
  208647. bool warnAboutOverwritingExistingFiles,
  208648. bool selectMultipleFiles,
  208649. FilePreviewComponent* extraInfoComponent)
  208650. {
  208651. using namespace FileChooserHelpers;
  208652. const int numCharsAvailable = 32768;
  208653. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  208654. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  208655. int fnameIdx = 0;
  208656. JUCE_TRY
  208657. {
  208658. // use a modal window as the parent for this dialog box
  208659. // to block input from other app windows
  208660. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208661. Component w (String::empty);
  208662. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208663. mainMon.getY() + mainMon.getHeight() / 4,
  208664. 0, 0);
  208665. w.setOpaque (true);
  208666. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208667. w.addToDesktop (0);
  208668. if (extraInfoComponent == 0)
  208669. w.enterModalState();
  208670. String initialDir;
  208671. if (currentFileOrDirectory.isDirectory())
  208672. {
  208673. initialDir = currentFileOrDirectory.getFullPathName();
  208674. }
  208675. else
  208676. {
  208677. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  208678. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208679. }
  208680. if (currentExtraFileWin->isValidComponent())
  208681. {
  208682. jassertfalse;
  208683. return;
  208684. }
  208685. if (selectsDirectory)
  208686. {
  208687. LPITEMIDLIST list = 0;
  208688. filenameSpace.fillWith (0);
  208689. {
  208690. BROWSEINFO bi;
  208691. zerostruct (bi);
  208692. bi.hwndOwner = (HWND) w.getWindowHandle();
  208693. bi.pszDisplayName = fname;
  208694. bi.lpszTitle = title;
  208695. bi.lpfn = browseCallbackProc;
  208696. #ifdef BIF_USENEWUI
  208697. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208698. #else
  208699. bi.ulFlags = 0x50;
  208700. #endif
  208701. defaultDirPath = (const WCHAR*) initialDir;
  208702. list = SHBrowseForFolder (&bi);
  208703. if (! SHGetPathFromIDListW (list, fname))
  208704. {
  208705. fname[0] = 0;
  208706. returnedString = String::empty;
  208707. }
  208708. }
  208709. LPMALLOC al;
  208710. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208711. al->Free (list);
  208712. defaultDirPath = 0;
  208713. if (returnedString.isNotEmpty())
  208714. {
  208715. const String stringFName (fname);
  208716. results.add (File (stringFName).getSiblingFile (returnedString));
  208717. returnedString = String::empty;
  208718. return;
  208719. }
  208720. }
  208721. else
  208722. {
  208723. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208724. if (warnAboutOverwritingExistingFiles)
  208725. flags |= OFN_OVERWRITEPROMPT;
  208726. if (selectMultipleFiles)
  208727. flags |= OFN_ALLOWMULTISELECT;
  208728. if (extraInfoComponent != 0)
  208729. {
  208730. flags |= OFN_ENABLEHOOK;
  208731. currentExtraFileWin = new FPComponentHolder();
  208732. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  208733. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  208734. extraInfoComponent->getHeight());
  208735. currentExtraFileWin->addToDesktop (0);
  208736. currentExtraFileWin->enterModalState();
  208737. }
  208738. {
  208739. WCHAR filters [1024];
  208740. zeromem (filters, sizeof (filters));
  208741. filter.copyToUnicode (filters, 1024);
  208742. filter.copyToUnicode (filters + filter.length() + 1,
  208743. 1022 - filter.length());
  208744. OPENFILENAMEW of;
  208745. zerostruct (of);
  208746. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208747. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208748. #else
  208749. of.lStructSize = sizeof (of);
  208750. #endif
  208751. of.hwndOwner = (HWND) w.getWindowHandle();
  208752. of.lpstrFilter = filters;
  208753. of.nFilterIndex = 1;
  208754. of.lpstrFile = fname;
  208755. of.nMaxFile = numCharsAvailable;
  208756. of.lpstrInitialDir = initialDir;
  208757. of.lpstrTitle = title;
  208758. of.Flags = flags;
  208759. if (extraInfoComponent != 0)
  208760. of.lpfnHook = &openCallback;
  208761. if (isSaveDialogue)
  208762. {
  208763. if (! GetSaveFileName (&of))
  208764. fname[0] = 0;
  208765. else
  208766. fnameIdx = of.nFileOffset;
  208767. }
  208768. else
  208769. {
  208770. if (! GetOpenFileName (&of))
  208771. fname[0] = 0;
  208772. else
  208773. fnameIdx = of.nFileOffset;
  208774. }
  208775. }
  208776. }
  208777. }
  208778. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  208779. catch (...)
  208780. {
  208781. fname[0] = 0;
  208782. }
  208783. #endif
  208784. deleteAndZero (currentExtraFileWin);
  208785. const WCHAR* const files = fname;
  208786. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  208787. {
  208788. const WCHAR* filename = files + fnameIdx;
  208789. while (*filename != 0)
  208790. {
  208791. const String filepath (String (files) + "\\" + String (filename));
  208792. results.add (File (filepath));
  208793. filename += CharacterFunctions::length (filename) + 1;
  208794. }
  208795. }
  208796. else if (files[0] != 0)
  208797. {
  208798. results.add (File (files));
  208799. }
  208800. }
  208801. #endif
  208802. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208803. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208804. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208805. // compiled on its own).
  208806. #if JUCE_INCLUDED_FILE
  208807. void SystemClipboard::copyTextToClipboard (const String& text)
  208808. {
  208809. if (OpenClipboard (0) != 0)
  208810. {
  208811. if (EmptyClipboard() != 0)
  208812. {
  208813. const int len = text.length();
  208814. if (len > 0)
  208815. {
  208816. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208817. (len + 1) * sizeof (wchar_t));
  208818. if (bufH != 0)
  208819. {
  208820. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208821. text.copyToUnicode (data, len);
  208822. GlobalUnlock (bufH);
  208823. SetClipboardData (CF_UNICODETEXT, bufH);
  208824. }
  208825. }
  208826. }
  208827. CloseClipboard();
  208828. }
  208829. }
  208830. const String SystemClipboard::getTextFromClipboard()
  208831. {
  208832. String result;
  208833. if (OpenClipboard (0) != 0)
  208834. {
  208835. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208836. if (bufH != 0)
  208837. {
  208838. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208839. if (data != 0)
  208840. {
  208841. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208842. GlobalUnlock (bufH);
  208843. }
  208844. }
  208845. CloseClipboard();
  208846. }
  208847. return result;
  208848. }
  208849. #endif
  208850. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208851. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208852. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208853. // compiled on its own).
  208854. #if JUCE_INCLUDED_FILE
  208855. namespace ActiveXHelpers
  208856. {
  208857. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208858. {
  208859. public:
  208860. JuceIStorage() {}
  208861. ~JuceIStorage() {}
  208862. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208863. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208864. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208865. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208866. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208867. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208868. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208869. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208870. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208871. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208872. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208873. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208874. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208875. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208876. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208877. juce_UseDebuggingNewOperator
  208878. };
  208879. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208880. {
  208881. HWND window;
  208882. public:
  208883. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208884. ~JuceOleInPlaceFrame() {}
  208885. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208886. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208887. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208888. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208889. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208890. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208891. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208892. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208893. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208894. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208895. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208896. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208897. juce_UseDebuggingNewOperator
  208898. };
  208899. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208900. {
  208901. HWND window;
  208902. JuceOleInPlaceFrame* frame;
  208903. public:
  208904. JuceIOleInPlaceSite (HWND window_)
  208905. : window (window_),
  208906. frame (new JuceOleInPlaceFrame (window))
  208907. {}
  208908. ~JuceIOleInPlaceSite()
  208909. {
  208910. frame->Release();
  208911. }
  208912. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208913. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208914. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208915. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208916. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208917. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208918. {
  208919. *lplpFrame = frame;
  208920. *lplpDoc = 0;
  208921. lpFrameInfo->fMDIApp = FALSE;
  208922. lpFrameInfo->hwndFrame = window;
  208923. lpFrameInfo->haccel = 0;
  208924. lpFrameInfo->cAccelEntries = 0;
  208925. return S_OK;
  208926. }
  208927. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208928. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208929. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208930. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208931. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208932. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208933. juce_UseDebuggingNewOperator
  208934. };
  208935. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  208936. {
  208937. JuceIOleInPlaceSite* inplaceSite;
  208938. public:
  208939. JuceIOleClientSite (HWND window)
  208940. : inplaceSite (new JuceIOleInPlaceSite (window))
  208941. {}
  208942. ~JuceIOleClientSite()
  208943. {
  208944. inplaceSite->Release();
  208945. }
  208946. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  208947. {
  208948. if (type == IID_IOleInPlaceSite)
  208949. {
  208950. inplaceSite->AddRef();
  208951. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  208952. return S_OK;
  208953. }
  208954. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  208955. }
  208956. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208957. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208958. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208959. HRESULT __stdcall ShowObject() { return S_OK; }
  208960. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208961. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208962. juce_UseDebuggingNewOperator
  208963. };
  208964. static Array<ActiveXControlComponent*> activeXComps;
  208965. static HWND getHWND (const ActiveXControlComponent* const component)
  208966. {
  208967. HWND hwnd = 0;
  208968. const IID iid = IID_IOleWindow;
  208969. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208970. if (window != 0)
  208971. {
  208972. window->GetWindow (&hwnd);
  208973. window->Release();
  208974. }
  208975. return hwnd;
  208976. }
  208977. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208978. {
  208979. RECT activeXRect, peerRect;
  208980. GetWindowRect (hwnd, &activeXRect);
  208981. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208982. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  208983. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  208984. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  208985. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208986. switch (message)
  208987. {
  208988. case WM_MOUSEMOVE:
  208989. case WM_LBUTTONDOWN:
  208990. case WM_MBUTTONDOWN:
  208991. case WM_RBUTTONDOWN:
  208992. case WM_LBUTTONUP:
  208993. case WM_MBUTTONUP:
  208994. case WM_RBUTTONUP:
  208995. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  208996. break;
  208997. default:
  208998. break;
  208999. }
  209000. }
  209001. }
  209002. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209003. {
  209004. ActiveXControlComponent* const owner;
  209005. bool wasShowing;
  209006. public:
  209007. HWND controlHWND;
  209008. IStorage* storage;
  209009. IOleClientSite* clientSite;
  209010. IOleObject* control;
  209011. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  209012. : ComponentMovementWatcher (owner_),
  209013. owner (owner_),
  209014. wasShowing (owner_ != 0 && owner_->isShowing()),
  209015. controlHWND (0),
  209016. storage (new ActiveXHelpers::JuceIStorage()),
  209017. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209018. control (0)
  209019. {
  209020. }
  209021. ~Pimpl()
  209022. {
  209023. if (control != 0)
  209024. {
  209025. control->Close (OLECLOSE_NOSAVE);
  209026. control->Release();
  209027. }
  209028. clientSite->Release();
  209029. storage->Release();
  209030. }
  209031. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209032. {
  209033. Component* const topComp = owner->getTopLevelComponent();
  209034. if (topComp->getPeer() != 0)
  209035. {
  209036. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  209037. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  209038. }
  209039. }
  209040. void componentPeerChanged()
  209041. {
  209042. const bool isShowingNow = owner->isShowing();
  209043. if (wasShowing != isShowingNow)
  209044. {
  209045. wasShowing = isShowingNow;
  209046. owner->setControlVisible (isShowingNow);
  209047. }
  209048. componentMovedOrResized (true, true);
  209049. }
  209050. void componentVisibilityChanged (Component&)
  209051. {
  209052. componentPeerChanged();
  209053. }
  209054. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209055. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209056. {
  209057. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209058. {
  209059. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209060. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209061. {
  209062. switch (message)
  209063. {
  209064. case WM_MOUSEMOVE:
  209065. case WM_LBUTTONDOWN:
  209066. case WM_MBUTTONDOWN:
  209067. case WM_RBUTTONDOWN:
  209068. case WM_LBUTTONUP:
  209069. case WM_MBUTTONUP:
  209070. case WM_RBUTTONUP:
  209071. case WM_LBUTTONDBLCLK:
  209072. case WM_MBUTTONDBLCLK:
  209073. case WM_RBUTTONDBLCLK:
  209074. if (ax->isShowing())
  209075. {
  209076. ComponentPeer* const peer = ax->getPeer();
  209077. if (peer != 0)
  209078. {
  209079. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209080. if (! ax->areMouseEventsAllowed())
  209081. return 0;
  209082. }
  209083. }
  209084. break;
  209085. default:
  209086. break;
  209087. }
  209088. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209089. }
  209090. }
  209091. return DefWindowProc (hwnd, message, wParam, lParam);
  209092. }
  209093. };
  209094. ActiveXControlComponent::ActiveXControlComponent()
  209095. : originalWndProc (0),
  209096. mouseEventsAllowed (true)
  209097. {
  209098. ActiveXHelpers::activeXComps.add (this);
  209099. }
  209100. ActiveXControlComponent::~ActiveXControlComponent()
  209101. {
  209102. deleteControl();
  209103. ActiveXHelpers::activeXComps.removeValue (this);
  209104. }
  209105. void ActiveXControlComponent::paint (Graphics& g)
  209106. {
  209107. if (control == 0)
  209108. g.fillAll (Colours::lightgrey);
  209109. }
  209110. bool ActiveXControlComponent::createControl (const void* controlIID)
  209111. {
  209112. deleteControl();
  209113. ComponentPeer* const peer = getPeer();
  209114. // the component must have already been added to a real window when you call this!
  209115. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209116. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209117. {
  209118. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209119. HWND hwnd = (HWND) peer->getNativeHandle();
  209120. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  209121. HRESULT hr;
  209122. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209123. newControl->clientSite, newControl->storage,
  209124. (void**) &(newControl->control))) == S_OK)
  209125. {
  209126. newControl->control->SetHostNames (L"Juce", 0);
  209127. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209128. {
  209129. RECT rect;
  209130. rect.left = pos.getX();
  209131. rect.top = pos.getY();
  209132. rect.right = pos.getX() + getWidth();
  209133. rect.bottom = pos.getY() + getHeight();
  209134. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209135. {
  209136. control = newControl;
  209137. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209138. control->controlHWND = ActiveXHelpers::getHWND (this);
  209139. if (control->controlHWND != 0)
  209140. {
  209141. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209142. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209143. }
  209144. return true;
  209145. }
  209146. }
  209147. }
  209148. }
  209149. return false;
  209150. }
  209151. void ActiveXControlComponent::deleteControl()
  209152. {
  209153. control = 0;
  209154. originalWndProc = 0;
  209155. }
  209156. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209157. {
  209158. void* result = 0;
  209159. if (control != 0 && control->control != 0
  209160. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209161. return result;
  209162. return 0;
  209163. }
  209164. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209165. {
  209166. if (control->controlHWND != 0)
  209167. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209168. }
  209169. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209170. {
  209171. if (control->controlHWND != 0)
  209172. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209173. }
  209174. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209175. {
  209176. mouseEventsAllowed = eventsCanReachControl;
  209177. }
  209178. #endif
  209179. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209180. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209181. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209182. // compiled on its own).
  209183. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209184. using namespace QTOLibrary;
  209185. using namespace QTOControlLib;
  209186. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209187. static bool isQTAvailable = false;
  209188. class QuickTimeMovieComponent::Pimpl
  209189. {
  209190. public:
  209191. Pimpl() : dataHandle (0)
  209192. {
  209193. }
  209194. ~Pimpl()
  209195. {
  209196. clearHandle();
  209197. }
  209198. void clearHandle()
  209199. {
  209200. if (dataHandle != 0)
  209201. {
  209202. DisposeHandle (dataHandle);
  209203. dataHandle = 0;
  209204. }
  209205. }
  209206. IQTControlPtr qtControl;
  209207. IQTMoviePtr qtMovie;
  209208. Handle dataHandle;
  209209. };
  209210. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209211. : movieLoaded (false),
  209212. controllerVisible (true)
  209213. {
  209214. pimpl = new Pimpl();
  209215. setMouseEventsAllowed (false);
  209216. }
  209217. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209218. {
  209219. closeMovie();
  209220. pimpl->qtControl = 0;
  209221. deleteControl();
  209222. pimpl = 0;
  209223. }
  209224. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209225. {
  209226. if (! isQTAvailable)
  209227. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209228. return isQTAvailable;
  209229. }
  209230. void QuickTimeMovieComponent::createControlIfNeeded()
  209231. {
  209232. if (isShowing() && ! isControlCreated())
  209233. {
  209234. const IID qtIID = __uuidof (QTControl);
  209235. if (createControl (&qtIID))
  209236. {
  209237. const IID qtInterfaceIID = __uuidof (IQTControl);
  209238. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209239. if (pimpl->qtControl != 0)
  209240. {
  209241. pimpl->qtControl->Release(); // it has one ref too many at this point
  209242. pimpl->qtControl->QuickTimeInitialize();
  209243. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209244. if (movieFile != File::nonexistent)
  209245. loadMovie (movieFile, controllerVisible);
  209246. }
  209247. }
  209248. }
  209249. }
  209250. bool QuickTimeMovieComponent::isControlCreated() const
  209251. {
  209252. return isControlOpen();
  209253. }
  209254. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209255. const bool isControllerVisible)
  209256. {
  209257. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209258. movieFile = File::nonexistent;
  209259. movieLoaded = false;
  209260. pimpl->qtMovie = 0;
  209261. controllerVisible = isControllerVisible;
  209262. createControlIfNeeded();
  209263. if (isControlCreated())
  209264. {
  209265. if (pimpl->qtControl != 0)
  209266. {
  209267. pimpl->qtControl->Put_MovieHandle (0);
  209268. pimpl->clearHandle();
  209269. Movie movie;
  209270. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209271. {
  209272. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209273. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209274. if (pimpl->qtMovie != 0)
  209275. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209276. : qtMovieControllerTypeNone);
  209277. }
  209278. if (movie == 0)
  209279. pimpl->clearHandle();
  209280. }
  209281. movieLoaded = (pimpl->qtMovie != 0);
  209282. }
  209283. else
  209284. {
  209285. // You're trying to open a movie when the control hasn't yet been created, probably because
  209286. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209287. jassertfalse;
  209288. }
  209289. return movieLoaded;
  209290. }
  209291. void QuickTimeMovieComponent::closeMovie()
  209292. {
  209293. stop();
  209294. movieFile = File::nonexistent;
  209295. movieLoaded = false;
  209296. pimpl->qtMovie = 0;
  209297. if (pimpl->qtControl != 0)
  209298. pimpl->qtControl->Put_MovieHandle (0);
  209299. pimpl->clearHandle();
  209300. }
  209301. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209302. {
  209303. return movieFile;
  209304. }
  209305. bool QuickTimeMovieComponent::isMovieOpen() const
  209306. {
  209307. return movieLoaded;
  209308. }
  209309. double QuickTimeMovieComponent::getMovieDuration() const
  209310. {
  209311. if (pimpl->qtMovie != 0)
  209312. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209313. return 0.0;
  209314. }
  209315. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209316. {
  209317. if (pimpl->qtMovie != 0)
  209318. {
  209319. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209320. width = r.right - r.left;
  209321. height = r.bottom - r.top;
  209322. }
  209323. else
  209324. {
  209325. width = height = 0;
  209326. }
  209327. }
  209328. void QuickTimeMovieComponent::play()
  209329. {
  209330. if (pimpl->qtMovie != 0)
  209331. pimpl->qtMovie->Play();
  209332. }
  209333. void QuickTimeMovieComponent::stop()
  209334. {
  209335. if (pimpl->qtMovie != 0)
  209336. pimpl->qtMovie->Stop();
  209337. }
  209338. bool QuickTimeMovieComponent::isPlaying() const
  209339. {
  209340. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209341. }
  209342. void QuickTimeMovieComponent::setPosition (const double seconds)
  209343. {
  209344. if (pimpl->qtMovie != 0)
  209345. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209346. }
  209347. double QuickTimeMovieComponent::getPosition() const
  209348. {
  209349. if (pimpl->qtMovie != 0)
  209350. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209351. return 0.0;
  209352. }
  209353. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209354. {
  209355. if (pimpl->qtMovie != 0)
  209356. pimpl->qtMovie->PutRate (newSpeed);
  209357. }
  209358. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209359. {
  209360. if (pimpl->qtMovie != 0)
  209361. {
  209362. pimpl->qtMovie->PutAudioVolume (newVolume);
  209363. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209364. }
  209365. }
  209366. float QuickTimeMovieComponent::getMovieVolume() const
  209367. {
  209368. if (pimpl->qtMovie != 0)
  209369. return pimpl->qtMovie->GetAudioVolume();
  209370. return 0.0f;
  209371. }
  209372. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209373. {
  209374. if (pimpl->qtMovie != 0)
  209375. pimpl->qtMovie->PutLoop (shouldLoop);
  209376. }
  209377. bool QuickTimeMovieComponent::isLooping() const
  209378. {
  209379. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209380. }
  209381. bool QuickTimeMovieComponent::isControllerVisible() const
  209382. {
  209383. return controllerVisible;
  209384. }
  209385. void QuickTimeMovieComponent::parentHierarchyChanged()
  209386. {
  209387. createControlIfNeeded();
  209388. QTCompBaseClass::parentHierarchyChanged();
  209389. }
  209390. void QuickTimeMovieComponent::visibilityChanged()
  209391. {
  209392. createControlIfNeeded();
  209393. QTCompBaseClass::visibilityChanged();
  209394. }
  209395. void QuickTimeMovieComponent::paint (Graphics& g)
  209396. {
  209397. if (! isControlCreated())
  209398. g.fillAll (Colours::black);
  209399. }
  209400. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209401. {
  209402. Handle dataRef = 0;
  209403. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209404. if (err == noErr)
  209405. {
  209406. Str255 suffix;
  209407. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209408. StringPtr name = suffix;
  209409. err = PtrAndHand (name, dataRef, name[0] + 1);
  209410. if (err == noErr)
  209411. {
  209412. long atoms[3];
  209413. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209414. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209415. atoms[2] = EndianU32_NtoB (MovieFileType);
  209416. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209417. if (err == noErr)
  209418. return dataRef;
  209419. }
  209420. DisposeHandle (dataRef);
  209421. }
  209422. return 0;
  209423. }
  209424. static CFStringRef juceStringToCFString (const String& s)
  209425. {
  209426. const int len = s.length();
  209427. const juce_wchar* const t = s;
  209428. HeapBlock <UniChar> temp (len + 2);
  209429. for (int i = 0; i <= len; ++i)
  209430. temp[i] = t[i];
  209431. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209432. }
  209433. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209434. {
  209435. Boolean trueBool = true;
  209436. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209437. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209438. props[prop].propValueSize = sizeof (trueBool);
  209439. props[prop].propValueAddress = &trueBool;
  209440. ++prop;
  209441. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209442. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209443. props[prop].propValueSize = sizeof (trueBool);
  209444. props[prop].propValueAddress = &trueBool;
  209445. ++prop;
  209446. Boolean isActive = true;
  209447. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209448. props[prop].propID = kQTNewMoviePropertyID_Active;
  209449. props[prop].propValueSize = sizeof (isActive);
  209450. props[prop].propValueAddress = &isActive;
  209451. ++prop;
  209452. MacSetPort (0);
  209453. jassert (prop <= 5);
  209454. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209455. return err == noErr;
  209456. }
  209457. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209458. {
  209459. if (input == 0)
  209460. return false;
  209461. dataHandle = 0;
  209462. bool ok = false;
  209463. QTNewMoviePropertyElement props[5];
  209464. zeromem (props, sizeof (props));
  209465. int prop = 0;
  209466. DataReferenceRecord dr;
  209467. props[prop].propClass = kQTPropertyClass_DataLocation;
  209468. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209469. props[prop].propValueSize = sizeof (dr);
  209470. props[prop].propValueAddress = &dr;
  209471. ++prop;
  209472. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209473. if (fin != 0)
  209474. {
  209475. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209476. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209477. &dr.dataRef, &dr.dataRefType);
  209478. ok = openMovie (props, prop, movie);
  209479. DisposeHandle (dr.dataRef);
  209480. CFRelease (filePath);
  209481. }
  209482. else
  209483. {
  209484. // sanity-check because this currently needs to load the whole stream into memory..
  209485. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209486. dataHandle = NewHandle ((Size) input->getTotalLength());
  209487. HLock (dataHandle);
  209488. // read the entire stream into memory - this is a pain, but can't get it to work
  209489. // properly using a custom callback to supply the data.
  209490. input->read (*dataHandle, (int) input->getTotalLength());
  209491. HUnlock (dataHandle);
  209492. // different types to get QT to try. (We should really be a bit smarter here by
  209493. // working out in advance which one the stream contains, rather than just trying
  209494. // each one)
  209495. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209496. "\04.avi", "\04.m4a" };
  209497. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209498. {
  209499. /* // this fails for some bizarre reason - it can be bodged to work with
  209500. // movies, but can't seem to do it for other file types..
  209501. QTNewMovieUserProcRecord procInfo;
  209502. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209503. procInfo.getMovieUserProcRefcon = this;
  209504. procInfo.defaultDataRef.dataRef = dataRef;
  209505. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209506. props[prop].propClass = kQTPropertyClass_DataLocation;
  209507. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209508. props[prop].propValueSize = sizeof (procInfo);
  209509. props[prop].propValueAddress = (void*) &procInfo;
  209510. ++prop; */
  209511. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209512. dr.dataRefType = HandleDataHandlerSubType;
  209513. ok = openMovie (props, prop, movie);
  209514. DisposeHandle (dr.dataRef);
  209515. }
  209516. }
  209517. return ok;
  209518. }
  209519. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209520. const bool isControllerVisible)
  209521. {
  209522. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209523. movieFile = movieFile_;
  209524. return ok;
  209525. }
  209526. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209527. const bool isControllerVisible)
  209528. {
  209529. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209530. }
  209531. void QuickTimeMovieComponent::goToStart()
  209532. {
  209533. setPosition (0.0);
  209534. }
  209535. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209536. const RectanglePlacement& placement)
  209537. {
  209538. int normalWidth, normalHeight;
  209539. getMovieNormalSize (normalWidth, normalHeight);
  209540. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209541. {
  209542. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209543. placement.applyTo (x, y, w, h,
  209544. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209545. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209546. if (w > 0 && h > 0)
  209547. {
  209548. setBounds (roundToInt (x), roundToInt (y),
  209549. roundToInt (w), roundToInt (h));
  209550. }
  209551. }
  209552. else
  209553. {
  209554. setBounds (spaceToFitWithin);
  209555. }
  209556. }
  209557. #endif
  209558. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209559. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209560. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209561. // compiled on its own).
  209562. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209563. class WebBrowserComponentInternal : public ActiveXControlComponent
  209564. {
  209565. public:
  209566. WebBrowserComponentInternal()
  209567. : browser (0),
  209568. connectionPoint (0),
  209569. adviseCookie (0)
  209570. {
  209571. }
  209572. ~WebBrowserComponentInternal()
  209573. {
  209574. if (connectionPoint != 0)
  209575. connectionPoint->Unadvise (adviseCookie);
  209576. if (browser != 0)
  209577. browser->Release();
  209578. }
  209579. void createBrowser()
  209580. {
  209581. createControl (&CLSID_WebBrowser);
  209582. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209583. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209584. if (connectionPointContainer != 0)
  209585. {
  209586. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209587. &connectionPoint);
  209588. if (connectionPoint != 0)
  209589. {
  209590. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209591. jassert (owner != 0);
  209592. EventHandler* handler = new EventHandler (owner);
  209593. connectionPoint->Advise (handler, &adviseCookie);
  209594. handler->Release();
  209595. }
  209596. }
  209597. }
  209598. void goToURL (const String& url,
  209599. const StringArray* headers,
  209600. const MemoryBlock* postData)
  209601. {
  209602. if (browser != 0)
  209603. {
  209604. LPSAFEARRAY sa = 0;
  209605. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209606. VariantInit (&flags);
  209607. VariantInit (&frame);
  209608. VariantInit (&postDataVar);
  209609. VariantInit (&headersVar);
  209610. if (headers != 0)
  209611. {
  209612. V_VT (&headersVar) = VT_BSTR;
  209613. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209614. }
  209615. if (postData != 0 && postData->getSize() > 0)
  209616. {
  209617. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209618. if (sa != 0)
  209619. {
  209620. void* data = 0;
  209621. SafeArrayAccessData (sa, &data);
  209622. jassert (data != 0);
  209623. if (data != 0)
  209624. {
  209625. postData->copyTo (data, 0, postData->getSize());
  209626. SafeArrayUnaccessData (sa);
  209627. VARIANT postDataVar2;
  209628. VariantInit (&postDataVar2);
  209629. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209630. V_ARRAY (&postDataVar2) = sa;
  209631. postDataVar = postDataVar2;
  209632. }
  209633. }
  209634. }
  209635. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209636. &flags, &frame,
  209637. &postDataVar, &headersVar);
  209638. if (sa != 0)
  209639. SafeArrayDestroy (sa);
  209640. VariantClear (&flags);
  209641. VariantClear (&frame);
  209642. VariantClear (&postDataVar);
  209643. VariantClear (&headersVar);
  209644. }
  209645. }
  209646. IWebBrowser2* browser;
  209647. juce_UseDebuggingNewOperator
  209648. private:
  209649. IConnectionPoint* connectionPoint;
  209650. DWORD adviseCookie;
  209651. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209652. public ComponentMovementWatcher
  209653. {
  209654. public:
  209655. EventHandler (WebBrowserComponent* owner_)
  209656. : ComponentMovementWatcher (owner_),
  209657. owner (owner_)
  209658. {
  209659. }
  209660. ~EventHandler()
  209661. {
  209662. }
  209663. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209664. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209665. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209666. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209667. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209668. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209669. UINT __RPC_FAR* /*puArgErr*/)
  209670. {
  209671. switch (dispIdMember)
  209672. {
  209673. case DISPID_BEFORENAVIGATE2:
  209674. {
  209675. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209676. String url;
  209677. if ((vurl->vt & VT_BYREF) != 0)
  209678. url = *vurl->pbstrVal;
  209679. else
  209680. url = vurl->bstrVal;
  209681. *pDispParams->rgvarg->pboolVal
  209682. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209683. : VARIANT_TRUE;
  209684. return S_OK;
  209685. }
  209686. default:
  209687. break;
  209688. }
  209689. return E_NOTIMPL;
  209690. }
  209691. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209692. void componentPeerChanged() {}
  209693. void componentVisibilityChanged (Component&)
  209694. {
  209695. owner->visibilityChanged();
  209696. }
  209697. juce_UseDebuggingNewOperator
  209698. private:
  209699. WebBrowserComponent* const owner;
  209700. EventHandler (const EventHandler&);
  209701. EventHandler& operator= (const EventHandler&);
  209702. };
  209703. };
  209704. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209705. : browser (0),
  209706. blankPageShown (false),
  209707. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209708. {
  209709. setOpaque (true);
  209710. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209711. }
  209712. WebBrowserComponent::~WebBrowserComponent()
  209713. {
  209714. delete browser;
  209715. }
  209716. void WebBrowserComponent::goToURL (const String& url,
  209717. const StringArray* headers,
  209718. const MemoryBlock* postData)
  209719. {
  209720. lastURL = url;
  209721. lastHeaders.clear();
  209722. if (headers != 0)
  209723. lastHeaders = *headers;
  209724. lastPostData.setSize (0);
  209725. if (postData != 0)
  209726. lastPostData = *postData;
  209727. blankPageShown = false;
  209728. browser->goToURL (url, headers, postData);
  209729. }
  209730. void WebBrowserComponent::stop()
  209731. {
  209732. if (browser->browser != 0)
  209733. browser->browser->Stop();
  209734. }
  209735. void WebBrowserComponent::goBack()
  209736. {
  209737. lastURL = String::empty;
  209738. blankPageShown = false;
  209739. if (browser->browser != 0)
  209740. browser->browser->GoBack();
  209741. }
  209742. void WebBrowserComponent::goForward()
  209743. {
  209744. lastURL = String::empty;
  209745. if (browser->browser != 0)
  209746. browser->browser->GoForward();
  209747. }
  209748. void WebBrowserComponent::refresh()
  209749. {
  209750. if (browser->browser != 0)
  209751. browser->browser->Refresh();
  209752. }
  209753. void WebBrowserComponent::paint (Graphics& g)
  209754. {
  209755. if (browser->browser == 0)
  209756. g.fillAll (Colours::white);
  209757. }
  209758. void WebBrowserComponent::checkWindowAssociation()
  209759. {
  209760. if (isShowing())
  209761. {
  209762. if (browser->browser == 0 && getPeer() != 0)
  209763. {
  209764. browser->createBrowser();
  209765. reloadLastURL();
  209766. }
  209767. else
  209768. {
  209769. if (blankPageShown)
  209770. goBack();
  209771. }
  209772. }
  209773. else
  209774. {
  209775. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209776. {
  209777. // when the component becomes invisible, some stuff like flash
  209778. // carries on playing audio, so we need to force it onto a blank
  209779. // page to avoid this..
  209780. blankPageShown = true;
  209781. browser->goToURL ("about:blank", 0, 0);
  209782. }
  209783. }
  209784. }
  209785. void WebBrowserComponent::reloadLastURL()
  209786. {
  209787. if (lastURL.isNotEmpty())
  209788. {
  209789. goToURL (lastURL, &lastHeaders, &lastPostData);
  209790. lastURL = String::empty;
  209791. }
  209792. }
  209793. void WebBrowserComponent::parentHierarchyChanged()
  209794. {
  209795. checkWindowAssociation();
  209796. }
  209797. void WebBrowserComponent::resized()
  209798. {
  209799. browser->setSize (getWidth(), getHeight());
  209800. }
  209801. void WebBrowserComponent::visibilityChanged()
  209802. {
  209803. checkWindowAssociation();
  209804. }
  209805. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209806. {
  209807. return true;
  209808. }
  209809. #endif
  209810. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209811. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209812. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209813. // compiled on its own).
  209814. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209815. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209816. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209817. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209818. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209819. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209820. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209821. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209822. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209823. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209824. #define WGL_ACCELERATION_ARB 0x2003
  209825. #define WGL_SWAP_METHOD_ARB 0x2007
  209826. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209827. #define WGL_PIXEL_TYPE_ARB 0x2013
  209828. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209829. #define WGL_COLOR_BITS_ARB 0x2014
  209830. #define WGL_RED_BITS_ARB 0x2015
  209831. #define WGL_GREEN_BITS_ARB 0x2017
  209832. #define WGL_BLUE_BITS_ARB 0x2019
  209833. #define WGL_ALPHA_BITS_ARB 0x201B
  209834. #define WGL_DEPTH_BITS_ARB 0x2022
  209835. #define WGL_STENCIL_BITS_ARB 0x2023
  209836. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209837. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209838. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209839. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209840. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209841. #define WGL_STEREO_ARB 0x2012
  209842. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209843. #define WGL_SAMPLES_ARB 0x2042
  209844. #define WGL_TYPE_RGBA_ARB 0x202B
  209845. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209846. {
  209847. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209848. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209849. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209850. else
  209851. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209852. }
  209853. class WindowedGLContext : public OpenGLContext
  209854. {
  209855. public:
  209856. WindowedGLContext (Component* const component_,
  209857. HGLRC contextToShareWith,
  209858. const OpenGLPixelFormat& pixelFormat)
  209859. : renderContext (0),
  209860. dc (0),
  209861. component (component_)
  209862. {
  209863. jassert (component != 0);
  209864. createNativeWindow();
  209865. // Use a default pixel format that should be supported everywhere
  209866. PIXELFORMATDESCRIPTOR pfd;
  209867. zerostruct (pfd);
  209868. pfd.nSize = sizeof (pfd);
  209869. pfd.nVersion = 1;
  209870. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209871. pfd.iPixelType = PFD_TYPE_RGBA;
  209872. pfd.cColorBits = 24;
  209873. pfd.cDepthBits = 16;
  209874. const int format = ChoosePixelFormat (dc, &pfd);
  209875. if (format != 0)
  209876. SetPixelFormat (dc, format, &pfd);
  209877. renderContext = wglCreateContext (dc);
  209878. makeActive();
  209879. setPixelFormat (pixelFormat);
  209880. if (contextToShareWith != 0 && renderContext != 0)
  209881. wglShareLists (contextToShareWith, renderContext);
  209882. }
  209883. ~WindowedGLContext()
  209884. {
  209885. deleteContext();
  209886. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209887. nativeWindow = 0;
  209888. }
  209889. void deleteContext()
  209890. {
  209891. makeInactive();
  209892. if (renderContext != 0)
  209893. {
  209894. wglDeleteContext (renderContext);
  209895. renderContext = 0;
  209896. }
  209897. }
  209898. bool makeActive() const throw()
  209899. {
  209900. jassert (renderContext != 0);
  209901. return wglMakeCurrent (dc, renderContext) != 0;
  209902. }
  209903. bool makeInactive() const throw()
  209904. {
  209905. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209906. }
  209907. bool isActive() const throw()
  209908. {
  209909. return wglGetCurrentContext() == renderContext;
  209910. }
  209911. const OpenGLPixelFormat getPixelFormat() const
  209912. {
  209913. OpenGLPixelFormat pf;
  209914. makeActive();
  209915. StringArray availableExtensions;
  209916. getWglExtensions (dc, availableExtensions);
  209917. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209918. return pf;
  209919. }
  209920. void* getRawContext() const throw()
  209921. {
  209922. return renderContext;
  209923. }
  209924. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209925. {
  209926. makeActive();
  209927. PIXELFORMATDESCRIPTOR pfd;
  209928. zerostruct (pfd);
  209929. pfd.nSize = sizeof (pfd);
  209930. pfd.nVersion = 1;
  209931. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209932. pfd.iPixelType = PFD_TYPE_RGBA;
  209933. pfd.iLayerType = PFD_MAIN_PLANE;
  209934. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209935. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209936. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209937. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209938. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209939. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209940. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209941. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209942. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209943. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209944. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209945. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209946. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209947. int format = 0;
  209948. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209949. StringArray availableExtensions;
  209950. getWglExtensions (dc, availableExtensions);
  209951. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209952. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209953. {
  209954. int attributes[64];
  209955. int n = 0;
  209956. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209957. attributes[n++] = GL_TRUE;
  209958. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209959. attributes[n++] = GL_TRUE;
  209960. attributes[n++] = WGL_ACCELERATION_ARB;
  209961. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209962. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209963. attributes[n++] = GL_TRUE;
  209964. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209965. attributes[n++] = WGL_TYPE_RGBA_ARB;
  209966. attributes[n++] = WGL_COLOR_BITS_ARB;
  209967. attributes[n++] = pfd.cColorBits;
  209968. attributes[n++] = WGL_RED_BITS_ARB;
  209969. attributes[n++] = pixelFormat.redBits;
  209970. attributes[n++] = WGL_GREEN_BITS_ARB;
  209971. attributes[n++] = pixelFormat.greenBits;
  209972. attributes[n++] = WGL_BLUE_BITS_ARB;
  209973. attributes[n++] = pixelFormat.blueBits;
  209974. attributes[n++] = WGL_ALPHA_BITS_ARB;
  209975. attributes[n++] = pixelFormat.alphaBits;
  209976. attributes[n++] = WGL_DEPTH_BITS_ARB;
  209977. attributes[n++] = pixelFormat.depthBufferBits;
  209978. if (pixelFormat.stencilBufferBits > 0)
  209979. {
  209980. attributes[n++] = WGL_STENCIL_BITS_ARB;
  209981. attributes[n++] = pixelFormat.stencilBufferBits;
  209982. }
  209983. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  209984. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  209985. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  209986. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  209987. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  209988. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  209989. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209990. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  209991. if (availableExtensions.contains ("WGL_ARB_multisample")
  209992. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  209993. {
  209994. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  209995. attributes[n++] = 1;
  209996. attributes[n++] = WGL_SAMPLES_ARB;
  209997. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  209998. }
  209999. attributes[n++] = 0;
  210000. UINT formatsCount;
  210001. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210002. (void) ok;
  210003. jassert (ok);
  210004. }
  210005. else
  210006. {
  210007. format = ChoosePixelFormat (dc, &pfd);
  210008. }
  210009. if (format != 0)
  210010. {
  210011. makeInactive();
  210012. // win32 can't change the pixel format of a window, so need to delete the
  210013. // old one and create a new one..
  210014. jassert (nativeWindow != 0);
  210015. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210016. nativeWindow = 0;
  210017. createNativeWindow();
  210018. if (SetPixelFormat (dc, format, &pfd))
  210019. {
  210020. wglDeleteContext (renderContext);
  210021. renderContext = wglCreateContext (dc);
  210022. jassert (renderContext != 0);
  210023. return renderContext != 0;
  210024. }
  210025. }
  210026. return false;
  210027. }
  210028. void updateWindowPosition (int x, int y, int w, int h, int)
  210029. {
  210030. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210031. x, y, w, h,
  210032. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210033. }
  210034. void repaint()
  210035. {
  210036. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210037. }
  210038. void swapBuffers()
  210039. {
  210040. SwapBuffers (dc);
  210041. }
  210042. bool setSwapInterval (int numFramesPerSwap)
  210043. {
  210044. makeActive();
  210045. StringArray availableExtensions;
  210046. getWglExtensions (dc, availableExtensions);
  210047. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210048. return availableExtensions.contains ("WGL_EXT_swap_control")
  210049. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210050. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210051. }
  210052. int getSwapInterval() const
  210053. {
  210054. makeActive();
  210055. StringArray availableExtensions;
  210056. getWglExtensions (dc, availableExtensions);
  210057. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210058. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210059. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210060. return wglGetSwapIntervalEXT();
  210061. return 0;
  210062. }
  210063. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210064. {
  210065. jassert (isActive());
  210066. StringArray availableExtensions;
  210067. getWglExtensions (dc, availableExtensions);
  210068. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210069. int numTypes = 0;
  210070. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210071. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210072. {
  210073. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210074. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210075. jassertfalse;
  210076. }
  210077. else
  210078. {
  210079. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210080. }
  210081. OpenGLPixelFormat pf;
  210082. for (int i = 0; i < numTypes; ++i)
  210083. {
  210084. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210085. {
  210086. bool alreadyListed = false;
  210087. for (int j = results.size(); --j >= 0;)
  210088. if (pf == *results.getUnchecked(j))
  210089. alreadyListed = true;
  210090. if (! alreadyListed)
  210091. results.add (new OpenGLPixelFormat (pf));
  210092. }
  210093. }
  210094. }
  210095. void* getNativeWindowHandle() const
  210096. {
  210097. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210098. }
  210099. juce_UseDebuggingNewOperator
  210100. HGLRC renderContext;
  210101. private:
  210102. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210103. Component* const component;
  210104. HDC dc;
  210105. void createNativeWindow()
  210106. {
  210107. nativeWindow = new Win32ComponentPeer (component, 0);
  210108. nativeWindow->dontRepaint = true;
  210109. nativeWindow->setVisible (true);
  210110. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  210111. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210112. if (peer != 0)
  210113. {
  210114. SetParent (hwnd, (HWND) peer->getNativeHandle());
  210115. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  210116. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  210117. }
  210118. dc = GetDC (hwnd);
  210119. }
  210120. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210121. OpenGLPixelFormat& result,
  210122. const StringArray& availableExtensions) const throw()
  210123. {
  210124. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210125. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210126. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210127. {
  210128. int attributes[32];
  210129. int numAttributes = 0;
  210130. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210131. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210132. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210133. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210134. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210135. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210136. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210137. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210138. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210139. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210140. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210141. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210142. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210143. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210144. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210145. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210146. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210147. int values[32];
  210148. zeromem (values, sizeof (values));
  210149. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210150. {
  210151. int n = 0;
  210152. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210153. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210154. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210155. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210156. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210157. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210158. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210159. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210160. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210161. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210162. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210163. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210164. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210165. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210166. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210167. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210168. return isValidFormat;
  210169. }
  210170. else
  210171. {
  210172. jassertfalse;
  210173. }
  210174. }
  210175. else
  210176. {
  210177. PIXELFORMATDESCRIPTOR pfd;
  210178. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210179. {
  210180. result.redBits = pfd.cRedBits;
  210181. result.greenBits = pfd.cGreenBits;
  210182. result.blueBits = pfd.cBlueBits;
  210183. result.alphaBits = pfd.cAlphaBits;
  210184. result.depthBufferBits = pfd.cDepthBits;
  210185. result.stencilBufferBits = pfd.cStencilBits;
  210186. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210187. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210188. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210189. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210190. result.fullSceneAntiAliasingNumSamples = 0;
  210191. return true;
  210192. }
  210193. else
  210194. {
  210195. jassertfalse;
  210196. }
  210197. }
  210198. return false;
  210199. }
  210200. WindowedGLContext (const WindowedGLContext&);
  210201. WindowedGLContext& operator= (const WindowedGLContext&);
  210202. };
  210203. OpenGLContext* OpenGLComponent::createContext()
  210204. {
  210205. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210206. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210207. preferredPixelFormat));
  210208. return (c->renderContext != 0) ? c.release() : 0;
  210209. }
  210210. void* OpenGLComponent::getNativeWindowHandle() const
  210211. {
  210212. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210213. }
  210214. void juce_glViewport (const int w, const int h)
  210215. {
  210216. glViewport (0, 0, w, h);
  210217. }
  210218. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210219. OwnedArray <OpenGLPixelFormat>& results)
  210220. {
  210221. Component tempComp;
  210222. {
  210223. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210224. wc.makeActive();
  210225. wc.findAlternativeOpenGLPixelFormats (results);
  210226. }
  210227. }
  210228. #endif
  210229. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210230. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210231. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210232. // compiled on its own).
  210233. #if JUCE_INCLUDED_FILE
  210234. #if JUCE_USE_CDREADER
  210235. namespace CDReaderHelpers
  210236. {
  210237. //***************************************************************************
  210238. // %%% TARGET STATUS VALUES %%%
  210239. //***************************************************************************
  210240. #define STATUS_GOOD 0x00 // Status Good
  210241. #define STATUS_CHKCOND 0x02 // Check Condition
  210242. #define STATUS_CONDMET 0x04 // Condition Met
  210243. #define STATUS_BUSY 0x08 // Busy
  210244. #define STATUS_INTERM 0x10 // Intermediate
  210245. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210246. #define STATUS_RESCONF 0x18 // Reservation conflict
  210247. #define STATUS_COMTERM 0x22 // Command Terminated
  210248. #define STATUS_QFULL 0x28 // Queue full
  210249. //***************************************************************************
  210250. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210251. //***************************************************************************
  210252. #define MAXLUN 7 // Maximum Logical Unit Id
  210253. #define MAXTARG 7 // Maximum Target Id
  210254. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210255. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210256. //***************************************************************************
  210257. // %%% Commands for all Device Types %%%
  210258. //***************************************************************************
  210259. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210260. #define SCSI_COMPARE 0x39 // Compare (O)
  210261. #define SCSI_COPY 0x18 // Copy (O)
  210262. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210263. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210264. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210265. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210266. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210267. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210268. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210269. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210270. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210271. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210272. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210273. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210274. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210275. //***************************************************************************
  210276. // %%% Commands Unique to Direct Access Devices %%%
  210277. //***************************************************************************
  210278. #define SCSI_COMPARE 0x39 // Compare (O)
  210279. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210280. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210281. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210282. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210283. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210284. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210285. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210286. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210287. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210288. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210289. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210290. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210291. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210292. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210293. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210294. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210295. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210296. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210297. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210298. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210299. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210300. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210301. #define SCSI_VERIFY 0x2F // Verify (O)
  210302. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210303. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210304. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210305. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210306. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210307. //***************************************************************************
  210308. // %%% Commands Unique to Sequential Access Devices %%%
  210309. //***************************************************************************
  210310. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210311. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210312. #define SCSI_LOCATE 0x2B // Locate (O)
  210313. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210314. #define SCSI_READ_POS 0x34 // Read Position (O)
  210315. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210316. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210317. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210318. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210319. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210320. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210321. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210322. //***************************************************************************
  210323. // %%% Commands Unique to Printer Devices %%%
  210324. //***************************************************************************
  210325. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210326. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210327. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210328. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210329. //***************************************************************************
  210330. // %%% Commands Unique to Processor Devices %%%
  210331. //***************************************************************************
  210332. #define SCSI_RECEIVE 0x08 // Receive (O)
  210333. #define SCSI_SEND 0x0A // Send (O)
  210334. //***************************************************************************
  210335. // %%% Commands Unique to Write-Once Devices %%%
  210336. //***************************************************************************
  210337. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210338. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210339. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210340. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210341. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210342. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210343. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210344. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210345. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210346. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210347. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210348. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210349. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210350. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210351. //***************************************************************************
  210352. // %%% Commands Unique to CD-ROM Devices %%%
  210353. //***************************************************************************
  210354. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210355. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210356. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210357. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210358. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210359. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210360. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210361. #define SCSI_READHEADER 0x44 // Read Header (O)
  210362. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210363. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210364. //***************************************************************************
  210365. // %%% Commands Unique to Scanner Devices %%%
  210366. //***************************************************************************
  210367. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210368. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210369. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210370. #define SCSI_SCAN 0x1B // Scan (O)
  210371. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210372. //***************************************************************************
  210373. // %%% Commands Unique to Optical Memory Devices %%%
  210374. //***************************************************************************
  210375. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210376. //***************************************************************************
  210377. // %%% Commands Unique to Medium Changer Devices %%%
  210378. //***************************************************************************
  210379. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210380. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210381. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210382. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210383. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210384. //***************************************************************************
  210385. // %%% Commands Unique to Communication Devices %%%
  210386. //***************************************************************************
  210387. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210388. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210389. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210390. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210391. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210392. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210393. //***************************************************************************
  210394. // %%% Request Sense Data Format %%%
  210395. //***************************************************************************
  210396. typedef struct {
  210397. BYTE ErrorCode; // Error Code (70H or 71H)
  210398. BYTE SegmentNum; // Number of current segment descriptor
  210399. BYTE SenseKey; // Sense Key(See bit definitions too)
  210400. BYTE InfoByte0; // Information MSB
  210401. BYTE InfoByte1; // Information MID
  210402. BYTE InfoByte2; // Information MID
  210403. BYTE InfoByte3; // Information LSB
  210404. BYTE AddSenLen; // Additional Sense Length
  210405. BYTE ComSpecInf0; // Command Specific Information MSB
  210406. BYTE ComSpecInf1; // Command Specific Information MID
  210407. BYTE ComSpecInf2; // Command Specific Information MID
  210408. BYTE ComSpecInf3; // Command Specific Information LSB
  210409. BYTE AddSenseCode; // Additional Sense Code
  210410. BYTE AddSenQual; // Additional Sense Code Qualifier
  210411. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210412. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210413. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210414. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210415. BYTE AddSenseBytes; // Additional Sense Bytes
  210416. } SENSE_DATA_FMT;
  210417. //***************************************************************************
  210418. // %%% REQUEST SENSE ERROR CODE %%%
  210419. //***************************************************************************
  210420. #define SERROR_CURRENT 0x70 // Current Errors
  210421. #define SERROR_DEFERED 0x71 // Deferred Errors
  210422. //***************************************************************************
  210423. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210424. //***************************************************************************
  210425. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210426. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210427. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210428. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210429. //***************************************************************************
  210430. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210431. //***************************************************************************
  210432. #define KEY_NOSENSE 0x00 // No Sense
  210433. #define KEY_RECERROR 0x01 // Recovered Error
  210434. #define KEY_NOTREADY 0x02 // Not Ready
  210435. #define KEY_MEDIUMERR 0x03 // Medium Error
  210436. #define KEY_HARDERROR 0x04 // Hardware Error
  210437. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210438. #define KEY_UNITATT 0x06 // Unit Attention
  210439. #define KEY_DATAPROT 0x07 // Data Protect
  210440. #define KEY_BLANKCHK 0x08 // Blank Check
  210441. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210442. #define KEY_COPYABORT 0x0A // Copy Abort
  210443. #define KEY_EQUAL 0x0C // Equal (Search)
  210444. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210445. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210446. #define KEY_RESERVED 0x0F // Reserved
  210447. //***************************************************************************
  210448. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210449. //***************************************************************************
  210450. #define DTYPE_DASD 0x00 // Disk Device
  210451. #define DTYPE_SEQD 0x01 // Tape Device
  210452. #define DTYPE_PRNT 0x02 // Printer
  210453. #define DTYPE_PROC 0x03 // Processor
  210454. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210455. #define DTYPE_CROM 0x05 // CD-ROM device
  210456. #define DTYPE_SCAN 0x06 // Scanner device
  210457. #define DTYPE_OPTI 0x07 // Optical memory device
  210458. #define DTYPE_JUKE 0x08 // Medium Changer device
  210459. #define DTYPE_COMM 0x09 // Communications device
  210460. #define DTYPE_RESL 0x0A // Reserved (low)
  210461. #define DTYPE_RESH 0x1E // Reserved (high)
  210462. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210463. //***************************************************************************
  210464. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210465. //***************************************************************************
  210466. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210467. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210468. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210469. #define ANSI_RESLO 0x3 // Reserved (low)
  210470. #define ANSI_RESHI 0x7 // Reserved (high)
  210471. typedef struct
  210472. {
  210473. USHORT Length;
  210474. UCHAR ScsiStatus;
  210475. UCHAR PathId;
  210476. UCHAR TargetId;
  210477. UCHAR Lun;
  210478. UCHAR CdbLength;
  210479. UCHAR SenseInfoLength;
  210480. UCHAR DataIn;
  210481. ULONG DataTransferLength;
  210482. ULONG TimeOutValue;
  210483. ULONG DataBufferOffset;
  210484. ULONG SenseInfoOffset;
  210485. UCHAR Cdb[16];
  210486. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210487. typedef struct
  210488. {
  210489. USHORT Length;
  210490. UCHAR ScsiStatus;
  210491. UCHAR PathId;
  210492. UCHAR TargetId;
  210493. UCHAR Lun;
  210494. UCHAR CdbLength;
  210495. UCHAR SenseInfoLength;
  210496. UCHAR DataIn;
  210497. ULONG DataTransferLength;
  210498. ULONG TimeOutValue;
  210499. PVOID DataBuffer;
  210500. ULONG SenseInfoOffset;
  210501. UCHAR Cdb[16];
  210502. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210503. typedef struct
  210504. {
  210505. SCSI_PASS_THROUGH_DIRECT spt;
  210506. ULONG Filler;
  210507. UCHAR ucSenseBuf[32];
  210508. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210509. typedef struct
  210510. {
  210511. ULONG Length;
  210512. UCHAR PortNumber;
  210513. UCHAR PathId;
  210514. UCHAR TargetId;
  210515. UCHAR Lun;
  210516. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210517. #define METHOD_BUFFERED 0
  210518. #define METHOD_IN_DIRECT 1
  210519. #define METHOD_OUT_DIRECT 2
  210520. #define METHOD_NEITHER 3
  210521. #define FILE_ANY_ACCESS 0
  210522. #ifndef FILE_READ_ACCESS
  210523. #define FILE_READ_ACCESS (0x0001)
  210524. #endif
  210525. #ifndef FILE_WRITE_ACCESS
  210526. #define FILE_WRITE_ACCESS (0x0002)
  210527. #endif
  210528. #define IOCTL_SCSI_BASE 0x00000004
  210529. #define SCSI_IOCTL_DATA_OUT 0
  210530. #define SCSI_IOCTL_DATA_IN 1
  210531. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210532. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210533. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210534. )
  210535. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210536. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210537. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210538. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210539. #define SENSE_LEN 14
  210540. #define SRB_DIR_SCSI 0x00
  210541. #define SRB_POSTING 0x01
  210542. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210543. #define SRB_DIR_IN 0x08
  210544. #define SRB_DIR_OUT 0x10
  210545. #define SRB_EVENT_NOTIFY 0x40
  210546. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210547. #define MAX_SRB_TIMEOUT 1080001u
  210548. #define DEFAULT_SRB_TIMEOUT 1080001u
  210549. #define SC_HA_INQUIRY 0x00
  210550. #define SC_GET_DEV_TYPE 0x01
  210551. #define SC_EXEC_SCSI_CMD 0x02
  210552. #define SC_ABORT_SRB 0x03
  210553. #define SC_RESET_DEV 0x04
  210554. #define SC_SET_HA_PARMS 0x05
  210555. #define SC_GET_DISK_INFO 0x06
  210556. #define SC_RESCAN_SCSI_BUS 0x07
  210557. #define SC_GETSET_TIMEOUTS 0x08
  210558. #define SS_PENDING 0x00
  210559. #define SS_COMP 0x01
  210560. #define SS_ABORTED 0x02
  210561. #define SS_ABORT_FAIL 0x03
  210562. #define SS_ERR 0x04
  210563. #define SS_INVALID_CMD 0x80
  210564. #define SS_INVALID_HA 0x81
  210565. #define SS_NO_DEVICE 0x82
  210566. #define SS_INVALID_SRB 0xE0
  210567. #define SS_OLD_MANAGER 0xE1
  210568. #define SS_BUFFER_ALIGN 0xE1
  210569. #define SS_ILLEGAL_MODE 0xE2
  210570. #define SS_NO_ASPI 0xE3
  210571. #define SS_FAILED_INIT 0xE4
  210572. #define SS_ASPI_IS_BUSY 0xE5
  210573. #define SS_BUFFER_TO_BIG 0xE6
  210574. #define SS_BUFFER_TOO_BIG 0xE6
  210575. #define SS_MISMATCHED_COMPONENTS 0xE7
  210576. #define SS_NO_ADAPTERS 0xE8
  210577. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210578. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210579. #define SS_BAD_INSTALL 0xEB
  210580. #define HASTAT_OK 0x00
  210581. #define HASTAT_SEL_TO 0x11
  210582. #define HASTAT_DO_DU 0x12
  210583. #define HASTAT_BUS_FREE 0x13
  210584. #define HASTAT_PHASE_ERR 0x14
  210585. #define HASTAT_TIMEOUT 0x09
  210586. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210587. #define HASTAT_MESSAGE_REJECT 0x0D
  210588. #define HASTAT_BUS_RESET 0x0E
  210589. #define HASTAT_PARITY_ERROR 0x0F
  210590. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210591. #define PACKED
  210592. #pragma pack(1)
  210593. typedef struct
  210594. {
  210595. BYTE SRB_Cmd;
  210596. BYTE SRB_Status;
  210597. BYTE SRB_HaID;
  210598. BYTE SRB_Flags;
  210599. DWORD SRB_Hdr_Rsvd;
  210600. BYTE HA_Count;
  210601. BYTE HA_SCSI_ID;
  210602. BYTE HA_ManagerId[16];
  210603. BYTE HA_Identifier[16];
  210604. BYTE HA_Unique[16];
  210605. WORD HA_Rsvd1;
  210606. BYTE pad[20];
  210607. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210608. typedef struct
  210609. {
  210610. BYTE SRB_Cmd;
  210611. BYTE SRB_Status;
  210612. BYTE SRB_HaID;
  210613. BYTE SRB_Flags;
  210614. DWORD SRB_Hdr_Rsvd;
  210615. BYTE SRB_Target;
  210616. BYTE SRB_Lun;
  210617. BYTE SRB_DeviceType;
  210618. BYTE SRB_Rsvd1;
  210619. BYTE pad[68];
  210620. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210621. typedef struct
  210622. {
  210623. BYTE SRB_Cmd;
  210624. BYTE SRB_Status;
  210625. BYTE SRB_HaID;
  210626. BYTE SRB_Flags;
  210627. DWORD SRB_Hdr_Rsvd;
  210628. BYTE SRB_Target;
  210629. BYTE SRB_Lun;
  210630. WORD SRB_Rsvd1;
  210631. DWORD SRB_BufLen;
  210632. BYTE FAR *SRB_BufPointer;
  210633. BYTE SRB_SenseLen;
  210634. BYTE SRB_CDBLen;
  210635. BYTE SRB_HaStat;
  210636. BYTE SRB_TargStat;
  210637. VOID FAR *SRB_PostProc;
  210638. BYTE SRB_Rsvd2[20];
  210639. BYTE CDBByte[16];
  210640. BYTE SenseArea[SENSE_LEN+2];
  210641. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210642. typedef struct
  210643. {
  210644. BYTE SRB_Cmd;
  210645. BYTE SRB_Status;
  210646. BYTE SRB_HaId;
  210647. BYTE SRB_Flags;
  210648. DWORD SRB_Hdr_Rsvd;
  210649. } PACKED SRB, *PSRB, FAR *LPSRB;
  210650. #pragma pack()
  210651. struct CDDeviceInfo
  210652. {
  210653. char vendor[9];
  210654. char productId[17];
  210655. char rev[5];
  210656. char vendorSpec[21];
  210657. BYTE ha;
  210658. BYTE tgt;
  210659. BYTE lun;
  210660. char scsiDriveLetter; // will be 0 if not using scsi
  210661. };
  210662. class CDReadBuffer
  210663. {
  210664. public:
  210665. int startFrame;
  210666. int numFrames;
  210667. int dataStartOffset;
  210668. int dataLength;
  210669. int bufferSize;
  210670. HeapBlock<BYTE> buffer;
  210671. int index;
  210672. bool wantsIndex;
  210673. CDReadBuffer (const int numberOfFrames)
  210674. : startFrame (0),
  210675. numFrames (0),
  210676. dataStartOffset (0),
  210677. dataLength (0),
  210678. bufferSize (2352 * numberOfFrames),
  210679. buffer (bufferSize),
  210680. index (0),
  210681. wantsIndex (false)
  210682. {
  210683. }
  210684. bool isZero() const throw()
  210685. {
  210686. BYTE* p = buffer + dataStartOffset;
  210687. for (int i = dataLength; --i >= 0;)
  210688. if (*p++ != 0)
  210689. return false;
  210690. return true;
  210691. }
  210692. };
  210693. class CDDeviceHandle;
  210694. class CDController
  210695. {
  210696. public:
  210697. CDController();
  210698. virtual ~CDController();
  210699. virtual bool read (CDReadBuffer* t) = 0;
  210700. virtual void shutDown();
  210701. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210702. int getLastIndex();
  210703. public:
  210704. bool initialised;
  210705. CDDeviceHandle* deviceInfo;
  210706. int framesToCheck, framesOverlap;
  210707. void prepare (SRB_ExecSCSICmd& s);
  210708. void perform (SRB_ExecSCSICmd& s);
  210709. void setPaused (bool paused);
  210710. };
  210711. #pragma pack(1)
  210712. struct TOCTRACK
  210713. {
  210714. BYTE rsvd;
  210715. BYTE ADR;
  210716. BYTE trackNumber;
  210717. BYTE rsvd2;
  210718. BYTE addr[4];
  210719. };
  210720. struct TOC
  210721. {
  210722. WORD tocLen;
  210723. BYTE firstTrack;
  210724. BYTE lastTrack;
  210725. TOCTRACK tracks[100];
  210726. };
  210727. #pragma pack()
  210728. enum
  210729. {
  210730. READTYPE_ANY = 0,
  210731. READTYPE_ATAPI1 = 1,
  210732. READTYPE_ATAPI2 = 2,
  210733. READTYPE_READ6 = 3,
  210734. READTYPE_READ10 = 4,
  210735. READTYPE_READ_D8 = 5,
  210736. READTYPE_READ_D4 = 6,
  210737. READTYPE_READ_D4_1 = 7,
  210738. READTYPE_READ10_2 = 8
  210739. };
  210740. class CDDeviceHandle
  210741. {
  210742. public:
  210743. CDDeviceHandle (const CDDeviceInfo* const device)
  210744. : scsiHandle (0),
  210745. readType (READTYPE_ANY),
  210746. controller (0)
  210747. {
  210748. memcpy (&info, device, sizeof (info));
  210749. }
  210750. ~CDDeviceHandle()
  210751. {
  210752. if (controller != 0)
  210753. {
  210754. controller->shutDown();
  210755. controller = 0;
  210756. }
  210757. if (scsiHandle != 0)
  210758. CloseHandle (scsiHandle);
  210759. }
  210760. bool readTOC (TOC* lpToc);
  210761. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210762. void openDrawer (bool shouldBeOpen);
  210763. CDDeviceInfo info;
  210764. HANDLE scsiHandle;
  210765. BYTE readType;
  210766. private:
  210767. ScopedPointer<CDController> controller;
  210768. bool testController (const int readType,
  210769. CDController* const newController,
  210770. CDReadBuffer* const bufferToUse);
  210771. };
  210772. DWORD (*fGetASPI32SupportInfo)(void);
  210773. DWORD (*fSendASPI32Command)(LPSRB);
  210774. static HINSTANCE winAspiLib = 0;
  210775. static bool usingScsi = false;
  210776. static bool initialised = false;
  210777. static bool InitialiseCDRipper()
  210778. {
  210779. if (! initialised)
  210780. {
  210781. initialised = true;
  210782. OSVERSIONINFO info;
  210783. info.dwOSVersionInfoSize = sizeof (info);
  210784. GetVersionEx (&info);
  210785. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210786. if (! usingScsi)
  210787. {
  210788. fGetASPI32SupportInfo = 0;
  210789. fSendASPI32Command = 0;
  210790. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210791. if (winAspiLib != 0)
  210792. {
  210793. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210794. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210795. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210796. return false;
  210797. }
  210798. else
  210799. {
  210800. usingScsi = true;
  210801. }
  210802. }
  210803. }
  210804. return true;
  210805. }
  210806. static void DeinitialiseCDRipper()
  210807. {
  210808. if (winAspiLib != 0)
  210809. {
  210810. fGetASPI32SupportInfo = 0;
  210811. fSendASPI32Command = 0;
  210812. FreeLibrary (winAspiLib);
  210813. winAspiLib = 0;
  210814. }
  210815. initialised = false;
  210816. }
  210817. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  210818. {
  210819. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210820. OSVERSIONINFO info;
  210821. info.dwOSVersionInfoSize = sizeof (info);
  210822. GetVersionEx (&info);
  210823. DWORD flags = GENERIC_READ;
  210824. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  210825. flags = GENERIC_READ | GENERIC_WRITE;
  210826. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210827. if (h == INVALID_HANDLE_VALUE)
  210828. {
  210829. flags ^= GENERIC_WRITE;
  210830. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210831. }
  210832. return h;
  210833. }
  210834. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  210835. const char driveLetter,
  210836. HANDLE& deviceHandle,
  210837. const bool retryOnFailure = true)
  210838. {
  210839. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210840. zerostruct (s);
  210841. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210842. s.spt.CdbLength = srb->SRB_CDBLen;
  210843. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210844. ? SCSI_IOCTL_DATA_IN
  210845. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210846. ? SCSI_IOCTL_DATA_OUT
  210847. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210848. s.spt.DataTransferLength = srb->SRB_BufLen;
  210849. s.spt.TimeOutValue = 5;
  210850. s.spt.DataBuffer = srb->SRB_BufPointer;
  210851. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210852. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210853. srb->SRB_Status = SS_ERR;
  210854. srb->SRB_TargStat = 0x0004;
  210855. DWORD bytesReturned = 0;
  210856. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210857. &s, sizeof (s),
  210858. &s, sizeof (s),
  210859. &bytesReturned, 0) != 0)
  210860. {
  210861. srb->SRB_Status = SS_COMP;
  210862. }
  210863. else if (retryOnFailure)
  210864. {
  210865. const DWORD error = GetLastError();
  210866. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210867. {
  210868. if (error != ERROR_INVALID_HANDLE)
  210869. CloseHandle (deviceHandle);
  210870. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  210871. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210872. }
  210873. }
  210874. return srb->SRB_Status;
  210875. }
  210876. // Controller types..
  210877. class ControllerType1 : public CDController
  210878. {
  210879. public:
  210880. ControllerType1() {}
  210881. ~ControllerType1() {}
  210882. bool read (CDReadBuffer* rb)
  210883. {
  210884. if (rb->numFrames * 2352 > rb->bufferSize)
  210885. return false;
  210886. SRB_ExecSCSICmd s;
  210887. prepare (s);
  210888. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210889. s.SRB_BufLen = rb->bufferSize;
  210890. s.SRB_BufPointer = rb->buffer;
  210891. s.SRB_CDBLen = 12;
  210892. s.CDBByte[0] = 0xBE;
  210893. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  210894. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  210895. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  210896. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  210897. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  210898. perform (s);
  210899. if (s.SRB_Status != SS_COMP)
  210900. return false;
  210901. rb->dataLength = rb->numFrames * 2352;
  210902. rb->dataStartOffset = 0;
  210903. return true;
  210904. }
  210905. };
  210906. class ControllerType2 : public CDController
  210907. {
  210908. public:
  210909. ControllerType2() {}
  210910. ~ControllerType2() {}
  210911. void shutDown()
  210912. {
  210913. if (initialised)
  210914. {
  210915. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210916. SRB_ExecSCSICmd s;
  210917. prepare (s);
  210918. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210919. s.SRB_BufLen = 0x0C;
  210920. s.SRB_BufPointer = bufPointer;
  210921. s.SRB_CDBLen = 6;
  210922. s.CDBByte[0] = 0x15;
  210923. s.CDBByte[4] = 0x0C;
  210924. perform (s);
  210925. }
  210926. }
  210927. bool init()
  210928. {
  210929. SRB_ExecSCSICmd s;
  210930. s.SRB_Status = SS_ERR;
  210931. if (deviceInfo->readType == READTYPE_READ10_2)
  210932. {
  210933. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210934. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210935. for (int i = 0; i < 2; ++i)
  210936. {
  210937. prepare (s);
  210938. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210939. s.SRB_BufLen = 0x14;
  210940. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210941. s.SRB_CDBLen = 6;
  210942. s.CDBByte[0] = 0x15;
  210943. s.CDBByte[1] = 0x10;
  210944. s.CDBByte[4] = 0x14;
  210945. perform (s);
  210946. if (s.SRB_Status != SS_COMP)
  210947. return false;
  210948. }
  210949. }
  210950. else
  210951. {
  210952. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210953. prepare (s);
  210954. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210955. s.SRB_BufLen = 0x0C;
  210956. s.SRB_BufPointer = bufPointer;
  210957. s.SRB_CDBLen = 6;
  210958. s.CDBByte[0] = 0x15;
  210959. s.CDBByte[4] = 0x0C;
  210960. perform (s);
  210961. }
  210962. return s.SRB_Status == SS_COMP;
  210963. }
  210964. bool read (CDReadBuffer* rb)
  210965. {
  210966. if (rb->numFrames * 2352 > rb->bufferSize)
  210967. return false;
  210968. if (!initialised)
  210969. {
  210970. initialised = init();
  210971. if (!initialised)
  210972. return false;
  210973. }
  210974. SRB_ExecSCSICmd s;
  210975. prepare (s);
  210976. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210977. s.SRB_BufLen = rb->bufferSize;
  210978. s.SRB_BufPointer = rb->buffer;
  210979. s.SRB_CDBLen = 10;
  210980. s.CDBByte[0] = 0x28;
  210981. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  210982. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  210983. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  210984. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  210985. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  210986. perform (s);
  210987. if (s.SRB_Status != SS_COMP)
  210988. return false;
  210989. rb->dataLength = rb->numFrames * 2352;
  210990. rb->dataStartOffset = 0;
  210991. return true;
  210992. }
  210993. };
  210994. class ControllerType3 : public CDController
  210995. {
  210996. public:
  210997. ControllerType3() {}
  210998. ~ControllerType3() {}
  210999. bool read (CDReadBuffer* rb)
  211000. {
  211001. if (rb->numFrames * 2352 > rb->bufferSize)
  211002. return false;
  211003. if (!initialised)
  211004. {
  211005. setPaused (false);
  211006. initialised = true;
  211007. }
  211008. SRB_ExecSCSICmd s;
  211009. prepare (s);
  211010. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211011. s.SRB_BufLen = rb->numFrames * 2352;
  211012. s.SRB_BufPointer = rb->buffer;
  211013. s.SRB_CDBLen = 12;
  211014. s.CDBByte[0] = 0xD8;
  211015. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211016. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211017. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211018. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211019. perform (s);
  211020. if (s.SRB_Status != SS_COMP)
  211021. return false;
  211022. rb->dataLength = rb->numFrames * 2352;
  211023. rb->dataStartOffset = 0;
  211024. return true;
  211025. }
  211026. };
  211027. class ControllerType4 : public CDController
  211028. {
  211029. public:
  211030. ControllerType4() {}
  211031. ~ControllerType4() {}
  211032. bool selectD4Mode()
  211033. {
  211034. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211035. SRB_ExecSCSICmd s;
  211036. prepare (s);
  211037. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211038. s.SRB_CDBLen = 6;
  211039. s.SRB_BufLen = 12;
  211040. s.SRB_BufPointer = bufPointer;
  211041. s.CDBByte[0] = 0x15;
  211042. s.CDBByte[1] = 0x10;
  211043. s.CDBByte[4] = 0x08;
  211044. perform (s);
  211045. return s.SRB_Status == SS_COMP;
  211046. }
  211047. bool read (CDReadBuffer* rb)
  211048. {
  211049. if (rb->numFrames * 2352 > rb->bufferSize)
  211050. return false;
  211051. if (!initialised)
  211052. {
  211053. setPaused (true);
  211054. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211055. selectD4Mode();
  211056. initialised = true;
  211057. }
  211058. SRB_ExecSCSICmd s;
  211059. prepare (s);
  211060. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211061. s.SRB_BufLen = rb->bufferSize;
  211062. s.SRB_BufPointer = rb->buffer;
  211063. s.SRB_CDBLen = 10;
  211064. s.CDBByte[0] = 0xD4;
  211065. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211066. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211067. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211068. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211069. perform (s);
  211070. if (s.SRB_Status != SS_COMP)
  211071. return false;
  211072. rb->dataLength = rb->numFrames * 2352;
  211073. rb->dataStartOffset = 0;
  211074. return true;
  211075. }
  211076. };
  211077. CDController::CDController() : initialised (false)
  211078. {
  211079. }
  211080. CDController::~CDController()
  211081. {
  211082. }
  211083. void CDController::prepare (SRB_ExecSCSICmd& s)
  211084. {
  211085. zerostruct (s);
  211086. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211087. s.SRB_HaID = deviceInfo->info.ha;
  211088. s.SRB_Target = deviceInfo->info.tgt;
  211089. s.SRB_Lun = deviceInfo->info.lun;
  211090. s.SRB_SenseLen = SENSE_LEN;
  211091. }
  211092. void CDController::perform (SRB_ExecSCSICmd& s)
  211093. {
  211094. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211095. s.SRB_PostProc = event;
  211096. ResetEvent (event);
  211097. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211098. deviceInfo->info.scsiDriveLetter,
  211099. deviceInfo->scsiHandle)
  211100. : fSendASPI32Command ((LPSRB)&s);
  211101. if (status == SS_PENDING)
  211102. WaitForSingleObject (event, 4000);
  211103. CloseHandle (event);
  211104. }
  211105. void CDController::setPaused (bool paused)
  211106. {
  211107. SRB_ExecSCSICmd s;
  211108. prepare (s);
  211109. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211110. s.SRB_CDBLen = 10;
  211111. s.CDBByte[0] = 0x4B;
  211112. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211113. perform (s);
  211114. }
  211115. void CDController::shutDown()
  211116. {
  211117. }
  211118. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211119. {
  211120. if (overlapBuffer != 0)
  211121. {
  211122. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211123. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211124. if (doJitter
  211125. && overlapBuffer->startFrame > 0
  211126. && overlapBuffer->numFrames > 0
  211127. && overlapBuffer->dataLength > 0)
  211128. {
  211129. const int numFrames = rb->numFrames;
  211130. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211131. {
  211132. rb->startFrame -= framesOverlap;
  211133. if (framesToCheck < framesOverlap
  211134. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211135. rb->numFrames += framesOverlap;
  211136. }
  211137. else
  211138. {
  211139. overlapBuffer->dataLength = 0;
  211140. overlapBuffer->startFrame = 0;
  211141. overlapBuffer->numFrames = 0;
  211142. }
  211143. }
  211144. if (! read (rb))
  211145. return false;
  211146. if (doJitter)
  211147. {
  211148. const int checkLen = framesToCheck * 2352;
  211149. const int maxToCheck = rb->dataLength - checkLen;
  211150. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211151. return true;
  211152. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211153. bool found = false;
  211154. for (int i = 0; i < maxToCheck; ++i)
  211155. {
  211156. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211157. {
  211158. i += checkLen;
  211159. rb->dataStartOffset = i;
  211160. rb->dataLength -= i;
  211161. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211162. found = true;
  211163. break;
  211164. }
  211165. }
  211166. rb->numFrames = rb->dataLength / 2352;
  211167. rb->dataLength = 2352 * rb->numFrames;
  211168. if (!found)
  211169. return false;
  211170. }
  211171. if (canDoJitter)
  211172. {
  211173. memcpy (overlapBuffer->buffer,
  211174. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211175. 2352 * framesToCheck);
  211176. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211177. overlapBuffer->numFrames = framesToCheck;
  211178. overlapBuffer->dataLength = 2352 * framesToCheck;
  211179. overlapBuffer->dataStartOffset = 0;
  211180. }
  211181. else
  211182. {
  211183. overlapBuffer->startFrame = 0;
  211184. overlapBuffer->numFrames = 0;
  211185. overlapBuffer->dataLength = 0;
  211186. }
  211187. return true;
  211188. }
  211189. else
  211190. {
  211191. return read (rb);
  211192. }
  211193. }
  211194. int CDController::getLastIndex()
  211195. {
  211196. char qdata[100];
  211197. SRB_ExecSCSICmd s;
  211198. prepare (s);
  211199. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211200. s.SRB_BufLen = sizeof (qdata);
  211201. s.SRB_BufPointer = (BYTE*)qdata;
  211202. s.SRB_CDBLen = 12;
  211203. s.CDBByte[0] = 0x42;
  211204. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211205. s.CDBByte[2] = 64;
  211206. s.CDBByte[3] = 1; // get current position
  211207. s.CDBByte[7] = 0;
  211208. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211209. perform (s);
  211210. if (s.SRB_Status == SS_COMP)
  211211. return qdata[7];
  211212. return 0;
  211213. }
  211214. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211215. {
  211216. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211217. SRB_ExecSCSICmd s;
  211218. zerostruct (s);
  211219. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211220. s.SRB_HaID = info.ha;
  211221. s.SRB_Target = info.tgt;
  211222. s.SRB_Lun = info.lun;
  211223. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211224. s.SRB_BufLen = 0x324;
  211225. s.SRB_BufPointer = (BYTE*)lpToc;
  211226. s.SRB_SenseLen = 0x0E;
  211227. s.SRB_CDBLen = 0x0A;
  211228. s.SRB_PostProc = event;
  211229. s.CDBByte[0] = 0x43;
  211230. s.CDBByte[1] = 0x00;
  211231. s.CDBByte[7] = 0x03;
  211232. s.CDBByte[8] = 0x24;
  211233. ResetEvent (event);
  211234. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211235. : fSendASPI32Command ((LPSRB)&s);
  211236. if (status == SS_PENDING)
  211237. WaitForSingleObject (event, 4000);
  211238. CloseHandle (event);
  211239. return (s.SRB_Status == SS_COMP);
  211240. }
  211241. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211242. CDReadBuffer* const overlapBuffer)
  211243. {
  211244. if (controller == 0)
  211245. {
  211246. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211247. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211248. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211249. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211250. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211251. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211252. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211253. }
  211254. buffer->index = 0;
  211255. if ((controller != 0)
  211256. && controller->readAudio (buffer, overlapBuffer))
  211257. {
  211258. if (buffer->wantsIndex)
  211259. buffer->index = controller->getLastIndex();
  211260. return true;
  211261. }
  211262. return false;
  211263. }
  211264. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211265. {
  211266. if (shouldBeOpen)
  211267. {
  211268. if (controller != 0)
  211269. {
  211270. controller->shutDown();
  211271. controller = 0;
  211272. }
  211273. if (scsiHandle != 0)
  211274. {
  211275. CloseHandle (scsiHandle);
  211276. scsiHandle = 0;
  211277. }
  211278. }
  211279. SRB_ExecSCSICmd s;
  211280. zerostruct (s);
  211281. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211282. s.SRB_HaID = info.ha;
  211283. s.SRB_Target = info.tgt;
  211284. s.SRB_Lun = info.lun;
  211285. s.SRB_SenseLen = SENSE_LEN;
  211286. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211287. s.SRB_BufLen = 0;
  211288. s.SRB_BufPointer = 0;
  211289. s.SRB_CDBLen = 12;
  211290. s.CDBByte[0] = 0x1b;
  211291. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211292. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211293. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211294. s.SRB_PostProc = event;
  211295. ResetEvent (event);
  211296. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211297. : fSendASPI32Command ((LPSRB)&s);
  211298. if (status == SS_PENDING)
  211299. WaitForSingleObject (event, 4000);
  211300. CloseHandle (event);
  211301. }
  211302. bool CDDeviceHandle::testController (const int type,
  211303. CDController* const newController,
  211304. CDReadBuffer* const rb)
  211305. {
  211306. controller = newController;
  211307. readType = (BYTE)type;
  211308. controller->deviceInfo = this;
  211309. controller->framesToCheck = 1;
  211310. controller->framesOverlap = 3;
  211311. bool passed = false;
  211312. memset (rb->buffer, 0xcd, rb->bufferSize);
  211313. if (controller->read (rb))
  211314. {
  211315. passed = true;
  211316. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211317. int wrong = 0;
  211318. for (int i = rb->dataLength / 4; --i >= 0;)
  211319. {
  211320. if (*p++ == (int) 0xcdcdcdcd)
  211321. {
  211322. if (++wrong == 4)
  211323. {
  211324. passed = false;
  211325. break;
  211326. }
  211327. }
  211328. else
  211329. {
  211330. wrong = 0;
  211331. }
  211332. }
  211333. }
  211334. if (! passed)
  211335. {
  211336. controller->shutDown();
  211337. controller = 0;
  211338. }
  211339. return passed;
  211340. }
  211341. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211342. {
  211343. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211344. const int bufSize = 128;
  211345. BYTE buffer[bufSize];
  211346. zeromem (buffer, bufSize);
  211347. SRB_ExecSCSICmd s;
  211348. zerostruct (s);
  211349. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211350. s.SRB_HaID = ha;
  211351. s.SRB_Target = tgt;
  211352. s.SRB_Lun = lun;
  211353. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211354. s.SRB_BufLen = bufSize;
  211355. s.SRB_BufPointer = buffer;
  211356. s.SRB_SenseLen = SENSE_LEN;
  211357. s.SRB_CDBLen = 6;
  211358. s.SRB_PostProc = event;
  211359. s.CDBByte[0] = SCSI_INQUIRY;
  211360. s.CDBByte[4] = 100;
  211361. ResetEvent (event);
  211362. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211363. WaitForSingleObject (event, 4000);
  211364. CloseHandle (event);
  211365. if (s.SRB_Status == SS_COMP)
  211366. {
  211367. memcpy (dev->vendor, &buffer[8], 8);
  211368. memcpy (dev->productId, &buffer[16], 16);
  211369. memcpy (dev->rev, &buffer[32], 4);
  211370. memcpy (dev->vendorSpec, &buffer[36], 20);
  211371. }
  211372. }
  211373. static int FindCDDevices (CDDeviceInfo* const list,
  211374. int maxItems)
  211375. {
  211376. int count = 0;
  211377. if (usingScsi)
  211378. {
  211379. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211380. {
  211381. TCHAR drivePath[8];
  211382. drivePath[0] = driveLetter;
  211383. drivePath[1] = ':';
  211384. drivePath[2] = '\\';
  211385. drivePath[3] = 0;
  211386. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211387. {
  211388. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211389. if (h != INVALID_HANDLE_VALUE)
  211390. {
  211391. BYTE buffer[100], passThroughStruct[1024];
  211392. zeromem (buffer, sizeof (buffer));
  211393. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211394. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211395. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211396. p->spt.CdbLength = 6;
  211397. p->spt.SenseInfoLength = 24;
  211398. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211399. p->spt.DataTransferLength = 100;
  211400. p->spt.TimeOutValue = 2;
  211401. p->spt.DataBuffer = buffer;
  211402. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211403. p->spt.Cdb[0] = 0x12;
  211404. p->spt.Cdb[4] = 100;
  211405. DWORD bytesReturned = 0;
  211406. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211407. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211408. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211409. &bytesReturned, 0) != 0)
  211410. {
  211411. zeromem (&list[count], sizeof (CDDeviceInfo));
  211412. list[count].scsiDriveLetter = driveLetter;
  211413. memcpy (list[count].vendor, &buffer[8], 8);
  211414. memcpy (list[count].productId, &buffer[16], 16);
  211415. memcpy (list[count].rev, &buffer[32], 4);
  211416. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211417. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211418. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211419. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211420. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211421. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211422. &bytesReturned, 0) != 0)
  211423. {
  211424. list[count].ha = scsiAddr->PortNumber;
  211425. list[count].tgt = scsiAddr->TargetId;
  211426. list[count].lun = scsiAddr->Lun;
  211427. ++count;
  211428. }
  211429. }
  211430. CloseHandle (h);
  211431. }
  211432. }
  211433. }
  211434. }
  211435. else
  211436. {
  211437. const DWORD d = fGetASPI32SupportInfo();
  211438. BYTE status = HIBYTE (LOWORD (d));
  211439. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211440. return 0;
  211441. const int numAdapters = LOBYTE (LOWORD (d));
  211442. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211443. {
  211444. SRB_HAInquiry s;
  211445. zerostruct (s);
  211446. s.SRB_Cmd = SC_HA_INQUIRY;
  211447. s.SRB_HaID = ha;
  211448. fSendASPI32Command ((LPSRB)&s);
  211449. if (s.SRB_Status == SS_COMP)
  211450. {
  211451. maxItems = (int)s.HA_Unique[3];
  211452. if (maxItems == 0)
  211453. maxItems = 8;
  211454. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211455. {
  211456. for (BYTE lun = 0; lun < 8; ++lun)
  211457. {
  211458. SRB_GDEVBlock sb;
  211459. zerostruct (sb);
  211460. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211461. sb.SRB_HaID = ha;
  211462. sb.SRB_Target = tgt;
  211463. sb.SRB_Lun = lun;
  211464. fSendASPI32Command ((LPSRB) &sb);
  211465. if (sb.SRB_Status == SS_COMP
  211466. && sb.SRB_DeviceType == DTYPE_CROM)
  211467. {
  211468. zeromem (&list[count], sizeof (CDDeviceInfo));
  211469. list[count].ha = ha;
  211470. list[count].tgt = tgt;
  211471. list[count].lun = lun;
  211472. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211473. ++count;
  211474. }
  211475. }
  211476. }
  211477. }
  211478. }
  211479. }
  211480. return count;
  211481. }
  211482. static int ripperUsers = 0;
  211483. static bool initialisedOk = false;
  211484. class DeinitialiseTimer : private Timer,
  211485. private DeletedAtShutdown
  211486. {
  211487. DeinitialiseTimer (const DeinitialiseTimer&);
  211488. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211489. public:
  211490. DeinitialiseTimer()
  211491. {
  211492. startTimer (4000);
  211493. }
  211494. ~DeinitialiseTimer()
  211495. {
  211496. if (--ripperUsers == 0)
  211497. DeinitialiseCDRipper();
  211498. }
  211499. void timerCallback()
  211500. {
  211501. delete this;
  211502. }
  211503. juce_UseDebuggingNewOperator
  211504. };
  211505. static void incUserCount()
  211506. {
  211507. if (ripperUsers++ == 0)
  211508. initialisedOk = InitialiseCDRipper();
  211509. }
  211510. static void decUserCount()
  211511. {
  211512. new DeinitialiseTimer();
  211513. }
  211514. struct CDDeviceWrapper
  211515. {
  211516. ScopedPointer<CDDeviceHandle> cdH;
  211517. ScopedPointer<CDReadBuffer> overlapBuffer;
  211518. bool jitter;
  211519. };
  211520. static int getAddressOf (const TOCTRACK* const t)
  211521. {
  211522. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211523. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211524. }
  211525. static const int samplesPerFrame = 44100 / 75;
  211526. static const int bytesPerFrame = samplesPerFrame * 4;
  211527. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211528. {
  211529. SRB_GDEVBlock s;
  211530. zerostruct (s);
  211531. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211532. s.SRB_HaID = device->ha;
  211533. s.SRB_Target = device->tgt;
  211534. s.SRB_Lun = device->lun;
  211535. if (usingScsi)
  211536. {
  211537. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211538. if (h != INVALID_HANDLE_VALUE)
  211539. {
  211540. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211541. cdh->scsiHandle = h;
  211542. return cdh;
  211543. }
  211544. }
  211545. else
  211546. {
  211547. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211548. && s.SRB_DeviceType == DTYPE_CROM)
  211549. {
  211550. return new CDDeviceHandle (device);
  211551. }
  211552. }
  211553. return 0;
  211554. }
  211555. }
  211556. const StringArray AudioCDReader::getAvailableCDNames()
  211557. {
  211558. using namespace CDReaderHelpers;
  211559. StringArray results;
  211560. incUserCount();
  211561. if (initialisedOk)
  211562. {
  211563. CDDeviceInfo list[8];
  211564. const int num = FindCDDevices (list, 8);
  211565. decUserCount();
  211566. for (int i = 0; i < num; ++i)
  211567. {
  211568. String s;
  211569. if (list[i].scsiDriveLetter > 0)
  211570. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211571. s << String (list[i].vendor).trim()
  211572. << ' ' << String (list[i].productId).trim()
  211573. << ' ' << String (list[i].rev).trim();
  211574. results.add (s);
  211575. }
  211576. }
  211577. return results;
  211578. }
  211579. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211580. {
  211581. using namespace CDReaderHelpers;
  211582. incUserCount();
  211583. if (initialisedOk)
  211584. {
  211585. CDDeviceInfo list[8];
  211586. const int num = FindCDDevices (list, 8);
  211587. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211588. {
  211589. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211590. if (handle != 0)
  211591. {
  211592. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211593. d->cdH = handle;
  211594. d->overlapBuffer = new CDReadBuffer(3);
  211595. return new AudioCDReader (d);
  211596. }
  211597. }
  211598. }
  211599. decUserCount();
  211600. return 0;
  211601. }
  211602. AudioCDReader::AudioCDReader (void* handle_)
  211603. : AudioFormatReader (0, "CD Audio"),
  211604. handle (handle_),
  211605. indexingEnabled (false),
  211606. lastIndex (0),
  211607. firstFrameInBuffer (0),
  211608. samplesInBuffer (0)
  211609. {
  211610. using namespace CDReaderHelpers;
  211611. jassert (handle_ != 0);
  211612. refreshTrackLengths();
  211613. sampleRate = 44100.0;
  211614. bitsPerSample = 16;
  211615. numChannels = 2;
  211616. usesFloatingPointData = false;
  211617. buffer.setSize (4 * bytesPerFrame, true);
  211618. }
  211619. AudioCDReader::~AudioCDReader()
  211620. {
  211621. using namespace CDReaderHelpers;
  211622. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211623. delete device;
  211624. decUserCount();
  211625. }
  211626. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211627. int64 startSampleInFile, int numSamples)
  211628. {
  211629. using namespace CDReaderHelpers;
  211630. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211631. bool ok = true;
  211632. while (numSamples > 0)
  211633. {
  211634. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211635. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211636. if (startSampleInFile >= bufferStartSample
  211637. && startSampleInFile < bufferEndSample)
  211638. {
  211639. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211640. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211641. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211642. const short* src = (const short*) buffer.getData();
  211643. src += 2 * (startSampleInFile - bufferStartSample);
  211644. for (int i = 0; i < toDo; ++i)
  211645. {
  211646. l[i] = src [i << 1] << 16;
  211647. if (r != 0)
  211648. r[i] = src [(i << 1) + 1] << 16;
  211649. }
  211650. startOffsetInDestBuffer += toDo;
  211651. startSampleInFile += toDo;
  211652. numSamples -= toDo;
  211653. }
  211654. else
  211655. {
  211656. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211657. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211658. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211659. {
  211660. device->overlapBuffer->dataLength = 0;
  211661. device->overlapBuffer->startFrame = 0;
  211662. device->overlapBuffer->numFrames = 0;
  211663. device->jitter = false;
  211664. }
  211665. firstFrameInBuffer = frameNeeded;
  211666. lastIndex = 0;
  211667. CDReadBuffer readBuffer (framesInBuffer + 4);
  211668. readBuffer.wantsIndex = indexingEnabled;
  211669. int i;
  211670. for (i = 5; --i >= 0;)
  211671. {
  211672. readBuffer.startFrame = frameNeeded;
  211673. readBuffer.numFrames = framesInBuffer;
  211674. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211675. break;
  211676. else
  211677. device->overlapBuffer->dataLength = 0;
  211678. }
  211679. if (i >= 0)
  211680. {
  211681. memcpy ((char*) buffer.getData(),
  211682. readBuffer.buffer + readBuffer.dataStartOffset,
  211683. readBuffer.dataLength);
  211684. samplesInBuffer = readBuffer.dataLength >> 2;
  211685. lastIndex = readBuffer.index;
  211686. }
  211687. else
  211688. {
  211689. int* l = destSamples[0] + startOffsetInDestBuffer;
  211690. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211691. while (--numSamples >= 0)
  211692. {
  211693. *l++ = 0;
  211694. if (r != 0)
  211695. *r++ = 0;
  211696. }
  211697. // sometimes the read fails for just the very last couple of blocks, so
  211698. // we'll ignore and errors in the last half-second of the disk..
  211699. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211700. break;
  211701. }
  211702. }
  211703. }
  211704. return ok;
  211705. }
  211706. bool AudioCDReader::isCDStillPresent() const
  211707. {
  211708. using namespace CDReaderHelpers;
  211709. TOC toc;
  211710. zerostruct (toc);
  211711. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211712. }
  211713. void AudioCDReader::refreshTrackLengths()
  211714. {
  211715. using namespace CDReaderHelpers;
  211716. trackStartSamples.clear();
  211717. zeromem (audioTracks, sizeof (audioTracks));
  211718. TOC toc;
  211719. zerostruct (toc);
  211720. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211721. {
  211722. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211723. for (int i = 0; i <= numTracks; ++i)
  211724. {
  211725. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211726. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211727. }
  211728. }
  211729. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211730. }
  211731. bool AudioCDReader::isTrackAudio (int trackNum) const
  211732. {
  211733. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211734. }
  211735. void AudioCDReader::enableIndexScanning (bool b)
  211736. {
  211737. indexingEnabled = b;
  211738. }
  211739. int AudioCDReader::getLastIndex() const
  211740. {
  211741. return lastIndex;
  211742. }
  211743. const int framesPerIndexRead = 4;
  211744. int AudioCDReader::getIndexAt (int samplePos)
  211745. {
  211746. using namespace CDReaderHelpers;
  211747. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211748. const int frameNeeded = samplePos / samplesPerFrame;
  211749. device->overlapBuffer->dataLength = 0;
  211750. device->overlapBuffer->startFrame = 0;
  211751. device->overlapBuffer->numFrames = 0;
  211752. device->jitter = false;
  211753. firstFrameInBuffer = 0;
  211754. lastIndex = 0;
  211755. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211756. readBuffer.wantsIndex = true;
  211757. int i;
  211758. for (i = 5; --i >= 0;)
  211759. {
  211760. readBuffer.startFrame = frameNeeded;
  211761. readBuffer.numFrames = framesPerIndexRead;
  211762. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211763. break;
  211764. }
  211765. if (i >= 0)
  211766. return readBuffer.index;
  211767. return -1;
  211768. }
  211769. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211770. {
  211771. using namespace CDReaderHelpers;
  211772. Array <int> indexes;
  211773. const int trackStart = getPositionOfTrackStart (trackNumber);
  211774. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211775. bool needToScan = true;
  211776. if (trackEnd - trackStart > 20 * 44100)
  211777. {
  211778. // check the end of the track for indexes before scanning the whole thing
  211779. needToScan = false;
  211780. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211781. bool seenAnIndex = false;
  211782. while (pos <= trackEnd - samplesPerFrame)
  211783. {
  211784. const int index = getIndexAt (pos);
  211785. if (index == 0)
  211786. {
  211787. // lead-out, so skip back a bit if we've not found any indexes yet..
  211788. if (seenAnIndex)
  211789. break;
  211790. pos -= 44100 * 5;
  211791. if (pos < trackStart)
  211792. break;
  211793. }
  211794. else
  211795. {
  211796. if (index > 0)
  211797. seenAnIndex = true;
  211798. if (index > 1)
  211799. {
  211800. needToScan = true;
  211801. break;
  211802. }
  211803. pos += samplesPerFrame * framesPerIndexRead;
  211804. }
  211805. }
  211806. }
  211807. if (needToScan)
  211808. {
  211809. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211810. int pos = trackStart;
  211811. int last = -1;
  211812. while (pos < trackEnd - samplesPerFrame * 10)
  211813. {
  211814. const int frameNeeded = pos / samplesPerFrame;
  211815. device->overlapBuffer->dataLength = 0;
  211816. device->overlapBuffer->startFrame = 0;
  211817. device->overlapBuffer->numFrames = 0;
  211818. device->jitter = false;
  211819. firstFrameInBuffer = 0;
  211820. CDReadBuffer readBuffer (4);
  211821. readBuffer.wantsIndex = true;
  211822. int i;
  211823. for (i = 5; --i >= 0;)
  211824. {
  211825. readBuffer.startFrame = frameNeeded;
  211826. readBuffer.numFrames = framesPerIndexRead;
  211827. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211828. break;
  211829. }
  211830. if (i < 0)
  211831. break;
  211832. if (readBuffer.index > last && readBuffer.index > 1)
  211833. {
  211834. last = readBuffer.index;
  211835. indexes.add (pos);
  211836. }
  211837. pos += samplesPerFrame * framesPerIndexRead;
  211838. }
  211839. indexes.removeValue (trackStart);
  211840. }
  211841. return indexes;
  211842. }
  211843. void AudioCDReader::ejectDisk()
  211844. {
  211845. using namespace CDReaderHelpers;
  211846. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  211847. }
  211848. #endif
  211849. #if JUCE_USE_CDBURNER
  211850. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211851. {
  211852. CoInitialize (0);
  211853. IDiscMaster* dm;
  211854. IDiscRecorder* result = 0;
  211855. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211856. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211857. IID_IDiscMaster,
  211858. (void**) &dm)))
  211859. {
  211860. if (SUCCEEDED (dm->Open()))
  211861. {
  211862. IEnumDiscRecorders* drEnum = 0;
  211863. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211864. {
  211865. IDiscRecorder* dr = 0;
  211866. DWORD dummy;
  211867. int index = 0;
  211868. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211869. {
  211870. if (indexToOpen == index)
  211871. {
  211872. result = dr;
  211873. break;
  211874. }
  211875. else if (list != 0)
  211876. {
  211877. BSTR path;
  211878. if (SUCCEEDED (dr->GetPath (&path)))
  211879. list->add ((const WCHAR*) path);
  211880. }
  211881. ++index;
  211882. dr->Release();
  211883. }
  211884. drEnum->Release();
  211885. }
  211886. if (master == 0)
  211887. dm->Close();
  211888. }
  211889. if (master != 0)
  211890. *master = dm;
  211891. else
  211892. dm->Release();
  211893. }
  211894. return result;
  211895. }
  211896. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211897. public Timer
  211898. {
  211899. public:
  211900. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211901. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211902. listener (0), progress (0), shouldCancel (false)
  211903. {
  211904. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211905. jassert (SUCCEEDED (hr));
  211906. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211907. //jassert (SUCCEEDED (hr));
  211908. lastState = getDiskState();
  211909. startTimer (2000);
  211910. }
  211911. ~Pimpl() {}
  211912. void releaseObjects()
  211913. {
  211914. discRecorder->Close();
  211915. if (redbook != 0)
  211916. redbook->Release();
  211917. discRecorder->Release();
  211918. discMaster->Release();
  211919. Release();
  211920. }
  211921. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211922. {
  211923. if (listener != 0 && ! shouldCancel)
  211924. shouldCancel = listener->audioCDBurnProgress (progress);
  211925. *pbCancel = shouldCancel;
  211926. return S_OK;
  211927. }
  211928. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211929. {
  211930. progress = nCompleted / (float) nTotal;
  211931. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211932. return E_NOTIMPL;
  211933. }
  211934. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211935. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211936. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211937. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211938. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211939. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211940. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211941. class ScopedDiscOpener
  211942. {
  211943. public:
  211944. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211945. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211946. private:
  211947. Pimpl& pimpl;
  211948. ScopedDiscOpener (const ScopedDiscOpener&);
  211949. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  211950. };
  211951. DiskState getDiskState()
  211952. {
  211953. const ScopedDiscOpener opener (*this);
  211954. long type, flags;
  211955. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211956. if (FAILED (hr))
  211957. return unknown;
  211958. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211959. return writableDiskPresent;
  211960. if (type == 0)
  211961. return noDisc;
  211962. else
  211963. return readOnlyDiskPresent;
  211964. }
  211965. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211966. {
  211967. ComSmartPtr<IPropertyStorage> prop;
  211968. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  211969. return defaultReturn;
  211970. PROPSPEC iPropSpec;
  211971. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211972. iPropSpec.lpwstr = name;
  211973. PROPVARIANT iPropVariant;
  211974. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211975. ? defaultReturn : (int) iPropVariant.lVal;
  211976. }
  211977. bool setIntProperty (const LPOLESTR name, const int value) const
  211978. {
  211979. ComSmartPtr<IPropertyStorage> prop;
  211980. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  211981. return false;
  211982. PROPSPEC iPropSpec;
  211983. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211984. iPropSpec.lpwstr = name;
  211985. PROPVARIANT iPropVariant;
  211986. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211987. return false;
  211988. iPropVariant.lVal = (long) value;
  211989. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211990. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211991. }
  211992. void timerCallback()
  211993. {
  211994. const DiskState state = getDiskState();
  211995. if (state != lastState)
  211996. {
  211997. lastState = state;
  211998. owner.sendChangeMessage (&owner);
  211999. }
  212000. }
  212001. AudioCDBurner& owner;
  212002. DiskState lastState;
  212003. IDiscMaster* discMaster;
  212004. IDiscRecorder* discRecorder;
  212005. IRedbookDiscMaster* redbook;
  212006. AudioCDBurner::BurnProgressListener* listener;
  212007. float progress;
  212008. bool shouldCancel;
  212009. };
  212010. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212011. {
  212012. IDiscMaster* discMaster = 0;
  212013. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212014. if (discRecorder != 0)
  212015. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212016. }
  212017. AudioCDBurner::~AudioCDBurner()
  212018. {
  212019. if (pimpl != 0)
  212020. pimpl.release()->releaseObjects();
  212021. }
  212022. const StringArray AudioCDBurner::findAvailableDevices()
  212023. {
  212024. StringArray devs;
  212025. enumCDBurners (&devs, -1, 0);
  212026. return devs;
  212027. }
  212028. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212029. {
  212030. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212031. if (b->pimpl == 0)
  212032. b = 0;
  212033. return b.release();
  212034. }
  212035. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212036. {
  212037. return pimpl->getDiskState();
  212038. }
  212039. bool AudioCDBurner::isDiskPresent() const
  212040. {
  212041. return getDiskState() == writableDiskPresent;
  212042. }
  212043. bool AudioCDBurner::openTray()
  212044. {
  212045. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212046. return SUCCEEDED (pimpl->discRecorder->Eject());
  212047. }
  212048. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212049. {
  212050. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212051. DiskState oldState = getDiskState();
  212052. DiskState newState = oldState;
  212053. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212054. {
  212055. newState = getDiskState();
  212056. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212057. }
  212058. return newState;
  212059. }
  212060. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212061. {
  212062. Array<int> results;
  212063. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212064. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212065. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212066. if (speeds[i] <= maxSpeed)
  212067. results.add (speeds[i]);
  212068. results.addIfNotAlreadyThere (maxSpeed);
  212069. return results;
  212070. }
  212071. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212072. {
  212073. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212074. return false;
  212075. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212076. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212077. }
  212078. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212079. {
  212080. long blocksFree = 0;
  212081. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212082. return blocksFree;
  212083. }
  212084. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212085. bool performFakeBurnForTesting, int writeSpeed)
  212086. {
  212087. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212088. pimpl->listener = listener;
  212089. pimpl->progress = 0;
  212090. pimpl->shouldCancel = false;
  212091. UINT_PTR cookie;
  212092. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212093. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212094. ejectDiscAfterwards);
  212095. String error;
  212096. if (hr != S_OK)
  212097. {
  212098. const char* e = "Couldn't open or write to the CD device";
  212099. if (hr == IMAPI_E_USERABORT)
  212100. e = "User cancelled the write operation";
  212101. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212102. e = "No Disk present";
  212103. error = e;
  212104. }
  212105. pimpl->discMaster->ProgressUnadvise (cookie);
  212106. pimpl->listener = 0;
  212107. return error;
  212108. }
  212109. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212110. {
  212111. if (audioSource == 0)
  212112. return false;
  212113. ScopedPointer<AudioSource> source (audioSource);
  212114. long bytesPerBlock;
  212115. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212116. const int samplesPerBlock = bytesPerBlock / 4;
  212117. bool ok = true;
  212118. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212119. HeapBlock <byte> buffer (bytesPerBlock);
  212120. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212121. int samplesDone = 0;
  212122. source->prepareToPlay (samplesPerBlock, 44100.0);
  212123. while (ok)
  212124. {
  212125. {
  212126. AudioSourceChannelInfo info;
  212127. info.buffer = &sourceBuffer;
  212128. info.numSamples = samplesPerBlock;
  212129. info.startSample = 0;
  212130. sourceBuffer.clear();
  212131. source->getNextAudioBlock (info);
  212132. }
  212133. zeromem (buffer, bytesPerBlock);
  212134. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  212135. buffer, samplesPerBlock, 4);
  212136. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  212137. buffer + 2, samplesPerBlock, 4);
  212138. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212139. if (FAILED (hr))
  212140. ok = false;
  212141. samplesDone += samplesPerBlock;
  212142. if (samplesDone >= numSamples)
  212143. break;
  212144. }
  212145. hr = pimpl->redbook->CloseAudioTrack();
  212146. return ok && hr == S_OK;
  212147. }
  212148. #endif
  212149. #endif
  212150. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212151. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212152. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212153. // compiled on its own).
  212154. #if JUCE_INCLUDED_FILE
  212155. using ::free;
  212156. namespace MidiConstants
  212157. {
  212158. static const int midiBufferSize = 1024 * 10;
  212159. static const int numInHeaders = 32;
  212160. static const int inBufferSize = 256;
  212161. }
  212162. class MidiInThread : public Thread
  212163. {
  212164. public:
  212165. MidiInThread (MidiInput* const input_,
  212166. MidiInputCallback* const callback_)
  212167. : Thread ("Juce Midi"),
  212168. hIn (0),
  212169. input (input_),
  212170. callback (callback_),
  212171. isStarted (false),
  212172. startTime (0),
  212173. pendingLength(0)
  212174. {
  212175. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  212176. {
  212177. zeromem (&hdr[i], sizeof (MIDIHDR));
  212178. hdr[i].lpData = inData[i];
  212179. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  212180. }
  212181. };
  212182. ~MidiInThread()
  212183. {
  212184. stop();
  212185. if (hIn != 0)
  212186. {
  212187. int count = 5;
  212188. while (--count >= 0)
  212189. {
  212190. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  212191. break;
  212192. Sleep (20);
  212193. }
  212194. }
  212195. }
  212196. void handle (const uint32 message, const uint32 timeStamp)
  212197. {
  212198. const int byte = message & 0xff;
  212199. if (byte < 0x80)
  212200. return;
  212201. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  212202. const double time = timeStampToTime (timeStamp);
  212203. {
  212204. const ScopedLock sl (lock);
  212205. if (pendingLength < MidiConstants::midiBufferSize - 12)
  212206. {
  212207. char* const p = pending + pendingLength;
  212208. *(double*) p = time;
  212209. *(uint32*) (p + 8) = numBytes;
  212210. *(uint32*) (p + 12) = message;
  212211. pendingLength += 12 + numBytes;
  212212. }
  212213. else
  212214. {
  212215. jassertfalse; // midi buffer overflow! You might need to increase the size..
  212216. }
  212217. }
  212218. notify();
  212219. }
  212220. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212221. {
  212222. const int num = hdr->dwBytesRecorded;
  212223. if (num > 0)
  212224. {
  212225. const double time = timeStampToTime (timeStamp);
  212226. {
  212227. const ScopedLock sl (lock);
  212228. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  212229. {
  212230. char* const p = pending + pendingLength;
  212231. *(double*) p = time;
  212232. *(uint32*) (p + 8) = num;
  212233. memcpy (p + 12, hdr->lpData, num);
  212234. pendingLength += 12 + num;
  212235. }
  212236. else
  212237. {
  212238. jassertfalse; // midi buffer overflow! You might need to increase the size..
  212239. }
  212240. }
  212241. notify();
  212242. }
  212243. }
  212244. void writeBlock (const int i)
  212245. {
  212246. hdr[i].dwBytesRecorded = 0;
  212247. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  212248. jassert (res == MMSYSERR_NOERROR);
  212249. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  212250. jassert (res == MMSYSERR_NOERROR);
  212251. }
  212252. void run()
  212253. {
  212254. MemoryBlock pendingCopy (64);
  212255. while (! threadShouldExit())
  212256. {
  212257. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  212258. {
  212259. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212260. {
  212261. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  212262. (void) res;
  212263. jassert (res == MMSYSERR_NOERROR);
  212264. writeBlock (i);
  212265. }
  212266. }
  212267. int len;
  212268. {
  212269. const ScopedLock sl (lock);
  212270. len = pendingLength;
  212271. if (len > 0)
  212272. {
  212273. pendingCopy.ensureSize (len);
  212274. pendingCopy.copyFrom (pending, 0, len);
  212275. pendingLength = 0;
  212276. }
  212277. }
  212278. //xxx needs to figure out if blocks are broken up or not
  212279. if (len == 0)
  212280. {
  212281. wait (500);
  212282. }
  212283. else
  212284. {
  212285. const char* p = (const char*) pendingCopy.getData();
  212286. while (len > 0)
  212287. {
  212288. const double time = *(const double*) p;
  212289. const int messageLen = *(const int*) (p + 8);
  212290. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  212291. callback->handleIncomingMidiMessage (input, message);
  212292. p += 12 + messageLen;
  212293. len -= 12 + messageLen;
  212294. }
  212295. }
  212296. }
  212297. }
  212298. void start()
  212299. {
  212300. jassert (hIn != 0);
  212301. if (hIn != 0 && ! isStarted)
  212302. {
  212303. stop();
  212304. activeMidiThreads.addIfNotAlreadyThere (this);
  212305. int i;
  212306. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  212307. writeBlock (i);
  212308. startTime = Time::getMillisecondCounter();
  212309. MMRESULT res = midiInStart (hIn);
  212310. jassert (res == MMSYSERR_NOERROR);
  212311. if (res == MMSYSERR_NOERROR)
  212312. {
  212313. isStarted = true;
  212314. pendingLength = 0;
  212315. startThread (6);
  212316. }
  212317. }
  212318. }
  212319. void stop()
  212320. {
  212321. if (isStarted)
  212322. {
  212323. stopThread (5000);
  212324. midiInReset (hIn);
  212325. midiInStop (hIn);
  212326. activeMidiThreads.removeValue (this);
  212327. { const ScopedLock sl (lock); }
  212328. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  212329. {
  212330. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212331. {
  212332. int c = 10;
  212333. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  212334. Sleep (20);
  212335. jassert (c >= 0);
  212336. }
  212337. }
  212338. isStarted = false;
  212339. pendingLength = 0;
  212340. }
  212341. }
  212342. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212343. {
  212344. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  212345. if (thread != 0 && activeMidiThreads.contains (thread))
  212346. {
  212347. if (uMsg == MIM_DATA)
  212348. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  212349. else if (uMsg == MIM_LONGDATA)
  212350. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212351. }
  212352. }
  212353. juce_UseDebuggingNewOperator
  212354. HMIDIIN hIn;
  212355. private:
  212356. static Array <void*, CriticalSection> activeMidiThreads;
  212357. MidiInput* input;
  212358. MidiInputCallback* callback;
  212359. bool isStarted;
  212360. uint32 startTime;
  212361. CriticalSection lock;
  212362. MIDIHDR hdr [MidiConstants::numInHeaders];
  212363. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  212364. int pendingLength;
  212365. char pending [MidiConstants::midiBufferSize];
  212366. double timeStampToTime (uint32 timeStamp)
  212367. {
  212368. timeStamp += startTime;
  212369. const uint32 now = Time::getMillisecondCounter();
  212370. if (timeStamp > now)
  212371. {
  212372. if (timeStamp > now + 2)
  212373. --startTime;
  212374. timeStamp = now;
  212375. }
  212376. return 0.001 * timeStamp;
  212377. }
  212378. MidiInThread (const MidiInThread&);
  212379. MidiInThread& operator= (const MidiInThread&);
  212380. };
  212381. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  212382. const StringArray MidiInput::getDevices()
  212383. {
  212384. StringArray s;
  212385. const int num = midiInGetNumDevs();
  212386. for (int i = 0; i < num; ++i)
  212387. {
  212388. MIDIINCAPS mc;
  212389. zerostruct (mc);
  212390. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212391. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212392. }
  212393. return s;
  212394. }
  212395. int MidiInput::getDefaultDeviceIndex()
  212396. {
  212397. return 0;
  212398. }
  212399. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212400. {
  212401. if (callback == 0)
  212402. return 0;
  212403. UINT deviceId = MIDI_MAPPER;
  212404. int n = 0;
  212405. String name;
  212406. const int num = midiInGetNumDevs();
  212407. for (int i = 0; i < num; ++i)
  212408. {
  212409. MIDIINCAPS mc;
  212410. zerostruct (mc);
  212411. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212412. {
  212413. if (index == n)
  212414. {
  212415. deviceId = i;
  212416. name = String (mc.szPname, sizeof (mc.szPname));
  212417. break;
  212418. }
  212419. ++n;
  212420. }
  212421. }
  212422. ScopedPointer <MidiInput> in (new MidiInput (name));
  212423. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  212424. HMIDIIN h;
  212425. HRESULT err = midiInOpen (&h, deviceId,
  212426. (DWORD_PTR) &MidiInThread::midiInCallback,
  212427. (DWORD_PTR) (MidiInThread*) thread,
  212428. CALLBACK_FUNCTION);
  212429. if (err == MMSYSERR_NOERROR)
  212430. {
  212431. thread->hIn = h;
  212432. in->internal = thread.release();
  212433. return in.release();
  212434. }
  212435. return 0;
  212436. }
  212437. MidiInput::MidiInput (const String& name_)
  212438. : name (name_),
  212439. internal (0)
  212440. {
  212441. }
  212442. MidiInput::~MidiInput()
  212443. {
  212444. delete static_cast <MidiInThread*> (internal);
  212445. }
  212446. void MidiInput::start()
  212447. {
  212448. static_cast <MidiInThread*> (internal)->start();
  212449. }
  212450. void MidiInput::stop()
  212451. {
  212452. static_cast <MidiInThread*> (internal)->stop();
  212453. }
  212454. struct MidiOutHandle
  212455. {
  212456. int refCount;
  212457. UINT deviceId;
  212458. HMIDIOUT handle;
  212459. static Array<MidiOutHandle*> activeHandles;
  212460. juce_UseDebuggingNewOperator
  212461. };
  212462. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212463. const StringArray MidiOutput::getDevices()
  212464. {
  212465. StringArray s;
  212466. const int num = midiOutGetNumDevs();
  212467. for (int i = 0; i < num; ++i)
  212468. {
  212469. MIDIOUTCAPS mc;
  212470. zerostruct (mc);
  212471. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212472. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212473. }
  212474. return s;
  212475. }
  212476. int MidiOutput::getDefaultDeviceIndex()
  212477. {
  212478. const int num = midiOutGetNumDevs();
  212479. int n = 0;
  212480. for (int i = 0; i < num; ++i)
  212481. {
  212482. MIDIOUTCAPS mc;
  212483. zerostruct (mc);
  212484. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212485. {
  212486. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212487. return n;
  212488. ++n;
  212489. }
  212490. }
  212491. return 0;
  212492. }
  212493. MidiOutput* MidiOutput::openDevice (int index)
  212494. {
  212495. UINT deviceId = MIDI_MAPPER;
  212496. const int num = midiOutGetNumDevs();
  212497. int i, n = 0;
  212498. for (i = 0; i < num; ++i)
  212499. {
  212500. MIDIOUTCAPS mc;
  212501. zerostruct (mc);
  212502. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212503. {
  212504. // use the microsoft sw synth as a default - best not to allow deviceId
  212505. // to be MIDI_MAPPER, or else device sharing breaks
  212506. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212507. deviceId = i;
  212508. if (index == n)
  212509. {
  212510. deviceId = i;
  212511. break;
  212512. }
  212513. ++n;
  212514. }
  212515. }
  212516. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212517. {
  212518. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212519. if (han != 0 && han->deviceId == deviceId)
  212520. {
  212521. han->refCount++;
  212522. MidiOutput* const out = new MidiOutput();
  212523. out->internal = han;
  212524. return out;
  212525. }
  212526. }
  212527. for (i = 4; --i >= 0;)
  212528. {
  212529. HMIDIOUT h = 0;
  212530. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212531. if (res == MMSYSERR_NOERROR)
  212532. {
  212533. MidiOutHandle* const han = new MidiOutHandle();
  212534. han->deviceId = deviceId;
  212535. han->refCount = 1;
  212536. han->handle = h;
  212537. MidiOutHandle::activeHandles.add (han);
  212538. MidiOutput* const out = new MidiOutput();
  212539. out->internal = han;
  212540. return out;
  212541. }
  212542. else if (res == MMSYSERR_ALLOCATED)
  212543. {
  212544. Sleep (100);
  212545. }
  212546. else
  212547. {
  212548. break;
  212549. }
  212550. }
  212551. return 0;
  212552. }
  212553. MidiOutput::~MidiOutput()
  212554. {
  212555. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212556. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212557. {
  212558. midiOutClose (h->handle);
  212559. MidiOutHandle::activeHandles.removeValue (h);
  212560. delete h;
  212561. }
  212562. }
  212563. void MidiOutput::reset()
  212564. {
  212565. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212566. midiOutReset (h->handle);
  212567. }
  212568. bool MidiOutput::getVolume (float& leftVol,
  212569. float& rightVol)
  212570. {
  212571. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212572. DWORD n;
  212573. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212574. {
  212575. const unsigned short* const nn = (const unsigned short*) &n;
  212576. rightVol = nn[0] / (float) 0xffff;
  212577. leftVol = nn[1] / (float) 0xffff;
  212578. return true;
  212579. }
  212580. else
  212581. {
  212582. rightVol = leftVol = 1.0f;
  212583. return false;
  212584. }
  212585. }
  212586. void MidiOutput::setVolume (float leftVol,
  212587. float rightVol)
  212588. {
  212589. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212590. DWORD n;
  212591. unsigned short* const nn = (unsigned short*) &n;
  212592. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212593. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212594. midiOutSetVolume (handle->handle, n);
  212595. }
  212596. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212597. {
  212598. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212599. if (message.getRawDataSize() > 3
  212600. || message.isSysEx())
  212601. {
  212602. MIDIHDR h;
  212603. zerostruct (h);
  212604. h.lpData = (char*) message.getRawData();
  212605. h.dwBufferLength = message.getRawDataSize();
  212606. h.dwBytesRecorded = message.getRawDataSize();
  212607. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212608. {
  212609. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212610. if (res == MMSYSERR_NOERROR)
  212611. {
  212612. while ((h.dwFlags & MHDR_DONE) == 0)
  212613. Sleep (1);
  212614. int count = 500; // 1 sec timeout
  212615. while (--count >= 0)
  212616. {
  212617. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212618. if (res == MIDIERR_STILLPLAYING)
  212619. Sleep (2);
  212620. else
  212621. break;
  212622. }
  212623. }
  212624. }
  212625. }
  212626. else
  212627. {
  212628. midiOutShortMsg (handle->handle,
  212629. *(unsigned int*) message.getRawData());
  212630. }
  212631. }
  212632. #endif
  212633. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212634. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212635. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212636. // compiled on its own).
  212637. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212638. #undef WINDOWS
  212639. // #define ASIO_DEBUGGING 1
  212640. #if ASIO_DEBUGGING
  212641. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212642. #else
  212643. #define log(a) {}
  212644. #endif
  212645. #if ASIO_DEBUGGING
  212646. static void logError (const String& context, long error)
  212647. {
  212648. String err ("unknown error");
  212649. if (error == ASE_NotPresent) err = "Not Present";
  212650. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212651. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212652. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212653. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212654. else if (error == ASE_NoClock) err = "No Clock";
  212655. else if (error == ASE_NoMemory) err = "Out of memory";
  212656. log ("!!error: " + context + " - " + err);
  212657. }
  212658. #else
  212659. #define logError(a, b) {}
  212660. #endif
  212661. class ASIOAudioIODevice;
  212662. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212663. static const int maxASIOChannels = 160;
  212664. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212665. private Timer
  212666. {
  212667. public:
  212668. Component ourWindow;
  212669. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212670. const String& optionalDllForDirectLoading_)
  212671. : AudioIODevice (name_, "ASIO"),
  212672. asioObject (0),
  212673. classId (classId_),
  212674. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212675. currentBitDepth (16),
  212676. currentSampleRate (0),
  212677. isOpen_ (false),
  212678. isStarted (false),
  212679. postOutput (true),
  212680. insideControlPanelModalLoop (false),
  212681. shouldUsePreferredSize (false)
  212682. {
  212683. name = name_;
  212684. ourWindow.addToDesktop (0);
  212685. windowHandle = ourWindow.getWindowHandle();
  212686. jassert (currentASIODev [slotNumber] == 0);
  212687. currentASIODev [slotNumber] = this;
  212688. openDevice();
  212689. }
  212690. ~ASIOAudioIODevice()
  212691. {
  212692. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212693. if (currentASIODev[i] == this)
  212694. currentASIODev[i] = 0;
  212695. close();
  212696. log ("ASIO - exiting");
  212697. removeCurrentDriver();
  212698. }
  212699. void updateSampleRates()
  212700. {
  212701. // find a list of sample rates..
  212702. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212703. sampleRates.clear();
  212704. if (asioObject != 0)
  212705. {
  212706. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212707. {
  212708. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212709. if (err == 0)
  212710. {
  212711. sampleRates.add ((int) possibleSampleRates[index]);
  212712. log ("rate: " + String ((int) possibleSampleRates[index]));
  212713. }
  212714. else if (err != ASE_NoClock)
  212715. {
  212716. logError ("CanSampleRate", err);
  212717. }
  212718. }
  212719. if (sampleRates.size() == 0)
  212720. {
  212721. double cr = 0;
  212722. const long err = asioObject->getSampleRate (&cr);
  212723. log ("No sample rates supported - current rate: " + String ((int) cr));
  212724. if (err == 0)
  212725. sampleRates.add ((int) cr);
  212726. }
  212727. }
  212728. }
  212729. const StringArray getOutputChannelNames()
  212730. {
  212731. return outputChannelNames;
  212732. }
  212733. const StringArray getInputChannelNames()
  212734. {
  212735. return inputChannelNames;
  212736. }
  212737. int getNumSampleRates()
  212738. {
  212739. return sampleRates.size();
  212740. }
  212741. double getSampleRate (int index)
  212742. {
  212743. return sampleRates [index];
  212744. }
  212745. int getNumBufferSizesAvailable()
  212746. {
  212747. return bufferSizes.size();
  212748. }
  212749. int getBufferSizeSamples (int index)
  212750. {
  212751. return bufferSizes [index];
  212752. }
  212753. int getDefaultBufferSize()
  212754. {
  212755. return preferredSize;
  212756. }
  212757. const String open (const BigInteger& inputChannels,
  212758. const BigInteger& outputChannels,
  212759. double sr,
  212760. int bufferSizeSamples)
  212761. {
  212762. close();
  212763. currentCallback = 0;
  212764. if (bufferSizeSamples <= 0)
  212765. shouldUsePreferredSize = true;
  212766. if (asioObject == 0 || ! isASIOOpen)
  212767. {
  212768. log ("Warning: device not open");
  212769. const String err (openDevice());
  212770. if (asioObject == 0 || ! isASIOOpen)
  212771. return err;
  212772. }
  212773. isStarted = false;
  212774. bufferIndex = -1;
  212775. long err = 0;
  212776. long newPreferredSize = 0;
  212777. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212778. minSize = 0;
  212779. maxSize = 0;
  212780. newPreferredSize = 0;
  212781. granularity = 0;
  212782. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212783. {
  212784. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212785. shouldUsePreferredSize = true;
  212786. preferredSize = newPreferredSize;
  212787. }
  212788. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212789. // dynamic changes to the buffer size...
  212790. shouldUsePreferredSize = shouldUsePreferredSize
  212791. || getName().containsIgnoreCase ("Digidesign");
  212792. if (shouldUsePreferredSize)
  212793. {
  212794. log ("Using preferred size for buffer..");
  212795. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212796. {
  212797. bufferSizeSamples = preferredSize;
  212798. }
  212799. else
  212800. {
  212801. bufferSizeSamples = 1024;
  212802. logError ("GetBufferSize1", err);
  212803. }
  212804. shouldUsePreferredSize = false;
  212805. }
  212806. int sampleRate = roundDoubleToInt (sr);
  212807. currentSampleRate = sampleRate;
  212808. currentBlockSizeSamples = bufferSizeSamples;
  212809. currentChansOut.clear();
  212810. currentChansIn.clear();
  212811. zeromem (inBuffers, sizeof (inBuffers));
  212812. zeromem (outBuffers, sizeof (outBuffers));
  212813. updateSampleRates();
  212814. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212815. sampleRate = sampleRates[0];
  212816. jassert (sampleRate != 0);
  212817. if (sampleRate == 0)
  212818. sampleRate = 44100;
  212819. long numSources = 32;
  212820. ASIOClockSource clocks[32];
  212821. zeromem (clocks, sizeof (clocks));
  212822. asioObject->getClockSources (clocks, &numSources);
  212823. bool isSourceSet = false;
  212824. // careful not to remove this loop because it does more than just logging!
  212825. int i;
  212826. for (i = 0; i < numSources; ++i)
  212827. {
  212828. String s ("clock: ");
  212829. s += clocks[i].name;
  212830. if (clocks[i].isCurrentSource)
  212831. {
  212832. isSourceSet = true;
  212833. s << " (cur)";
  212834. }
  212835. log (s);
  212836. }
  212837. if (numSources > 1 && ! isSourceSet)
  212838. {
  212839. log ("setting clock source");
  212840. asioObject->setClockSource (clocks[0].index);
  212841. Thread::sleep (20);
  212842. }
  212843. else
  212844. {
  212845. if (numSources == 0)
  212846. {
  212847. log ("ASIO - no clock sources!");
  212848. }
  212849. }
  212850. double cr = 0;
  212851. err = asioObject->getSampleRate (&cr);
  212852. if (err == 0)
  212853. {
  212854. currentSampleRate = cr;
  212855. }
  212856. else
  212857. {
  212858. logError ("GetSampleRate", err);
  212859. currentSampleRate = 0;
  212860. }
  212861. error = String::empty;
  212862. needToReset = false;
  212863. isReSync = false;
  212864. err = 0;
  212865. bool buffersCreated = false;
  212866. if (currentSampleRate != sampleRate)
  212867. {
  212868. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212869. err = asioObject->setSampleRate (sampleRate);
  212870. if (err == ASE_NoClock && numSources > 0)
  212871. {
  212872. log ("trying to set a clock source..");
  212873. Thread::sleep (10);
  212874. err = asioObject->setClockSource (clocks[0].index);
  212875. if (err != 0)
  212876. {
  212877. logError ("SetClock", err);
  212878. }
  212879. Thread::sleep (10);
  212880. err = asioObject->setSampleRate (sampleRate);
  212881. }
  212882. }
  212883. if (err == 0)
  212884. {
  212885. currentSampleRate = sampleRate;
  212886. if (needToReset)
  212887. {
  212888. if (isReSync)
  212889. {
  212890. log ("Resync request");
  212891. }
  212892. log ("! Resetting ASIO after sample rate change");
  212893. removeCurrentDriver();
  212894. loadDriver();
  212895. const String error (initDriver());
  212896. if (error.isNotEmpty())
  212897. {
  212898. log ("ASIOInit: " + error);
  212899. }
  212900. needToReset = false;
  212901. isReSync = false;
  212902. }
  212903. numActiveInputChans = 0;
  212904. numActiveOutputChans = 0;
  212905. ASIOBufferInfo* info = bufferInfos;
  212906. int i;
  212907. for (i = 0; i < totalNumInputChans; ++i)
  212908. {
  212909. if (inputChannels[i])
  212910. {
  212911. currentChansIn.setBit (i);
  212912. info->isInput = 1;
  212913. info->channelNum = i;
  212914. info->buffers[0] = info->buffers[1] = 0;
  212915. ++info;
  212916. ++numActiveInputChans;
  212917. }
  212918. }
  212919. for (i = 0; i < totalNumOutputChans; ++i)
  212920. {
  212921. if (outputChannels[i])
  212922. {
  212923. currentChansOut.setBit (i);
  212924. info->isInput = 0;
  212925. info->channelNum = i;
  212926. info->buffers[0] = info->buffers[1] = 0;
  212927. ++info;
  212928. ++numActiveOutputChans;
  212929. }
  212930. }
  212931. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212932. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212933. if (currentASIODev[0] == this)
  212934. {
  212935. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212936. callbacks.asioMessage = &asioMessagesCallback0;
  212937. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212938. }
  212939. else if (currentASIODev[1] == this)
  212940. {
  212941. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212942. callbacks.asioMessage = &asioMessagesCallback1;
  212943. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212944. }
  212945. else if (currentASIODev[2] == this)
  212946. {
  212947. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212948. callbacks.asioMessage = &asioMessagesCallback2;
  212949. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212950. }
  212951. else
  212952. {
  212953. jassertfalse;
  212954. }
  212955. log ("disposing buffers");
  212956. err = asioObject->disposeBuffers();
  212957. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212958. err = asioObject->createBuffers (bufferInfos,
  212959. totalBuffers,
  212960. currentBlockSizeSamples,
  212961. &callbacks);
  212962. if (err != 0)
  212963. {
  212964. currentBlockSizeSamples = preferredSize;
  212965. logError ("create buffers 2", err);
  212966. asioObject->disposeBuffers();
  212967. err = asioObject->createBuffers (bufferInfos,
  212968. totalBuffers,
  212969. currentBlockSizeSamples,
  212970. &callbacks);
  212971. }
  212972. if (err == 0)
  212973. {
  212974. buffersCreated = true;
  212975. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212976. int n = 0;
  212977. Array <int> types;
  212978. currentBitDepth = 16;
  212979. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212980. {
  212981. if (inputChannels[i])
  212982. {
  212983. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212984. ASIOChannelInfo channelInfo;
  212985. zerostruct (channelInfo);
  212986. channelInfo.channel = i;
  212987. channelInfo.isInput = 1;
  212988. asioObject->getChannelInfo (&channelInfo);
  212989. types.addIfNotAlreadyThere (channelInfo.type);
  212990. typeToFormatParameters (channelInfo.type,
  212991. inputChannelBitDepths[n],
  212992. inputChannelBytesPerSample[n],
  212993. inputChannelIsFloat[n],
  212994. inputChannelLittleEndian[n]);
  212995. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212996. ++n;
  212997. }
  212998. }
  212999. jassert (numActiveInputChans == n);
  213000. n = 0;
  213001. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213002. {
  213003. if (outputChannels[i])
  213004. {
  213005. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213006. ASIOChannelInfo channelInfo;
  213007. zerostruct (channelInfo);
  213008. channelInfo.channel = i;
  213009. channelInfo.isInput = 0;
  213010. asioObject->getChannelInfo (&channelInfo);
  213011. types.addIfNotAlreadyThere (channelInfo.type);
  213012. typeToFormatParameters (channelInfo.type,
  213013. outputChannelBitDepths[n],
  213014. outputChannelBytesPerSample[n],
  213015. outputChannelIsFloat[n],
  213016. outputChannelLittleEndian[n]);
  213017. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213018. ++n;
  213019. }
  213020. }
  213021. jassert (numActiveOutputChans == n);
  213022. for (i = types.size(); --i >= 0;)
  213023. {
  213024. log ("channel format: " + String (types[i]));
  213025. }
  213026. jassert (n <= totalBuffers);
  213027. for (i = 0; i < numActiveOutputChans; ++i)
  213028. {
  213029. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213030. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213031. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213032. {
  213033. log ("!! Null buffers");
  213034. }
  213035. else
  213036. {
  213037. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213038. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213039. }
  213040. }
  213041. inputLatency = outputLatency = 0;
  213042. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213043. {
  213044. log ("ASIO - no latencies");
  213045. }
  213046. else
  213047. {
  213048. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213049. }
  213050. isOpen_ = true;
  213051. log ("starting ASIO");
  213052. calledback = false;
  213053. err = asioObject->start();
  213054. if (err != 0)
  213055. {
  213056. isOpen_ = false;
  213057. log ("ASIO - stop on failure");
  213058. Thread::sleep (10);
  213059. asioObject->stop();
  213060. error = "Can't start device";
  213061. Thread::sleep (10);
  213062. }
  213063. else
  213064. {
  213065. int count = 300;
  213066. while (--count > 0 && ! calledback)
  213067. Thread::sleep (10);
  213068. isStarted = true;
  213069. if (! calledback)
  213070. {
  213071. error = "Device didn't start correctly";
  213072. log ("ASIO didn't callback - stopping..");
  213073. asioObject->stop();
  213074. }
  213075. }
  213076. }
  213077. else
  213078. {
  213079. error = "Can't create i/o buffers";
  213080. }
  213081. }
  213082. else
  213083. {
  213084. error = "Can't set sample rate: ";
  213085. error << sampleRate;
  213086. }
  213087. if (error.isNotEmpty())
  213088. {
  213089. logError (error, err);
  213090. if (asioObject != 0 && buffersCreated)
  213091. asioObject->disposeBuffers();
  213092. Thread::sleep (20);
  213093. isStarted = false;
  213094. isOpen_ = false;
  213095. const String errorCopy (error);
  213096. close(); // (this resets the error string)
  213097. error = errorCopy;
  213098. }
  213099. needToReset = false;
  213100. isReSync = false;
  213101. return error;
  213102. }
  213103. void close()
  213104. {
  213105. error = String::empty;
  213106. stopTimer();
  213107. stop();
  213108. if (isASIOOpen && isOpen_)
  213109. {
  213110. const ScopedLock sl (callbackLock);
  213111. isOpen_ = false;
  213112. isStarted = false;
  213113. needToReset = false;
  213114. isReSync = false;
  213115. log ("ASIO - stopping");
  213116. if (asioObject != 0)
  213117. {
  213118. Thread::sleep (20);
  213119. asioObject->stop();
  213120. Thread::sleep (10);
  213121. asioObject->disposeBuffers();
  213122. }
  213123. Thread::sleep (10);
  213124. }
  213125. }
  213126. bool isOpen()
  213127. {
  213128. return isOpen_ || insideControlPanelModalLoop;
  213129. }
  213130. int getCurrentBufferSizeSamples()
  213131. {
  213132. return currentBlockSizeSamples;
  213133. }
  213134. double getCurrentSampleRate()
  213135. {
  213136. return currentSampleRate;
  213137. }
  213138. const BigInteger getActiveOutputChannels() const
  213139. {
  213140. return currentChansOut;
  213141. }
  213142. const BigInteger getActiveInputChannels() const
  213143. {
  213144. return currentChansIn;
  213145. }
  213146. int getCurrentBitDepth()
  213147. {
  213148. return currentBitDepth;
  213149. }
  213150. int getOutputLatencyInSamples()
  213151. {
  213152. return outputLatency + currentBlockSizeSamples / 4;
  213153. }
  213154. int getInputLatencyInSamples()
  213155. {
  213156. return inputLatency + currentBlockSizeSamples / 4;
  213157. }
  213158. void start (AudioIODeviceCallback* callback)
  213159. {
  213160. if (callback != 0)
  213161. {
  213162. callback->audioDeviceAboutToStart (this);
  213163. const ScopedLock sl (callbackLock);
  213164. currentCallback = callback;
  213165. }
  213166. }
  213167. void stop()
  213168. {
  213169. AudioIODeviceCallback* const lastCallback = currentCallback;
  213170. {
  213171. const ScopedLock sl (callbackLock);
  213172. currentCallback = 0;
  213173. }
  213174. if (lastCallback != 0)
  213175. lastCallback->audioDeviceStopped();
  213176. }
  213177. bool isPlaying()
  213178. {
  213179. return isASIOOpen && (currentCallback != 0);
  213180. }
  213181. const String getLastError()
  213182. {
  213183. return error;
  213184. }
  213185. bool hasControlPanel() const
  213186. {
  213187. return true;
  213188. }
  213189. bool showControlPanel()
  213190. {
  213191. log ("ASIO - showing control panel");
  213192. Component modalWindow (String::empty);
  213193. modalWindow.setOpaque (true);
  213194. modalWindow.addToDesktop (0);
  213195. modalWindow.enterModalState();
  213196. bool done = false;
  213197. JUCE_TRY
  213198. {
  213199. // are there are devices that need to be closed before showing their control panel?
  213200. // close();
  213201. insideControlPanelModalLoop = true;
  213202. const uint32 started = Time::getMillisecondCounter();
  213203. if (asioObject != 0)
  213204. {
  213205. asioObject->controlPanel();
  213206. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213207. log ("spent: " + String (spent));
  213208. if (spent > 300)
  213209. {
  213210. shouldUsePreferredSize = true;
  213211. done = true;
  213212. }
  213213. }
  213214. }
  213215. JUCE_CATCH_ALL
  213216. insideControlPanelModalLoop = false;
  213217. return done;
  213218. }
  213219. void resetRequest() throw()
  213220. {
  213221. needToReset = true;
  213222. }
  213223. void resyncRequest() throw()
  213224. {
  213225. needToReset = true;
  213226. isReSync = true;
  213227. }
  213228. void timerCallback()
  213229. {
  213230. if (! insideControlPanelModalLoop)
  213231. {
  213232. stopTimer();
  213233. // used to cause a reset
  213234. log ("! ASIO restart request!");
  213235. if (isOpen_)
  213236. {
  213237. AudioIODeviceCallback* const oldCallback = currentCallback;
  213238. close();
  213239. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213240. currentSampleRate, currentBlockSizeSamples);
  213241. if (oldCallback != 0)
  213242. start (oldCallback);
  213243. }
  213244. }
  213245. else
  213246. {
  213247. startTimer (100);
  213248. }
  213249. }
  213250. juce_UseDebuggingNewOperator
  213251. private:
  213252. IASIO* volatile asioObject;
  213253. ASIOCallbacks callbacks;
  213254. void* windowHandle;
  213255. CLSID classId;
  213256. const String optionalDllForDirectLoading;
  213257. String error;
  213258. long totalNumInputChans, totalNumOutputChans;
  213259. StringArray inputChannelNames, outputChannelNames;
  213260. Array<int> sampleRates, bufferSizes;
  213261. long inputLatency, outputLatency;
  213262. long minSize, maxSize, preferredSize, granularity;
  213263. int volatile currentBlockSizeSamples;
  213264. int volatile currentBitDepth;
  213265. double volatile currentSampleRate;
  213266. BigInteger currentChansOut, currentChansIn;
  213267. AudioIODeviceCallback* volatile currentCallback;
  213268. CriticalSection callbackLock;
  213269. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213270. float* inBuffers [maxASIOChannels];
  213271. float* outBuffers [maxASIOChannels];
  213272. int inputChannelBitDepths [maxASIOChannels];
  213273. int outputChannelBitDepths [maxASIOChannels];
  213274. int inputChannelBytesPerSample [maxASIOChannels];
  213275. int outputChannelBytesPerSample [maxASIOChannels];
  213276. bool inputChannelIsFloat [maxASIOChannels];
  213277. bool outputChannelIsFloat [maxASIOChannels];
  213278. bool inputChannelLittleEndian [maxASIOChannels];
  213279. bool outputChannelLittleEndian [maxASIOChannels];
  213280. WaitableEvent event1;
  213281. HeapBlock <float> tempBuffer;
  213282. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213283. bool isOpen_, isStarted;
  213284. bool volatile isASIOOpen;
  213285. bool volatile calledback;
  213286. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213287. bool volatile insideControlPanelModalLoop;
  213288. bool volatile shouldUsePreferredSize;
  213289. void removeCurrentDriver()
  213290. {
  213291. if (asioObject != 0)
  213292. {
  213293. asioObject->Release();
  213294. asioObject = 0;
  213295. }
  213296. }
  213297. bool loadDriver()
  213298. {
  213299. removeCurrentDriver();
  213300. JUCE_TRY
  213301. {
  213302. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213303. classId, (void**) &asioObject) == S_OK)
  213304. {
  213305. return true;
  213306. }
  213307. // If a class isn't registered but we have a path for it, we can fallback to
  213308. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213309. if (optionalDllForDirectLoading.isNotEmpty())
  213310. {
  213311. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213312. if (h != 0)
  213313. {
  213314. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213315. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213316. if (dllGetClassObject != 0)
  213317. {
  213318. IClassFactory* classFactory = 0;
  213319. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213320. if (classFactory != 0)
  213321. {
  213322. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213323. classFactory->Release();
  213324. }
  213325. return asioObject != 0;
  213326. }
  213327. }
  213328. }
  213329. }
  213330. JUCE_CATCH_ALL
  213331. asioObject = 0;
  213332. return false;
  213333. }
  213334. const String initDriver()
  213335. {
  213336. if (asioObject != 0)
  213337. {
  213338. char buffer [256];
  213339. zeromem (buffer, sizeof (buffer));
  213340. if (! asioObject->init (windowHandle))
  213341. {
  213342. asioObject->getErrorMessage (buffer);
  213343. return String (buffer, sizeof (buffer) - 1);
  213344. }
  213345. // just in case any daft drivers expect this to be called..
  213346. asioObject->getDriverName (buffer);
  213347. return String::empty;
  213348. }
  213349. return "No Driver";
  213350. }
  213351. const String openDevice()
  213352. {
  213353. // use this in case the driver starts opening dialog boxes..
  213354. Component modalWindow (String::empty);
  213355. modalWindow.setOpaque (true);
  213356. modalWindow.addToDesktop (0);
  213357. modalWindow.enterModalState();
  213358. // open the device and get its info..
  213359. log ("opening ASIO device: " + getName());
  213360. needToReset = false;
  213361. isReSync = false;
  213362. outputChannelNames.clear();
  213363. inputChannelNames.clear();
  213364. bufferSizes.clear();
  213365. sampleRates.clear();
  213366. isASIOOpen = false;
  213367. isOpen_ = false;
  213368. totalNumInputChans = 0;
  213369. totalNumOutputChans = 0;
  213370. numActiveInputChans = 0;
  213371. numActiveOutputChans = 0;
  213372. currentCallback = 0;
  213373. error = String::empty;
  213374. if (getName().isEmpty())
  213375. return error;
  213376. long err = 0;
  213377. if (loadDriver())
  213378. {
  213379. if ((error = initDriver()).isEmpty())
  213380. {
  213381. numActiveInputChans = 0;
  213382. numActiveOutputChans = 0;
  213383. totalNumInputChans = 0;
  213384. totalNumOutputChans = 0;
  213385. if (asioObject != 0
  213386. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213387. {
  213388. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213389. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213390. {
  213391. // find a list of buffer sizes..
  213392. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213393. if (granularity >= 0)
  213394. {
  213395. granularity = jmax (1, (int) granularity);
  213396. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213397. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213398. }
  213399. else if (granularity < 0)
  213400. {
  213401. for (int i = 0; i < 18; ++i)
  213402. {
  213403. const int s = (1 << i);
  213404. if (s >= minSize && s <= maxSize)
  213405. bufferSizes.add (s);
  213406. }
  213407. }
  213408. if (! bufferSizes.contains (preferredSize))
  213409. bufferSizes.insert (0, preferredSize);
  213410. double currentRate = 0;
  213411. asioObject->getSampleRate (&currentRate);
  213412. if (currentRate <= 0.0 || currentRate > 192001.0)
  213413. {
  213414. log ("setting sample rate");
  213415. err = asioObject->setSampleRate (44100.0);
  213416. if (err != 0)
  213417. {
  213418. logError ("setting sample rate", err);
  213419. }
  213420. asioObject->getSampleRate (&currentRate);
  213421. }
  213422. currentSampleRate = currentRate;
  213423. postOutput = (asioObject->outputReady() == 0);
  213424. if (postOutput)
  213425. {
  213426. log ("ASIO outputReady = ok");
  213427. }
  213428. updateSampleRates();
  213429. // ..because cubase does it at this point
  213430. inputLatency = outputLatency = 0;
  213431. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213432. {
  213433. log ("ASIO - no latencies");
  213434. }
  213435. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213436. // create some dummy buffers now.. because cubase does..
  213437. numActiveInputChans = 0;
  213438. numActiveOutputChans = 0;
  213439. ASIOBufferInfo* info = bufferInfos;
  213440. int i, numChans = 0;
  213441. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213442. {
  213443. info->isInput = 1;
  213444. info->channelNum = i;
  213445. info->buffers[0] = info->buffers[1] = 0;
  213446. ++info;
  213447. ++numChans;
  213448. }
  213449. const int outputBufferIndex = numChans;
  213450. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213451. {
  213452. info->isInput = 0;
  213453. info->channelNum = i;
  213454. info->buffers[0] = info->buffers[1] = 0;
  213455. ++info;
  213456. ++numChans;
  213457. }
  213458. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213459. if (currentASIODev[0] == this)
  213460. {
  213461. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213462. callbacks.asioMessage = &asioMessagesCallback0;
  213463. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213464. }
  213465. else if (currentASIODev[1] == this)
  213466. {
  213467. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213468. callbacks.asioMessage = &asioMessagesCallback1;
  213469. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213470. }
  213471. else if (currentASIODev[2] == this)
  213472. {
  213473. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213474. callbacks.asioMessage = &asioMessagesCallback2;
  213475. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213476. }
  213477. else
  213478. {
  213479. jassertfalse;
  213480. }
  213481. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213482. if (preferredSize > 0)
  213483. {
  213484. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213485. if (err != 0)
  213486. {
  213487. logError ("dummy buffers", err);
  213488. }
  213489. }
  213490. long newInps = 0, newOuts = 0;
  213491. asioObject->getChannels (&newInps, &newOuts);
  213492. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213493. {
  213494. totalNumInputChans = newInps;
  213495. totalNumOutputChans = newOuts;
  213496. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213497. }
  213498. updateSampleRates();
  213499. ASIOChannelInfo channelInfo;
  213500. channelInfo.type = 0;
  213501. for (i = 0; i < totalNumInputChans; ++i)
  213502. {
  213503. zerostruct (channelInfo);
  213504. channelInfo.channel = i;
  213505. channelInfo.isInput = 1;
  213506. asioObject->getChannelInfo (&channelInfo);
  213507. inputChannelNames.add (String (channelInfo.name));
  213508. }
  213509. for (i = 0; i < totalNumOutputChans; ++i)
  213510. {
  213511. zerostruct (channelInfo);
  213512. channelInfo.channel = i;
  213513. channelInfo.isInput = 0;
  213514. asioObject->getChannelInfo (&channelInfo);
  213515. outputChannelNames.add (String (channelInfo.name));
  213516. typeToFormatParameters (channelInfo.type,
  213517. outputChannelBitDepths[i],
  213518. outputChannelBytesPerSample[i],
  213519. outputChannelIsFloat[i],
  213520. outputChannelLittleEndian[i]);
  213521. if (i < 2)
  213522. {
  213523. // clear the channels that are used with the dummy stuff
  213524. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213525. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213526. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213527. }
  213528. }
  213529. outputChannelNames.trim();
  213530. inputChannelNames.trim();
  213531. outputChannelNames.appendNumbersToDuplicates (false, true);
  213532. inputChannelNames.appendNumbersToDuplicates (false, true);
  213533. // start and stop because cubase does it..
  213534. asioObject->getLatencies (&inputLatency, &outputLatency);
  213535. if ((err = asioObject->start()) != 0)
  213536. {
  213537. // ignore an error here, as it might start later after setting other stuff up
  213538. logError ("ASIO start", err);
  213539. }
  213540. Thread::sleep (100);
  213541. asioObject->stop();
  213542. }
  213543. else
  213544. {
  213545. error = "Can't detect buffer sizes";
  213546. }
  213547. }
  213548. else
  213549. {
  213550. error = "Can't detect asio channels";
  213551. }
  213552. }
  213553. }
  213554. else
  213555. {
  213556. error = "No such device";
  213557. }
  213558. if (error.isNotEmpty())
  213559. {
  213560. logError (error, err);
  213561. if (asioObject != 0)
  213562. asioObject->disposeBuffers();
  213563. removeCurrentDriver();
  213564. isASIOOpen = false;
  213565. }
  213566. else
  213567. {
  213568. isASIOOpen = true;
  213569. log ("ASIO device open");
  213570. }
  213571. isOpen_ = false;
  213572. needToReset = false;
  213573. isReSync = false;
  213574. return error;
  213575. }
  213576. void callback (const long index)
  213577. {
  213578. if (isStarted)
  213579. {
  213580. bufferIndex = index;
  213581. processBuffer();
  213582. }
  213583. else
  213584. {
  213585. if (postOutput && (asioObject != 0))
  213586. asioObject->outputReady();
  213587. }
  213588. calledback = true;
  213589. }
  213590. void processBuffer()
  213591. {
  213592. const ASIOBufferInfo* const infos = bufferInfos;
  213593. const int bi = bufferIndex;
  213594. const ScopedLock sl (callbackLock);
  213595. if (needToReset)
  213596. {
  213597. needToReset = false;
  213598. if (isReSync)
  213599. {
  213600. log ("! ASIO resync");
  213601. isReSync = false;
  213602. }
  213603. else
  213604. {
  213605. startTimer (20);
  213606. }
  213607. }
  213608. if (bi >= 0)
  213609. {
  213610. const int samps = currentBlockSizeSamples;
  213611. if (currentCallback != 0)
  213612. {
  213613. int i;
  213614. for (i = 0; i < numActiveInputChans; ++i)
  213615. {
  213616. float* const dst = inBuffers[i];
  213617. jassert (dst != 0);
  213618. const char* const src = (const char*) (infos[i].buffers[bi]);
  213619. if (inputChannelIsFloat[i])
  213620. {
  213621. memcpy (dst, src, samps * sizeof (float));
  213622. }
  213623. else
  213624. {
  213625. jassert (dst == tempBuffer + (samps * i));
  213626. switch (inputChannelBitDepths[i])
  213627. {
  213628. case 16:
  213629. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213630. samps, inputChannelLittleEndian[i]);
  213631. break;
  213632. case 24:
  213633. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213634. samps, inputChannelLittleEndian[i]);
  213635. break;
  213636. case 32:
  213637. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213638. samps, inputChannelLittleEndian[i]);
  213639. break;
  213640. case 64:
  213641. jassertfalse;
  213642. break;
  213643. }
  213644. }
  213645. }
  213646. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213647. numActiveInputChans,
  213648. outBuffers,
  213649. numActiveOutputChans,
  213650. samps);
  213651. for (i = 0; i < numActiveOutputChans; ++i)
  213652. {
  213653. float* const src = outBuffers[i];
  213654. jassert (src != 0);
  213655. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213656. if (outputChannelIsFloat[i])
  213657. {
  213658. memcpy (dst, src, samps * sizeof (float));
  213659. }
  213660. else
  213661. {
  213662. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213663. switch (outputChannelBitDepths[i])
  213664. {
  213665. case 16:
  213666. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213667. samps, outputChannelLittleEndian[i]);
  213668. break;
  213669. case 24:
  213670. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213671. samps, outputChannelLittleEndian[i]);
  213672. break;
  213673. case 32:
  213674. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213675. samps, outputChannelLittleEndian[i]);
  213676. break;
  213677. case 64:
  213678. jassertfalse;
  213679. break;
  213680. }
  213681. }
  213682. }
  213683. }
  213684. else
  213685. {
  213686. for (int i = 0; i < numActiveOutputChans; ++i)
  213687. {
  213688. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213689. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213690. }
  213691. }
  213692. }
  213693. if (postOutput)
  213694. asioObject->outputReady();
  213695. }
  213696. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213697. {
  213698. if (currentASIODev[0] != 0)
  213699. currentASIODev[0]->callback (index);
  213700. return 0;
  213701. }
  213702. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213703. {
  213704. if (currentASIODev[1] != 0)
  213705. currentASIODev[1]->callback (index);
  213706. return 0;
  213707. }
  213708. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213709. {
  213710. if (currentASIODev[2] != 0)
  213711. currentASIODev[2]->callback (index);
  213712. return 0;
  213713. }
  213714. static void bufferSwitchCallback0 (long index, long)
  213715. {
  213716. if (currentASIODev[0] != 0)
  213717. currentASIODev[0]->callback (index);
  213718. }
  213719. static void bufferSwitchCallback1 (long index, long)
  213720. {
  213721. if (currentASIODev[1] != 0)
  213722. currentASIODev[1]->callback (index);
  213723. }
  213724. static void bufferSwitchCallback2 (long index, long)
  213725. {
  213726. if (currentASIODev[2] != 0)
  213727. currentASIODev[2]->callback (index);
  213728. }
  213729. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  213730. {
  213731. return asioMessagesCallback (selector, value, 0);
  213732. }
  213733. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  213734. {
  213735. return asioMessagesCallback (selector, value, 1);
  213736. }
  213737. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  213738. {
  213739. return asioMessagesCallback (selector, value, 2);
  213740. }
  213741. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  213742. {
  213743. switch (selector)
  213744. {
  213745. case kAsioSelectorSupported:
  213746. if (value == kAsioResetRequest
  213747. || value == kAsioEngineVersion
  213748. || value == kAsioResyncRequest
  213749. || value == kAsioLatenciesChanged
  213750. || value == kAsioSupportsInputMonitor)
  213751. return 1;
  213752. break;
  213753. case kAsioBufferSizeChange:
  213754. break;
  213755. case kAsioResetRequest:
  213756. if (currentASIODev[deviceIndex] != 0)
  213757. currentASIODev[deviceIndex]->resetRequest();
  213758. return 1;
  213759. case kAsioResyncRequest:
  213760. if (currentASIODev[deviceIndex] != 0)
  213761. currentASIODev[deviceIndex]->resyncRequest();
  213762. return 1;
  213763. case kAsioLatenciesChanged:
  213764. return 1;
  213765. case kAsioEngineVersion:
  213766. return 2;
  213767. case kAsioSupportsTimeInfo:
  213768. case kAsioSupportsTimeCode:
  213769. return 0;
  213770. }
  213771. return 0;
  213772. }
  213773. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  213774. {
  213775. }
  213776. static void convertInt16ToFloat (const char* src,
  213777. float* dest,
  213778. const int srcStrideBytes,
  213779. int numSamples,
  213780. const bool littleEndian) throw()
  213781. {
  213782. const double g = 1.0 / 32768.0;
  213783. if (littleEndian)
  213784. {
  213785. while (--numSamples >= 0)
  213786. {
  213787. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213788. src += srcStrideBytes;
  213789. }
  213790. }
  213791. else
  213792. {
  213793. while (--numSamples >= 0)
  213794. {
  213795. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213796. src += srcStrideBytes;
  213797. }
  213798. }
  213799. }
  213800. static void convertFloatToInt16 (const float* src,
  213801. char* dest,
  213802. const int dstStrideBytes,
  213803. int numSamples,
  213804. const bool littleEndian) throw()
  213805. {
  213806. const double maxVal = (double) 0x7fff;
  213807. if (littleEndian)
  213808. {
  213809. while (--numSamples >= 0)
  213810. {
  213811. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213812. dest += dstStrideBytes;
  213813. }
  213814. }
  213815. else
  213816. {
  213817. while (--numSamples >= 0)
  213818. {
  213819. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213820. dest += dstStrideBytes;
  213821. }
  213822. }
  213823. }
  213824. static void convertInt24ToFloat (const char* src,
  213825. float* dest,
  213826. const int srcStrideBytes,
  213827. int numSamples,
  213828. const bool littleEndian) throw()
  213829. {
  213830. const double g = 1.0 / 0x7fffff;
  213831. if (littleEndian)
  213832. {
  213833. while (--numSamples >= 0)
  213834. {
  213835. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213836. src += srcStrideBytes;
  213837. }
  213838. }
  213839. else
  213840. {
  213841. while (--numSamples >= 0)
  213842. {
  213843. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213844. src += srcStrideBytes;
  213845. }
  213846. }
  213847. }
  213848. static void convertFloatToInt24 (const float* src,
  213849. char* dest,
  213850. const int dstStrideBytes,
  213851. int numSamples,
  213852. const bool littleEndian) throw()
  213853. {
  213854. const double maxVal = (double) 0x7fffff;
  213855. if (littleEndian)
  213856. {
  213857. while (--numSamples >= 0)
  213858. {
  213859. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213860. dest += dstStrideBytes;
  213861. }
  213862. }
  213863. else
  213864. {
  213865. while (--numSamples >= 0)
  213866. {
  213867. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213868. dest += dstStrideBytes;
  213869. }
  213870. }
  213871. }
  213872. static void convertInt32ToFloat (const char* src,
  213873. float* dest,
  213874. const int srcStrideBytes,
  213875. int numSamples,
  213876. const bool littleEndian) throw()
  213877. {
  213878. const double g = 1.0 / 0x7fffffff;
  213879. if (littleEndian)
  213880. {
  213881. while (--numSamples >= 0)
  213882. {
  213883. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213884. src += srcStrideBytes;
  213885. }
  213886. }
  213887. else
  213888. {
  213889. while (--numSamples >= 0)
  213890. {
  213891. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213892. src += srcStrideBytes;
  213893. }
  213894. }
  213895. }
  213896. static void convertFloatToInt32 (const float* src,
  213897. char* dest,
  213898. const int dstStrideBytes,
  213899. int numSamples,
  213900. const bool littleEndian) throw()
  213901. {
  213902. const double maxVal = (double) 0x7fffffff;
  213903. if (littleEndian)
  213904. {
  213905. while (--numSamples >= 0)
  213906. {
  213907. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213908. dest += dstStrideBytes;
  213909. }
  213910. }
  213911. else
  213912. {
  213913. while (--numSamples >= 0)
  213914. {
  213915. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213916. dest += dstStrideBytes;
  213917. }
  213918. }
  213919. }
  213920. static void typeToFormatParameters (const long type,
  213921. int& bitDepth,
  213922. int& byteStride,
  213923. bool& formatIsFloat,
  213924. bool& littleEndian) throw()
  213925. {
  213926. bitDepth = 0;
  213927. littleEndian = false;
  213928. formatIsFloat = false;
  213929. switch (type)
  213930. {
  213931. case ASIOSTInt16MSB:
  213932. case ASIOSTInt16LSB:
  213933. case ASIOSTInt32MSB16:
  213934. case ASIOSTInt32LSB16:
  213935. bitDepth = 16; break;
  213936. case ASIOSTFloat32MSB:
  213937. case ASIOSTFloat32LSB:
  213938. formatIsFloat = true;
  213939. bitDepth = 32; break;
  213940. case ASIOSTInt32MSB:
  213941. case ASIOSTInt32LSB:
  213942. bitDepth = 32; break;
  213943. case ASIOSTInt24MSB:
  213944. case ASIOSTInt24LSB:
  213945. case ASIOSTInt32MSB24:
  213946. case ASIOSTInt32LSB24:
  213947. case ASIOSTInt32MSB18:
  213948. case ASIOSTInt32MSB20:
  213949. case ASIOSTInt32LSB18:
  213950. case ASIOSTInt32LSB20:
  213951. bitDepth = 24; break;
  213952. case ASIOSTFloat64MSB:
  213953. case ASIOSTFloat64LSB:
  213954. default:
  213955. bitDepth = 64;
  213956. break;
  213957. }
  213958. switch (type)
  213959. {
  213960. case ASIOSTInt16MSB:
  213961. case ASIOSTInt32MSB16:
  213962. case ASIOSTFloat32MSB:
  213963. case ASIOSTFloat64MSB:
  213964. case ASIOSTInt32MSB:
  213965. case ASIOSTInt32MSB18:
  213966. case ASIOSTInt32MSB20:
  213967. case ASIOSTInt32MSB24:
  213968. case ASIOSTInt24MSB:
  213969. littleEndian = false; break;
  213970. case ASIOSTInt16LSB:
  213971. case ASIOSTInt32LSB16:
  213972. case ASIOSTFloat32LSB:
  213973. case ASIOSTFloat64LSB:
  213974. case ASIOSTInt32LSB:
  213975. case ASIOSTInt32LSB18:
  213976. case ASIOSTInt32LSB20:
  213977. case ASIOSTInt32LSB24:
  213978. case ASIOSTInt24LSB:
  213979. littleEndian = true; break;
  213980. default:
  213981. break;
  213982. }
  213983. switch (type)
  213984. {
  213985. case ASIOSTInt16LSB:
  213986. case ASIOSTInt16MSB:
  213987. byteStride = 2; break;
  213988. case ASIOSTInt24LSB:
  213989. case ASIOSTInt24MSB:
  213990. byteStride = 3; break;
  213991. case ASIOSTInt32MSB16:
  213992. case ASIOSTInt32LSB16:
  213993. case ASIOSTInt32MSB:
  213994. case ASIOSTInt32MSB18:
  213995. case ASIOSTInt32MSB20:
  213996. case ASIOSTInt32MSB24:
  213997. case ASIOSTInt32LSB:
  213998. case ASIOSTInt32LSB18:
  213999. case ASIOSTInt32LSB20:
  214000. case ASIOSTInt32LSB24:
  214001. case ASIOSTFloat32LSB:
  214002. case ASIOSTFloat32MSB:
  214003. byteStride = 4; break;
  214004. case ASIOSTFloat64MSB:
  214005. case ASIOSTFloat64LSB:
  214006. byteStride = 8; break;
  214007. default:
  214008. break;
  214009. }
  214010. }
  214011. };
  214012. class ASIOAudioIODeviceType : public AudioIODeviceType
  214013. {
  214014. public:
  214015. ASIOAudioIODeviceType()
  214016. : AudioIODeviceType ("ASIO"),
  214017. hasScanned (false)
  214018. {
  214019. CoInitialize (0);
  214020. }
  214021. ~ASIOAudioIODeviceType()
  214022. {
  214023. }
  214024. void scanForDevices()
  214025. {
  214026. hasScanned = true;
  214027. deviceNames.clear();
  214028. classIds.clear();
  214029. HKEY hk = 0;
  214030. int index = 0;
  214031. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214032. {
  214033. for (;;)
  214034. {
  214035. char name [256];
  214036. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214037. {
  214038. addDriverInfo (name, hk);
  214039. }
  214040. else
  214041. {
  214042. break;
  214043. }
  214044. }
  214045. RegCloseKey (hk);
  214046. }
  214047. }
  214048. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214049. {
  214050. jassert (hasScanned); // need to call scanForDevices() before doing this
  214051. return deviceNames;
  214052. }
  214053. int getDefaultDeviceIndex (bool) const
  214054. {
  214055. jassert (hasScanned); // need to call scanForDevices() before doing this
  214056. for (int i = deviceNames.size(); --i >= 0;)
  214057. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214058. return i; // asio4all is a safe choice for a default..
  214059. #if JUCE_DEBUG
  214060. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214061. return 1; // (the digi m-box driver crashes the app when you run
  214062. // it in the debugger, which can be a bit annoying)
  214063. #endif
  214064. return 0;
  214065. }
  214066. static int findFreeSlot()
  214067. {
  214068. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214069. if (currentASIODev[i] == 0)
  214070. return i;
  214071. jassertfalse; // unfortunately you can only have a finite number
  214072. // of ASIO devices open at the same time..
  214073. return -1;
  214074. }
  214075. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214076. {
  214077. jassert (hasScanned); // need to call scanForDevices() before doing this
  214078. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214079. }
  214080. bool hasSeparateInputsAndOutputs() const { return false; }
  214081. AudioIODevice* createDevice (const String& outputDeviceName,
  214082. const String& inputDeviceName)
  214083. {
  214084. // ASIO can't open two different devices for input and output - they must be the same one.
  214085. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214086. jassert (hasScanned); // need to call scanForDevices() before doing this
  214087. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214088. : inputDeviceName);
  214089. if (index >= 0)
  214090. {
  214091. const int freeSlot = findFreeSlot();
  214092. if (freeSlot >= 0)
  214093. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214094. }
  214095. return 0;
  214096. }
  214097. juce_UseDebuggingNewOperator
  214098. private:
  214099. StringArray deviceNames;
  214100. OwnedArray <CLSID> classIds;
  214101. bool hasScanned;
  214102. static bool checkClassIsOk (const String& classId)
  214103. {
  214104. HKEY hk = 0;
  214105. bool ok = false;
  214106. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214107. {
  214108. int index = 0;
  214109. for (;;)
  214110. {
  214111. WCHAR buf [512];
  214112. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214113. {
  214114. if (classId.equalsIgnoreCase (buf))
  214115. {
  214116. HKEY subKey, pathKey;
  214117. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214118. {
  214119. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214120. {
  214121. WCHAR pathName [1024];
  214122. DWORD dtype = REG_SZ;
  214123. DWORD dsize = sizeof (pathName);
  214124. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214125. ok = File (pathName).exists();
  214126. RegCloseKey (pathKey);
  214127. }
  214128. RegCloseKey (subKey);
  214129. }
  214130. break;
  214131. }
  214132. }
  214133. else
  214134. {
  214135. break;
  214136. }
  214137. }
  214138. RegCloseKey (hk);
  214139. }
  214140. return ok;
  214141. }
  214142. void addDriverInfo (const String& keyName, HKEY hk)
  214143. {
  214144. HKEY subKey;
  214145. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214146. {
  214147. WCHAR buf [256];
  214148. zerostruct (buf);
  214149. DWORD dtype = REG_SZ;
  214150. DWORD dsize = sizeof (buf);
  214151. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214152. {
  214153. if (dsize > 0 && checkClassIsOk (buf))
  214154. {
  214155. CLSID classId;
  214156. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214157. {
  214158. dtype = REG_SZ;
  214159. dsize = sizeof (buf);
  214160. String deviceName;
  214161. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214162. deviceName = buf;
  214163. else
  214164. deviceName = keyName;
  214165. log ("found " + deviceName);
  214166. deviceNames.add (deviceName);
  214167. classIds.add (new CLSID (classId));
  214168. }
  214169. }
  214170. RegCloseKey (subKey);
  214171. }
  214172. }
  214173. }
  214174. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214175. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214176. };
  214177. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214178. {
  214179. return new ASIOAudioIODeviceType();
  214180. }
  214181. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214182. void* guid,
  214183. const String& optionalDllForDirectLoading)
  214184. {
  214185. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214186. if (freeSlot < 0)
  214187. return 0;
  214188. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214189. }
  214190. #undef log
  214191. #endif
  214192. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214193. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214194. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214195. // compiled on its own).
  214196. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214197. END_JUCE_NAMESPACE
  214198. extern "C"
  214199. {
  214200. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214201. typedef struct typeDSBUFFERDESC
  214202. {
  214203. DWORD dwSize;
  214204. DWORD dwFlags;
  214205. DWORD dwBufferBytes;
  214206. DWORD dwReserved;
  214207. LPWAVEFORMATEX lpwfxFormat;
  214208. GUID guid3DAlgorithm;
  214209. } DSBUFFERDESC;
  214210. struct IDirectSoundBuffer;
  214211. #undef INTERFACE
  214212. #define INTERFACE IDirectSound
  214213. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214214. {
  214215. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214216. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214217. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214218. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214219. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214220. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214221. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214222. STDMETHOD(Compact) (THIS) PURE;
  214223. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214224. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214225. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214226. };
  214227. #undef INTERFACE
  214228. #define INTERFACE IDirectSoundBuffer
  214229. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214230. {
  214231. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214232. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214233. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214234. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214235. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214236. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214237. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214238. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214239. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214240. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214241. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214242. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214243. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214244. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214245. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214246. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214247. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214248. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214249. STDMETHOD(Stop) (THIS) PURE;
  214250. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214251. STDMETHOD(Restore) (THIS) PURE;
  214252. };
  214253. typedef struct typeDSCBUFFERDESC
  214254. {
  214255. DWORD dwSize;
  214256. DWORD dwFlags;
  214257. DWORD dwBufferBytes;
  214258. DWORD dwReserved;
  214259. LPWAVEFORMATEX lpwfxFormat;
  214260. } DSCBUFFERDESC;
  214261. struct IDirectSoundCaptureBuffer;
  214262. #undef INTERFACE
  214263. #define INTERFACE IDirectSoundCapture
  214264. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214265. {
  214266. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214267. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214268. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214269. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214270. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214271. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214272. };
  214273. #undef INTERFACE
  214274. #define INTERFACE IDirectSoundCaptureBuffer
  214275. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214276. {
  214277. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214278. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214279. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214280. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214281. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214282. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214283. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214284. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214285. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214286. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214287. STDMETHOD(Stop) (THIS) PURE;
  214288. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214289. };
  214290. };
  214291. BEGIN_JUCE_NAMESPACE
  214292. static const String getDSErrorMessage (HRESULT hr)
  214293. {
  214294. const char* result = 0;
  214295. switch (hr)
  214296. {
  214297. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214298. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214299. case E_INVALIDARG: result = "Invalid parameter"; break;
  214300. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214301. case E_FAIL: result = "Generic error"; break;
  214302. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214303. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214304. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214305. case E_NOTIMPL: result = "Unsupported function"; break;
  214306. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214307. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214308. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214309. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214310. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214311. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214312. case E_NOINTERFACE: result = "No interface"; break;
  214313. case S_OK: result = "No error"; break;
  214314. default: return "Unknown error: " + String ((int) hr);
  214315. }
  214316. return result;
  214317. }
  214318. #define DS_DEBUGGING 1
  214319. #ifdef DS_DEBUGGING
  214320. #define CATCH JUCE_CATCH_EXCEPTION
  214321. #undef log
  214322. #define log(a) Logger::writeToLog(a);
  214323. #undef logError
  214324. #define logError(a) logDSError(a, __LINE__);
  214325. static void logDSError (HRESULT hr, int lineNum)
  214326. {
  214327. if (hr != S_OK)
  214328. {
  214329. String error ("DS error at line ");
  214330. error << lineNum << " - " << getDSErrorMessage (hr);
  214331. log (error);
  214332. }
  214333. }
  214334. #else
  214335. #define CATCH JUCE_CATCH_ALL
  214336. #define log(a)
  214337. #define logError(a)
  214338. #endif
  214339. #define DSOUND_FUNCTION(functionName, params) \
  214340. typedef HRESULT (WINAPI *type##functionName) params; \
  214341. static type##functionName ds##functionName = 0;
  214342. #define DSOUND_FUNCTION_LOAD(functionName) \
  214343. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214344. jassert (ds##functionName != 0);
  214345. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214346. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214347. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214348. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214349. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214350. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214351. static void initialiseDSoundFunctions()
  214352. {
  214353. if (dsDirectSoundCreate == 0)
  214354. {
  214355. HMODULE h = LoadLibraryA ("dsound.dll");
  214356. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214357. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214358. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214359. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214360. }
  214361. }
  214362. class DSoundInternalOutChannel
  214363. {
  214364. String name;
  214365. LPGUID guid;
  214366. int sampleRate, bufferSizeSamples;
  214367. float* leftBuffer;
  214368. float* rightBuffer;
  214369. IDirectSound* pDirectSound;
  214370. IDirectSoundBuffer* pOutputBuffer;
  214371. DWORD writeOffset;
  214372. int totalBytesPerBuffer;
  214373. int bytesPerBuffer;
  214374. unsigned int lastPlayCursor;
  214375. public:
  214376. int bitDepth;
  214377. bool doneFlag;
  214378. DSoundInternalOutChannel (const String& name_,
  214379. LPGUID guid_,
  214380. int rate,
  214381. int bufferSize,
  214382. float* left,
  214383. float* right)
  214384. : name (name_),
  214385. guid (guid_),
  214386. sampleRate (rate),
  214387. bufferSizeSamples (bufferSize),
  214388. leftBuffer (left),
  214389. rightBuffer (right),
  214390. pDirectSound (0),
  214391. pOutputBuffer (0),
  214392. bitDepth (16)
  214393. {
  214394. }
  214395. ~DSoundInternalOutChannel()
  214396. {
  214397. close();
  214398. }
  214399. void close()
  214400. {
  214401. HRESULT hr;
  214402. if (pOutputBuffer != 0)
  214403. {
  214404. JUCE_TRY
  214405. {
  214406. log ("closing dsound out: " + name);
  214407. hr = pOutputBuffer->Stop();
  214408. logError (hr);
  214409. }
  214410. CATCH
  214411. JUCE_TRY
  214412. {
  214413. hr = pOutputBuffer->Release();
  214414. logError (hr);
  214415. }
  214416. CATCH
  214417. pOutputBuffer = 0;
  214418. }
  214419. if (pDirectSound != 0)
  214420. {
  214421. JUCE_TRY
  214422. {
  214423. hr = pDirectSound->Release();
  214424. logError (hr);
  214425. }
  214426. CATCH
  214427. pDirectSound = 0;
  214428. }
  214429. }
  214430. const String open()
  214431. {
  214432. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214433. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214434. pDirectSound = 0;
  214435. pOutputBuffer = 0;
  214436. writeOffset = 0;
  214437. String error;
  214438. HRESULT hr = E_NOINTERFACE;
  214439. if (dsDirectSoundCreate != 0)
  214440. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214441. if (hr == S_OK)
  214442. {
  214443. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214444. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214445. const int numChannels = 2;
  214446. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214447. logError (hr);
  214448. if (hr == S_OK)
  214449. {
  214450. IDirectSoundBuffer* pPrimaryBuffer;
  214451. DSBUFFERDESC primaryDesc;
  214452. zerostruct (primaryDesc);
  214453. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214454. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214455. primaryDesc.dwBufferBytes = 0;
  214456. primaryDesc.lpwfxFormat = 0;
  214457. log ("opening dsound out step 2");
  214458. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214459. logError (hr);
  214460. if (hr == S_OK)
  214461. {
  214462. WAVEFORMATEX wfFormat;
  214463. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214464. wfFormat.nChannels = (unsigned short) numChannels;
  214465. wfFormat.nSamplesPerSec = sampleRate;
  214466. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214467. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214468. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214469. wfFormat.cbSize = 0;
  214470. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214471. logError (hr);
  214472. if (hr == S_OK)
  214473. {
  214474. DSBUFFERDESC secondaryDesc;
  214475. zerostruct (secondaryDesc);
  214476. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214477. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214478. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214479. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214480. secondaryDesc.lpwfxFormat = &wfFormat;
  214481. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214482. logError (hr);
  214483. if (hr == S_OK)
  214484. {
  214485. log ("opening dsound out step 3");
  214486. DWORD dwDataLen;
  214487. unsigned char* pDSBuffData;
  214488. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214489. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214490. logError (hr);
  214491. if (hr == S_OK)
  214492. {
  214493. zeromem (pDSBuffData, dwDataLen);
  214494. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214495. if (hr == S_OK)
  214496. {
  214497. hr = pOutputBuffer->SetCurrentPosition (0);
  214498. if (hr == S_OK)
  214499. {
  214500. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214501. if (hr == S_OK)
  214502. return String::empty;
  214503. }
  214504. }
  214505. }
  214506. }
  214507. }
  214508. }
  214509. }
  214510. }
  214511. error = getDSErrorMessage (hr);
  214512. close();
  214513. return error;
  214514. }
  214515. void synchronisePosition()
  214516. {
  214517. if (pOutputBuffer != 0)
  214518. {
  214519. DWORD playCursor;
  214520. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214521. }
  214522. }
  214523. bool service()
  214524. {
  214525. if (pOutputBuffer == 0)
  214526. return true;
  214527. DWORD playCursor, writeCursor;
  214528. for (;;)
  214529. {
  214530. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214531. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214532. {
  214533. pOutputBuffer->Restore();
  214534. continue;
  214535. }
  214536. if (hr == S_OK)
  214537. break;
  214538. logError (hr);
  214539. jassertfalse;
  214540. return true;
  214541. }
  214542. int playWriteGap = writeCursor - playCursor;
  214543. if (playWriteGap < 0)
  214544. playWriteGap += totalBytesPerBuffer;
  214545. int bytesEmpty = playCursor - writeOffset;
  214546. if (bytesEmpty < 0)
  214547. bytesEmpty += totalBytesPerBuffer;
  214548. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214549. {
  214550. writeOffset = writeCursor;
  214551. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214552. }
  214553. if (bytesEmpty >= bytesPerBuffer)
  214554. {
  214555. LPBYTE lpbuf1 = 0;
  214556. LPBYTE lpbuf2 = 0;
  214557. DWORD dwSize1 = 0;
  214558. DWORD dwSize2 = 0;
  214559. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214560. bytesPerBuffer,
  214561. (void**) &lpbuf1, &dwSize1,
  214562. (void**) &lpbuf2, &dwSize2, 0);
  214563. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214564. {
  214565. pOutputBuffer->Restore();
  214566. hr = pOutputBuffer->Lock (writeOffset,
  214567. bytesPerBuffer,
  214568. (void**) &lpbuf1, &dwSize1,
  214569. (void**) &lpbuf2, &dwSize2, 0);
  214570. }
  214571. if (hr == S_OK)
  214572. {
  214573. if (bitDepth == 16)
  214574. {
  214575. const float gainL = 32767.0f;
  214576. const float gainR = 32767.0f;
  214577. int* dest = (int*)lpbuf1;
  214578. const float* left = leftBuffer;
  214579. const float* right = rightBuffer;
  214580. int samples1 = dwSize1 >> 2;
  214581. int samples2 = dwSize2 >> 2;
  214582. if (left == 0)
  214583. {
  214584. while (--samples1 >= 0)
  214585. {
  214586. int r = roundToInt (gainR * *right++);
  214587. if (r < -32768)
  214588. r = -32768;
  214589. else if (r > 32767)
  214590. r = 32767;
  214591. *dest++ = (r << 16);
  214592. }
  214593. dest = (int*)lpbuf2;
  214594. while (--samples2 >= 0)
  214595. {
  214596. int r = roundToInt (gainR * *right++);
  214597. if (r < -32768)
  214598. r = -32768;
  214599. else if (r > 32767)
  214600. r = 32767;
  214601. *dest++ = (r << 16);
  214602. }
  214603. }
  214604. else if (right == 0)
  214605. {
  214606. while (--samples1 >= 0)
  214607. {
  214608. int l = roundToInt (gainL * *left++);
  214609. if (l < -32768)
  214610. l = -32768;
  214611. else if (l > 32767)
  214612. l = 32767;
  214613. l &= 0xffff;
  214614. *dest++ = l;
  214615. }
  214616. dest = (int*)lpbuf2;
  214617. while (--samples2 >= 0)
  214618. {
  214619. int l = roundToInt (gainL * *left++);
  214620. if (l < -32768)
  214621. l = -32768;
  214622. else if (l > 32767)
  214623. l = 32767;
  214624. l &= 0xffff;
  214625. *dest++ = l;
  214626. }
  214627. }
  214628. else
  214629. {
  214630. while (--samples1 >= 0)
  214631. {
  214632. int l = roundToInt (gainL * *left++);
  214633. if (l < -32768)
  214634. l = -32768;
  214635. else if (l > 32767)
  214636. l = 32767;
  214637. l &= 0xffff;
  214638. int r = roundToInt (gainR * *right++);
  214639. if (r < -32768)
  214640. r = -32768;
  214641. else if (r > 32767)
  214642. r = 32767;
  214643. *dest++ = (r << 16) | l;
  214644. }
  214645. dest = (int*)lpbuf2;
  214646. while (--samples2 >= 0)
  214647. {
  214648. int l = roundToInt (gainL * *left++);
  214649. if (l < -32768)
  214650. l = -32768;
  214651. else if (l > 32767)
  214652. l = 32767;
  214653. l &= 0xffff;
  214654. int r = roundToInt (gainR * *right++);
  214655. if (r < -32768)
  214656. r = -32768;
  214657. else if (r > 32767)
  214658. r = 32767;
  214659. *dest++ = (r << 16) | l;
  214660. }
  214661. }
  214662. }
  214663. else
  214664. {
  214665. jassertfalse;
  214666. }
  214667. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214668. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214669. }
  214670. else
  214671. {
  214672. jassertfalse;
  214673. logError (hr);
  214674. }
  214675. bytesEmpty -= bytesPerBuffer;
  214676. return true;
  214677. }
  214678. else
  214679. {
  214680. return false;
  214681. }
  214682. }
  214683. };
  214684. struct DSoundInternalInChannel
  214685. {
  214686. String name;
  214687. LPGUID guid;
  214688. int sampleRate, bufferSizeSamples;
  214689. float* leftBuffer;
  214690. float* rightBuffer;
  214691. IDirectSound* pDirectSound;
  214692. IDirectSoundCapture* pDirectSoundCapture;
  214693. IDirectSoundCaptureBuffer* pInputBuffer;
  214694. public:
  214695. unsigned int readOffset;
  214696. int bytesPerBuffer, totalBytesPerBuffer;
  214697. int bitDepth;
  214698. bool doneFlag;
  214699. DSoundInternalInChannel (const String& name_,
  214700. LPGUID guid_,
  214701. int rate,
  214702. int bufferSize,
  214703. float* left,
  214704. float* right)
  214705. : name (name_),
  214706. guid (guid_),
  214707. sampleRate (rate),
  214708. bufferSizeSamples (bufferSize),
  214709. leftBuffer (left),
  214710. rightBuffer (right),
  214711. pDirectSound (0),
  214712. pDirectSoundCapture (0),
  214713. pInputBuffer (0),
  214714. bitDepth (16)
  214715. {
  214716. }
  214717. ~DSoundInternalInChannel()
  214718. {
  214719. close();
  214720. }
  214721. void close()
  214722. {
  214723. HRESULT hr;
  214724. if (pInputBuffer != 0)
  214725. {
  214726. JUCE_TRY
  214727. {
  214728. log ("closing dsound in: " + name);
  214729. hr = pInputBuffer->Stop();
  214730. logError (hr);
  214731. }
  214732. CATCH
  214733. JUCE_TRY
  214734. {
  214735. hr = pInputBuffer->Release();
  214736. logError (hr);
  214737. }
  214738. CATCH
  214739. pInputBuffer = 0;
  214740. }
  214741. if (pDirectSoundCapture != 0)
  214742. {
  214743. JUCE_TRY
  214744. {
  214745. hr = pDirectSoundCapture->Release();
  214746. logError (hr);
  214747. }
  214748. CATCH
  214749. pDirectSoundCapture = 0;
  214750. }
  214751. if (pDirectSound != 0)
  214752. {
  214753. JUCE_TRY
  214754. {
  214755. hr = pDirectSound->Release();
  214756. logError (hr);
  214757. }
  214758. CATCH
  214759. pDirectSound = 0;
  214760. }
  214761. }
  214762. const String open()
  214763. {
  214764. log ("opening dsound in device: " + name
  214765. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214766. pDirectSound = 0;
  214767. pDirectSoundCapture = 0;
  214768. pInputBuffer = 0;
  214769. readOffset = 0;
  214770. totalBytesPerBuffer = 0;
  214771. String error;
  214772. HRESULT hr = E_NOINTERFACE;
  214773. if (dsDirectSoundCaptureCreate != 0)
  214774. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214775. logError (hr);
  214776. if (hr == S_OK)
  214777. {
  214778. const int numChannels = 2;
  214779. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214780. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214781. WAVEFORMATEX wfFormat;
  214782. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214783. wfFormat.nChannels = (unsigned short)numChannels;
  214784. wfFormat.nSamplesPerSec = sampleRate;
  214785. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214786. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214787. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214788. wfFormat.cbSize = 0;
  214789. DSCBUFFERDESC captureDesc;
  214790. zerostruct (captureDesc);
  214791. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214792. captureDesc.dwFlags = 0;
  214793. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214794. captureDesc.lpwfxFormat = &wfFormat;
  214795. log ("opening dsound in step 2");
  214796. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214797. logError (hr);
  214798. if (hr == S_OK)
  214799. {
  214800. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214801. logError (hr);
  214802. if (hr == S_OK)
  214803. return String::empty;
  214804. }
  214805. }
  214806. error = getDSErrorMessage (hr);
  214807. close();
  214808. return error;
  214809. }
  214810. void synchronisePosition()
  214811. {
  214812. if (pInputBuffer != 0)
  214813. {
  214814. DWORD capturePos;
  214815. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214816. }
  214817. }
  214818. bool service()
  214819. {
  214820. if (pInputBuffer == 0)
  214821. return true;
  214822. DWORD capturePos, readPos;
  214823. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214824. logError (hr);
  214825. if (hr != S_OK)
  214826. return true;
  214827. int bytesFilled = readPos - readOffset;
  214828. if (bytesFilled < 0)
  214829. bytesFilled += totalBytesPerBuffer;
  214830. if (bytesFilled >= bytesPerBuffer)
  214831. {
  214832. LPBYTE lpbuf1 = 0;
  214833. LPBYTE lpbuf2 = 0;
  214834. DWORD dwsize1 = 0;
  214835. DWORD dwsize2 = 0;
  214836. HRESULT hr = pInputBuffer->Lock (readOffset,
  214837. bytesPerBuffer,
  214838. (void**) &lpbuf1, &dwsize1,
  214839. (void**) &lpbuf2, &dwsize2, 0);
  214840. if (hr == S_OK)
  214841. {
  214842. if (bitDepth == 16)
  214843. {
  214844. const float g = 1.0f / 32768.0f;
  214845. float* destL = leftBuffer;
  214846. float* destR = rightBuffer;
  214847. int samples1 = dwsize1 >> 2;
  214848. int samples2 = dwsize2 >> 2;
  214849. const short* src = (const short*)lpbuf1;
  214850. if (destL == 0)
  214851. {
  214852. while (--samples1 >= 0)
  214853. {
  214854. ++src;
  214855. *destR++ = *src++ * g;
  214856. }
  214857. src = (const short*)lpbuf2;
  214858. while (--samples2 >= 0)
  214859. {
  214860. ++src;
  214861. *destR++ = *src++ * g;
  214862. }
  214863. }
  214864. else if (destR == 0)
  214865. {
  214866. while (--samples1 >= 0)
  214867. {
  214868. *destL++ = *src++ * g;
  214869. ++src;
  214870. }
  214871. src = (const short*)lpbuf2;
  214872. while (--samples2 >= 0)
  214873. {
  214874. *destL++ = *src++ * g;
  214875. ++src;
  214876. }
  214877. }
  214878. else
  214879. {
  214880. while (--samples1 >= 0)
  214881. {
  214882. *destL++ = *src++ * g;
  214883. *destR++ = *src++ * g;
  214884. }
  214885. src = (const short*)lpbuf2;
  214886. while (--samples2 >= 0)
  214887. {
  214888. *destL++ = *src++ * g;
  214889. *destR++ = *src++ * g;
  214890. }
  214891. }
  214892. }
  214893. else
  214894. {
  214895. jassertfalse;
  214896. }
  214897. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214898. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214899. }
  214900. else
  214901. {
  214902. logError (hr);
  214903. jassertfalse;
  214904. }
  214905. bytesFilled -= bytesPerBuffer;
  214906. return true;
  214907. }
  214908. else
  214909. {
  214910. return false;
  214911. }
  214912. }
  214913. };
  214914. class DSoundAudioIODevice : public AudioIODevice,
  214915. public Thread
  214916. {
  214917. public:
  214918. DSoundAudioIODevice (const String& deviceName,
  214919. const int outputDeviceIndex_,
  214920. const int inputDeviceIndex_)
  214921. : AudioIODevice (deviceName, "DirectSound"),
  214922. Thread ("Juce DSound"),
  214923. isOpen_ (false),
  214924. isStarted (false),
  214925. outputDeviceIndex (outputDeviceIndex_),
  214926. inputDeviceIndex (inputDeviceIndex_),
  214927. totalSamplesOut (0),
  214928. sampleRate (0.0),
  214929. inputBuffers (1, 1),
  214930. outputBuffers (1, 1),
  214931. callback (0),
  214932. bufferSizeSamples (0)
  214933. {
  214934. if (outputDeviceIndex_ >= 0)
  214935. {
  214936. outChannels.add (TRANS("Left"));
  214937. outChannels.add (TRANS("Right"));
  214938. }
  214939. if (inputDeviceIndex_ >= 0)
  214940. {
  214941. inChannels.add (TRANS("Left"));
  214942. inChannels.add (TRANS("Right"));
  214943. }
  214944. }
  214945. ~DSoundAudioIODevice()
  214946. {
  214947. close();
  214948. }
  214949. const StringArray getOutputChannelNames()
  214950. {
  214951. return outChannels;
  214952. }
  214953. const StringArray getInputChannelNames()
  214954. {
  214955. return inChannels;
  214956. }
  214957. int getNumSampleRates()
  214958. {
  214959. return 4;
  214960. }
  214961. double getSampleRate (int index)
  214962. {
  214963. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214964. return samps [jlimit (0, 3, index)];
  214965. }
  214966. int getNumBufferSizesAvailable()
  214967. {
  214968. return 50;
  214969. }
  214970. int getBufferSizeSamples (int index)
  214971. {
  214972. int n = 64;
  214973. for (int i = 0; i < index; ++i)
  214974. n += (n < 512) ? 32
  214975. : ((n < 1024) ? 64
  214976. : ((n < 2048) ? 128 : 256));
  214977. return n;
  214978. }
  214979. int getDefaultBufferSize()
  214980. {
  214981. return 2560;
  214982. }
  214983. const String open (const BigInteger& inputChannels,
  214984. const BigInteger& outputChannels,
  214985. double sampleRate,
  214986. int bufferSizeSamples)
  214987. {
  214988. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214989. isOpen_ = lastError.isEmpty();
  214990. return lastError;
  214991. }
  214992. void close()
  214993. {
  214994. stop();
  214995. if (isOpen_)
  214996. {
  214997. closeDevice();
  214998. isOpen_ = false;
  214999. }
  215000. }
  215001. bool isOpen()
  215002. {
  215003. return isOpen_ && isThreadRunning();
  215004. }
  215005. int getCurrentBufferSizeSamples()
  215006. {
  215007. return bufferSizeSamples;
  215008. }
  215009. double getCurrentSampleRate()
  215010. {
  215011. return sampleRate;
  215012. }
  215013. int getCurrentBitDepth()
  215014. {
  215015. int i, bits = 256;
  215016. for (i = inChans.size(); --i >= 0;)
  215017. bits = jmin (bits, inChans[i]->bitDepth);
  215018. for (i = outChans.size(); --i >= 0;)
  215019. bits = jmin (bits, outChans[i]->bitDepth);
  215020. if (bits > 32)
  215021. bits = 16;
  215022. return bits;
  215023. }
  215024. const BigInteger getActiveOutputChannels() const
  215025. {
  215026. return enabledOutputs;
  215027. }
  215028. const BigInteger getActiveInputChannels() const
  215029. {
  215030. return enabledInputs;
  215031. }
  215032. int getOutputLatencyInSamples()
  215033. {
  215034. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215035. }
  215036. int getInputLatencyInSamples()
  215037. {
  215038. return getOutputLatencyInSamples();
  215039. }
  215040. void start (AudioIODeviceCallback* call)
  215041. {
  215042. if (isOpen_ && call != 0 && ! isStarted)
  215043. {
  215044. if (! isThreadRunning())
  215045. {
  215046. // something gone wrong and the thread's stopped..
  215047. isOpen_ = false;
  215048. return;
  215049. }
  215050. call->audioDeviceAboutToStart (this);
  215051. const ScopedLock sl (startStopLock);
  215052. callback = call;
  215053. isStarted = true;
  215054. }
  215055. }
  215056. void stop()
  215057. {
  215058. if (isStarted)
  215059. {
  215060. AudioIODeviceCallback* const callbackLocal = callback;
  215061. {
  215062. const ScopedLock sl (startStopLock);
  215063. isStarted = false;
  215064. }
  215065. if (callbackLocal != 0)
  215066. callbackLocal->audioDeviceStopped();
  215067. }
  215068. }
  215069. bool isPlaying()
  215070. {
  215071. return isStarted && isOpen_ && isThreadRunning();
  215072. }
  215073. const String getLastError()
  215074. {
  215075. return lastError;
  215076. }
  215077. juce_UseDebuggingNewOperator
  215078. StringArray inChannels, outChannels;
  215079. int outputDeviceIndex, inputDeviceIndex;
  215080. private:
  215081. bool isOpen_;
  215082. bool isStarted;
  215083. String lastError;
  215084. OwnedArray <DSoundInternalInChannel> inChans;
  215085. OwnedArray <DSoundInternalOutChannel> outChans;
  215086. WaitableEvent startEvent;
  215087. int bufferSizeSamples;
  215088. int volatile totalSamplesOut;
  215089. int64 volatile lastBlockTime;
  215090. double sampleRate;
  215091. BigInteger enabledInputs, enabledOutputs;
  215092. AudioSampleBuffer inputBuffers, outputBuffers;
  215093. AudioIODeviceCallback* callback;
  215094. CriticalSection startStopLock;
  215095. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215096. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215097. const String openDevice (const BigInteger& inputChannels,
  215098. const BigInteger& outputChannels,
  215099. double sampleRate_,
  215100. int bufferSizeSamples_);
  215101. void closeDevice()
  215102. {
  215103. isStarted = false;
  215104. stopThread (5000);
  215105. inChans.clear();
  215106. outChans.clear();
  215107. inputBuffers.setSize (1, 1);
  215108. outputBuffers.setSize (1, 1);
  215109. }
  215110. void resync()
  215111. {
  215112. if (! threadShouldExit())
  215113. {
  215114. sleep (5);
  215115. int i;
  215116. for (i = 0; i < outChans.size(); ++i)
  215117. outChans.getUnchecked(i)->synchronisePosition();
  215118. for (i = 0; i < inChans.size(); ++i)
  215119. inChans.getUnchecked(i)->synchronisePosition();
  215120. }
  215121. }
  215122. public:
  215123. void run()
  215124. {
  215125. while (! threadShouldExit())
  215126. {
  215127. if (wait (100))
  215128. break;
  215129. }
  215130. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215131. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215132. while (! threadShouldExit())
  215133. {
  215134. int numToDo = 0;
  215135. uint32 startTime = Time::getMillisecondCounter();
  215136. int i;
  215137. for (i = inChans.size(); --i >= 0;)
  215138. {
  215139. inChans.getUnchecked(i)->doneFlag = false;
  215140. ++numToDo;
  215141. }
  215142. for (i = outChans.size(); --i >= 0;)
  215143. {
  215144. outChans.getUnchecked(i)->doneFlag = false;
  215145. ++numToDo;
  215146. }
  215147. if (numToDo > 0)
  215148. {
  215149. const int maxCount = 3;
  215150. int count = maxCount;
  215151. for (;;)
  215152. {
  215153. for (i = inChans.size(); --i >= 0;)
  215154. {
  215155. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215156. if ((! in->doneFlag) && in->service())
  215157. {
  215158. in->doneFlag = true;
  215159. --numToDo;
  215160. }
  215161. }
  215162. for (i = outChans.size(); --i >= 0;)
  215163. {
  215164. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215165. if ((! out->doneFlag) && out->service())
  215166. {
  215167. out->doneFlag = true;
  215168. --numToDo;
  215169. }
  215170. }
  215171. if (numToDo <= 0)
  215172. break;
  215173. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215174. {
  215175. resync();
  215176. break;
  215177. }
  215178. if (--count <= 0)
  215179. {
  215180. Sleep (1);
  215181. count = maxCount;
  215182. }
  215183. if (threadShouldExit())
  215184. return;
  215185. }
  215186. }
  215187. else
  215188. {
  215189. sleep (1);
  215190. }
  215191. const ScopedLock sl (startStopLock);
  215192. if (isStarted)
  215193. {
  215194. JUCE_TRY
  215195. {
  215196. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215197. inputBuffers.getNumChannels(),
  215198. outputBuffers.getArrayOfChannels(),
  215199. outputBuffers.getNumChannels(),
  215200. bufferSizeSamples);
  215201. }
  215202. JUCE_CATCH_EXCEPTION
  215203. totalSamplesOut += bufferSizeSamples;
  215204. }
  215205. else
  215206. {
  215207. outputBuffers.clear();
  215208. totalSamplesOut = 0;
  215209. sleep (1);
  215210. }
  215211. }
  215212. }
  215213. };
  215214. class DSoundAudioIODeviceType : public AudioIODeviceType
  215215. {
  215216. public:
  215217. DSoundAudioIODeviceType()
  215218. : AudioIODeviceType ("DirectSound"),
  215219. hasScanned (false)
  215220. {
  215221. initialiseDSoundFunctions();
  215222. }
  215223. ~DSoundAudioIODeviceType()
  215224. {
  215225. }
  215226. void scanForDevices()
  215227. {
  215228. hasScanned = true;
  215229. outputDeviceNames.clear();
  215230. outputGuids.clear();
  215231. inputDeviceNames.clear();
  215232. inputGuids.clear();
  215233. if (dsDirectSoundEnumerateW != 0)
  215234. {
  215235. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215236. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215237. }
  215238. }
  215239. const StringArray getDeviceNames (bool wantInputNames) const
  215240. {
  215241. jassert (hasScanned); // need to call scanForDevices() before doing this
  215242. return wantInputNames ? inputDeviceNames
  215243. : outputDeviceNames;
  215244. }
  215245. int getDefaultDeviceIndex (bool /*forInput*/) const
  215246. {
  215247. jassert (hasScanned); // need to call scanForDevices() before doing this
  215248. return 0;
  215249. }
  215250. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215251. {
  215252. jassert (hasScanned); // need to call scanForDevices() before doing this
  215253. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215254. if (d == 0)
  215255. return -1;
  215256. return asInput ? d->inputDeviceIndex
  215257. : d->outputDeviceIndex;
  215258. }
  215259. bool hasSeparateInputsAndOutputs() const { return true; }
  215260. AudioIODevice* createDevice (const String& outputDeviceName,
  215261. const String& inputDeviceName)
  215262. {
  215263. jassert (hasScanned); // need to call scanForDevices() before doing this
  215264. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215265. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215266. if (outputIndex >= 0 || inputIndex >= 0)
  215267. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215268. : inputDeviceName,
  215269. outputIndex, inputIndex);
  215270. return 0;
  215271. }
  215272. juce_UseDebuggingNewOperator
  215273. StringArray outputDeviceNames;
  215274. OwnedArray <GUID> outputGuids;
  215275. StringArray inputDeviceNames;
  215276. OwnedArray <GUID> inputGuids;
  215277. private:
  215278. bool hasScanned;
  215279. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215280. {
  215281. desc = desc.trim();
  215282. if (desc.isNotEmpty())
  215283. {
  215284. const String origDesc (desc);
  215285. int n = 2;
  215286. while (outputDeviceNames.contains (desc))
  215287. desc = origDesc + " (" + String (n++) + ")";
  215288. outputDeviceNames.add (desc);
  215289. if (lpGUID != 0)
  215290. outputGuids.add (new GUID (*lpGUID));
  215291. else
  215292. outputGuids.add (0);
  215293. }
  215294. return TRUE;
  215295. }
  215296. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215297. {
  215298. return ((DSoundAudioIODeviceType*) object)
  215299. ->outputEnumProc (lpGUID, String (description));
  215300. }
  215301. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215302. {
  215303. return ((DSoundAudioIODeviceType*) object)
  215304. ->outputEnumProc (lpGUID, String (description));
  215305. }
  215306. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215307. {
  215308. desc = desc.trim();
  215309. if (desc.isNotEmpty())
  215310. {
  215311. const String origDesc (desc);
  215312. int n = 2;
  215313. while (inputDeviceNames.contains (desc))
  215314. desc = origDesc + " (" + String (n++) + ")";
  215315. inputDeviceNames.add (desc);
  215316. if (lpGUID != 0)
  215317. inputGuids.add (new GUID (*lpGUID));
  215318. else
  215319. inputGuids.add (0);
  215320. }
  215321. return TRUE;
  215322. }
  215323. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215324. {
  215325. return ((DSoundAudioIODeviceType*) object)
  215326. ->inputEnumProc (lpGUID, String (description));
  215327. }
  215328. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215329. {
  215330. return ((DSoundAudioIODeviceType*) object)
  215331. ->inputEnumProc (lpGUID, String (description));
  215332. }
  215333. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215334. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215335. };
  215336. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215337. const BigInteger& outputChannels,
  215338. double sampleRate_,
  215339. int bufferSizeSamples_)
  215340. {
  215341. closeDevice();
  215342. totalSamplesOut = 0;
  215343. sampleRate = sampleRate_;
  215344. if (bufferSizeSamples_ <= 0)
  215345. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215346. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215347. DSoundAudioIODeviceType dlh;
  215348. dlh.scanForDevices();
  215349. enabledInputs = inputChannels;
  215350. enabledInputs.setRange (inChannels.size(),
  215351. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215352. false);
  215353. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215354. inputBuffers.clear();
  215355. int i, numIns = 0;
  215356. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215357. {
  215358. float* left = 0;
  215359. if (enabledInputs[i])
  215360. left = inputBuffers.getSampleData (numIns++);
  215361. float* right = 0;
  215362. if (enabledInputs[i + 1])
  215363. right = inputBuffers.getSampleData (numIns++);
  215364. if (left != 0 || right != 0)
  215365. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215366. dlh.inputGuids [inputDeviceIndex],
  215367. (int) sampleRate, bufferSizeSamples,
  215368. left, right));
  215369. }
  215370. enabledOutputs = outputChannels;
  215371. enabledOutputs.setRange (outChannels.size(),
  215372. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215373. false);
  215374. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215375. outputBuffers.clear();
  215376. int numOuts = 0;
  215377. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215378. {
  215379. float* left = 0;
  215380. if (enabledOutputs[i])
  215381. left = outputBuffers.getSampleData (numOuts++);
  215382. float* right = 0;
  215383. if (enabledOutputs[i + 1])
  215384. right = outputBuffers.getSampleData (numOuts++);
  215385. if (left != 0 || right != 0)
  215386. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215387. dlh.outputGuids [outputDeviceIndex],
  215388. (int) sampleRate, bufferSizeSamples,
  215389. left, right));
  215390. }
  215391. String error;
  215392. // boost our priority while opening the devices to try to get better sync between them
  215393. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215394. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215395. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215396. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215397. for (i = 0; i < outChans.size(); ++i)
  215398. {
  215399. error = outChans[i]->open();
  215400. if (error.isNotEmpty())
  215401. {
  215402. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215403. break;
  215404. }
  215405. }
  215406. if (error.isEmpty())
  215407. {
  215408. for (i = 0; i < inChans.size(); ++i)
  215409. {
  215410. error = inChans[i]->open();
  215411. if (error.isNotEmpty())
  215412. {
  215413. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215414. break;
  215415. }
  215416. }
  215417. }
  215418. if (error.isEmpty())
  215419. {
  215420. totalSamplesOut = 0;
  215421. for (i = 0; i < outChans.size(); ++i)
  215422. outChans.getUnchecked(i)->synchronisePosition();
  215423. for (i = 0; i < inChans.size(); ++i)
  215424. inChans.getUnchecked(i)->synchronisePosition();
  215425. startThread (9);
  215426. sleep (10);
  215427. notify();
  215428. }
  215429. else
  215430. {
  215431. log (error);
  215432. }
  215433. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215434. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215435. return error;
  215436. }
  215437. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215438. {
  215439. return new DSoundAudioIODeviceType();
  215440. }
  215441. #undef log
  215442. #endif
  215443. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215444. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215445. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215446. // compiled on its own).
  215447. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215448. #if 1
  215449. const String getAudioErrorDesc (HRESULT hr)
  215450. {
  215451. const char* e = 0;
  215452. switch (hr)
  215453. {
  215454. case E_POINTER: e = "E_POINTER"; break;
  215455. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  215456. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  215457. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215458. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215459. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215460. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  215461. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215462. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  215463. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215464. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  215465. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  215466. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215467. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215468. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215469. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215470. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215471. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215472. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215473. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215474. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215475. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215476. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215477. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  215478. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215479. default: return String::toHexString ((int) hr);
  215480. }
  215481. return e;
  215482. }
  215483. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  215484. #define OK(a) wasapi_checkResult(a)
  215485. static bool wasapi_checkResult (HRESULT hr)
  215486. {
  215487. logFailure (hr);
  215488. return SUCCEEDED (hr);
  215489. }
  215490. #else
  215491. #define logFailure(hr) {}
  215492. #define OK(a) SUCCEEDED(a)
  215493. #endif
  215494. static const String wasapi_getDeviceID (IMMDevice* const device)
  215495. {
  215496. String s;
  215497. WCHAR* deviceId = 0;
  215498. if (OK (device->GetId (&deviceId)))
  215499. {
  215500. s = String (deviceId);
  215501. CoTaskMemFree (deviceId);
  215502. }
  215503. return s;
  215504. }
  215505. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  215506. {
  215507. EDataFlow flow = eRender;
  215508. ComSmartPtr <IMMEndpoint> endPoint;
  215509. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  215510. (void) OK (endPoint->GetDataFlow (&flow));
  215511. return flow;
  215512. }
  215513. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215514. {
  215515. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215516. }
  215517. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215518. {
  215519. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215520. : sizeof (WAVEFORMATEX));
  215521. }
  215522. class WASAPIDeviceBase
  215523. {
  215524. public:
  215525. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215526. : device (device_),
  215527. sampleRate (0),
  215528. numChannels (0),
  215529. actualNumChannels (0),
  215530. defaultSampleRate (0),
  215531. minBufferSize (0),
  215532. defaultBufferSize (0),
  215533. latencySamples (0),
  215534. useExclusiveMode (useExclusiveMode_)
  215535. {
  215536. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215537. ComSmartPtr <IAudioClient> tempClient (createClient());
  215538. if (tempClient == 0)
  215539. return;
  215540. REFERENCE_TIME defaultPeriod, minPeriod;
  215541. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215542. return;
  215543. WAVEFORMATEX* mixFormat = 0;
  215544. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  215545. return;
  215546. WAVEFORMATEXTENSIBLE format;
  215547. wasapi_copyWavFormat (format, mixFormat);
  215548. CoTaskMemFree (mixFormat);
  215549. actualNumChannels = numChannels = format.Format.nChannels;
  215550. defaultSampleRate = format.Format.nSamplesPerSec;
  215551. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  215552. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  215553. rates.addUsingDefaultSort (defaultSampleRate);
  215554. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215555. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215556. {
  215557. if (ratesToTest[i] == defaultSampleRate)
  215558. continue;
  215559. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215560. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215561. (WAVEFORMATEX*) &format, 0)))
  215562. if (! rates.contains (ratesToTest[i]))
  215563. rates.addUsingDefaultSort (ratesToTest[i]);
  215564. }
  215565. }
  215566. ~WASAPIDeviceBase()
  215567. {
  215568. device = 0;
  215569. CloseHandle (clientEvent);
  215570. }
  215571. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215572. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215573. {
  215574. sampleRate = newSampleRate;
  215575. channels = newChannels;
  215576. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215577. numChannels = channels.getHighestBit() + 1;
  215578. if (numChannels == 0)
  215579. return true;
  215580. client = createClient();
  215581. if (client != 0
  215582. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215583. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215584. {
  215585. channelMaps.clear();
  215586. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215587. if (channels[i])
  215588. channelMaps.add (i);
  215589. REFERENCE_TIME latency;
  215590. if (OK (client->GetStreamLatency (&latency)))
  215591. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  215592. (void) OK (client->GetBufferSize (&actualBufferSize));
  215593. return OK (client->SetEventHandle (clientEvent));
  215594. }
  215595. return false;
  215596. }
  215597. void closeClient()
  215598. {
  215599. if (client != 0)
  215600. client->Stop();
  215601. client = 0;
  215602. ResetEvent (clientEvent);
  215603. }
  215604. ComSmartPtr <IMMDevice> device;
  215605. ComSmartPtr <IAudioClient> client;
  215606. double sampleRate, defaultSampleRate;
  215607. int numChannels, actualNumChannels;
  215608. int minBufferSize, defaultBufferSize, latencySamples;
  215609. const bool useExclusiveMode;
  215610. Array <double> rates;
  215611. HANDLE clientEvent;
  215612. BigInteger channels;
  215613. AudioDataConverters::DataFormat dataFormat;
  215614. Array <int> channelMaps;
  215615. UINT32 actualBufferSize;
  215616. int bytesPerSample;
  215617. private:
  215618. const ComSmartPtr <IAudioClient> createClient()
  215619. {
  215620. ComSmartPtr <IAudioClient> client;
  215621. if (device != 0)
  215622. {
  215623. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  215624. logFailure (hr);
  215625. }
  215626. return client;
  215627. }
  215628. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215629. {
  215630. WAVEFORMATEXTENSIBLE format;
  215631. zerostruct (format);
  215632. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215633. {
  215634. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215635. }
  215636. else
  215637. {
  215638. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215639. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215640. }
  215641. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215642. format.Format.nChannels = (WORD) numChannels;
  215643. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215644. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215645. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215646. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215647. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215648. switch (numChannels)
  215649. {
  215650. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215651. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215652. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215653. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215654. 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;
  215655. default: break;
  215656. }
  215657. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215658. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215659. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215660. logFailure (hr);
  215661. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215662. {
  215663. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215664. hr = S_OK;
  215665. }
  215666. CoTaskMemFree (nearestFormat);
  215667. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215668. if (useExclusiveMode)
  215669. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215670. GUID session;
  215671. if (hr == S_OK
  215672. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215673. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215674. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215675. {
  215676. actualNumChannels = format.Format.nChannels;
  215677. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215678. bytesPerSample = format.Format.wBitsPerSample / 8;
  215679. dataFormat = isFloat ? AudioDataConverters::float32LE
  215680. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  215681. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  215682. : AudioDataConverters::int16LE)));
  215683. return true;
  215684. }
  215685. return false;
  215686. }
  215687. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215688. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215689. };
  215690. class WASAPIInputDevice : public WASAPIDeviceBase
  215691. {
  215692. public:
  215693. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215694. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215695. reservoir (1, 1)
  215696. {
  215697. }
  215698. ~WASAPIInputDevice()
  215699. {
  215700. close();
  215701. }
  215702. bool open (const double newSampleRate, const BigInteger& newChannels)
  215703. {
  215704. reservoirSize = 0;
  215705. reservoirCapacity = 16384;
  215706. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215707. return openClient (newSampleRate, newChannels)
  215708. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  215709. }
  215710. void close()
  215711. {
  215712. closeClient();
  215713. captureClient = 0;
  215714. reservoir.setSize (0);
  215715. }
  215716. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215717. {
  215718. if (numChannels <= 0)
  215719. return;
  215720. int offset = 0;
  215721. while (bufferSize > 0)
  215722. {
  215723. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215724. {
  215725. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215726. for (int i = 0; i < numDestBuffers; ++i)
  215727. {
  215728. float* const dest = destBuffers[i] + offset;
  215729. const int srcChan = channelMaps.getUnchecked(i);
  215730. switch (dataFormat)
  215731. {
  215732. case AudioDataConverters::float32LE:
  215733. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215734. break;
  215735. case AudioDataConverters::int32LE:
  215736. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215737. break;
  215738. case AudioDataConverters::int24LE:
  215739. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  215740. break;
  215741. case AudioDataConverters::int16LE:
  215742. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  215743. break;
  215744. default: jassertfalse; break;
  215745. }
  215746. }
  215747. bufferSize -= samplesToDo;
  215748. offset += samplesToDo;
  215749. reservoirSize -= samplesToDo;
  215750. }
  215751. else
  215752. {
  215753. UINT32 packetLength = 0;
  215754. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  215755. break;
  215756. if (packetLength == 0)
  215757. {
  215758. if (thread.threadShouldExit())
  215759. break;
  215760. Thread::sleep (1);
  215761. continue;
  215762. }
  215763. uint8* inputData = 0;
  215764. UINT32 numSamplesAvailable;
  215765. DWORD flags;
  215766. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215767. {
  215768. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215769. for (int i = 0; i < numDestBuffers; ++i)
  215770. {
  215771. float* const dest = destBuffers[i] + offset;
  215772. const int srcChan = channelMaps.getUnchecked(i);
  215773. switch (dataFormat)
  215774. {
  215775. case AudioDataConverters::float32LE:
  215776. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215777. break;
  215778. case AudioDataConverters::int32LE:
  215779. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215780. break;
  215781. case AudioDataConverters::int24LE:
  215782. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  215783. break;
  215784. case AudioDataConverters::int16LE:
  215785. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  215786. break;
  215787. default: jassertfalse; break;
  215788. }
  215789. }
  215790. bufferSize -= samplesToDo;
  215791. offset += samplesToDo;
  215792. if (samplesToDo < (int) numSamplesAvailable)
  215793. {
  215794. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215795. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215796. bytesPerSample * actualNumChannels * reservoirSize);
  215797. }
  215798. captureClient->ReleaseBuffer (numSamplesAvailable);
  215799. }
  215800. }
  215801. }
  215802. }
  215803. ComSmartPtr <IAudioCaptureClient> captureClient;
  215804. MemoryBlock reservoir;
  215805. int reservoirSize, reservoirCapacity;
  215806. private:
  215807. WASAPIInputDevice (const WASAPIInputDevice&);
  215808. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215809. };
  215810. class WASAPIOutputDevice : public WASAPIDeviceBase
  215811. {
  215812. public:
  215813. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215814. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215815. {
  215816. }
  215817. ~WASAPIOutputDevice()
  215818. {
  215819. close();
  215820. }
  215821. bool open (const double newSampleRate, const BigInteger& newChannels)
  215822. {
  215823. return openClient (newSampleRate, newChannels)
  215824. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  215825. }
  215826. void close()
  215827. {
  215828. closeClient();
  215829. renderClient = 0;
  215830. }
  215831. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215832. {
  215833. if (numChannels <= 0)
  215834. return;
  215835. int offset = 0;
  215836. while (bufferSize > 0)
  215837. {
  215838. UINT32 padding = 0;
  215839. if (! OK (client->GetCurrentPadding (&padding)))
  215840. return;
  215841. int samplesToDo = useExclusiveMode ? bufferSize
  215842. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215843. if (samplesToDo <= 0)
  215844. {
  215845. if (thread.threadShouldExit())
  215846. break;
  215847. Thread::sleep (0);
  215848. continue;
  215849. }
  215850. uint8* outputData = 0;
  215851. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  215852. {
  215853. for (int i = 0; i < numSrcBuffers; ++i)
  215854. {
  215855. const float* const source = srcBuffers[i] + offset;
  215856. const int destChan = channelMaps.getUnchecked(i);
  215857. switch (dataFormat)
  215858. {
  215859. case AudioDataConverters::float32LE:
  215860. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  215861. break;
  215862. case AudioDataConverters::int32LE:
  215863. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  215864. break;
  215865. case AudioDataConverters::int24LE:
  215866. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  215867. break;
  215868. case AudioDataConverters::int16LE:
  215869. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  215870. break;
  215871. default: jassertfalse; break;
  215872. }
  215873. }
  215874. renderClient->ReleaseBuffer (samplesToDo, 0);
  215875. offset += samplesToDo;
  215876. bufferSize -= samplesToDo;
  215877. }
  215878. }
  215879. }
  215880. ComSmartPtr <IAudioRenderClient> renderClient;
  215881. private:
  215882. WASAPIOutputDevice (const WASAPIOutputDevice&);
  215883. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  215884. };
  215885. class WASAPIAudioIODevice : public AudioIODevice,
  215886. public Thread
  215887. {
  215888. public:
  215889. WASAPIAudioIODevice (const String& deviceName,
  215890. const String& outputDeviceId_,
  215891. const String& inputDeviceId_,
  215892. const bool useExclusiveMode_)
  215893. : AudioIODevice (deviceName, "Windows Audio"),
  215894. Thread ("Juce WASAPI"),
  215895. isOpen_ (false),
  215896. isStarted (false),
  215897. outputDeviceId (outputDeviceId_),
  215898. inputDeviceId (inputDeviceId_),
  215899. useExclusiveMode (useExclusiveMode_),
  215900. currentBufferSizeSamples (0),
  215901. currentSampleRate (0),
  215902. callback (0)
  215903. {
  215904. }
  215905. ~WASAPIAudioIODevice()
  215906. {
  215907. close();
  215908. }
  215909. bool initialise()
  215910. {
  215911. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215912. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215913. latencyIn = latencyOut = 0;
  215914. Array <double> ratesIn, ratesOut;
  215915. if (createDevices())
  215916. {
  215917. jassert (inputDevice != 0 || outputDevice != 0);
  215918. if (inputDevice != 0 && outputDevice != 0)
  215919. {
  215920. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215921. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215922. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215923. sampleRates = inputDevice->rates;
  215924. sampleRates.removeValuesNotIn (outputDevice->rates);
  215925. }
  215926. else
  215927. {
  215928. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215929. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215930. defaultSampleRate = d->defaultSampleRate;
  215931. minBufferSize = d->minBufferSize;
  215932. defaultBufferSize = d->defaultBufferSize;
  215933. sampleRates = d->rates;
  215934. }
  215935. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215936. if (minBufferSize != defaultBufferSize)
  215937. bufferSizes.addUsingDefaultSort (minBufferSize);
  215938. int n = 64;
  215939. for (int i = 0; i < 40; ++i)
  215940. {
  215941. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215942. bufferSizes.addUsingDefaultSort (n);
  215943. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215944. }
  215945. return true;
  215946. }
  215947. return false;
  215948. }
  215949. const StringArray getOutputChannelNames()
  215950. {
  215951. StringArray outChannels;
  215952. if (outputDevice != 0)
  215953. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215954. outChannels.add ("Output channel " + String (i));
  215955. return outChannels;
  215956. }
  215957. const StringArray getInputChannelNames()
  215958. {
  215959. StringArray inChannels;
  215960. if (inputDevice != 0)
  215961. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215962. inChannels.add ("Input channel " + String (i));
  215963. return inChannels;
  215964. }
  215965. int getNumSampleRates() { return sampleRates.size(); }
  215966. double getSampleRate (int index) { return sampleRates [index]; }
  215967. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215968. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215969. int getDefaultBufferSize() { return defaultBufferSize; }
  215970. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215971. double getCurrentSampleRate() { return currentSampleRate; }
  215972. int getCurrentBitDepth() { return 32; }
  215973. int getOutputLatencyInSamples() { return latencyOut; }
  215974. int getInputLatencyInSamples() { return latencyIn; }
  215975. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215976. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215977. const String getLastError() { return lastError; }
  215978. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215979. double sampleRate, int bufferSizeSamples)
  215980. {
  215981. close();
  215982. lastError = String::empty;
  215983. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215984. {
  215985. lastError = "The input and output devices don't share a common sample rate!";
  215986. return lastError;
  215987. }
  215988. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215989. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215990. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215991. {
  215992. lastError = "Couldn't open the input device!";
  215993. return lastError;
  215994. }
  215995. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215996. {
  215997. close();
  215998. lastError = "Couldn't open the output device!";
  215999. return lastError;
  216000. }
  216001. if (inputDevice != 0)
  216002. ResetEvent (inputDevice->clientEvent);
  216003. if (outputDevice != 0)
  216004. ResetEvent (outputDevice->clientEvent);
  216005. startThread (8);
  216006. Thread::sleep (5);
  216007. if (inputDevice != 0 && inputDevice->client != 0)
  216008. {
  216009. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216010. HRESULT hr = inputDevice->client->Start();
  216011. logFailure (hr); //xxx handle this
  216012. }
  216013. if (outputDevice != 0 && outputDevice->client != 0)
  216014. {
  216015. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216016. HRESULT hr = outputDevice->client->Start();
  216017. logFailure (hr); //xxx handle this
  216018. }
  216019. isOpen_ = true;
  216020. return lastError;
  216021. }
  216022. void close()
  216023. {
  216024. stop();
  216025. if (inputDevice != 0)
  216026. SetEvent (inputDevice->clientEvent);
  216027. if (outputDevice != 0)
  216028. SetEvent (outputDevice->clientEvent);
  216029. stopThread (5000);
  216030. if (inputDevice != 0)
  216031. inputDevice->close();
  216032. if (outputDevice != 0)
  216033. outputDevice->close();
  216034. isOpen_ = false;
  216035. }
  216036. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216037. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216038. void start (AudioIODeviceCallback* call)
  216039. {
  216040. if (isOpen_ && call != 0 && ! isStarted)
  216041. {
  216042. if (! isThreadRunning())
  216043. {
  216044. // something's gone wrong and the thread's stopped..
  216045. isOpen_ = false;
  216046. return;
  216047. }
  216048. call->audioDeviceAboutToStart (this);
  216049. const ScopedLock sl (startStopLock);
  216050. callback = call;
  216051. isStarted = true;
  216052. }
  216053. }
  216054. void stop()
  216055. {
  216056. if (isStarted)
  216057. {
  216058. AudioIODeviceCallback* const callbackLocal = callback;
  216059. {
  216060. const ScopedLock sl (startStopLock);
  216061. isStarted = false;
  216062. }
  216063. if (callbackLocal != 0)
  216064. callbackLocal->audioDeviceStopped();
  216065. }
  216066. }
  216067. void setMMThreadPriority()
  216068. {
  216069. DynamicLibraryLoader dll ("avrt.dll");
  216070. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216071. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216072. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216073. {
  216074. DWORD dummy = 0;
  216075. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216076. if (h != 0)
  216077. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216078. }
  216079. }
  216080. void run()
  216081. {
  216082. setMMThreadPriority();
  216083. const int bufferSize = currentBufferSizeSamples;
  216084. HANDLE events[2];
  216085. int numEvents = 0;
  216086. if (inputDevice != 0)
  216087. events [numEvents++] = inputDevice->clientEvent;
  216088. if (outputDevice != 0)
  216089. events [numEvents++] = outputDevice->clientEvent;
  216090. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216091. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216092. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216093. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216094. float** const inputBuffers = ins.getArrayOfChannels();
  216095. float** const outputBuffers = outs.getArrayOfChannels();
  216096. ins.clear();
  216097. while (! threadShouldExit())
  216098. {
  216099. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216100. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216101. if (result == WAIT_TIMEOUT)
  216102. continue;
  216103. if (threadShouldExit())
  216104. break;
  216105. if (inputDevice != 0)
  216106. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216107. // Make the callback..
  216108. {
  216109. const ScopedLock sl (startStopLock);
  216110. if (isStarted)
  216111. {
  216112. JUCE_TRY
  216113. {
  216114. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216115. numInputBuffers,
  216116. outputBuffers,
  216117. numOutputBuffers,
  216118. bufferSize);
  216119. }
  216120. JUCE_CATCH_EXCEPTION
  216121. }
  216122. else
  216123. {
  216124. outs.clear();
  216125. }
  216126. }
  216127. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216128. continue;
  216129. if (outputDevice != 0)
  216130. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216131. }
  216132. }
  216133. juce_UseDebuggingNewOperator
  216134. String outputDeviceId, inputDeviceId;
  216135. String lastError;
  216136. private:
  216137. // Device stats...
  216138. ScopedPointer<WASAPIInputDevice> inputDevice;
  216139. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216140. const bool useExclusiveMode;
  216141. double defaultSampleRate;
  216142. int minBufferSize, defaultBufferSize;
  216143. int latencyIn, latencyOut;
  216144. Array <double> sampleRates;
  216145. Array <int> bufferSizes;
  216146. // Active state...
  216147. bool isOpen_, isStarted;
  216148. int currentBufferSizeSamples;
  216149. double currentSampleRate;
  216150. AudioIODeviceCallback* callback;
  216151. CriticalSection startStopLock;
  216152. bool createDevices()
  216153. {
  216154. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216155. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216156. return false;
  216157. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216158. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  216159. return false;
  216160. UINT32 numDevices = 0;
  216161. if (! OK (deviceCollection->GetCount (&numDevices)))
  216162. return false;
  216163. for (UINT32 i = 0; i < numDevices; ++i)
  216164. {
  216165. ComSmartPtr <IMMDevice> device;
  216166. if (! OK (deviceCollection->Item (i, &device)))
  216167. continue;
  216168. const String deviceId (wasapi_getDeviceID (device));
  216169. if (deviceId.isEmpty())
  216170. continue;
  216171. const EDataFlow flow = wasapi_getDataFlow (device);
  216172. if (deviceId == inputDeviceId && flow == eCapture)
  216173. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216174. else if (deviceId == outputDeviceId && flow == eRender)
  216175. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216176. }
  216177. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216178. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216179. }
  216180. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216181. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216182. };
  216183. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216184. {
  216185. public:
  216186. WASAPIAudioIODeviceType()
  216187. : AudioIODeviceType ("Windows Audio"),
  216188. hasScanned (false)
  216189. {
  216190. }
  216191. ~WASAPIAudioIODeviceType()
  216192. {
  216193. }
  216194. void scanForDevices()
  216195. {
  216196. hasScanned = true;
  216197. outputDeviceNames.clear();
  216198. inputDeviceNames.clear();
  216199. outputDeviceIds.clear();
  216200. inputDeviceIds.clear();
  216201. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216202. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216203. return;
  216204. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216205. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216206. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216207. UINT32 numDevices = 0;
  216208. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  216209. && OK (deviceCollection->GetCount (&numDevices))))
  216210. return;
  216211. for (UINT32 i = 0; i < numDevices; ++i)
  216212. {
  216213. ComSmartPtr <IMMDevice> device;
  216214. if (! OK (deviceCollection->Item (i, &device)))
  216215. continue;
  216216. const String deviceId (wasapi_getDeviceID (device));
  216217. DWORD state = 0;
  216218. if (! OK (device->GetState (&state)))
  216219. continue;
  216220. if (state != DEVICE_STATE_ACTIVE)
  216221. continue;
  216222. String name;
  216223. {
  216224. ComSmartPtr <IPropertyStore> properties;
  216225. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  216226. continue;
  216227. PROPVARIANT value;
  216228. PropVariantInit (&value);
  216229. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216230. name = value.pwszVal;
  216231. PropVariantClear (&value);
  216232. }
  216233. const EDataFlow flow = wasapi_getDataFlow (device);
  216234. if (flow == eRender)
  216235. {
  216236. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216237. outputDeviceIds.insert (index, deviceId);
  216238. outputDeviceNames.insert (index, name);
  216239. }
  216240. else if (flow == eCapture)
  216241. {
  216242. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216243. inputDeviceIds.insert (index, deviceId);
  216244. inputDeviceNames.insert (index, name);
  216245. }
  216246. }
  216247. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216248. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216249. }
  216250. const StringArray getDeviceNames (bool wantInputNames) const
  216251. {
  216252. jassert (hasScanned); // need to call scanForDevices() before doing this
  216253. return wantInputNames ? inputDeviceNames
  216254. : outputDeviceNames;
  216255. }
  216256. int getDefaultDeviceIndex (bool /*forInput*/) const
  216257. {
  216258. jassert (hasScanned); // need to call scanForDevices() before doing this
  216259. return 0;
  216260. }
  216261. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216262. {
  216263. jassert (hasScanned); // need to call scanForDevices() before doing this
  216264. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216265. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216266. : outputDeviceIds.indexOf (d->outputDeviceId));
  216267. }
  216268. bool hasSeparateInputsAndOutputs() const { return true; }
  216269. AudioIODevice* createDevice (const String& outputDeviceName,
  216270. const String& inputDeviceName)
  216271. {
  216272. jassert (hasScanned); // need to call scanForDevices() before doing this
  216273. const bool useExclusiveMode = false;
  216274. ScopedPointer<WASAPIAudioIODevice> device;
  216275. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216276. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216277. if (outputIndex >= 0 || inputIndex >= 0)
  216278. {
  216279. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216280. : inputDeviceName,
  216281. outputDeviceIds [outputIndex],
  216282. inputDeviceIds [inputIndex],
  216283. useExclusiveMode);
  216284. if (! device->initialise())
  216285. device = 0;
  216286. }
  216287. return device.release();
  216288. }
  216289. juce_UseDebuggingNewOperator
  216290. StringArray outputDeviceNames, outputDeviceIds;
  216291. StringArray inputDeviceNames, inputDeviceIds;
  216292. private:
  216293. bool hasScanned;
  216294. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216295. {
  216296. String s;
  216297. IMMDevice* dev = 0;
  216298. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216299. eMultimedia, &dev)))
  216300. {
  216301. WCHAR* deviceId = 0;
  216302. if (OK (dev->GetId (&deviceId)))
  216303. {
  216304. s = String (deviceId);
  216305. CoTaskMemFree (deviceId);
  216306. }
  216307. dev->Release();
  216308. }
  216309. return s;
  216310. }
  216311. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216312. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216313. };
  216314. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216315. {
  216316. return new WASAPIAudioIODeviceType();
  216317. }
  216318. #undef logFailure
  216319. #undef OK
  216320. #endif
  216321. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216322. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216323. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216324. // compiled on its own).
  216325. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216326. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216327. {
  216328. public:
  216329. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216330. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216331. const ComSmartPtr <IBaseFilter>& filter_,
  216332. int minWidth, int minHeight,
  216333. int maxWidth, int maxHeight)
  216334. : owner (owner_),
  216335. captureGraphBuilder (captureGraphBuilder_),
  216336. filter (filter_),
  216337. ok (false),
  216338. imageNeedsFlipping (false),
  216339. width (0),
  216340. height (0),
  216341. activeUsers (0),
  216342. recordNextFrameTime (false)
  216343. {
  216344. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216345. if (FAILED (hr))
  216346. return;
  216347. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216348. if (FAILED (hr))
  216349. return;
  216350. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  216351. if (FAILED (hr))
  216352. return;
  216353. {
  216354. ComSmartPtr <IAMStreamConfig> streamConfig;
  216355. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216356. IID_IAMStreamConfig, (void**) &streamConfig);
  216357. if (streamConfig != 0)
  216358. {
  216359. getVideoSizes (streamConfig);
  216360. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216361. return;
  216362. }
  216363. }
  216364. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216365. if (FAILED (hr))
  216366. return;
  216367. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216368. if (FAILED (hr))
  216369. return;
  216370. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216371. if (FAILED (hr))
  216372. return;
  216373. if (! connectFilters (filter, smartTee))
  216374. return;
  216375. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216376. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216377. if (FAILED (hr))
  216378. return;
  216379. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  216380. if (FAILED (hr))
  216381. return;
  216382. AM_MEDIA_TYPE mt;
  216383. zerostruct (mt);
  216384. mt.majortype = MEDIATYPE_Video;
  216385. mt.subtype = MEDIASUBTYPE_RGB24;
  216386. mt.formattype = FORMAT_VideoInfo;
  216387. sampleGrabber->SetMediaType (&mt);
  216388. callback = new GrabberCallback (*this);
  216389. sampleGrabber->SetCallback (callback, 1);
  216390. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216391. if (FAILED (hr))
  216392. return;
  216393. ComSmartPtr <IPin> grabberInputPin;
  216394. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  216395. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  216396. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  216397. return;
  216398. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216399. if (FAILED (hr))
  216400. return;
  216401. zerostruct (mt);
  216402. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216403. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216404. width = pVih->bmiHeader.biWidth;
  216405. height = pVih->bmiHeader.biHeight;
  216406. ComSmartPtr <IBaseFilter> nullFilter;
  216407. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216408. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216409. if (connectFilters (sampleGrabberBase, nullFilter)
  216410. && addGraphToRot())
  216411. {
  216412. activeImage = Image (Image::RGB, width, height, true);
  216413. loadingImage = Image (Image::RGB, width, height, true);
  216414. ok = true;
  216415. }
  216416. }
  216417. ~DShowCameraDeviceInteral()
  216418. {
  216419. if (mediaControl != 0)
  216420. mediaControl->Stop();
  216421. removeGraphFromRot();
  216422. for (int i = viewerComps.size(); --i >= 0;)
  216423. viewerComps.getUnchecked(i)->ownerDeleted();
  216424. callback = 0;
  216425. graphBuilder = 0;
  216426. sampleGrabber = 0;
  216427. mediaControl = 0;
  216428. filter = 0;
  216429. captureGraphBuilder = 0;
  216430. smartTee = 0;
  216431. smartTeePreviewOutputPin = 0;
  216432. smartTeeCaptureOutputPin = 0;
  216433. asfWriter = 0;
  216434. }
  216435. void addUser()
  216436. {
  216437. if (ok && activeUsers++ == 0)
  216438. mediaControl->Run();
  216439. }
  216440. void removeUser()
  216441. {
  216442. if (ok && --activeUsers == 0)
  216443. mediaControl->Stop();
  216444. }
  216445. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216446. {
  216447. if (recordNextFrameTime)
  216448. {
  216449. const double defaultCameraLatency = 0.1;
  216450. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216451. recordNextFrameTime = false;
  216452. ComSmartPtr <IPin> pin;
  216453. if (getPin (filter, PINDIR_OUTPUT, &pin))
  216454. {
  216455. ComSmartPtr <IAMPushSource> pushSource;
  216456. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  216457. if (pushSource != 0)
  216458. {
  216459. REFERENCE_TIME latency = 0;
  216460. hr = pushSource->GetLatency (&latency);
  216461. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216462. }
  216463. }
  216464. }
  216465. {
  216466. const int lineStride = width * 3;
  216467. const ScopedLock sl (imageSwapLock);
  216468. {
  216469. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216470. for (int i = 0; i < height; ++i)
  216471. memcpy (destData.getLinePointer ((height - 1) - i),
  216472. buffer + lineStride * i,
  216473. lineStride);
  216474. }
  216475. imageNeedsFlipping = true;
  216476. }
  216477. if (listeners.size() > 0)
  216478. callListeners (loadingImage);
  216479. sendChangeMessage (this);
  216480. }
  216481. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216482. {
  216483. if (imageNeedsFlipping)
  216484. {
  216485. const ScopedLock sl (imageSwapLock);
  216486. swapVariables (loadingImage, activeImage);
  216487. imageNeedsFlipping = false;
  216488. }
  216489. RectanglePlacement rp (RectanglePlacement::centred);
  216490. double dx = 0, dy = 0, dw = width, dh = height;
  216491. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216492. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216493. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216494. g.saveState();
  216495. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216496. g.fillAll (Colours::black);
  216497. g.restoreState();
  216498. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216499. }
  216500. bool createFileCaptureFilter (const File& file)
  216501. {
  216502. removeFileCaptureFilter();
  216503. file.deleteFile();
  216504. mediaControl->Stop();
  216505. firstRecordedTime = Time();
  216506. recordNextFrameTime = true;
  216507. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216508. if (SUCCEEDED (hr))
  216509. {
  216510. ComSmartPtr <IFileSinkFilter> fileSink;
  216511. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  216512. if (SUCCEEDED (hr))
  216513. {
  216514. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216515. if (SUCCEEDED (hr))
  216516. {
  216517. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216518. if (SUCCEEDED (hr))
  216519. {
  216520. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216521. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  216522. asfConfig->SetIndexMode (true);
  216523. ComSmartPtr <IWMProfileManager> profileManager;
  216524. hr = WMCreateProfileManager (&profileManager);
  216525. // This gibberish is the DirectShow profile for a video-only wmv file.
  216526. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216527. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216528. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216529. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216530. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216531. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216532. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216533. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216534. prof = prof.replace ("$WIDTH", String (width))
  216535. .replace ("$HEIGHT", String (height));
  216536. ComSmartPtr <IWMProfile> currentProfile;
  216537. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  216538. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216539. if (SUCCEEDED (hr))
  216540. {
  216541. ComSmartPtr <IPin> asfWriterInputPin;
  216542. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  216543. {
  216544. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216545. if (SUCCEEDED (hr)
  216546. && ok && activeUsers > 0
  216547. && SUCCEEDED (mediaControl->Run()))
  216548. {
  216549. return true;
  216550. }
  216551. }
  216552. }
  216553. }
  216554. }
  216555. }
  216556. }
  216557. removeFileCaptureFilter();
  216558. if (ok && activeUsers > 0)
  216559. mediaControl->Run();
  216560. return false;
  216561. }
  216562. void removeFileCaptureFilter()
  216563. {
  216564. mediaControl->Stop();
  216565. if (asfWriter != 0)
  216566. {
  216567. graphBuilder->RemoveFilter (asfWriter);
  216568. asfWriter = 0;
  216569. }
  216570. if (ok && activeUsers > 0)
  216571. mediaControl->Run();
  216572. }
  216573. void addListener (CameraDevice::Listener* listenerToAdd)
  216574. {
  216575. const ScopedLock sl (listenerLock);
  216576. if (listeners.size() == 0)
  216577. addUser();
  216578. listeners.addIfNotAlreadyThere (listenerToAdd);
  216579. }
  216580. void removeListener (CameraDevice::Listener* listenerToRemove)
  216581. {
  216582. const ScopedLock sl (listenerLock);
  216583. listeners.removeValue (listenerToRemove);
  216584. if (listeners.size() == 0)
  216585. removeUser();
  216586. }
  216587. void callListeners (const Image& image)
  216588. {
  216589. const ScopedLock sl (listenerLock);
  216590. for (int i = listeners.size(); --i >= 0;)
  216591. {
  216592. CameraDevice::Listener* const l = listeners[i];
  216593. if (l != 0)
  216594. l->imageReceived (image);
  216595. }
  216596. }
  216597. class DShowCaptureViewerComp : public Component,
  216598. public ChangeListener
  216599. {
  216600. public:
  216601. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216602. : owner (owner_)
  216603. {
  216604. setOpaque (true);
  216605. owner->addChangeListener (this);
  216606. owner->addUser();
  216607. owner->viewerComps.add (this);
  216608. setSize (owner_->width, owner_->height);
  216609. }
  216610. ~DShowCaptureViewerComp()
  216611. {
  216612. if (owner != 0)
  216613. {
  216614. owner->viewerComps.removeValue (this);
  216615. owner->removeUser();
  216616. owner->removeChangeListener (this);
  216617. }
  216618. }
  216619. void ownerDeleted()
  216620. {
  216621. owner = 0;
  216622. }
  216623. void paint (Graphics& g)
  216624. {
  216625. g.setColour (Colours::black);
  216626. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216627. if (owner != 0)
  216628. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216629. else
  216630. g.fillAll (Colours::black);
  216631. }
  216632. void changeListenerCallback (void*)
  216633. {
  216634. repaint();
  216635. }
  216636. private:
  216637. DShowCameraDeviceInteral* owner;
  216638. };
  216639. bool ok;
  216640. int width, height;
  216641. Time firstRecordedTime;
  216642. Array <DShowCaptureViewerComp*> viewerComps;
  216643. private:
  216644. CameraDevice* const owner;
  216645. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216646. ComSmartPtr <IBaseFilter> filter;
  216647. ComSmartPtr <IBaseFilter> smartTee;
  216648. ComSmartPtr <IGraphBuilder> graphBuilder;
  216649. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216650. ComSmartPtr <IMediaControl> mediaControl;
  216651. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216652. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216653. ComSmartPtr <IBaseFilter> asfWriter;
  216654. int activeUsers;
  216655. Array <int> widths, heights;
  216656. DWORD graphRegistrationID;
  216657. CriticalSection imageSwapLock;
  216658. bool imageNeedsFlipping;
  216659. Image loadingImage;
  216660. Image activeImage;
  216661. bool recordNextFrameTime;
  216662. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216663. {
  216664. widths.clear();
  216665. heights.clear();
  216666. int count = 0, size = 0;
  216667. streamConfig->GetNumberOfCapabilities (&count, &size);
  216668. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216669. {
  216670. for (int i = 0; i < count; ++i)
  216671. {
  216672. VIDEO_STREAM_CONFIG_CAPS scc;
  216673. AM_MEDIA_TYPE* config;
  216674. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216675. if (SUCCEEDED (hr))
  216676. {
  216677. const int w = scc.InputSize.cx;
  216678. const int h = scc.InputSize.cy;
  216679. bool duplicate = false;
  216680. for (int j = widths.size(); --j >= 0;)
  216681. {
  216682. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216683. {
  216684. duplicate = true;
  216685. break;
  216686. }
  216687. }
  216688. if (! duplicate)
  216689. {
  216690. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216691. widths.add (w);
  216692. heights.add (h);
  216693. }
  216694. deleteMediaType (config);
  216695. }
  216696. }
  216697. }
  216698. }
  216699. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216700. const int minWidth, const int minHeight,
  216701. const int maxWidth, const int maxHeight)
  216702. {
  216703. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216704. streamConfig->GetNumberOfCapabilities (&count, &size);
  216705. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216706. {
  216707. AM_MEDIA_TYPE* config;
  216708. VIDEO_STREAM_CONFIG_CAPS scc;
  216709. for (int i = 0; i < count; ++i)
  216710. {
  216711. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216712. if (SUCCEEDED (hr))
  216713. {
  216714. if (scc.InputSize.cx >= minWidth
  216715. && scc.InputSize.cy >= minHeight
  216716. && scc.InputSize.cx <= maxWidth
  216717. && scc.InputSize.cy <= maxHeight)
  216718. {
  216719. int area = scc.InputSize.cx * scc.InputSize.cy;
  216720. if (area > bestArea)
  216721. {
  216722. bestIndex = i;
  216723. bestArea = area;
  216724. }
  216725. }
  216726. deleteMediaType (config);
  216727. }
  216728. }
  216729. if (bestIndex >= 0)
  216730. {
  216731. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216732. hr = streamConfig->SetFormat (config);
  216733. deleteMediaType (config);
  216734. return SUCCEEDED (hr);
  216735. }
  216736. }
  216737. return false;
  216738. }
  216739. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  216740. {
  216741. ComSmartPtr <IEnumPins> enumerator;
  216742. ComSmartPtr <IPin> pin;
  216743. filter->EnumPins (&enumerator);
  216744. while (enumerator->Next (1, &pin, 0) == S_OK)
  216745. {
  216746. PIN_DIRECTION dir;
  216747. pin->QueryDirection (&dir);
  216748. if (wantedDirection == dir)
  216749. {
  216750. PIN_INFO info;
  216751. zerostruct (info);
  216752. pin->QueryPinInfo (&info);
  216753. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216754. {
  216755. pin->AddRef();
  216756. *result = pin;
  216757. return true;
  216758. }
  216759. }
  216760. }
  216761. return false;
  216762. }
  216763. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216764. {
  216765. ComSmartPtr <IPin> in, out;
  216766. return getPin (first, PINDIR_OUTPUT, &out)
  216767. && getPin (second, PINDIR_INPUT, &in)
  216768. && SUCCEEDED (graphBuilder->Connect (out, in));
  216769. }
  216770. bool addGraphToRot()
  216771. {
  216772. ComSmartPtr <IRunningObjectTable> rot;
  216773. if (FAILED (GetRunningObjectTable (0, &rot)))
  216774. return false;
  216775. ComSmartPtr <IMoniker> moniker;
  216776. WCHAR buffer[128];
  216777. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  216778. if (FAILED (hr))
  216779. return false;
  216780. graphRegistrationID = 0;
  216781. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216782. }
  216783. void removeGraphFromRot()
  216784. {
  216785. ComSmartPtr <IRunningObjectTable> rot;
  216786. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  216787. rot->Revoke (graphRegistrationID);
  216788. }
  216789. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216790. {
  216791. if (pmt->cbFormat != 0)
  216792. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216793. if (pmt->pUnk != 0)
  216794. pmt->pUnk->Release();
  216795. CoTaskMemFree (pmt);
  216796. }
  216797. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216798. {
  216799. public:
  216800. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216801. : owner (owner_)
  216802. {
  216803. }
  216804. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216805. {
  216806. return E_FAIL;
  216807. }
  216808. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216809. {
  216810. owner.handleFrame (time, buffer, bufferSize);
  216811. return S_OK;
  216812. }
  216813. private:
  216814. DShowCameraDeviceInteral& owner;
  216815. GrabberCallback (const GrabberCallback&);
  216816. GrabberCallback& operator= (const GrabberCallback&);
  216817. };
  216818. ComSmartPtr <GrabberCallback> callback;
  216819. Array <CameraDevice::Listener*> listeners;
  216820. CriticalSection listenerLock;
  216821. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216822. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216823. };
  216824. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216825. : name (name_)
  216826. {
  216827. isRecording = false;
  216828. }
  216829. CameraDevice::~CameraDevice()
  216830. {
  216831. stopRecording();
  216832. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216833. internal = 0;
  216834. }
  216835. Component* CameraDevice::createViewerComponent()
  216836. {
  216837. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216838. }
  216839. const String CameraDevice::getFileExtension()
  216840. {
  216841. return ".wmv";
  216842. }
  216843. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216844. {
  216845. stopRecording();
  216846. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216847. d->addUser();
  216848. isRecording = d->createFileCaptureFilter (file);
  216849. }
  216850. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216851. {
  216852. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216853. return d->firstRecordedTime;
  216854. }
  216855. void CameraDevice::stopRecording()
  216856. {
  216857. if (isRecording)
  216858. {
  216859. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216860. d->removeFileCaptureFilter();
  216861. d->removeUser();
  216862. isRecording = false;
  216863. }
  216864. }
  216865. void CameraDevice::addListener (Listener* listenerToAdd)
  216866. {
  216867. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216868. if (listenerToAdd != 0)
  216869. d->addListener (listenerToAdd);
  216870. }
  216871. void CameraDevice::removeListener (Listener* listenerToRemove)
  216872. {
  216873. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216874. if (listenerToRemove != 0)
  216875. d->removeListener (listenerToRemove);
  216876. }
  216877. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216878. const int deviceIndexToOpen,
  216879. String& name)
  216880. {
  216881. int index = 0;
  216882. ComSmartPtr <IBaseFilter> result;
  216883. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216884. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216885. if (SUCCEEDED (hr))
  216886. {
  216887. ComSmartPtr <IEnumMoniker> enumerator;
  216888. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  216889. if (SUCCEEDED (hr) && enumerator != 0)
  216890. {
  216891. ComSmartPtr <IBaseFilter> captureFilter;
  216892. ComSmartPtr <IMoniker> moniker;
  216893. ULONG fetched;
  216894. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  216895. {
  216896. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  216897. if (SUCCEEDED (hr))
  216898. {
  216899. ComSmartPtr <IPropertyBag> propertyBag;
  216900. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  216901. if (SUCCEEDED (hr))
  216902. {
  216903. VARIANT var;
  216904. var.vt = VT_BSTR;
  216905. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216906. propertyBag = 0;
  216907. if (SUCCEEDED (hr))
  216908. {
  216909. if (names != 0)
  216910. names->add (var.bstrVal);
  216911. if (index == deviceIndexToOpen)
  216912. {
  216913. name = var.bstrVal;
  216914. result = captureFilter;
  216915. captureFilter = 0;
  216916. break;
  216917. }
  216918. ++index;
  216919. }
  216920. moniker = 0;
  216921. }
  216922. captureFilter = 0;
  216923. }
  216924. }
  216925. }
  216926. }
  216927. return result;
  216928. }
  216929. const StringArray CameraDevice::getAvailableDevices()
  216930. {
  216931. StringArray devs;
  216932. String dummy;
  216933. enumerateCameras (&devs, -1, dummy);
  216934. return devs;
  216935. }
  216936. CameraDevice* CameraDevice::openDevice (int index,
  216937. int minWidth, int minHeight,
  216938. int maxWidth, int maxHeight)
  216939. {
  216940. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216941. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216942. if (SUCCEEDED (hr))
  216943. {
  216944. String name;
  216945. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216946. if (filter != 0)
  216947. {
  216948. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216949. DShowCameraDeviceInteral* const intern
  216950. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216951. minWidth, minHeight, maxWidth, maxHeight);
  216952. cam->internal = intern;
  216953. if (intern->ok)
  216954. return cam.release();
  216955. }
  216956. }
  216957. return 0;
  216958. }
  216959. #endif
  216960. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216961. #endif
  216962. // Auto-link the other win32 libs that are needed by library calls..
  216963. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216964. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216965. // Auto-links to various win32 libs that are needed by library calls..
  216966. #pragma comment(lib, "kernel32.lib")
  216967. #pragma comment(lib, "user32.lib")
  216968. #pragma comment(lib, "shell32.lib")
  216969. #pragma comment(lib, "gdi32.lib")
  216970. #pragma comment(lib, "vfw32.lib")
  216971. #pragma comment(lib, "comdlg32.lib")
  216972. #pragma comment(lib, "winmm.lib")
  216973. #pragma comment(lib, "wininet.lib")
  216974. #pragma comment(lib, "ole32.lib")
  216975. #pragma comment(lib, "oleaut32.lib")
  216976. #pragma comment(lib, "advapi32.lib")
  216977. #pragma comment(lib, "ws2_32.lib")
  216978. #pragma comment(lib, "comsupp.lib")
  216979. #pragma comment(lib, "version.lib")
  216980. #if JUCE_OPENGL
  216981. #pragma comment(lib, "OpenGL32.Lib")
  216982. #pragma comment(lib, "GlU32.Lib")
  216983. #endif
  216984. #if JUCE_QUICKTIME
  216985. #pragma comment (lib, "QTMLClient.lib")
  216986. #endif
  216987. #if JUCE_USE_CAMERA
  216988. #pragma comment (lib, "Strmiids.lib")
  216989. #pragma comment (lib, "wmvcore.lib")
  216990. #endif
  216991. #if JUCE_DIRECT2D
  216992. #pragma comment (lib, "Dwrite.lib")
  216993. #pragma comment (lib, "D2d1.lib")
  216994. #endif
  216995. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216996. #endif
  216997. END_JUCE_NAMESPACE
  216998. #endif
  216999. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217000. #endif
  217001. #if JUCE_LINUX
  217002. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217003. /*
  217004. This file wraps together all the mac-specific code, so that
  217005. we can include all the native headers just once, and compile all our
  217006. platform-specific stuff in one big lump, keeping it out of the way of
  217007. the rest of the codebase.
  217008. */
  217009. #if JUCE_LINUX
  217010. BEGIN_JUCE_NAMESPACE
  217011. #define JUCE_INCLUDED_FILE 1
  217012. // Now include the actual code files..
  217013. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217014. /*
  217015. This file contains posix routines that are common to both the Linux and Mac builds.
  217016. It gets included directly in the cpp files for these platforms.
  217017. */
  217018. CriticalSection::CriticalSection() throw()
  217019. {
  217020. pthread_mutexattr_t atts;
  217021. pthread_mutexattr_init (&atts);
  217022. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217023. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217024. pthread_mutex_init (&internal, &atts);
  217025. }
  217026. CriticalSection::~CriticalSection() throw()
  217027. {
  217028. pthread_mutex_destroy (&internal);
  217029. }
  217030. void CriticalSection::enter() const throw()
  217031. {
  217032. pthread_mutex_lock (&internal);
  217033. }
  217034. bool CriticalSection::tryEnter() const throw()
  217035. {
  217036. return pthread_mutex_trylock (&internal) == 0;
  217037. }
  217038. void CriticalSection::exit() const throw()
  217039. {
  217040. pthread_mutex_unlock (&internal);
  217041. }
  217042. class WaitableEventImpl
  217043. {
  217044. public:
  217045. WaitableEventImpl (const bool manualReset_)
  217046. : triggered (false),
  217047. manualReset (manualReset_)
  217048. {
  217049. pthread_cond_init (&condition, 0);
  217050. pthread_mutexattr_t atts;
  217051. pthread_mutexattr_init (&atts);
  217052. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217053. pthread_mutex_init (&mutex, &atts);
  217054. }
  217055. ~WaitableEventImpl()
  217056. {
  217057. pthread_cond_destroy (&condition);
  217058. pthread_mutex_destroy (&mutex);
  217059. }
  217060. bool wait (const int timeOutMillisecs) throw()
  217061. {
  217062. pthread_mutex_lock (&mutex);
  217063. if (! triggered)
  217064. {
  217065. if (timeOutMillisecs < 0)
  217066. {
  217067. do
  217068. {
  217069. pthread_cond_wait (&condition, &mutex);
  217070. }
  217071. while (! triggered);
  217072. }
  217073. else
  217074. {
  217075. struct timeval now;
  217076. gettimeofday (&now, 0);
  217077. struct timespec time;
  217078. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217079. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217080. if (time.tv_nsec >= 1000000000)
  217081. {
  217082. time.tv_nsec -= 1000000000;
  217083. time.tv_sec++;
  217084. }
  217085. do
  217086. {
  217087. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217088. {
  217089. pthread_mutex_unlock (&mutex);
  217090. return false;
  217091. }
  217092. }
  217093. while (! triggered);
  217094. }
  217095. }
  217096. if (! manualReset)
  217097. triggered = false;
  217098. pthread_mutex_unlock (&mutex);
  217099. return true;
  217100. }
  217101. void signal() throw()
  217102. {
  217103. pthread_mutex_lock (&mutex);
  217104. triggered = true;
  217105. pthread_cond_broadcast (&condition);
  217106. pthread_mutex_unlock (&mutex);
  217107. }
  217108. void reset() throw()
  217109. {
  217110. pthread_mutex_lock (&mutex);
  217111. triggered = false;
  217112. pthread_mutex_unlock (&mutex);
  217113. }
  217114. private:
  217115. pthread_cond_t condition;
  217116. pthread_mutex_t mutex;
  217117. bool triggered;
  217118. const bool manualReset;
  217119. WaitableEventImpl (const WaitableEventImpl&);
  217120. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217121. };
  217122. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217123. : internal (new WaitableEventImpl (manualReset))
  217124. {
  217125. }
  217126. WaitableEvent::~WaitableEvent() throw()
  217127. {
  217128. delete static_cast <WaitableEventImpl*> (internal);
  217129. }
  217130. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217131. {
  217132. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217133. }
  217134. void WaitableEvent::signal() const throw()
  217135. {
  217136. static_cast <WaitableEventImpl*> (internal)->signal();
  217137. }
  217138. void WaitableEvent::reset() const throw()
  217139. {
  217140. static_cast <WaitableEventImpl*> (internal)->reset();
  217141. }
  217142. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217143. {
  217144. struct timespec time;
  217145. time.tv_sec = millisecs / 1000;
  217146. time.tv_nsec = (millisecs % 1000) * 1000000;
  217147. nanosleep (&time, 0);
  217148. }
  217149. const juce_wchar File::separator = '/';
  217150. const String File::separatorString ("/");
  217151. const File File::getCurrentWorkingDirectory()
  217152. {
  217153. HeapBlock<char> heapBuffer;
  217154. char localBuffer [1024];
  217155. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217156. int bufferSize = 4096;
  217157. while (cwd == 0 && errno == ERANGE)
  217158. {
  217159. heapBuffer.malloc (bufferSize);
  217160. cwd = getcwd (heapBuffer, bufferSize - 1);
  217161. bufferSize += 1024;
  217162. }
  217163. return File (String::fromUTF8 (cwd));
  217164. }
  217165. bool File::setAsCurrentWorkingDirectory() const
  217166. {
  217167. return chdir (getFullPathName().toUTF8()) == 0;
  217168. }
  217169. static bool juce_stat (const String& fileName, struct stat& info)
  217170. {
  217171. return fileName.isNotEmpty()
  217172. && (stat (fileName.toUTF8(), &info) == 0);
  217173. }
  217174. bool File::isDirectory() const
  217175. {
  217176. struct stat info;
  217177. return fullPath.isEmpty()
  217178. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217179. }
  217180. bool File::exists() const
  217181. {
  217182. return fullPath.isNotEmpty()
  217183. && access (fullPath.toUTF8(), F_OK) == 0;
  217184. }
  217185. bool File::existsAsFile() const
  217186. {
  217187. return exists() && ! isDirectory();
  217188. }
  217189. int64 File::getSize() const
  217190. {
  217191. struct stat info;
  217192. return juce_stat (fullPath, info) ? info.st_size : 0;
  217193. }
  217194. bool File::hasWriteAccess() const
  217195. {
  217196. if (exists())
  217197. return access (fullPath.toUTF8(), W_OK) == 0;
  217198. if ((! isDirectory()) && fullPath.containsChar (separator))
  217199. return getParentDirectory().hasWriteAccess();
  217200. return false;
  217201. }
  217202. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217203. {
  217204. struct stat info;
  217205. const int res = stat (fullPath.toUTF8(), &info);
  217206. if (res != 0)
  217207. return false;
  217208. info.st_mode &= 0777; // Just permissions
  217209. if (shouldBeReadOnly)
  217210. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217211. else
  217212. // Give everybody write permission?
  217213. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217214. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217215. }
  217216. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217217. {
  217218. modificationTime = 0;
  217219. accessTime = 0;
  217220. creationTime = 0;
  217221. struct stat info;
  217222. const int res = stat (fullPath.toUTF8(), &info);
  217223. if (res == 0)
  217224. {
  217225. modificationTime = (int64) info.st_mtime * 1000;
  217226. accessTime = (int64) info.st_atime * 1000;
  217227. creationTime = (int64) info.st_ctime * 1000;
  217228. }
  217229. }
  217230. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217231. {
  217232. struct utimbuf times;
  217233. times.actime = (time_t) (accessTime / 1000);
  217234. times.modtime = (time_t) (modificationTime / 1000);
  217235. return utime (fullPath.toUTF8(), &times) == 0;
  217236. }
  217237. bool File::deleteFile() const
  217238. {
  217239. if (! exists())
  217240. return true;
  217241. else if (isDirectory())
  217242. return rmdir (fullPath.toUTF8()) == 0;
  217243. else
  217244. return remove (fullPath.toUTF8()) == 0;
  217245. }
  217246. bool File::moveInternal (const File& dest) const
  217247. {
  217248. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217249. return true;
  217250. if (hasWriteAccess() && copyInternal (dest))
  217251. {
  217252. if (deleteFile())
  217253. return true;
  217254. dest.deleteFile();
  217255. }
  217256. return false;
  217257. }
  217258. void File::createDirectoryInternal (const String& fileName) const
  217259. {
  217260. mkdir (fileName.toUTF8(), 0777);
  217261. }
  217262. int64 juce_fileSetPosition (void* handle, int64 pos)
  217263. {
  217264. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217265. return pos;
  217266. return -1;
  217267. }
  217268. void FileInputStream::openHandle()
  217269. {
  217270. totalSize = file.getSize();
  217271. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217272. if (f != -1)
  217273. fileHandle = (void*) f;
  217274. }
  217275. void FileInputStream::closeHandle()
  217276. {
  217277. if (fileHandle != 0)
  217278. {
  217279. close ((int) (pointer_sized_int) fileHandle);
  217280. fileHandle = 0;
  217281. }
  217282. }
  217283. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217284. {
  217285. if (fileHandle != 0)
  217286. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217287. return 0;
  217288. }
  217289. void FileOutputStream::openHandle()
  217290. {
  217291. if (file.exists())
  217292. {
  217293. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217294. if (f != -1)
  217295. {
  217296. currentPosition = lseek (f, 0, SEEK_END);
  217297. if (currentPosition >= 0)
  217298. fileHandle = (void*) f;
  217299. else
  217300. close (f);
  217301. }
  217302. }
  217303. else
  217304. {
  217305. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217306. if (f != -1)
  217307. fileHandle = (void*) f;
  217308. }
  217309. }
  217310. void FileOutputStream::closeHandle()
  217311. {
  217312. if (fileHandle != 0)
  217313. {
  217314. close ((int) (pointer_sized_int) fileHandle);
  217315. fileHandle = 0;
  217316. }
  217317. }
  217318. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217319. {
  217320. if (fileHandle != 0)
  217321. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217322. return 0;
  217323. }
  217324. void FileOutputStream::flushInternal()
  217325. {
  217326. if (fileHandle != 0)
  217327. fsync ((int) (pointer_sized_int) fileHandle);
  217328. }
  217329. const File juce_getExecutableFile()
  217330. {
  217331. Dl_info exeInfo;
  217332. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217333. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217334. }
  217335. // if this file doesn't exist, find a parent of it that does..
  217336. static bool juce_doStatFS (File f, struct statfs& result)
  217337. {
  217338. for (int i = 5; --i >= 0;)
  217339. {
  217340. if (f.exists())
  217341. break;
  217342. f = f.getParentDirectory();
  217343. }
  217344. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217345. }
  217346. int64 File::getBytesFreeOnVolume() const
  217347. {
  217348. struct statfs buf;
  217349. if (juce_doStatFS (*this, buf))
  217350. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217351. return 0;
  217352. }
  217353. int64 File::getVolumeTotalSize() const
  217354. {
  217355. struct statfs buf;
  217356. if (juce_doStatFS (*this, buf))
  217357. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217358. return 0;
  217359. }
  217360. const String File::getVolumeLabel() const
  217361. {
  217362. #if JUCE_MAC
  217363. struct VolAttrBuf
  217364. {
  217365. u_int32_t length;
  217366. attrreference_t mountPointRef;
  217367. char mountPointSpace [MAXPATHLEN];
  217368. } attrBuf;
  217369. struct attrlist attrList;
  217370. zerostruct (attrList);
  217371. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217372. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217373. File f (*this);
  217374. for (;;)
  217375. {
  217376. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217377. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217378. (int) attrBuf.mountPointRef.attr_length);
  217379. const File parent (f.getParentDirectory());
  217380. if (f == parent)
  217381. break;
  217382. f = parent;
  217383. }
  217384. #endif
  217385. return String::empty;
  217386. }
  217387. int File::getVolumeSerialNumber() const
  217388. {
  217389. return 0; // xxx
  217390. }
  217391. void juce_runSystemCommand (const String& command)
  217392. {
  217393. int result = system (command.toUTF8());
  217394. (void) result;
  217395. }
  217396. const String juce_getOutputFromCommand (const String& command)
  217397. {
  217398. // slight bodge here, as we just pipe the output into a temp file and read it...
  217399. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217400. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217401. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217402. String result (tempFile.loadFileAsString());
  217403. tempFile.deleteFile();
  217404. return result;
  217405. }
  217406. class InterProcessLock::Pimpl
  217407. {
  217408. public:
  217409. Pimpl (const String& name, const int timeOutMillisecs)
  217410. : handle (0), refCount (1)
  217411. {
  217412. #if JUCE_MAC
  217413. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217414. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217415. #else
  217416. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217417. #endif
  217418. temp.create();
  217419. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217420. if (handle != 0)
  217421. {
  217422. struct flock fl;
  217423. zerostruct (fl);
  217424. fl.l_whence = SEEK_SET;
  217425. fl.l_type = F_WRLCK;
  217426. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217427. for (;;)
  217428. {
  217429. const int result = fcntl (handle, F_SETLK, &fl);
  217430. if (result >= 0)
  217431. return;
  217432. if (errno != EINTR)
  217433. {
  217434. if (timeOutMillisecs == 0
  217435. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217436. break;
  217437. Thread::sleep (10);
  217438. }
  217439. }
  217440. }
  217441. closeFile();
  217442. }
  217443. ~Pimpl()
  217444. {
  217445. closeFile();
  217446. }
  217447. void closeFile()
  217448. {
  217449. if (handle != 0)
  217450. {
  217451. struct flock fl;
  217452. zerostruct (fl);
  217453. fl.l_whence = SEEK_SET;
  217454. fl.l_type = F_UNLCK;
  217455. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217456. {}
  217457. close (handle);
  217458. handle = 0;
  217459. }
  217460. }
  217461. int handle, refCount;
  217462. };
  217463. InterProcessLock::InterProcessLock (const String& name_)
  217464. : name (name_)
  217465. {
  217466. }
  217467. InterProcessLock::~InterProcessLock()
  217468. {
  217469. }
  217470. bool InterProcessLock::enter (const int timeOutMillisecs)
  217471. {
  217472. const ScopedLock sl (lock);
  217473. if (pimpl == 0)
  217474. {
  217475. pimpl = new Pimpl (name, timeOutMillisecs);
  217476. if (pimpl->handle == 0)
  217477. pimpl = 0;
  217478. }
  217479. else
  217480. {
  217481. pimpl->refCount++;
  217482. }
  217483. return pimpl != 0;
  217484. }
  217485. void InterProcessLock::exit()
  217486. {
  217487. const ScopedLock sl (lock);
  217488. // Trying to release the lock too many times!
  217489. jassert (pimpl != 0);
  217490. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217491. pimpl = 0;
  217492. }
  217493. void JUCE_API juce_threadEntryPoint (void*);
  217494. void* threadEntryProc (void* userData)
  217495. {
  217496. JUCE_AUTORELEASEPOOL
  217497. juce_threadEntryPoint (userData);
  217498. return 0;
  217499. }
  217500. void* juce_createThread (void* userData)
  217501. {
  217502. pthread_t handle = 0;
  217503. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217504. {
  217505. pthread_detach (handle);
  217506. return (void*) handle;
  217507. }
  217508. return 0;
  217509. }
  217510. void juce_killThread (void* handle)
  217511. {
  217512. if (handle != 0)
  217513. pthread_cancel ((pthread_t) handle);
  217514. }
  217515. void juce_setCurrentThreadName (const String& /*name*/)
  217516. {
  217517. }
  217518. bool juce_setThreadPriority (void* handle, int priority)
  217519. {
  217520. struct sched_param param;
  217521. int policy;
  217522. priority = jlimit (0, 10, priority);
  217523. if (handle == 0)
  217524. handle = (void*) pthread_self();
  217525. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217526. return false;
  217527. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217528. const int minPriority = sched_get_priority_min (policy);
  217529. const int maxPriority = sched_get_priority_max (policy);
  217530. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217531. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217532. }
  217533. Thread::ThreadID Thread::getCurrentThreadId()
  217534. {
  217535. return (ThreadID) pthread_self();
  217536. }
  217537. void Thread::yield()
  217538. {
  217539. sched_yield();
  217540. }
  217541. /* Remove this macro if you're having problems compiling the cpu affinity
  217542. calls (the API for these has changed about quite a bit in various Linux
  217543. versions, and a lot of distros seem to ship with obsolete versions)
  217544. */
  217545. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217546. #define SUPPORT_AFFINITIES 1
  217547. #endif
  217548. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217549. {
  217550. #if SUPPORT_AFFINITIES
  217551. cpu_set_t affinity;
  217552. CPU_ZERO (&affinity);
  217553. for (int i = 0; i < 32; ++i)
  217554. if ((affinityMask & (1 << i)) != 0)
  217555. CPU_SET (i, &affinity);
  217556. /*
  217557. N.B. If this line causes a compile error, then you've probably not got the latest
  217558. version of glibc installed.
  217559. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217560. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217561. */
  217562. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217563. sched_yield();
  217564. #else
  217565. /* affinities aren't supported because either the appropriate header files weren't found,
  217566. or the SUPPORT_AFFINITIES macro was turned off
  217567. */
  217568. jassertfalse;
  217569. #endif
  217570. }
  217571. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217572. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217573. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217574. // compiled on its own).
  217575. #if JUCE_INCLUDED_FILE
  217576. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217577. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217578. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217579. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217580. bool File::copyInternal (const File& dest) const
  217581. {
  217582. FileInputStream in (*this);
  217583. if (dest.deleteFile())
  217584. {
  217585. {
  217586. FileOutputStream out (dest);
  217587. if (out.failedToOpen())
  217588. return false;
  217589. if (out.writeFromInputStream (in, -1) == getSize())
  217590. return true;
  217591. }
  217592. dest.deleteFile();
  217593. }
  217594. return false;
  217595. }
  217596. void File::findFileSystemRoots (Array<File>& destArray)
  217597. {
  217598. destArray.add (File ("/"));
  217599. }
  217600. bool File::isOnCDRomDrive() const
  217601. {
  217602. struct statfs buf;
  217603. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217604. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217605. }
  217606. bool File::isOnHardDisk() const
  217607. {
  217608. struct statfs buf;
  217609. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217610. {
  217611. switch (buf.f_type)
  217612. {
  217613. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217614. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217615. case U_NFS_SUPER_MAGIC: // Network NFS
  217616. case U_SMB_SUPER_MAGIC: // Network Samba
  217617. return false;
  217618. default:
  217619. // Assume anything else is a hard-disk (but note it could
  217620. // be a RAM disk. There isn't a good way of determining
  217621. // this for sure)
  217622. return true;
  217623. }
  217624. }
  217625. // Assume so if this fails for some reason
  217626. return true;
  217627. }
  217628. bool File::isOnRemovableDrive() const
  217629. {
  217630. jassertfalse; // xxx not implemented for linux!
  217631. return false;
  217632. }
  217633. bool File::isHidden() const
  217634. {
  217635. return getFileName().startsWithChar ('.');
  217636. }
  217637. static const File juce_readlink (const char* const utf8, const File& defaultFile)
  217638. {
  217639. const int size = 8192;
  217640. HeapBlock<char> buffer;
  217641. buffer.malloc (size + 4);
  217642. const size_t numBytes = readlink (utf8, buffer, size);
  217643. if (numBytes > 0 && numBytes <= size)
  217644. return File (String::fromUTF8 (buffer, (int) numBytes));
  217645. return defaultFile;
  217646. }
  217647. const File File::getLinkedTarget() const
  217648. {
  217649. return juce_readlink (getFullPathName().toUTF8(), *this);
  217650. }
  217651. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217652. const File File::getSpecialLocation (const SpecialLocationType type)
  217653. {
  217654. switch (type)
  217655. {
  217656. case userHomeDirectory:
  217657. {
  217658. const char* homeDir = getenv ("HOME");
  217659. if (homeDir == 0)
  217660. {
  217661. struct passwd* const pw = getpwuid (getuid());
  217662. if (pw != 0)
  217663. homeDir = pw->pw_dir;
  217664. }
  217665. return File (String::fromUTF8 (homeDir));
  217666. }
  217667. case userDocumentsDirectory:
  217668. case userMusicDirectory:
  217669. case userMoviesDirectory:
  217670. case userApplicationDataDirectory:
  217671. return File ("~");
  217672. case userDesktopDirectory:
  217673. return File ("~/Desktop");
  217674. case commonApplicationDataDirectory:
  217675. return File ("/var");
  217676. case globalApplicationsDirectory:
  217677. return File ("/usr");
  217678. case tempDirectory:
  217679. {
  217680. File tmp ("/var/tmp");
  217681. if (! tmp.isDirectory())
  217682. {
  217683. tmp = "/tmp";
  217684. if (! tmp.isDirectory())
  217685. tmp = File::getCurrentWorkingDirectory();
  217686. }
  217687. return tmp;
  217688. }
  217689. case invokedExecutableFile:
  217690. if (juce_Argv0 != 0)
  217691. return File (String::fromUTF8 (juce_Argv0));
  217692. // deliberate fall-through...
  217693. case currentExecutableFile:
  217694. case currentApplicationFile:
  217695. return juce_getExecutableFile();
  217696. case hostApplicationPath:
  217697. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217698. default:
  217699. jassertfalse; // unknown type?
  217700. break;
  217701. }
  217702. return File::nonexistent;
  217703. }
  217704. const String File::getVersion() const
  217705. {
  217706. return String::empty; // xxx not yet implemented
  217707. }
  217708. bool File::moveToTrash() const
  217709. {
  217710. if (! exists())
  217711. return true;
  217712. File trashCan ("~/.Trash");
  217713. if (! trashCan.isDirectory())
  217714. trashCan = "~/.local/share/Trash/files";
  217715. if (! trashCan.isDirectory())
  217716. return false;
  217717. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217718. getFileExtension()));
  217719. }
  217720. class DirectoryIterator::NativeIterator::Pimpl
  217721. {
  217722. public:
  217723. Pimpl (const File& directory, const String& wildCard_)
  217724. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217725. wildCard (wildCard_),
  217726. dir (opendir (directory.getFullPathName().toUTF8()))
  217727. {
  217728. if (wildCard == "*.*")
  217729. wildCard = "*";
  217730. wildcardUTF8 = wildCard.toUTF8();
  217731. }
  217732. ~Pimpl()
  217733. {
  217734. if (dir != 0)
  217735. closedir (dir);
  217736. }
  217737. bool next (String& filenameFound,
  217738. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217739. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217740. {
  217741. if (dir == 0)
  217742. return false;
  217743. for (;;)
  217744. {
  217745. struct dirent* const de = readdir (dir);
  217746. if (de == 0)
  217747. return false;
  217748. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217749. {
  217750. filenameFound = String::fromUTF8 (de->d_name);
  217751. const String path (parentDir + filenameFound);
  217752. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217753. {
  217754. struct stat info;
  217755. const bool statOk = juce_stat (path, info);
  217756. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217757. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217758. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217759. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217760. }
  217761. if (isHidden != 0)
  217762. *isHidden = filenameFound.startsWithChar ('.');
  217763. if (isReadOnly != 0)
  217764. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217765. return true;
  217766. }
  217767. }
  217768. }
  217769. private:
  217770. String parentDir, wildCard;
  217771. const char* wildcardUTF8;
  217772. DIR* dir;
  217773. Pimpl (const Pimpl&);
  217774. Pimpl& operator= (const Pimpl&);
  217775. };
  217776. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217777. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217778. {
  217779. }
  217780. DirectoryIterator::NativeIterator::~NativeIterator()
  217781. {
  217782. }
  217783. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217784. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217785. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217786. {
  217787. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217788. }
  217789. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217790. {
  217791. String cmdString (fileName.replace (" ", "\\ ",false));
  217792. cmdString << " " << parameters;
  217793. if (URL::isProbablyAWebsiteURL (fileName)
  217794. || cmdString.startsWithIgnoreCase ("file:")
  217795. || URL::isProbablyAnEmailAddress (fileName))
  217796. {
  217797. // create a command that tries to launch a bunch of likely browsers
  217798. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217799. StringArray cmdLines;
  217800. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217801. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217802. cmdString = cmdLines.joinIntoString (" || ");
  217803. }
  217804. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217805. const int cpid = fork();
  217806. if (cpid == 0)
  217807. {
  217808. setsid();
  217809. // Child process
  217810. execve (argv[0], (char**) argv, environ);
  217811. exit (0);
  217812. }
  217813. return cpid >= 0;
  217814. }
  217815. void File::revealToUser() const
  217816. {
  217817. if (isDirectory())
  217818. startAsProcess();
  217819. else if (getParentDirectory().exists())
  217820. getParentDirectory().startAsProcess();
  217821. }
  217822. #endif
  217823. /*** End of inlined file: juce_linux_Files.cpp ***/
  217824. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217825. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217826. // compiled on its own).
  217827. #if JUCE_INCLUDED_FILE
  217828. struct NamedPipeInternal
  217829. {
  217830. String pipeInName, pipeOutName;
  217831. int pipeIn, pipeOut;
  217832. bool volatile createdPipe, blocked, stopReadOperation;
  217833. static void signalHandler (int) {}
  217834. };
  217835. void NamedPipe::cancelPendingReads()
  217836. {
  217837. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217838. {
  217839. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217840. intern->stopReadOperation = true;
  217841. char buffer [1] = { 0 };
  217842. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217843. (void) bytesWritten;
  217844. int timeout = 2000;
  217845. while (intern->blocked && --timeout >= 0)
  217846. Thread::sleep (2);
  217847. intern->stopReadOperation = false;
  217848. }
  217849. }
  217850. void NamedPipe::close()
  217851. {
  217852. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217853. if (intern != 0)
  217854. {
  217855. internal = 0;
  217856. if (intern->pipeIn != -1)
  217857. ::close (intern->pipeIn);
  217858. if (intern->pipeOut != -1)
  217859. ::close (intern->pipeOut);
  217860. if (intern->createdPipe)
  217861. {
  217862. unlink (intern->pipeInName.toUTF8());
  217863. unlink (intern->pipeOutName.toUTF8());
  217864. }
  217865. delete intern;
  217866. }
  217867. }
  217868. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217869. {
  217870. close();
  217871. NamedPipeInternal* const intern = new NamedPipeInternal();
  217872. internal = intern;
  217873. intern->createdPipe = createPipe;
  217874. intern->blocked = false;
  217875. intern->stopReadOperation = false;
  217876. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217877. siginterrupt (SIGPIPE, 1);
  217878. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217879. intern->pipeInName = pipePath + "_in";
  217880. intern->pipeOutName = pipePath + "_out";
  217881. intern->pipeIn = -1;
  217882. intern->pipeOut = -1;
  217883. if (createPipe)
  217884. {
  217885. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217886. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217887. {
  217888. delete intern;
  217889. internal = 0;
  217890. return false;
  217891. }
  217892. }
  217893. return true;
  217894. }
  217895. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217896. {
  217897. int bytesRead = -1;
  217898. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217899. if (intern != 0)
  217900. {
  217901. intern->blocked = true;
  217902. if (intern->pipeIn == -1)
  217903. {
  217904. if (intern->createdPipe)
  217905. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217906. else
  217907. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217908. if (intern->pipeIn == -1)
  217909. {
  217910. intern->blocked = false;
  217911. return -1;
  217912. }
  217913. }
  217914. bytesRead = 0;
  217915. char* p = (char*) destBuffer;
  217916. while (bytesRead < maxBytesToRead)
  217917. {
  217918. const int bytesThisTime = maxBytesToRead - bytesRead;
  217919. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217920. if (numRead <= 0 || intern->stopReadOperation)
  217921. {
  217922. bytesRead = -1;
  217923. break;
  217924. }
  217925. bytesRead += numRead;
  217926. p += bytesRead;
  217927. }
  217928. intern->blocked = false;
  217929. }
  217930. return bytesRead;
  217931. }
  217932. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217933. {
  217934. int bytesWritten = -1;
  217935. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217936. if (intern != 0)
  217937. {
  217938. if (intern->pipeOut == -1)
  217939. {
  217940. if (intern->createdPipe)
  217941. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217942. else
  217943. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217944. if (intern->pipeOut == -1)
  217945. {
  217946. return -1;
  217947. }
  217948. }
  217949. const char* p = (const char*) sourceBuffer;
  217950. bytesWritten = 0;
  217951. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217952. while (bytesWritten < numBytesToWrite
  217953. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217954. {
  217955. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217956. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217957. if (numWritten <= 0)
  217958. {
  217959. bytesWritten = -1;
  217960. break;
  217961. }
  217962. bytesWritten += numWritten;
  217963. p += bytesWritten;
  217964. }
  217965. }
  217966. return bytesWritten;
  217967. }
  217968. #endif
  217969. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217970. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217971. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217972. // compiled on its own).
  217973. #if JUCE_INCLUDED_FILE
  217974. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  217975. {
  217976. int numResults = 0;
  217977. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217978. if (s != -1)
  217979. {
  217980. char buf [1024];
  217981. struct ifconf ifc;
  217982. ifc.ifc_len = sizeof (buf);
  217983. ifc.ifc_buf = buf;
  217984. ioctl (s, SIOCGIFCONF, &ifc);
  217985. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217986. {
  217987. struct ifreq ifr;
  217988. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217989. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217990. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217991. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  217992. && numResults < maxNum)
  217993. {
  217994. int64 a = 0;
  217995. for (int j = 6; --j >= 0;)
  217996. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  217997. *addresses++ = a;
  217998. ++numResults;
  217999. }
  218000. }
  218001. close (s);
  218002. }
  218003. return numResults;
  218004. }
  218005. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218006. const String& emailSubject,
  218007. const String& bodyText,
  218008. const StringArray& filesToAttach)
  218009. {
  218010. jassertfalse; // xxx todo
  218011. return false;
  218012. }
  218013. /** A HTTP input stream that uses sockets.
  218014. */
  218015. class JUCE_HTTPSocketStream
  218016. {
  218017. public:
  218018. JUCE_HTTPSocketStream()
  218019. : readPosition (0),
  218020. socketHandle (-1),
  218021. levelsOfRedirection (0),
  218022. timeoutSeconds (15)
  218023. {
  218024. }
  218025. ~JUCE_HTTPSocketStream()
  218026. {
  218027. closeSocket();
  218028. }
  218029. bool open (const String& url,
  218030. const String& headers,
  218031. const MemoryBlock& postData,
  218032. const bool isPost,
  218033. URL::OpenStreamProgressCallback* callback,
  218034. void* callbackContext,
  218035. int timeOutMs)
  218036. {
  218037. closeSocket();
  218038. uint32 timeOutTime = Time::getMillisecondCounter();
  218039. if (timeOutMs == 0)
  218040. timeOutTime += 60000;
  218041. else if (timeOutMs < 0)
  218042. timeOutTime = 0xffffffff;
  218043. else
  218044. timeOutTime += timeOutMs;
  218045. String hostName, hostPath;
  218046. int hostPort;
  218047. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218048. return false;
  218049. const struct hostent* host = 0;
  218050. int port = 0;
  218051. String proxyName, proxyPath;
  218052. int proxyPort = 0;
  218053. String proxyURL (getenv ("http_proxy"));
  218054. if (proxyURL.startsWithIgnoreCase ("http://"))
  218055. {
  218056. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218057. return false;
  218058. host = gethostbyname (proxyName.toUTF8());
  218059. port = proxyPort;
  218060. }
  218061. else
  218062. {
  218063. host = gethostbyname (hostName.toUTF8());
  218064. port = hostPort;
  218065. }
  218066. if (host == 0)
  218067. return false;
  218068. struct sockaddr_in address;
  218069. zerostruct (address);
  218070. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218071. address.sin_family = host->h_addrtype;
  218072. address.sin_port = htons (port);
  218073. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218074. if (socketHandle == -1)
  218075. return false;
  218076. int receiveBufferSize = 16384;
  218077. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218078. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218079. #if JUCE_MAC
  218080. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218081. #endif
  218082. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218083. {
  218084. closeSocket();
  218085. return false;
  218086. }
  218087. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218088. proxyName, proxyPort,
  218089. hostPath, url,
  218090. headers, postData,
  218091. isPost));
  218092. size_t totalHeaderSent = 0;
  218093. while (totalHeaderSent < requestHeader.getSize())
  218094. {
  218095. if (Time::getMillisecondCounter() > timeOutTime)
  218096. {
  218097. closeSocket();
  218098. return false;
  218099. }
  218100. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218101. if (send (socketHandle,
  218102. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218103. numToSend, 0)
  218104. != numToSend)
  218105. {
  218106. closeSocket();
  218107. return false;
  218108. }
  218109. totalHeaderSent += numToSend;
  218110. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218111. {
  218112. closeSocket();
  218113. return false;
  218114. }
  218115. }
  218116. const String responseHeader (readResponse (timeOutTime));
  218117. if (responseHeader.isNotEmpty())
  218118. {
  218119. //DBG (responseHeader);
  218120. headerLines.clear();
  218121. headerLines.addLines (responseHeader);
  218122. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218123. .substring (0, 3).getIntValue();
  218124. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218125. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218126. String location (findHeaderItem (headerLines, "Location:"));
  218127. if (statusCode >= 300 && statusCode < 400
  218128. && location.isNotEmpty())
  218129. {
  218130. if (! location.startsWithIgnoreCase ("http://"))
  218131. location = "http://" + location;
  218132. if (levelsOfRedirection++ < 3)
  218133. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218134. }
  218135. else
  218136. {
  218137. levelsOfRedirection = 0;
  218138. return true;
  218139. }
  218140. }
  218141. closeSocket();
  218142. return false;
  218143. }
  218144. int read (void* buffer, int bytesToRead)
  218145. {
  218146. fd_set readbits;
  218147. FD_ZERO (&readbits);
  218148. FD_SET (socketHandle, &readbits);
  218149. struct timeval tv;
  218150. tv.tv_sec = timeoutSeconds;
  218151. tv.tv_usec = 0;
  218152. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218153. return 0; // (timeout)
  218154. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218155. readPosition += bytesRead;
  218156. return bytesRead;
  218157. }
  218158. int readPosition;
  218159. StringArray headerLines;
  218160. juce_UseDebuggingNewOperator
  218161. private:
  218162. int socketHandle, levelsOfRedirection;
  218163. const int timeoutSeconds;
  218164. void closeSocket()
  218165. {
  218166. if (socketHandle >= 0)
  218167. close (socketHandle);
  218168. socketHandle = -1;
  218169. }
  218170. const MemoryBlock createRequestHeader (const String& hostName,
  218171. const int hostPort,
  218172. const String& proxyName,
  218173. const int proxyPort,
  218174. const String& hostPath,
  218175. const String& originalURL,
  218176. const String& headers,
  218177. const MemoryBlock& postData,
  218178. const bool isPost)
  218179. {
  218180. String header (isPost ? "POST " : "GET ");
  218181. if (proxyName.isEmpty())
  218182. {
  218183. header << hostPath << " HTTP/1.0\r\nHost: "
  218184. << hostName << ':' << hostPort;
  218185. }
  218186. else
  218187. {
  218188. header << originalURL << " HTTP/1.0\r\nHost: "
  218189. << proxyName << ':' << proxyPort;
  218190. }
  218191. header << "\r\nUser-Agent: JUCE/"
  218192. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218193. << "\r\nConnection: Close\r\nContent-Length: "
  218194. << postData.getSize() << "\r\n"
  218195. << headers << "\r\n";
  218196. MemoryBlock mb;
  218197. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218198. mb.append (postData.getData(), postData.getSize());
  218199. return mb;
  218200. }
  218201. const String readResponse (const uint32 timeOutTime)
  218202. {
  218203. int bytesRead = 0, numConsecutiveLFs = 0;
  218204. MemoryBlock buffer (1024, true);
  218205. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218206. && Time::getMillisecondCounter() <= timeOutTime)
  218207. {
  218208. fd_set readbits;
  218209. FD_ZERO (&readbits);
  218210. FD_SET (socketHandle, &readbits);
  218211. struct timeval tv;
  218212. tv.tv_sec = timeoutSeconds;
  218213. tv.tv_usec = 0;
  218214. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218215. return String::empty; // (timeout)
  218216. buffer.ensureSize (bytesRead + 8, true);
  218217. char* const dest = (char*) buffer.getData() + bytesRead;
  218218. if (recv (socketHandle, dest, 1, 0) == -1)
  218219. return String::empty;
  218220. const char lastByte = *dest;
  218221. ++bytesRead;
  218222. if (lastByte == '\n')
  218223. ++numConsecutiveLFs;
  218224. else if (lastByte != '\r')
  218225. numConsecutiveLFs = 0;
  218226. }
  218227. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218228. if (header.startsWithIgnoreCase ("HTTP/"))
  218229. return header.trimEnd();
  218230. return String::empty;
  218231. }
  218232. static bool decomposeURL (const String& url,
  218233. String& host, String& path, int& port)
  218234. {
  218235. if (! url.startsWithIgnoreCase ("http://"))
  218236. return false;
  218237. const int nextSlash = url.indexOfChar (7, '/');
  218238. int nextColon = url.indexOfChar (7, ':');
  218239. if (nextColon > nextSlash && nextSlash > 0)
  218240. nextColon = -1;
  218241. if (nextColon >= 0)
  218242. {
  218243. host = url.substring (7, nextColon);
  218244. if (nextSlash >= 0)
  218245. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218246. else
  218247. port = url.substring (nextColon + 1).getIntValue();
  218248. }
  218249. else
  218250. {
  218251. port = 80;
  218252. if (nextSlash >= 0)
  218253. host = url.substring (7, nextSlash);
  218254. else
  218255. host = url.substring (7);
  218256. }
  218257. if (nextSlash >= 0)
  218258. path = url.substring (nextSlash);
  218259. else
  218260. path = "/";
  218261. return true;
  218262. }
  218263. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218264. {
  218265. for (int i = 0; i < lines.size(); ++i)
  218266. if (lines[i].startsWithIgnoreCase (itemName))
  218267. return lines[i].substring (itemName.length()).trim();
  218268. return String::empty;
  218269. }
  218270. };
  218271. void* juce_openInternetFile (const String& url,
  218272. const String& headers,
  218273. const MemoryBlock& postData,
  218274. const bool isPost,
  218275. URL::OpenStreamProgressCallback* callback,
  218276. void* callbackContext,
  218277. int timeOutMs)
  218278. {
  218279. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218280. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218281. return s.release();
  218282. return 0;
  218283. }
  218284. void juce_closeInternetFile (void* handle)
  218285. {
  218286. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218287. }
  218288. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218289. {
  218290. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218291. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218292. }
  218293. int64 juce_getInternetFileContentLength (void* handle)
  218294. {
  218295. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218296. if (s != 0)
  218297. {
  218298. //xxx todo
  218299. jassertfalse
  218300. }
  218301. return -1;
  218302. }
  218303. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218304. {
  218305. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218306. if (s != 0)
  218307. {
  218308. for (int i = 0; i < s->headerLines.size(); ++i)
  218309. {
  218310. const String& headersEntry = s->headerLines[i];
  218311. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218312. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218313. const String previousValue (headers [key]);
  218314. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218315. }
  218316. }
  218317. }
  218318. int juce_seekInInternetFile (void* handle, int newPosition)
  218319. {
  218320. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218321. return s != 0 ? s->readPosition : 0;
  218322. }
  218323. #endif
  218324. /*** End of inlined file: juce_linux_Network.cpp ***/
  218325. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218326. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218327. // compiled on its own).
  218328. #if JUCE_INCLUDED_FILE
  218329. void Logger::outputDebugString (const String& text)
  218330. {
  218331. std::cerr << text << std::endl;
  218332. }
  218333. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218334. {
  218335. return Linux;
  218336. }
  218337. const String SystemStats::getOperatingSystemName()
  218338. {
  218339. return "Linux";
  218340. }
  218341. bool SystemStats::isOperatingSystem64Bit()
  218342. {
  218343. #if JUCE_64BIT
  218344. return true;
  218345. #else
  218346. //xxx not sure how to find this out?..
  218347. return false;
  218348. #endif
  218349. }
  218350. static const String juce_getCpuInfo (const char* const key)
  218351. {
  218352. StringArray lines;
  218353. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218354. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218355. if (lines[i].startsWithIgnoreCase (key))
  218356. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218357. return String::empty;
  218358. }
  218359. const String SystemStats::getCpuVendor()
  218360. {
  218361. return juce_getCpuInfo ("vendor_id");
  218362. }
  218363. int SystemStats::getCpuSpeedInMegaherz()
  218364. {
  218365. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218366. }
  218367. int SystemStats::getMemorySizeInMegabytes()
  218368. {
  218369. struct sysinfo sysi;
  218370. if (sysinfo (&sysi) == 0)
  218371. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218372. return 0;
  218373. }
  218374. int SystemStats::getPageSize()
  218375. {
  218376. return sysconf (_SC_PAGESIZE);
  218377. }
  218378. const String SystemStats::getLogonName()
  218379. {
  218380. const char* user = getenv ("USER");
  218381. if (user == 0)
  218382. {
  218383. struct passwd* const pw = getpwuid (getuid());
  218384. if (pw != 0)
  218385. user = pw->pw_name;
  218386. }
  218387. return String::fromUTF8 (user);
  218388. }
  218389. const String SystemStats::getFullUserName()
  218390. {
  218391. return getLogonName();
  218392. }
  218393. void SystemStats::initialiseStats()
  218394. {
  218395. const String flags (juce_getCpuInfo ("flags"));
  218396. cpuFlags.hasMMX = flags.contains ("mmx");
  218397. cpuFlags.hasSSE = flags.contains ("sse");
  218398. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218399. cpuFlags.has3DNow = flags.contains ("3dnow");
  218400. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218401. }
  218402. void PlatformUtilities::fpuReset()
  218403. {
  218404. }
  218405. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218406. {
  218407. if (gettimeofday (t, 0) != 0)
  218408. return false;
  218409. static unsigned int calibrate = 0;
  218410. static bool calibrated = false;
  218411. if (! calibrated)
  218412. {
  218413. calibrated = true;
  218414. struct sysinfo sysi;
  218415. if (sysinfo (&sysi) == 0)
  218416. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218417. }
  218418. t->tv_sec -= calibrate;
  218419. return true;
  218420. }
  218421. uint32 juce_millisecondsSinceStartup() throw()
  218422. {
  218423. timeval t;
  218424. if (juce_getTimeSinceStartup (&t))
  218425. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218426. return 0;
  218427. }
  218428. int64 Time::getHighResolutionTicks() throw()
  218429. {
  218430. timeval t;
  218431. if (juce_getTimeSinceStartup (&t))
  218432. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218433. return 0;
  218434. }
  218435. int64 Time::getHighResolutionTicksPerSecond() throw()
  218436. {
  218437. return 1000000; // (microseconds)
  218438. }
  218439. double Time::getMillisecondCounterHiRes() throw()
  218440. {
  218441. return getHighResolutionTicks() * 0.001;
  218442. }
  218443. bool Time::setSystemTimeToThisTime() const
  218444. {
  218445. timeval t;
  218446. t.tv_sec = millisSinceEpoch % 1000000;
  218447. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218448. return settimeofday (&t, 0) ? false : true;
  218449. }
  218450. #endif
  218451. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218452. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218453. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218454. // compiled on its own).
  218455. #if JUCE_INCLUDED_FILE
  218456. /*
  218457. Note that a lot of methods that you'd expect to find in this file actually
  218458. live in juce_posix_SharedCode.h!
  218459. */
  218460. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218461. void Process::setPriority (ProcessPriority prior)
  218462. {
  218463. struct sched_param param;
  218464. int policy, maxp, minp;
  218465. const int p = (int) prior;
  218466. if (p <= 1)
  218467. policy = SCHED_OTHER;
  218468. else
  218469. policy = SCHED_RR;
  218470. minp = sched_get_priority_min (policy);
  218471. maxp = sched_get_priority_max (policy);
  218472. if (p < 2)
  218473. param.sched_priority = 0;
  218474. else if (p == 2 )
  218475. // Set to middle of lower realtime priority range
  218476. param.sched_priority = minp + (maxp - minp) / 4;
  218477. else
  218478. // Set to middle of higher realtime priority range
  218479. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218480. pthread_setschedparam (pthread_self(), policy, &param);
  218481. }
  218482. void Process::terminate()
  218483. {
  218484. exit (0);
  218485. }
  218486. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218487. {
  218488. static char testResult = 0;
  218489. if (testResult == 0)
  218490. {
  218491. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218492. if (testResult >= 0)
  218493. {
  218494. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218495. testResult = 1;
  218496. }
  218497. }
  218498. return testResult < 0;
  218499. }
  218500. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218501. {
  218502. return juce_isRunningUnderDebugger();
  218503. }
  218504. void Process::raisePrivilege()
  218505. {
  218506. // If running suid root, change effective user
  218507. // to root
  218508. if (geteuid() != 0 && getuid() == 0)
  218509. {
  218510. setreuid (geteuid(), getuid());
  218511. setregid (getegid(), getgid());
  218512. }
  218513. }
  218514. void Process::lowerPrivilege()
  218515. {
  218516. // If runing suid root, change effective user
  218517. // back to real user
  218518. if (geteuid() == 0 && getuid() != 0)
  218519. {
  218520. setreuid (geteuid(), getuid());
  218521. setregid (getegid(), getgid());
  218522. }
  218523. }
  218524. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218525. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218526. {
  218527. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218528. }
  218529. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218530. {
  218531. dlclose(handle);
  218532. }
  218533. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218534. {
  218535. return dlsym (libraryHandle, procedureName.toCString());
  218536. }
  218537. #endif
  218538. #endif
  218539. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218540. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218541. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218542. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218543. // compiled on its own).
  218544. #if JUCE_INCLUDED_FILE
  218545. extern Display* display;
  218546. extern Window juce_messageWindowHandle;
  218547. namespace ClipboardHelpers
  218548. {
  218549. static String localClipboardContent;
  218550. static Atom atom_UTF8_STRING;
  218551. static Atom atom_CLIPBOARD;
  218552. static Atom atom_TARGETS;
  218553. static void initSelectionAtoms()
  218554. {
  218555. static bool isInitialised = false;
  218556. if (! isInitialised)
  218557. {
  218558. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218559. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218560. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218561. }
  218562. }
  218563. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218564. // works only for strings shorter than 1000000 bytes
  218565. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218566. {
  218567. String returnData;
  218568. char* clipData;
  218569. Atom actualType;
  218570. int actualFormat;
  218571. unsigned long numItems, bytesLeft;
  218572. if (XGetWindowProperty (display, window, prop,
  218573. 0L /* offset */, 1000000 /* length (max) */, False,
  218574. AnyPropertyType /* format */,
  218575. &actualType, &actualFormat, &numItems, &bytesLeft,
  218576. (unsigned char**) &clipData) == Success)
  218577. {
  218578. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218579. returnData = String::fromUTF8 (clipData, numItems);
  218580. else if (actualType == XA_STRING && actualFormat == 8)
  218581. returnData = String (clipData, numItems);
  218582. if (clipData != 0)
  218583. XFree (clipData);
  218584. jassert (bytesLeft == 0 || numItems == 1000000);
  218585. }
  218586. XDeleteProperty (display, window, prop);
  218587. return returnData;
  218588. }
  218589. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218590. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218591. {
  218592. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218593. // The selection owner will be asked to set the JUCE_SEL property on the
  218594. // juce_messageWindowHandle with the selection content
  218595. XConvertSelection (display, selection, requestedFormat, property_name,
  218596. juce_messageWindowHandle, CurrentTime);
  218597. int count = 50; // will wait at most for 200 ms
  218598. while (--count >= 0)
  218599. {
  218600. XEvent event;
  218601. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218602. {
  218603. if (event.xselection.property == property_name)
  218604. {
  218605. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218606. selectionContent = readWindowProperty (event.xselection.requestor,
  218607. event.xselection.property,
  218608. requestedFormat);
  218609. return true;
  218610. }
  218611. else
  218612. {
  218613. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218614. }
  218615. }
  218616. // not very elegant.. we could do a select() or something like that...
  218617. // however clipboard content requesting is inherently slow on x11, it
  218618. // often takes 50ms or more so...
  218619. Thread::sleep (4);
  218620. }
  218621. return false;
  218622. }
  218623. }
  218624. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218625. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218626. {
  218627. ClipboardHelpers::initSelectionAtoms();
  218628. // the selection content is sent to the target window as a window property
  218629. XSelectionEvent reply;
  218630. reply.type = SelectionNotify;
  218631. reply.display = evt.display;
  218632. reply.requestor = evt.requestor;
  218633. reply.selection = evt.selection;
  218634. reply.target = evt.target;
  218635. reply.property = None; // == "fail"
  218636. reply.time = evt.time;
  218637. HeapBlock <char> data;
  218638. int propertyFormat = 0, numDataItems = 0;
  218639. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218640. {
  218641. if (evt.target == XA_STRING)
  218642. {
  218643. // format data according to system locale
  218644. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218645. data.calloc (numDataItems + 1);
  218646. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218647. propertyFormat = 8; // bits/item
  218648. }
  218649. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218650. {
  218651. // translate to utf8
  218652. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218653. data.calloc (numDataItems + 1);
  218654. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218655. propertyFormat = 8; // bits/item
  218656. }
  218657. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218658. {
  218659. // another application wants to know what we are able to send
  218660. numDataItems = 2;
  218661. propertyFormat = 32; // atoms are 32-bit
  218662. data.calloc (numDataItems * 4);
  218663. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218664. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218665. atoms[1] = XA_STRING;
  218666. }
  218667. }
  218668. else
  218669. {
  218670. DBG ("requested unsupported clipboard");
  218671. }
  218672. if (data != 0)
  218673. {
  218674. const int maxReasonableSelectionSize = 1000000;
  218675. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218676. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218677. {
  218678. XChangeProperty (evt.display, evt.requestor,
  218679. evt.property, evt.target,
  218680. propertyFormat /* 8 or 32 */, PropModeReplace,
  218681. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218682. reply.property = evt.property; // " == success"
  218683. }
  218684. }
  218685. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218686. }
  218687. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218688. {
  218689. ClipboardHelpers::initSelectionAtoms();
  218690. ClipboardHelpers::localClipboardContent = clipText;
  218691. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218692. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218693. }
  218694. const String SystemClipboard::getTextFromClipboard()
  218695. {
  218696. ClipboardHelpers::initSelectionAtoms();
  218697. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218698. level" clipboard that is supposed to be filled by ctrl-C
  218699. etc). When a clipboard manager is running, the content of this
  218700. selection is preserved even when the original selection owner
  218701. exits.
  218702. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218703. filled by good old x11 apps such as xterm)
  218704. */
  218705. String content;
  218706. Atom selection = XA_PRIMARY;
  218707. Window selectionOwner = None;
  218708. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218709. {
  218710. selection = ClipboardHelpers::atom_CLIPBOARD;
  218711. selectionOwner = XGetSelectionOwner (display, selection);
  218712. }
  218713. if (selectionOwner != None)
  218714. {
  218715. if (selectionOwner == juce_messageWindowHandle)
  218716. {
  218717. content = ClipboardHelpers::localClipboardContent;
  218718. }
  218719. else
  218720. {
  218721. // first try: we want an utf8 string
  218722. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218723. if (! ok)
  218724. {
  218725. // second chance, ask for a good old locale-dependent string ..
  218726. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218727. }
  218728. }
  218729. }
  218730. return content;
  218731. }
  218732. #endif
  218733. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218734. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218735. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218736. // compiled on its own).
  218737. #if JUCE_INCLUDED_FILE
  218738. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218739. #define JUCE_DEBUG_XERRORS 1
  218740. #endif
  218741. Display* display = 0;
  218742. Window juce_messageWindowHandle = None;
  218743. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218744. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218745. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218746. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218747. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218748. class InternalMessageQueue
  218749. {
  218750. public:
  218751. InternalMessageQueue()
  218752. : bytesInSocket (0),
  218753. totalEventCount (0)
  218754. {
  218755. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218756. (void) ret; jassert (ret == 0);
  218757. //setNonBlocking (fd[0]);
  218758. //setNonBlocking (fd[1]);
  218759. }
  218760. ~InternalMessageQueue()
  218761. {
  218762. close (fd[0]);
  218763. close (fd[1]);
  218764. clearSingletonInstance();
  218765. }
  218766. void postMessage (Message* msg)
  218767. {
  218768. const int maxBytesInSocketQueue = 128;
  218769. ScopedLock sl (lock);
  218770. queue.add (msg);
  218771. if (bytesInSocket < maxBytesInSocketQueue)
  218772. {
  218773. ++bytesInSocket;
  218774. ScopedUnlock ul (lock);
  218775. const unsigned char x = 0xff;
  218776. size_t bytesWritten = write (fd[0], &x, 1);
  218777. (void) bytesWritten;
  218778. }
  218779. }
  218780. bool isEmpty() const
  218781. {
  218782. ScopedLock sl (lock);
  218783. return queue.size() == 0;
  218784. }
  218785. bool dispatchNextEvent()
  218786. {
  218787. // This alternates between giving priority to XEvents or internal messages,
  218788. // to keep everything running smoothly..
  218789. if ((++totalEventCount & 1) != 0)
  218790. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218791. else
  218792. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218793. }
  218794. // Wait for an event (either XEvent, or an internal Message)
  218795. bool sleepUntilEvent (const int timeoutMs)
  218796. {
  218797. if (! isEmpty())
  218798. return true;
  218799. if (display != 0)
  218800. {
  218801. ScopedXLock xlock;
  218802. if (XPending (display))
  218803. return true;
  218804. }
  218805. struct timeval tv;
  218806. tv.tv_sec = 0;
  218807. tv.tv_usec = timeoutMs * 1000;
  218808. int fd0 = getWaitHandle();
  218809. int fdmax = fd0;
  218810. fd_set readset;
  218811. FD_ZERO (&readset);
  218812. FD_SET (fd0, &readset);
  218813. if (display != 0)
  218814. {
  218815. ScopedXLock xlock;
  218816. int fd1 = XConnectionNumber (display);
  218817. FD_SET (fd1, &readset);
  218818. fdmax = jmax (fd0, fd1);
  218819. }
  218820. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218821. return (ret > 0); // ret <= 0 if error or timeout
  218822. }
  218823. struct MessageThreadFuncCall
  218824. {
  218825. enum { uniqueID = 0x73774623 };
  218826. MessageCallbackFunction* func;
  218827. void* parameter;
  218828. void* result;
  218829. CriticalSection lock;
  218830. WaitableEvent event;
  218831. };
  218832. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218833. private:
  218834. CriticalSection lock;
  218835. OwnedArray <Message> queue;
  218836. int fd[2];
  218837. int bytesInSocket;
  218838. int totalEventCount;
  218839. int getWaitHandle() const throw() { return fd[1]; }
  218840. static bool setNonBlocking (int handle)
  218841. {
  218842. int socketFlags = fcntl (handle, F_GETFL, 0);
  218843. if (socketFlags == -1)
  218844. return false;
  218845. socketFlags |= O_NONBLOCK;
  218846. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218847. }
  218848. static bool dispatchNextXEvent()
  218849. {
  218850. if (display == 0)
  218851. return false;
  218852. XEvent evt;
  218853. {
  218854. ScopedXLock xlock;
  218855. if (! XPending (display))
  218856. return false;
  218857. XNextEvent (display, &evt);
  218858. }
  218859. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218860. juce_handleSelectionRequest (evt.xselectionrequest);
  218861. else if (evt.xany.window != juce_messageWindowHandle)
  218862. juce_windowMessageReceive (&evt);
  218863. return true;
  218864. }
  218865. Message* popNextMessage()
  218866. {
  218867. ScopedLock sl (lock);
  218868. if (bytesInSocket > 0)
  218869. {
  218870. --bytesInSocket;
  218871. ScopedUnlock ul (lock);
  218872. unsigned char x;
  218873. size_t numBytes = read (fd[1], &x, 1);
  218874. (void) numBytes;
  218875. }
  218876. return queue.removeAndReturn (0);
  218877. }
  218878. bool dispatchNextInternalMessage()
  218879. {
  218880. ScopedPointer <Message> msg (popNextMessage());
  218881. if (msg == 0)
  218882. return false;
  218883. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218884. {
  218885. // Handle callback message
  218886. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218887. call->result = (*(call->func)) (call->parameter);
  218888. call->event.signal();
  218889. }
  218890. else
  218891. {
  218892. // Handle "normal" messages
  218893. MessageManager::getInstance()->deliverMessage (msg.release());
  218894. }
  218895. return true;
  218896. }
  218897. };
  218898. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218899. namespace LinuxErrorHandling
  218900. {
  218901. static bool errorOccurred = false;
  218902. static bool keyboardBreakOccurred = false;
  218903. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218904. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218905. // Usually happens when client-server connection is broken
  218906. static int ioErrorHandler (Display* display)
  218907. {
  218908. DBG ("ERROR: connection to X server broken.. terminating.");
  218909. if (JUCEApplication::isStandaloneApp())
  218910. MessageManager::getInstance()->stopDispatchLoop();
  218911. errorOccurred = true;
  218912. return 0;
  218913. }
  218914. // A protocol error has occurred
  218915. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218916. {
  218917. #if JUCE_DEBUG_XERRORS
  218918. char errorStr[64] = { 0 };
  218919. char requestStr[64] = { 0 };
  218920. XGetErrorText (display, event->error_code, errorStr, 64);
  218921. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218922. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218923. #endif
  218924. return 0;
  218925. }
  218926. static void installXErrorHandlers()
  218927. {
  218928. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218929. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218930. }
  218931. static void removeXErrorHandlers()
  218932. {
  218933. XSetIOErrorHandler (oldIOErrorHandler);
  218934. oldIOErrorHandler = 0;
  218935. XSetErrorHandler (oldErrorHandler);
  218936. oldErrorHandler = 0;
  218937. }
  218938. static void keyboardBreakSignalHandler (int sig)
  218939. {
  218940. if (sig == SIGINT)
  218941. keyboardBreakOccurred = true;
  218942. }
  218943. static void installKeyboardBreakHandler()
  218944. {
  218945. struct sigaction saction;
  218946. sigset_t maskSet;
  218947. sigemptyset (&maskSet);
  218948. saction.sa_handler = keyboardBreakSignalHandler;
  218949. saction.sa_mask = maskSet;
  218950. saction.sa_flags = 0;
  218951. sigaction (SIGINT, &saction, 0);
  218952. }
  218953. }
  218954. void MessageManager::doPlatformSpecificInitialisation()
  218955. {
  218956. // Initialise xlib for multiple thread support
  218957. static bool initThreadCalled = false;
  218958. if (! initThreadCalled)
  218959. {
  218960. if (! XInitThreads())
  218961. {
  218962. // This is fatal! Print error and closedown
  218963. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218964. if (JUCEApplication::isStandaloneApp())
  218965. Process::terminate();
  218966. return;
  218967. }
  218968. initThreadCalled = true;
  218969. }
  218970. LinuxErrorHandling::installXErrorHandlers();
  218971. LinuxErrorHandling::installKeyboardBreakHandler();
  218972. // Create the internal message queue
  218973. InternalMessageQueue::getInstance();
  218974. // Try to connect to a display
  218975. String displayName (getenv ("DISPLAY"));
  218976. if (displayName.isEmpty())
  218977. displayName = ":0.0";
  218978. display = XOpenDisplay (displayName.toCString());
  218979. if (display != 0) // This is not fatal! we can run headless.
  218980. {
  218981. // Create a context to store user data associated with Windows we create in WindowDriver
  218982. windowHandleXContext = XUniqueContext();
  218983. // We're only interested in client messages for this window, which are always sent
  218984. XSetWindowAttributes swa;
  218985. swa.event_mask = NoEventMask;
  218986. // Create our message window (this will never be mapped)
  218987. const int screen = DefaultScreen (display);
  218988. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218989. 0, 0, 1, 1, 0, 0, InputOnly,
  218990. DefaultVisual (display, screen),
  218991. CWEventMask, &swa);
  218992. }
  218993. }
  218994. void MessageManager::doPlatformSpecificShutdown()
  218995. {
  218996. InternalMessageQueue::deleteInstance();
  218997. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218998. {
  218999. XDestroyWindow (display, juce_messageWindowHandle);
  219000. XCloseDisplay (display);
  219001. juce_messageWindowHandle = 0;
  219002. display = 0;
  219003. LinuxErrorHandling::removeXErrorHandlers();
  219004. }
  219005. }
  219006. bool juce_postMessageToSystemQueue (Message* message)
  219007. {
  219008. if (LinuxErrorHandling::errorOccurred)
  219009. return false;
  219010. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219011. return true;
  219012. }
  219013. void MessageManager::broadcastMessage (const String& value)
  219014. {
  219015. /* TODO */
  219016. }
  219017. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219018. {
  219019. if (LinuxErrorHandling::errorOccurred)
  219020. return 0;
  219021. if (isThisTheMessageThread())
  219022. return func (parameter);
  219023. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219024. messageCallContext.func = func;
  219025. messageCallContext.parameter = parameter;
  219026. InternalMessageQueue::getInstanceWithoutCreating()
  219027. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219028. 0, 0, &messageCallContext));
  219029. // Wait for it to complete before continuing
  219030. messageCallContext.event.wait();
  219031. return messageCallContext.result;
  219032. }
  219033. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219034. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219035. {
  219036. while (! LinuxErrorHandling::errorOccurred)
  219037. {
  219038. if (LinuxErrorHandling::keyboardBreakOccurred)
  219039. {
  219040. LinuxErrorHandling::errorOccurred = true;
  219041. if (JUCEApplication::isStandaloneApp())
  219042. Process::terminate();
  219043. break;
  219044. }
  219045. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219046. return true;
  219047. if (returnIfNoPendingMessages)
  219048. break;
  219049. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219050. }
  219051. return false;
  219052. }
  219053. #endif
  219054. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219055. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219056. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219057. // compiled on its own).
  219058. #if JUCE_INCLUDED_FILE
  219059. class FreeTypeFontFace
  219060. {
  219061. public:
  219062. enum FontStyle
  219063. {
  219064. Plain = 0,
  219065. Bold = 1,
  219066. Italic = 2
  219067. };
  219068. FreeTypeFontFace (const String& familyName)
  219069. : hasSerif (false),
  219070. monospaced (false)
  219071. {
  219072. family = familyName;
  219073. }
  219074. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219075. {
  219076. if (names [(int) style].fileName.isEmpty())
  219077. {
  219078. names [(int) style].fileName = name;
  219079. names [(int) style].faceIndex = faceIndex;
  219080. }
  219081. }
  219082. const String& getFamilyName() const throw() { return family; }
  219083. const String& getFileName (const int style, int& faceIndex) const throw()
  219084. {
  219085. faceIndex = names[style].faceIndex;
  219086. return names[style].fileName;
  219087. }
  219088. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219089. bool getMonospaced() const throw() { return monospaced; }
  219090. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219091. bool getSerif() const throw() { return hasSerif; }
  219092. private:
  219093. String family;
  219094. struct FontNameIndex
  219095. {
  219096. String fileName;
  219097. int faceIndex;
  219098. };
  219099. FontNameIndex names[4];
  219100. bool hasSerif, monospaced;
  219101. };
  219102. class FreeTypeInterface : public DeletedAtShutdown
  219103. {
  219104. public:
  219105. FreeTypeInterface()
  219106. : ftLib (0),
  219107. lastFace (0),
  219108. lastBold (false),
  219109. lastItalic (false)
  219110. {
  219111. if (FT_Init_FreeType (&ftLib) != 0)
  219112. {
  219113. ftLib = 0;
  219114. DBG ("Failed to initialize FreeType");
  219115. }
  219116. StringArray fontDirs;
  219117. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219118. fontDirs.removeEmptyStrings (true);
  219119. if (fontDirs.size() == 0)
  219120. {
  219121. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219122. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219123. if (fontsInfo != 0)
  219124. {
  219125. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219126. {
  219127. fontDirs.add (e->getAllSubText().trim());
  219128. }
  219129. }
  219130. }
  219131. if (fontDirs.size() == 0)
  219132. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219133. for (int i = 0; i < fontDirs.size(); ++i)
  219134. enumerateFaces (fontDirs[i]);
  219135. }
  219136. ~FreeTypeInterface()
  219137. {
  219138. if (lastFace != 0)
  219139. FT_Done_Face (lastFace);
  219140. if (ftLib != 0)
  219141. FT_Done_FreeType (ftLib);
  219142. clearSingletonInstance();
  219143. }
  219144. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219145. {
  219146. for (int i = 0; i < faces.size(); i++)
  219147. if (faces[i]->getFamilyName() == familyName)
  219148. return faces[i];
  219149. if (! create)
  219150. return 0;
  219151. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219152. faces.add (newFace);
  219153. return newFace;
  219154. }
  219155. // Enumerate all font faces available in a given directory
  219156. void enumerateFaces (const String& path)
  219157. {
  219158. File dirPath (path);
  219159. if (path.isEmpty() || ! dirPath.isDirectory())
  219160. return;
  219161. DirectoryIterator di (dirPath, true);
  219162. while (di.next())
  219163. {
  219164. File possible (di.getFile());
  219165. if (possible.hasFileExtension ("ttf")
  219166. || possible.hasFileExtension ("pfb")
  219167. || possible.hasFileExtension ("pcf"))
  219168. {
  219169. FT_Face face;
  219170. int faceIndex = 0;
  219171. int numFaces = 0;
  219172. do
  219173. {
  219174. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219175. faceIndex, &face) == 0)
  219176. {
  219177. if (faceIndex == 0)
  219178. numFaces = face->num_faces;
  219179. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219180. {
  219181. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219182. int style = (int) FreeTypeFontFace::Plain;
  219183. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219184. style |= (int) FreeTypeFontFace::Bold;
  219185. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219186. style |= (int) FreeTypeFontFace::Italic;
  219187. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219188. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219189. // Surely there must be a better way to do this?
  219190. const String name (face->family_name);
  219191. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219192. || name.containsIgnoreCase ("Verdana")
  219193. || name.containsIgnoreCase ("Arial")));
  219194. }
  219195. FT_Done_Face (face);
  219196. }
  219197. ++faceIndex;
  219198. }
  219199. while (faceIndex < numFaces);
  219200. }
  219201. }
  219202. }
  219203. // Create a FreeType face object for a given font
  219204. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219205. {
  219206. FT_Face face = 0;
  219207. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219208. {
  219209. face = lastFace;
  219210. }
  219211. else
  219212. {
  219213. if (lastFace != 0)
  219214. {
  219215. FT_Done_Face (lastFace);
  219216. lastFace = 0;
  219217. }
  219218. lastFontName = fontName;
  219219. lastBold = bold;
  219220. lastItalic = italic;
  219221. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219222. if (ftFace != 0)
  219223. {
  219224. int style = (int) FreeTypeFontFace::Plain;
  219225. if (bold)
  219226. style |= (int) FreeTypeFontFace::Bold;
  219227. if (italic)
  219228. style |= (int) FreeTypeFontFace::Italic;
  219229. int faceIndex;
  219230. String fileName (ftFace->getFileName (style, faceIndex));
  219231. if (fileName.isEmpty())
  219232. {
  219233. style ^= (int) FreeTypeFontFace::Bold;
  219234. fileName = ftFace->getFileName (style, faceIndex);
  219235. if (fileName.isEmpty())
  219236. {
  219237. style ^= (int) FreeTypeFontFace::Bold;
  219238. style ^= (int) FreeTypeFontFace::Italic;
  219239. fileName = ftFace->getFileName (style, faceIndex);
  219240. if (! fileName.length())
  219241. {
  219242. style ^= (int) FreeTypeFontFace::Bold;
  219243. fileName = ftFace->getFileName (style, faceIndex);
  219244. }
  219245. }
  219246. }
  219247. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219248. {
  219249. face = lastFace;
  219250. // If there isn't a unicode charmap then select the first one.
  219251. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219252. FT_Set_Charmap (face, face->charmaps[0]);
  219253. }
  219254. }
  219255. }
  219256. return face;
  219257. }
  219258. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219259. {
  219260. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219261. const float height = (float) (face->ascender - face->descender);
  219262. const float scaleX = 1.0f / height;
  219263. const float scaleY = -1.0f / height;
  219264. Path destShape;
  219265. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219266. || face->glyph->format != ft_glyph_format_outline)
  219267. {
  219268. return false;
  219269. }
  219270. const FT_Outline* const outline = &face->glyph->outline;
  219271. const short* const contours = outline->contours;
  219272. const char* const tags = outline->tags;
  219273. FT_Vector* const points = outline->points;
  219274. for (int c = 0; c < outline->n_contours; c++)
  219275. {
  219276. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219277. const int endPoint = contours[c];
  219278. for (int p = startPoint; p <= endPoint; p++)
  219279. {
  219280. const float x = scaleX * points[p].x;
  219281. const float y = scaleY * points[p].y;
  219282. if (p == startPoint)
  219283. {
  219284. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219285. {
  219286. float x2 = scaleX * points [endPoint].x;
  219287. float y2 = scaleY * points [endPoint].y;
  219288. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219289. {
  219290. x2 = (x + x2) * 0.5f;
  219291. y2 = (y + y2) * 0.5f;
  219292. }
  219293. destShape.startNewSubPath (x2, y2);
  219294. }
  219295. else
  219296. {
  219297. destShape.startNewSubPath (x, y);
  219298. }
  219299. }
  219300. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219301. {
  219302. if (p != startPoint)
  219303. destShape.lineTo (x, y);
  219304. }
  219305. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219306. {
  219307. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219308. float x2 = scaleX * points [nextIndex].x;
  219309. float y2 = scaleY * points [nextIndex].y;
  219310. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219311. {
  219312. x2 = (x + x2) * 0.5f;
  219313. y2 = (y + y2) * 0.5f;
  219314. }
  219315. else
  219316. {
  219317. ++p;
  219318. }
  219319. destShape.quadraticTo (x, y, x2, y2);
  219320. }
  219321. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219322. {
  219323. if (p >= endPoint)
  219324. return false;
  219325. const int next1 = p + 1;
  219326. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219327. const float x2 = scaleX * points [next1].x;
  219328. const float y2 = scaleY * points [next1].y;
  219329. const float x3 = scaleX * points [next2].x;
  219330. const float y3 = scaleY * points [next2].y;
  219331. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219332. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219333. return false;
  219334. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219335. p += 2;
  219336. }
  219337. }
  219338. destShape.closeSubPath();
  219339. }
  219340. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219341. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219342. addKerning (face, dest, character, glyphIndex);
  219343. return true;
  219344. }
  219345. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219346. {
  219347. const float height = (float) (face->ascender - face->descender);
  219348. uint32 rightGlyphIndex;
  219349. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219350. while (rightGlyphIndex != 0)
  219351. {
  219352. FT_Vector kerning;
  219353. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219354. {
  219355. if (kerning.x != 0)
  219356. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219357. }
  219358. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219359. }
  219360. }
  219361. // Add a glyph to a font
  219362. bool addGlyphToFont (const uint32 character, const String& fontName,
  219363. bool bold, bool italic, CustomTypeface& dest)
  219364. {
  219365. FT_Face face = createFT_Face (fontName, bold, italic);
  219366. return face != 0 && addGlyph (face, dest, character);
  219367. }
  219368. void getFamilyNames (StringArray& familyNames) const
  219369. {
  219370. for (int i = 0; i < faces.size(); i++)
  219371. familyNames.add (faces[i]->getFamilyName());
  219372. }
  219373. void getMonospacedNames (StringArray& monoSpaced) const
  219374. {
  219375. for (int i = 0; i < faces.size(); i++)
  219376. if (faces[i]->getMonospaced())
  219377. monoSpaced.add (faces[i]->getFamilyName());
  219378. }
  219379. void getSerifNames (StringArray& serif) const
  219380. {
  219381. for (int i = 0; i < faces.size(); i++)
  219382. if (faces[i]->getSerif())
  219383. serif.add (faces[i]->getFamilyName());
  219384. }
  219385. void getSansSerifNames (StringArray& sansSerif) const
  219386. {
  219387. for (int i = 0; i < faces.size(); i++)
  219388. if (! faces[i]->getSerif())
  219389. sansSerif.add (faces[i]->getFamilyName());
  219390. }
  219391. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219392. private:
  219393. FT_Library ftLib;
  219394. FT_Face lastFace;
  219395. String lastFontName;
  219396. bool lastBold, lastItalic;
  219397. OwnedArray<FreeTypeFontFace> faces;
  219398. };
  219399. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219400. class FreetypeTypeface : public CustomTypeface
  219401. {
  219402. public:
  219403. FreetypeTypeface (const Font& font)
  219404. {
  219405. FT_Face face = FreeTypeInterface::getInstance()
  219406. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219407. if (face == 0)
  219408. {
  219409. #if JUCE_DEBUG
  219410. String msg ("Failed to create typeface: ");
  219411. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219412. DBG (msg);
  219413. #endif
  219414. }
  219415. else
  219416. {
  219417. setCharacteristics (font.getTypefaceName(),
  219418. face->ascender / (float) (face->ascender - face->descender),
  219419. font.isBold(), font.isItalic(),
  219420. L' ');
  219421. }
  219422. }
  219423. bool loadGlyphIfPossible (juce_wchar character)
  219424. {
  219425. return FreeTypeInterface::getInstance()
  219426. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219427. }
  219428. };
  219429. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219430. {
  219431. return new FreetypeTypeface (font);
  219432. }
  219433. const StringArray Font::findAllTypefaceNames()
  219434. {
  219435. StringArray s;
  219436. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219437. s.sort (true);
  219438. return s;
  219439. }
  219440. static const String pickBestFont (const StringArray& names,
  219441. const char* const choicesString)
  219442. {
  219443. StringArray choices;
  219444. choices.addTokens (String (choicesString), ",", String::empty);
  219445. choices.trim();
  219446. choices.removeEmptyStrings();
  219447. int i, j;
  219448. for (j = 0; j < choices.size(); ++j)
  219449. if (names.contains (choices[j], true))
  219450. return choices[j];
  219451. for (j = 0; j < choices.size(); ++j)
  219452. for (i = 0; i < names.size(); i++)
  219453. if (names[i].startsWithIgnoreCase (choices[j]))
  219454. return names[i];
  219455. for (j = 0; j < choices.size(); ++j)
  219456. for (i = 0; i < names.size(); i++)
  219457. if (names[i].containsIgnoreCase (choices[j]))
  219458. return names[i];
  219459. return names[0];
  219460. }
  219461. static const String linux_getDefaultSansSerifFontName()
  219462. {
  219463. StringArray allFonts;
  219464. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219465. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219466. }
  219467. static const String linux_getDefaultSerifFontName()
  219468. {
  219469. StringArray allFonts;
  219470. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219471. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219472. }
  219473. static const String linux_getDefaultMonospacedFontName()
  219474. {
  219475. StringArray allFonts;
  219476. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219477. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219478. }
  219479. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219480. {
  219481. defaultSans = linux_getDefaultSansSerifFontName();
  219482. defaultSerif = linux_getDefaultSerifFontName();
  219483. defaultFixed = linux_getDefaultMonospacedFontName();
  219484. }
  219485. #endif
  219486. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219487. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219488. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219489. // compiled on its own).
  219490. #if JUCE_INCLUDED_FILE
  219491. // These are defined in juce_linux_Messaging.cpp
  219492. extern Display* display;
  219493. extern XContext windowHandleXContext;
  219494. namespace Atoms
  219495. {
  219496. enum ProtocolItems
  219497. {
  219498. TAKE_FOCUS = 0,
  219499. DELETE_WINDOW = 1,
  219500. PING = 2
  219501. };
  219502. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219503. ActiveWin, Pid, WindowType, WindowState,
  219504. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219505. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219506. XdndActionDescription, XdndActionCopy,
  219507. allowedActions[5],
  219508. allowedMimeTypes[2];
  219509. const unsigned long DndVersion = 3;
  219510. static void initialiseAtoms()
  219511. {
  219512. static bool atomsInitialised = false;
  219513. if (! atomsInitialised)
  219514. {
  219515. atomsInitialised = true;
  219516. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219517. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219518. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219519. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219520. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219521. State = XInternAtom (display, "WM_STATE", True);
  219522. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219523. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219524. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219525. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219526. XdndAware = XInternAtom (display, "XdndAware", False);
  219527. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219528. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219529. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219530. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219531. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219532. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219533. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219534. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219535. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219536. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219537. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219538. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219539. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219540. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219541. allowedActions[1] = XdndActionCopy;
  219542. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219543. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219544. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219545. }
  219546. }
  219547. }
  219548. namespace Keys
  219549. {
  219550. enum MouseButtons
  219551. {
  219552. NoButton = 0,
  219553. LeftButton = 1,
  219554. MiddleButton = 2,
  219555. RightButton = 3,
  219556. WheelUp = 4,
  219557. WheelDown = 5
  219558. };
  219559. static int AltMask = 0;
  219560. static int NumLockMask = 0;
  219561. static bool numLock = false;
  219562. static bool capsLock = false;
  219563. static char keyStates [32];
  219564. static const int extendedKeyModifier = 0x10000000;
  219565. }
  219566. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219567. {
  219568. int keysym;
  219569. if (keyCode & Keys::extendedKeyModifier)
  219570. {
  219571. keysym = 0xff00 | (keyCode & 0xff);
  219572. }
  219573. else
  219574. {
  219575. keysym = keyCode;
  219576. if (keysym == (XK_Tab & 0xff)
  219577. || keysym == (XK_Return & 0xff)
  219578. || keysym == (XK_Escape & 0xff)
  219579. || keysym == (XK_BackSpace & 0xff))
  219580. {
  219581. keysym |= 0xff00;
  219582. }
  219583. }
  219584. ScopedXLock xlock;
  219585. const int keycode = XKeysymToKeycode (display, keysym);
  219586. const int keybyte = keycode >> 3;
  219587. const int keybit = (1 << (keycode & 7));
  219588. return (Keys::keyStates [keybyte] & keybit) != 0;
  219589. }
  219590. #if JUCE_USE_XSHM
  219591. namespace XSHMHelpers
  219592. {
  219593. static int trappedErrorCode = 0;
  219594. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219595. {
  219596. trappedErrorCode = err->error_code;
  219597. return 0;
  219598. }
  219599. static bool isShmAvailable() throw()
  219600. {
  219601. static bool isChecked = false;
  219602. static bool isAvailable = false;
  219603. if (! isChecked)
  219604. {
  219605. isChecked = true;
  219606. int major, minor;
  219607. Bool pixmaps;
  219608. ScopedXLock xlock;
  219609. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219610. {
  219611. trappedErrorCode = 0;
  219612. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219613. XShmSegmentInfo segmentInfo;
  219614. zerostruct (segmentInfo);
  219615. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219616. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219617. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219618. xImage->bytes_per_line * xImage->height,
  219619. IPC_CREAT | 0777)) >= 0)
  219620. {
  219621. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219622. if (segmentInfo.shmaddr != (void*) -1)
  219623. {
  219624. segmentInfo.readOnly = False;
  219625. xImage->data = segmentInfo.shmaddr;
  219626. XSync (display, False);
  219627. if (XShmAttach (display, &segmentInfo) != 0)
  219628. {
  219629. XSync (display, False);
  219630. XShmDetach (display, &segmentInfo);
  219631. isAvailable = true;
  219632. }
  219633. }
  219634. XFlush (display);
  219635. XDestroyImage (xImage);
  219636. shmdt (segmentInfo.shmaddr);
  219637. }
  219638. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219639. XSetErrorHandler (oldHandler);
  219640. if (trappedErrorCode != 0)
  219641. isAvailable = false;
  219642. }
  219643. }
  219644. return isAvailable;
  219645. }
  219646. }
  219647. #endif
  219648. #if JUCE_USE_XRENDER
  219649. namespace XRender
  219650. {
  219651. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219652. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219653. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219654. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219655. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219656. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219657. static tXRenderFindFormat xRenderFindFormat = 0;
  219658. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219659. static bool isAvailable()
  219660. {
  219661. static bool hasLoaded = false;
  219662. if (! hasLoaded)
  219663. {
  219664. ScopedXLock xlock;
  219665. hasLoaded = true;
  219666. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219667. if (h != 0)
  219668. {
  219669. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219670. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219671. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219672. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219673. }
  219674. if (xRenderQueryVersion != 0
  219675. && xRenderFindStandardFormat != 0
  219676. && xRenderFindFormat != 0
  219677. && xRenderFindVisualFormat != 0)
  219678. {
  219679. int major, minor;
  219680. if (xRenderQueryVersion (display, &major, &minor))
  219681. return true;
  219682. }
  219683. xRenderQueryVersion = 0;
  219684. }
  219685. return xRenderQueryVersion != 0;
  219686. }
  219687. static XRenderPictFormat* findPictureFormat()
  219688. {
  219689. ScopedXLock xlock;
  219690. XRenderPictFormat* pictFormat = 0;
  219691. if (isAvailable())
  219692. {
  219693. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219694. if (pictFormat == 0)
  219695. {
  219696. XRenderPictFormat desiredFormat;
  219697. desiredFormat.type = PictTypeDirect;
  219698. desiredFormat.depth = 32;
  219699. desiredFormat.direct.alphaMask = 0xff;
  219700. desiredFormat.direct.redMask = 0xff;
  219701. desiredFormat.direct.greenMask = 0xff;
  219702. desiredFormat.direct.blueMask = 0xff;
  219703. desiredFormat.direct.alpha = 24;
  219704. desiredFormat.direct.red = 16;
  219705. desiredFormat.direct.green = 8;
  219706. desiredFormat.direct.blue = 0;
  219707. pictFormat = xRenderFindFormat (display,
  219708. PictFormatType | PictFormatDepth
  219709. | PictFormatRedMask | PictFormatRed
  219710. | PictFormatGreenMask | PictFormatGreen
  219711. | PictFormatBlueMask | PictFormatBlue
  219712. | PictFormatAlphaMask | PictFormatAlpha,
  219713. &desiredFormat,
  219714. 0);
  219715. }
  219716. }
  219717. return pictFormat;
  219718. }
  219719. }
  219720. #endif
  219721. namespace Visuals
  219722. {
  219723. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219724. {
  219725. ScopedXLock xlock;
  219726. Visual* visual = 0;
  219727. int numVisuals = 0;
  219728. long desiredMask = VisualNoMask;
  219729. XVisualInfo desiredVisual;
  219730. desiredVisual.screen = DefaultScreen (display);
  219731. desiredVisual.depth = desiredDepth;
  219732. desiredMask = VisualScreenMask | VisualDepthMask;
  219733. if (desiredDepth == 32)
  219734. {
  219735. desiredVisual.c_class = TrueColor;
  219736. desiredVisual.red_mask = 0x00FF0000;
  219737. desiredVisual.green_mask = 0x0000FF00;
  219738. desiredVisual.blue_mask = 0x000000FF;
  219739. desiredVisual.bits_per_rgb = 8;
  219740. desiredMask |= VisualClassMask;
  219741. desiredMask |= VisualRedMaskMask;
  219742. desiredMask |= VisualGreenMaskMask;
  219743. desiredMask |= VisualBlueMaskMask;
  219744. desiredMask |= VisualBitsPerRGBMask;
  219745. }
  219746. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219747. desiredMask,
  219748. &desiredVisual,
  219749. &numVisuals);
  219750. if (xvinfos != 0)
  219751. {
  219752. for (int i = 0; i < numVisuals; i++)
  219753. {
  219754. if (xvinfos[i].depth == desiredDepth)
  219755. {
  219756. visual = xvinfos[i].visual;
  219757. break;
  219758. }
  219759. }
  219760. XFree (xvinfos);
  219761. }
  219762. return visual;
  219763. }
  219764. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219765. {
  219766. Visual* visual = 0;
  219767. if (desiredDepth == 32)
  219768. {
  219769. #if JUCE_USE_XSHM
  219770. if (XSHMHelpers::isShmAvailable())
  219771. {
  219772. #if JUCE_USE_XRENDER
  219773. if (XRender::isAvailable())
  219774. {
  219775. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219776. if (pictFormat != 0)
  219777. {
  219778. int numVisuals = 0;
  219779. XVisualInfo desiredVisual;
  219780. desiredVisual.screen = DefaultScreen (display);
  219781. desiredVisual.depth = 32;
  219782. desiredVisual.bits_per_rgb = 8;
  219783. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219784. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219785. &desiredVisual, &numVisuals);
  219786. if (xvinfos != 0)
  219787. {
  219788. for (int i = 0; i < numVisuals; ++i)
  219789. {
  219790. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219791. if (pictVisualFormat != 0
  219792. && pictVisualFormat->type == PictTypeDirect
  219793. && pictVisualFormat->direct.alphaMask)
  219794. {
  219795. visual = xvinfos[i].visual;
  219796. matchedDepth = 32;
  219797. break;
  219798. }
  219799. }
  219800. XFree (xvinfos);
  219801. }
  219802. }
  219803. }
  219804. #endif
  219805. if (visual == 0)
  219806. {
  219807. visual = findVisualWithDepth (32);
  219808. if (visual != 0)
  219809. matchedDepth = 32;
  219810. }
  219811. }
  219812. #endif
  219813. }
  219814. if (visual == 0 && desiredDepth >= 24)
  219815. {
  219816. visual = findVisualWithDepth (24);
  219817. if (visual != 0)
  219818. matchedDepth = 24;
  219819. }
  219820. if (visual == 0 && desiredDepth >= 16)
  219821. {
  219822. visual = findVisualWithDepth (16);
  219823. if (visual != 0)
  219824. matchedDepth = 16;
  219825. }
  219826. return visual;
  219827. }
  219828. }
  219829. class XBitmapImage : public Image::SharedImage
  219830. {
  219831. public:
  219832. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219833. const bool clearImage, const int imageDepth_, Visual* visual)
  219834. : Image::SharedImage (format_, w, h),
  219835. imageDepth (imageDepth_),
  219836. gc (None)
  219837. {
  219838. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219839. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219840. lineStride = ((w * pixelStride + 3) & ~3);
  219841. ScopedXLock xlock;
  219842. #if JUCE_USE_XSHM
  219843. usingXShm = false;
  219844. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219845. {
  219846. zerostruct (segmentInfo);
  219847. segmentInfo.shmid = -1;
  219848. segmentInfo.shmaddr = (char *) -1;
  219849. segmentInfo.readOnly = False;
  219850. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219851. if (xImage != 0)
  219852. {
  219853. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219854. xImage->bytes_per_line * xImage->height,
  219855. IPC_CREAT | 0777)) >= 0)
  219856. {
  219857. if (segmentInfo.shmid != -1)
  219858. {
  219859. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219860. if (segmentInfo.shmaddr != (void*) -1)
  219861. {
  219862. segmentInfo.readOnly = False;
  219863. xImage->data = segmentInfo.shmaddr;
  219864. imageData = (uint8*) segmentInfo.shmaddr;
  219865. if (XShmAttach (display, &segmentInfo) != 0)
  219866. usingXShm = true;
  219867. else
  219868. jassertfalse;
  219869. }
  219870. else
  219871. {
  219872. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219873. }
  219874. }
  219875. }
  219876. }
  219877. }
  219878. if (! usingXShm)
  219879. #endif
  219880. {
  219881. imageDataAllocated.malloc (lineStride * h);
  219882. imageData = imageDataAllocated;
  219883. if (format_ == Image::ARGB && clearImage)
  219884. zeromem (imageData, h * lineStride);
  219885. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219886. xImage->width = w;
  219887. xImage->height = h;
  219888. xImage->xoffset = 0;
  219889. xImage->format = ZPixmap;
  219890. xImage->data = (char*) imageData;
  219891. xImage->byte_order = ImageByteOrder (display);
  219892. xImage->bitmap_unit = BitmapUnit (display);
  219893. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219894. xImage->bitmap_pad = 32;
  219895. xImage->depth = pixelStride * 8;
  219896. xImage->bytes_per_line = lineStride;
  219897. xImage->bits_per_pixel = pixelStride * 8;
  219898. xImage->red_mask = 0x00FF0000;
  219899. xImage->green_mask = 0x0000FF00;
  219900. xImage->blue_mask = 0x000000FF;
  219901. if (imageDepth == 16)
  219902. {
  219903. const int pixelStride = 2;
  219904. const int lineStride = ((w * pixelStride + 3) & ~3);
  219905. imageData16Bit.malloc (lineStride * h);
  219906. xImage->data = imageData16Bit;
  219907. xImage->bitmap_pad = 16;
  219908. xImage->depth = pixelStride * 8;
  219909. xImage->bytes_per_line = lineStride;
  219910. xImage->bits_per_pixel = pixelStride * 8;
  219911. xImage->red_mask = visual->red_mask;
  219912. xImage->green_mask = visual->green_mask;
  219913. xImage->blue_mask = visual->blue_mask;
  219914. }
  219915. if (! XInitImage (xImage))
  219916. jassertfalse;
  219917. }
  219918. }
  219919. ~XBitmapImage()
  219920. {
  219921. ScopedXLock xlock;
  219922. if (gc != None)
  219923. XFreeGC (display, gc);
  219924. #if JUCE_USE_XSHM
  219925. if (usingXShm)
  219926. {
  219927. XShmDetach (display, &segmentInfo);
  219928. XFlush (display);
  219929. XDestroyImage (xImage);
  219930. shmdt (segmentInfo.shmaddr);
  219931. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219932. }
  219933. else
  219934. #endif
  219935. {
  219936. xImage->data = 0;
  219937. XDestroyImage (xImage);
  219938. }
  219939. }
  219940. Image::ImageType getType() const { return Image::NativeImage; }
  219941. LowLevelGraphicsContext* createLowLevelContext()
  219942. {
  219943. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219944. }
  219945. SharedImage* clone()
  219946. {
  219947. jassertfalse;
  219948. return 0;
  219949. }
  219950. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219951. {
  219952. ScopedXLock xlock;
  219953. if (gc == None)
  219954. {
  219955. XGCValues gcvalues;
  219956. gcvalues.foreground = None;
  219957. gcvalues.background = None;
  219958. gcvalues.function = GXcopy;
  219959. gcvalues.plane_mask = AllPlanes;
  219960. gcvalues.clip_mask = None;
  219961. gcvalues.graphics_exposures = False;
  219962. gc = XCreateGC (display, window,
  219963. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219964. &gcvalues);
  219965. }
  219966. if (imageDepth == 16)
  219967. {
  219968. const uint32 rMask = xImage->red_mask;
  219969. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219970. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219971. const uint32 gMask = xImage->green_mask;
  219972. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219973. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219974. const uint32 bMask = xImage->blue_mask;
  219975. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219976. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219977. const Image::BitmapData srcData (Image (this), false);
  219978. for (int y = sy; y < sy + dh; ++y)
  219979. {
  219980. const uint8* p = srcData.getPixelPointer (sx, y);
  219981. for (int x = sx; x < sx + dw; ++x)
  219982. {
  219983. const PixelRGB* const pixel = (const PixelRGB*) p;
  219984. p += srcData.pixelStride;
  219985. XPutPixel (xImage, x, y,
  219986. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219987. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219988. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219989. }
  219990. }
  219991. }
  219992. // blit results to screen.
  219993. #if JUCE_USE_XSHM
  219994. if (usingXShm)
  219995. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219996. else
  219997. #endif
  219998. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219999. }
  220000. juce_UseDebuggingNewOperator
  220001. private:
  220002. XImage* xImage;
  220003. const int imageDepth;
  220004. HeapBlock <uint8> imageDataAllocated;
  220005. HeapBlock <char> imageData16Bit;
  220006. GC gc;
  220007. #if JUCE_USE_XSHM
  220008. XShmSegmentInfo segmentInfo;
  220009. bool usingXShm;
  220010. #endif
  220011. static int getShiftNeeded (const uint32 mask) throw()
  220012. {
  220013. for (int i = 32; --i >= 0;)
  220014. if (((mask >> i) & 1) != 0)
  220015. return i - 7;
  220016. jassertfalse;
  220017. return 0;
  220018. }
  220019. };
  220020. class LinuxComponentPeer : public ComponentPeer
  220021. {
  220022. public:
  220023. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220024. : ComponentPeer (component, windowStyleFlags),
  220025. windowH (0),
  220026. parentWindow (0),
  220027. wx (0),
  220028. wy (0),
  220029. ww (0),
  220030. wh (0),
  220031. fullScreen (false),
  220032. mapped (false),
  220033. visual (0),
  220034. depth (0)
  220035. {
  220036. // it's dangerous to create a window on a thread other than the message thread..
  220037. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220038. repainter = new LinuxRepaintManager (this);
  220039. createWindow();
  220040. setTitle (component->getName());
  220041. }
  220042. ~LinuxComponentPeer()
  220043. {
  220044. // it's dangerous to delete a window on a thread other than the message thread..
  220045. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220046. deleteIconPixmaps();
  220047. destroyWindow();
  220048. windowH = 0;
  220049. }
  220050. void* getNativeHandle() const
  220051. {
  220052. return (void*) windowH;
  220053. }
  220054. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220055. {
  220056. XPointer peer = 0;
  220057. ScopedXLock xlock;
  220058. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220059. {
  220060. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220061. peer = 0;
  220062. }
  220063. return (LinuxComponentPeer*) peer;
  220064. }
  220065. void setVisible (bool shouldBeVisible)
  220066. {
  220067. ScopedXLock xlock;
  220068. if (shouldBeVisible)
  220069. XMapWindow (display, windowH);
  220070. else
  220071. XUnmapWindow (display, windowH);
  220072. }
  220073. void setTitle (const String& title)
  220074. {
  220075. setWindowTitle (windowH, title);
  220076. }
  220077. void setPosition (int x, int y)
  220078. {
  220079. setBounds (x, y, ww, wh, false);
  220080. }
  220081. void setSize (int w, int h)
  220082. {
  220083. setBounds (wx, wy, w, h, false);
  220084. }
  220085. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220086. {
  220087. fullScreen = isNowFullScreen;
  220088. if (windowH != 0)
  220089. {
  220090. Component::SafePointer<Component> deletionChecker (component);
  220091. wx = x;
  220092. wy = y;
  220093. ww = jmax (1, w);
  220094. wh = jmax (1, h);
  220095. ScopedXLock xlock;
  220096. // Make sure the Window manager does what we want
  220097. XSizeHints* hints = XAllocSizeHints();
  220098. hints->flags = USSize | USPosition;
  220099. hints->width = ww;
  220100. hints->height = wh;
  220101. hints->x = wx;
  220102. hints->y = wy;
  220103. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220104. {
  220105. hints->min_width = hints->max_width = hints->width;
  220106. hints->min_height = hints->max_height = hints->height;
  220107. hints->flags |= PMinSize | PMaxSize;
  220108. }
  220109. XSetWMNormalHints (display, windowH, hints);
  220110. XFree (hints);
  220111. XMoveResizeWindow (display, windowH,
  220112. wx - windowBorder.getLeft(),
  220113. wy - windowBorder.getTop(), ww, wh);
  220114. if (deletionChecker != 0)
  220115. {
  220116. updateBorderSize();
  220117. handleMovedOrResized();
  220118. }
  220119. }
  220120. }
  220121. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220122. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220123. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220124. {
  220125. return relativePosition + getScreenPosition();
  220126. }
  220127. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220128. {
  220129. return screenPosition - getScreenPosition();
  220130. }
  220131. void setMinimised (bool shouldBeMinimised)
  220132. {
  220133. if (shouldBeMinimised)
  220134. {
  220135. Window root = RootWindow (display, DefaultScreen (display));
  220136. XClientMessageEvent clientMsg;
  220137. clientMsg.display = display;
  220138. clientMsg.window = windowH;
  220139. clientMsg.type = ClientMessage;
  220140. clientMsg.format = 32;
  220141. clientMsg.message_type = Atoms::ChangeState;
  220142. clientMsg.data.l[0] = IconicState;
  220143. ScopedXLock xlock;
  220144. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220145. }
  220146. else
  220147. {
  220148. setVisible (true);
  220149. }
  220150. }
  220151. bool isMinimised() const
  220152. {
  220153. bool minimised = false;
  220154. unsigned char* stateProp;
  220155. unsigned long nitems, bytesLeft;
  220156. Atom actualType;
  220157. int actualFormat;
  220158. ScopedXLock xlock;
  220159. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220160. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220161. &stateProp) == Success
  220162. && actualType == Atoms::State
  220163. && actualFormat == 32
  220164. && nitems > 0)
  220165. {
  220166. if (((unsigned long*) stateProp)[0] == IconicState)
  220167. minimised = true;
  220168. XFree (stateProp);
  220169. }
  220170. return minimised;
  220171. }
  220172. void setFullScreen (const bool shouldBeFullScreen)
  220173. {
  220174. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220175. setMinimised (false);
  220176. if (fullScreen != shouldBeFullScreen)
  220177. {
  220178. if (shouldBeFullScreen)
  220179. r = Desktop::getInstance().getMainMonitorArea();
  220180. if (! r.isEmpty())
  220181. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220182. getComponent()->repaint();
  220183. }
  220184. }
  220185. bool isFullScreen() const
  220186. {
  220187. return fullScreen;
  220188. }
  220189. bool isChildWindowOf (Window possibleParent) const
  220190. {
  220191. Window* windowList = 0;
  220192. uint32 windowListSize = 0;
  220193. Window parent, root;
  220194. ScopedXLock xlock;
  220195. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220196. {
  220197. if (windowList != 0)
  220198. XFree (windowList);
  220199. return parent == possibleParent;
  220200. }
  220201. return false;
  220202. }
  220203. bool isFrontWindow() const
  220204. {
  220205. Window* windowList = 0;
  220206. uint32 windowListSize = 0;
  220207. bool result = false;
  220208. ScopedXLock xlock;
  220209. Window parent, root = RootWindow (display, DefaultScreen (display));
  220210. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220211. {
  220212. for (int i = windowListSize; --i >= 0;)
  220213. {
  220214. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220215. if (peer != 0)
  220216. {
  220217. result = (peer == this);
  220218. break;
  220219. }
  220220. }
  220221. }
  220222. if (windowList != 0)
  220223. XFree (windowList);
  220224. return result;
  220225. }
  220226. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220227. {
  220228. int x = position.getX();
  220229. int y = position.getY();
  220230. if (((unsigned int) x) >= (unsigned int) ww
  220231. || ((unsigned int) y) >= (unsigned int) wh)
  220232. return false;
  220233. bool inFront = false;
  220234. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220235. {
  220236. Component* const c = Desktop::getInstance().getComponent (i);
  220237. if (inFront)
  220238. {
  220239. if (c->contains (x + wx - c->getScreenX(),
  220240. y + wy - c->getScreenY()))
  220241. {
  220242. return false;
  220243. }
  220244. }
  220245. else if (c == getComponent())
  220246. {
  220247. inFront = true;
  220248. }
  220249. }
  220250. if (trueIfInAChildWindow)
  220251. return true;
  220252. ::Window root, child;
  220253. unsigned int bw, depth;
  220254. int wx, wy, w, h;
  220255. ScopedXLock xlock;
  220256. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220257. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220258. &bw, &depth))
  220259. {
  220260. return false;
  220261. }
  220262. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220263. return false;
  220264. return child == None;
  220265. }
  220266. const BorderSize getFrameSize() const
  220267. {
  220268. return BorderSize();
  220269. }
  220270. bool setAlwaysOnTop (bool alwaysOnTop)
  220271. {
  220272. return false;
  220273. }
  220274. void toFront (bool makeActive)
  220275. {
  220276. if (makeActive)
  220277. {
  220278. setVisible (true);
  220279. grabFocus();
  220280. }
  220281. XEvent ev;
  220282. ev.xclient.type = ClientMessage;
  220283. ev.xclient.serial = 0;
  220284. ev.xclient.send_event = True;
  220285. ev.xclient.message_type = Atoms::ActiveWin;
  220286. ev.xclient.window = windowH;
  220287. ev.xclient.format = 32;
  220288. ev.xclient.data.l[0] = 2;
  220289. ev.xclient.data.l[1] = CurrentTime;
  220290. ev.xclient.data.l[2] = 0;
  220291. ev.xclient.data.l[3] = 0;
  220292. ev.xclient.data.l[4] = 0;
  220293. {
  220294. ScopedXLock xlock;
  220295. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220296. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220297. XWindowAttributes attr;
  220298. XGetWindowAttributes (display, windowH, &attr);
  220299. if (component->isAlwaysOnTop())
  220300. XRaiseWindow (display, windowH);
  220301. XSync (display, False);
  220302. }
  220303. handleBroughtToFront();
  220304. }
  220305. void toBehind (ComponentPeer* other)
  220306. {
  220307. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220308. jassert (otherPeer != 0); // wrong type of window?
  220309. if (otherPeer != 0)
  220310. {
  220311. setMinimised (false);
  220312. Window newStack[] = { otherPeer->windowH, windowH };
  220313. ScopedXLock xlock;
  220314. XRestackWindows (display, newStack, 2);
  220315. }
  220316. }
  220317. bool isFocused() const
  220318. {
  220319. int revert = 0;
  220320. Window focusedWindow = 0;
  220321. ScopedXLock xlock;
  220322. XGetInputFocus (display, &focusedWindow, &revert);
  220323. return focusedWindow == windowH;
  220324. }
  220325. void grabFocus()
  220326. {
  220327. XWindowAttributes atts;
  220328. ScopedXLock xlock;
  220329. if (windowH != 0
  220330. && XGetWindowAttributes (display, windowH, &atts)
  220331. && atts.map_state == IsViewable
  220332. && ! isFocused())
  220333. {
  220334. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220335. isActiveApplication = true;
  220336. }
  220337. }
  220338. void textInputRequired (const Point<int>&)
  220339. {
  220340. }
  220341. void repaint (const Rectangle<int>& area)
  220342. {
  220343. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220344. }
  220345. void performAnyPendingRepaintsNow()
  220346. {
  220347. repainter->performAnyPendingRepaintsNow();
  220348. }
  220349. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220350. {
  220351. ScopedXLock xlock;
  220352. const int width = image.getWidth();
  220353. const int height = image.getHeight();
  220354. HeapBlock <char> colour (width * height);
  220355. int index = 0;
  220356. for (int y = 0; y < height; ++y)
  220357. for (int x = 0; x < width; ++x)
  220358. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220359. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220360. 0, colour.getData(),
  220361. width, height, 32, 0);
  220362. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220363. width, height, 24);
  220364. GC gc = XCreateGC (display, pixmap, 0, 0);
  220365. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220366. XFreeGC (display, gc);
  220367. return pixmap;
  220368. }
  220369. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220370. {
  220371. ScopedXLock xlock;
  220372. const int width = image.getWidth();
  220373. const int height = image.getHeight();
  220374. const int stride = (width + 7) >> 3;
  220375. HeapBlock <char> mask;
  220376. mask.calloc (stride * height);
  220377. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220378. for (int y = 0; y < height; ++y)
  220379. {
  220380. for (int x = 0; x < width; ++x)
  220381. {
  220382. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220383. const int offset = y * stride + (x >> 3);
  220384. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220385. mask[offset] |= bit;
  220386. }
  220387. }
  220388. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220389. mask.getData(), width, height, 1, 0, 1);
  220390. }
  220391. void setIcon (const Image& newIcon)
  220392. {
  220393. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220394. HeapBlock <unsigned long> data (dataSize);
  220395. int index = 0;
  220396. data[index++] = newIcon.getWidth();
  220397. data[index++] = newIcon.getHeight();
  220398. for (int y = 0; y < newIcon.getHeight(); ++y)
  220399. for (int x = 0; x < newIcon.getWidth(); ++x)
  220400. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220401. ScopedXLock xlock;
  220402. XChangeProperty (display, windowH,
  220403. XInternAtom (display, "_NET_WM_ICON", False),
  220404. XA_CARDINAL, 32, PropModeReplace,
  220405. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220406. deleteIconPixmaps();
  220407. XWMHints* wmHints = XGetWMHints (display, windowH);
  220408. if (wmHints == 0)
  220409. wmHints = XAllocWMHints();
  220410. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220411. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220412. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220413. XSetWMHints (display, windowH, wmHints);
  220414. XFree (wmHints);
  220415. XSync (display, False);
  220416. }
  220417. void deleteIconPixmaps()
  220418. {
  220419. ScopedXLock xlock;
  220420. XWMHints* wmHints = XGetWMHints (display, windowH);
  220421. if (wmHints != 0)
  220422. {
  220423. if ((wmHints->flags & IconPixmapHint) != 0)
  220424. {
  220425. wmHints->flags &= ~IconPixmapHint;
  220426. XFreePixmap (display, wmHints->icon_pixmap);
  220427. }
  220428. if ((wmHints->flags & IconMaskHint) != 0)
  220429. {
  220430. wmHints->flags &= ~IconMaskHint;
  220431. XFreePixmap (display, wmHints->icon_mask);
  220432. }
  220433. XSetWMHints (display, windowH, wmHints);
  220434. XFree (wmHints);
  220435. }
  220436. }
  220437. void handleWindowMessage (XEvent* event)
  220438. {
  220439. switch (event->xany.type)
  220440. {
  220441. case 2: // 'KeyPress'
  220442. {
  220443. ScopedXLock xlock;
  220444. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220445. updateKeyStates (keyEvent->keycode, true);
  220446. char utf8 [64];
  220447. zeromem (utf8, sizeof (utf8));
  220448. KeySym sym;
  220449. {
  220450. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220451. ::setlocale (LC_ALL, "");
  220452. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220453. ::setlocale (LC_ALL, oldLocale);
  220454. }
  220455. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220456. int keyCode = (int) unicodeChar;
  220457. if (keyCode < 0x20)
  220458. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220459. const ModifierKeys oldMods (currentModifiers);
  220460. bool keyPressed = false;
  220461. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220462. if ((sym & 0xff00) == 0xff00)
  220463. {
  220464. // Translate keypad
  220465. if (sym == XK_KP_Divide)
  220466. keyCode = XK_slash;
  220467. else if (sym == XK_KP_Multiply)
  220468. keyCode = XK_asterisk;
  220469. else if (sym == XK_KP_Subtract)
  220470. keyCode = XK_hyphen;
  220471. else if (sym == XK_KP_Add)
  220472. keyCode = XK_plus;
  220473. else if (sym == XK_KP_Enter)
  220474. keyCode = XK_Return;
  220475. else if (sym == XK_KP_Decimal)
  220476. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220477. else if (sym == XK_KP_0)
  220478. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220479. else if (sym == XK_KP_1)
  220480. keyCode = Keys::numLock ? XK_1 : XK_End;
  220481. else if (sym == XK_KP_2)
  220482. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220483. else if (sym == XK_KP_3)
  220484. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220485. else if (sym == XK_KP_4)
  220486. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220487. else if (sym == XK_KP_5)
  220488. keyCode = XK_5;
  220489. else if (sym == XK_KP_6)
  220490. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220491. else if (sym == XK_KP_7)
  220492. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220493. else if (sym == XK_KP_8)
  220494. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220495. else if (sym == XK_KP_9)
  220496. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220497. switch (sym)
  220498. {
  220499. case XK_Left:
  220500. case XK_Right:
  220501. case XK_Up:
  220502. case XK_Down:
  220503. case XK_Page_Up:
  220504. case XK_Page_Down:
  220505. case XK_End:
  220506. case XK_Home:
  220507. case XK_Delete:
  220508. case XK_Insert:
  220509. keyPressed = true;
  220510. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220511. break;
  220512. case XK_Tab:
  220513. case XK_Return:
  220514. case XK_Escape:
  220515. case XK_BackSpace:
  220516. keyPressed = true;
  220517. keyCode &= 0xff;
  220518. break;
  220519. default:
  220520. {
  220521. if (sym >= XK_F1 && sym <= XK_F16)
  220522. {
  220523. keyPressed = true;
  220524. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220525. }
  220526. break;
  220527. }
  220528. }
  220529. }
  220530. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220531. keyPressed = true;
  220532. if (oldMods != currentModifiers)
  220533. handleModifierKeysChange();
  220534. if (keyDownChange)
  220535. handleKeyUpOrDown (true);
  220536. if (keyPressed)
  220537. handleKeyPress (keyCode, unicodeChar);
  220538. break;
  220539. }
  220540. case KeyRelease:
  220541. {
  220542. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220543. updateKeyStates (keyEvent->keycode, false);
  220544. ScopedXLock xlock;
  220545. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220546. const ModifierKeys oldMods (currentModifiers);
  220547. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220548. if (oldMods != currentModifiers)
  220549. handleModifierKeysChange();
  220550. if (keyDownChange)
  220551. handleKeyUpOrDown (false);
  220552. break;
  220553. }
  220554. case ButtonPress:
  220555. {
  220556. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220557. updateKeyModifiers (buttonPressEvent->state);
  220558. bool buttonMsg = false;
  220559. const int map = pointerMap [buttonPressEvent->button - Button1];
  220560. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220561. {
  220562. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220563. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220564. }
  220565. if (map == Keys::LeftButton)
  220566. {
  220567. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220568. buttonMsg = true;
  220569. }
  220570. else if (map == Keys::RightButton)
  220571. {
  220572. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220573. buttonMsg = true;
  220574. }
  220575. else if (map == Keys::MiddleButton)
  220576. {
  220577. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220578. buttonMsg = true;
  220579. }
  220580. if (buttonMsg)
  220581. {
  220582. toFront (true);
  220583. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220584. getEventTime (buttonPressEvent->time));
  220585. }
  220586. clearLastMousePos();
  220587. break;
  220588. }
  220589. case ButtonRelease:
  220590. {
  220591. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220592. updateKeyModifiers (buttonRelEvent->state);
  220593. const int map = pointerMap [buttonRelEvent->button - Button1];
  220594. if (map == Keys::LeftButton)
  220595. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220596. else if (map == Keys::RightButton)
  220597. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220598. else if (map == Keys::MiddleButton)
  220599. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220600. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220601. getEventTime (buttonRelEvent->time));
  220602. clearLastMousePos();
  220603. break;
  220604. }
  220605. case MotionNotify:
  220606. {
  220607. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220608. updateKeyModifiers (movedEvent->state);
  220609. const Point<int> mousePos (Desktop::getMousePosition());
  220610. if (lastMousePos != mousePos)
  220611. {
  220612. lastMousePos = mousePos;
  220613. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220614. {
  220615. Window wRoot = 0, wParent = 0;
  220616. {
  220617. ScopedXLock xlock;
  220618. unsigned int numChildren;
  220619. Window* wChild = 0;
  220620. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220621. }
  220622. if (wParent != 0
  220623. && wParent != windowH
  220624. && wParent != wRoot)
  220625. {
  220626. parentWindow = wParent;
  220627. updateBounds();
  220628. }
  220629. else
  220630. {
  220631. parentWindow = 0;
  220632. }
  220633. }
  220634. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220635. }
  220636. break;
  220637. }
  220638. case EnterNotify:
  220639. {
  220640. clearLastMousePos();
  220641. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220642. if (! currentModifiers.isAnyMouseButtonDown())
  220643. {
  220644. updateKeyModifiers (enterEvent->state);
  220645. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220646. }
  220647. break;
  220648. }
  220649. case LeaveNotify:
  220650. {
  220651. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220652. // Suppress the normal leave if we've got a pointer grab, or if
  220653. // it's a bogus one caused by clicking a mouse button when running
  220654. // in a Window manager
  220655. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220656. || leaveEvent->mode == NotifyUngrab)
  220657. {
  220658. updateKeyModifiers (leaveEvent->state);
  220659. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220660. }
  220661. break;
  220662. }
  220663. case FocusIn:
  220664. {
  220665. isActiveApplication = true;
  220666. if (isFocused())
  220667. handleFocusGain();
  220668. break;
  220669. }
  220670. case FocusOut:
  220671. {
  220672. isActiveApplication = false;
  220673. if (! isFocused())
  220674. handleFocusLoss();
  220675. break;
  220676. }
  220677. case Expose:
  220678. {
  220679. // Batch together all pending expose events
  220680. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220681. XEvent nextEvent;
  220682. ScopedXLock xlock;
  220683. if (exposeEvent->window != windowH)
  220684. {
  220685. Window child;
  220686. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220687. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220688. &child);
  220689. }
  220690. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220691. exposeEvent->width, exposeEvent->height));
  220692. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220693. {
  220694. XPeekEvent (display, (XEvent*) &nextEvent);
  220695. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220696. break;
  220697. XNextEvent (display, (XEvent*) &nextEvent);
  220698. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220699. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220700. nextExposeEvent->width, nextExposeEvent->height));
  220701. }
  220702. break;
  220703. }
  220704. case CirculateNotify:
  220705. case CreateNotify:
  220706. case DestroyNotify:
  220707. // Think we can ignore these
  220708. break;
  220709. case ConfigureNotify:
  220710. {
  220711. updateBounds();
  220712. updateBorderSize();
  220713. handleMovedOrResized();
  220714. // if the native title bar is dragged, need to tell any active menus, etc.
  220715. if ((styleFlags & windowHasTitleBar) != 0
  220716. && component->isCurrentlyBlockedByAnotherModalComponent())
  220717. {
  220718. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220719. if (currentModalComp != 0)
  220720. currentModalComp->inputAttemptWhenModal();
  220721. }
  220722. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220723. if (confEvent->window == windowH
  220724. && confEvent->above != 0
  220725. && isFrontWindow())
  220726. {
  220727. handleBroughtToFront();
  220728. }
  220729. break;
  220730. }
  220731. case ReparentNotify:
  220732. {
  220733. parentWindow = 0;
  220734. Window wRoot = 0;
  220735. Window* wChild = 0;
  220736. unsigned int numChildren;
  220737. {
  220738. ScopedXLock xlock;
  220739. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220740. }
  220741. if (parentWindow == windowH || parentWindow == wRoot)
  220742. parentWindow = 0;
  220743. updateBounds();
  220744. updateBorderSize();
  220745. handleMovedOrResized();
  220746. break;
  220747. }
  220748. case GravityNotify:
  220749. {
  220750. updateBounds();
  220751. updateBorderSize();
  220752. handleMovedOrResized();
  220753. break;
  220754. }
  220755. case MapNotify:
  220756. mapped = true;
  220757. handleBroughtToFront();
  220758. break;
  220759. case UnmapNotify:
  220760. mapped = false;
  220761. break;
  220762. case MappingNotify:
  220763. {
  220764. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220765. if (mappingEvent->request != MappingPointer)
  220766. {
  220767. // Deal with modifier/keyboard mapping
  220768. ScopedXLock xlock;
  220769. XRefreshKeyboardMapping (mappingEvent);
  220770. updateModifierMappings();
  220771. }
  220772. break;
  220773. }
  220774. case ClientMessage:
  220775. {
  220776. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220777. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220778. {
  220779. const Atom atom = (Atom) clientMsg->data.l[0];
  220780. if (atom == Atoms::ProtocolList [Atoms::PING])
  220781. {
  220782. Window root = RootWindow (display, DefaultScreen (display));
  220783. event->xclient.window = root;
  220784. XSendEvent (display, root, False, NoEventMask, event);
  220785. XFlush (display);
  220786. }
  220787. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220788. {
  220789. XWindowAttributes atts;
  220790. ScopedXLock xlock;
  220791. if (clientMsg->window != 0
  220792. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220793. {
  220794. if (atts.map_state == IsViewable)
  220795. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220796. }
  220797. }
  220798. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220799. {
  220800. handleUserClosingWindow();
  220801. }
  220802. }
  220803. else if (clientMsg->message_type == Atoms::XdndEnter)
  220804. {
  220805. handleDragAndDropEnter (clientMsg);
  220806. }
  220807. else if (clientMsg->message_type == Atoms::XdndLeave)
  220808. {
  220809. resetDragAndDrop();
  220810. }
  220811. else if (clientMsg->message_type == Atoms::XdndPosition)
  220812. {
  220813. handleDragAndDropPosition (clientMsg);
  220814. }
  220815. else if (clientMsg->message_type == Atoms::XdndDrop)
  220816. {
  220817. handleDragAndDropDrop (clientMsg);
  220818. }
  220819. else if (clientMsg->message_type == Atoms::XdndStatus)
  220820. {
  220821. handleDragAndDropStatus (clientMsg);
  220822. }
  220823. else if (clientMsg->message_type == Atoms::XdndFinished)
  220824. {
  220825. resetDragAndDrop();
  220826. }
  220827. break;
  220828. }
  220829. case SelectionNotify:
  220830. handleDragAndDropSelection (event);
  220831. break;
  220832. case SelectionClear:
  220833. case SelectionRequest:
  220834. break;
  220835. default:
  220836. #if JUCE_USE_XSHM
  220837. {
  220838. ScopedXLock xlock;
  220839. if (event->xany.type == XShmGetEventBase (display))
  220840. repainter->notifyPaintCompleted();
  220841. }
  220842. #endif
  220843. break;
  220844. }
  220845. }
  220846. void showMouseCursor (Cursor cursor) throw()
  220847. {
  220848. ScopedXLock xlock;
  220849. XDefineCursor (display, windowH, cursor);
  220850. }
  220851. void setTaskBarIcon (const Image& image)
  220852. {
  220853. ScopedXLock xlock;
  220854. taskbarImage = image;
  220855. Screen* const screen = XDefaultScreenOfDisplay (display);
  220856. const int screenNumber = XScreenNumberOfScreen (screen);
  220857. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220858. screenAtom << screenNumber;
  220859. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220860. XGrabServer (display);
  220861. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220862. if (managerWin != None)
  220863. XSelectInput (display, managerWin, StructureNotifyMask);
  220864. XUngrabServer (display);
  220865. XFlush (display);
  220866. if (managerWin != None)
  220867. {
  220868. XEvent ev;
  220869. zerostruct (ev);
  220870. ev.xclient.type = ClientMessage;
  220871. ev.xclient.window = managerWin;
  220872. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220873. ev.xclient.format = 32;
  220874. ev.xclient.data.l[0] = CurrentTime;
  220875. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220876. ev.xclient.data.l[2] = windowH;
  220877. ev.xclient.data.l[3] = 0;
  220878. ev.xclient.data.l[4] = 0;
  220879. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220880. XSync (display, False);
  220881. }
  220882. // For older KDE's ...
  220883. long atomData = 1;
  220884. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220885. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220886. // For more recent KDE's...
  220887. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220888. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220889. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220890. XSizeHints* hints = XAllocSizeHints();
  220891. hints->flags = PMinSize;
  220892. hints->min_width = 22;
  220893. hints->min_height = 22;
  220894. XSetWMNormalHints (display, windowH, hints);
  220895. XFree (hints);
  220896. }
  220897. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220898. juce_UseDebuggingNewOperator
  220899. bool dontRepaint;
  220900. static ModifierKeys currentModifiers;
  220901. static bool isActiveApplication;
  220902. private:
  220903. class LinuxRepaintManager : public Timer
  220904. {
  220905. public:
  220906. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220907. : peer (peer_),
  220908. lastTimeImageUsed (0)
  220909. {
  220910. #if JUCE_USE_XSHM
  220911. shmCompletedDrawing = true;
  220912. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220913. if (useARGBImagesForRendering)
  220914. {
  220915. ScopedXLock xlock;
  220916. XShmSegmentInfo segmentinfo;
  220917. XImage* const testImage
  220918. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220919. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220920. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220921. XDestroyImage (testImage);
  220922. }
  220923. #endif
  220924. }
  220925. ~LinuxRepaintManager()
  220926. {
  220927. }
  220928. void timerCallback()
  220929. {
  220930. #if JUCE_USE_XSHM
  220931. if (! shmCompletedDrawing)
  220932. return;
  220933. #endif
  220934. if (! regionsNeedingRepaint.isEmpty())
  220935. {
  220936. stopTimer();
  220937. performAnyPendingRepaintsNow();
  220938. }
  220939. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220940. {
  220941. stopTimer();
  220942. image = Image::null;
  220943. }
  220944. }
  220945. void repaint (const Rectangle<int>& area)
  220946. {
  220947. if (! isTimerRunning())
  220948. startTimer (repaintTimerPeriod);
  220949. regionsNeedingRepaint.add (area);
  220950. }
  220951. void performAnyPendingRepaintsNow()
  220952. {
  220953. #if JUCE_USE_XSHM
  220954. if (! shmCompletedDrawing)
  220955. {
  220956. startTimer (repaintTimerPeriod);
  220957. return;
  220958. }
  220959. #endif
  220960. peer->clearMaskedRegion();
  220961. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220962. regionsNeedingRepaint.clear();
  220963. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220964. if (! totalArea.isEmpty())
  220965. {
  220966. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220967. || image.getHeight() < totalArea.getHeight())
  220968. {
  220969. #if JUCE_USE_XSHM
  220970. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220971. : Image::RGB,
  220972. #else
  220973. image = Image (new XBitmapImage (Image::RGB,
  220974. #endif
  220975. (totalArea.getWidth() + 31) & ~31,
  220976. (totalArea.getHeight() + 31) & ~31,
  220977. false, peer->depth, peer->visual));
  220978. }
  220979. startTimer (repaintTimerPeriod);
  220980. RectangleList adjustedList (originalRepaintRegion);
  220981. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220982. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220983. if (peer->depth == 32)
  220984. {
  220985. RectangleList::Iterator i (originalRepaintRegion);
  220986. while (i.next())
  220987. image.clear (*i.getRectangle() - totalArea.getPosition());
  220988. }
  220989. peer->handlePaint (context);
  220990. if (! peer->maskedRegion.isEmpty())
  220991. originalRepaintRegion.subtract (peer->maskedRegion);
  220992. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220993. {
  220994. #if JUCE_USE_XSHM
  220995. shmCompletedDrawing = false;
  220996. #endif
  220997. const Rectangle<int>& r = *i.getRectangle();
  220998. static_cast<XBitmapImage*> (image.getSharedImage())
  220999. ->blitToWindow (peer->windowH,
  221000. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221001. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221002. }
  221003. }
  221004. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221005. startTimer (repaintTimerPeriod);
  221006. }
  221007. #if JUCE_USE_XSHM
  221008. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221009. #endif
  221010. private:
  221011. enum { repaintTimerPeriod = 1000 / 100 };
  221012. LinuxComponentPeer* const peer;
  221013. Image image;
  221014. uint32 lastTimeImageUsed;
  221015. RectangleList regionsNeedingRepaint;
  221016. #if JUCE_USE_XSHM
  221017. bool useARGBImagesForRendering, shmCompletedDrawing;
  221018. #endif
  221019. LinuxRepaintManager (const LinuxRepaintManager&);
  221020. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221021. };
  221022. ScopedPointer <LinuxRepaintManager> repainter;
  221023. friend class LinuxRepaintManager;
  221024. Window windowH, parentWindow;
  221025. int wx, wy, ww, wh;
  221026. Image taskbarImage;
  221027. bool fullScreen, mapped;
  221028. Visual* visual;
  221029. int depth;
  221030. BorderSize windowBorder;
  221031. struct MotifWmHints
  221032. {
  221033. unsigned long flags;
  221034. unsigned long functions;
  221035. unsigned long decorations;
  221036. long input_mode;
  221037. unsigned long status;
  221038. };
  221039. static void updateKeyStates (const int keycode, const bool press) throw()
  221040. {
  221041. const int keybyte = keycode >> 3;
  221042. const int keybit = (1 << (keycode & 7));
  221043. if (press)
  221044. Keys::keyStates [keybyte] |= keybit;
  221045. else
  221046. Keys::keyStates [keybyte] &= ~keybit;
  221047. }
  221048. static void updateKeyModifiers (const int status) throw()
  221049. {
  221050. int keyMods = 0;
  221051. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221052. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221053. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221054. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221055. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221056. Keys::capsLock = ((status & LockMask) != 0);
  221057. }
  221058. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221059. {
  221060. int modifier = 0;
  221061. bool isModifier = true;
  221062. switch (sym)
  221063. {
  221064. case XK_Shift_L:
  221065. case XK_Shift_R:
  221066. modifier = ModifierKeys::shiftModifier;
  221067. break;
  221068. case XK_Control_L:
  221069. case XK_Control_R:
  221070. modifier = ModifierKeys::ctrlModifier;
  221071. break;
  221072. case XK_Alt_L:
  221073. case XK_Alt_R:
  221074. modifier = ModifierKeys::altModifier;
  221075. break;
  221076. case XK_Num_Lock:
  221077. if (press)
  221078. Keys::numLock = ! Keys::numLock;
  221079. break;
  221080. case XK_Caps_Lock:
  221081. if (press)
  221082. Keys::capsLock = ! Keys::capsLock;
  221083. break;
  221084. case XK_Scroll_Lock:
  221085. break;
  221086. default:
  221087. isModifier = false;
  221088. break;
  221089. }
  221090. if (modifier != 0)
  221091. {
  221092. if (press)
  221093. currentModifiers = currentModifiers.withFlags (modifier);
  221094. else
  221095. currentModifiers = currentModifiers.withoutFlags (modifier);
  221096. }
  221097. return isModifier;
  221098. }
  221099. // Alt and Num lock are not defined by standard X
  221100. // modifier constants: check what they're mapped to
  221101. static void updateModifierMappings() throw()
  221102. {
  221103. ScopedXLock xlock;
  221104. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221105. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221106. Keys::AltMask = 0;
  221107. Keys::NumLockMask = 0;
  221108. XModifierKeymap* mapping = XGetModifierMapping (display);
  221109. if (mapping)
  221110. {
  221111. for (int i = 0; i < 8; i++)
  221112. {
  221113. if (mapping->modifiermap [i << 1] == altLeftCode)
  221114. Keys::AltMask = 1 << i;
  221115. else if (mapping->modifiermap [i << 1] == numLockCode)
  221116. Keys::NumLockMask = 1 << i;
  221117. }
  221118. XFreeModifiermap (mapping);
  221119. }
  221120. }
  221121. void removeWindowDecorations (Window wndH)
  221122. {
  221123. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221124. if (hints != None)
  221125. {
  221126. MotifWmHints motifHints;
  221127. zerostruct (motifHints);
  221128. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221129. motifHints.decorations = 0;
  221130. ScopedXLock xlock;
  221131. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221132. (unsigned char*) &motifHints, 4);
  221133. }
  221134. hints = XInternAtom (display, "_WIN_HINTS", True);
  221135. if (hints != None)
  221136. {
  221137. long gnomeHints = 0;
  221138. ScopedXLock xlock;
  221139. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221140. (unsigned char*) &gnomeHints, 1);
  221141. }
  221142. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221143. if (hints != None)
  221144. {
  221145. long kwmHints = 2; /*KDE_tinyDecoration*/
  221146. ScopedXLock xlock;
  221147. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221148. (unsigned char*) &kwmHints, 1);
  221149. }
  221150. }
  221151. void addWindowButtons (Window wndH)
  221152. {
  221153. ScopedXLock xlock;
  221154. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221155. if (hints != None)
  221156. {
  221157. MotifWmHints motifHints;
  221158. zerostruct (motifHints);
  221159. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221160. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221161. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221162. if ((styleFlags & windowHasCloseButton) != 0)
  221163. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221164. if ((styleFlags & windowHasMinimiseButton) != 0)
  221165. {
  221166. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221167. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221168. }
  221169. if ((styleFlags & windowHasMaximiseButton) != 0)
  221170. {
  221171. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221172. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221173. }
  221174. if ((styleFlags & windowIsResizable) != 0)
  221175. {
  221176. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221177. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221178. }
  221179. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221180. }
  221181. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221182. if (hints != None)
  221183. {
  221184. int netHints [6];
  221185. int num = 0;
  221186. if ((styleFlags & windowIsResizable) != 0)
  221187. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221188. if ((styleFlags & windowHasMaximiseButton) != 0)
  221189. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221190. if ((styleFlags & windowHasMinimiseButton) != 0)
  221191. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221192. if ((styleFlags & windowHasCloseButton) != 0)
  221193. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221194. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221195. }
  221196. }
  221197. void setWindowType()
  221198. {
  221199. int netHints [2];
  221200. int numHints = 0;
  221201. if ((styleFlags & windowIsTemporary) != 0
  221202. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221203. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221204. else
  221205. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221206. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221207. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221208. (unsigned char*) &netHints, numHints);
  221209. numHints = 0;
  221210. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221211. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221212. if (component->isAlwaysOnTop())
  221213. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221214. if (numHints > 0)
  221215. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221216. (unsigned char*) &netHints, numHints);
  221217. }
  221218. void createWindow()
  221219. {
  221220. ScopedXLock xlock;
  221221. Atoms::initialiseAtoms();
  221222. resetDragAndDrop();
  221223. // Get defaults for various properties
  221224. const int screen = DefaultScreen (display);
  221225. Window root = RootWindow (display, screen);
  221226. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221227. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221228. if (visual == 0)
  221229. {
  221230. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221231. Process::terminate();
  221232. }
  221233. // Create and install a colormap suitable fr our visual
  221234. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221235. XInstallColormap (display, colormap);
  221236. // Set up the window attributes
  221237. XSetWindowAttributes swa;
  221238. swa.border_pixel = 0;
  221239. swa.background_pixmap = None;
  221240. swa.colormap = colormap;
  221241. swa.event_mask = getAllEventsMask();
  221242. windowH = XCreateWindow (display, root,
  221243. 0, 0, 1, 1,
  221244. 0, depth, InputOutput, visual,
  221245. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221246. &swa);
  221247. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221248. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221249. GrabModeAsync, GrabModeAsync, None, None);
  221250. // Set the window context to identify the window handle object
  221251. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221252. {
  221253. // Failed
  221254. jassertfalse;
  221255. Logger::outputDebugString ("Failed to create context information for window.\n");
  221256. XDestroyWindow (display, windowH);
  221257. windowH = 0;
  221258. return;
  221259. }
  221260. // Set window manager hints
  221261. XWMHints* wmHints = XAllocWMHints();
  221262. wmHints->flags = InputHint | StateHint;
  221263. wmHints->input = True; // Locally active input model
  221264. wmHints->initial_state = NormalState;
  221265. XSetWMHints (display, windowH, wmHints);
  221266. XFree (wmHints);
  221267. // Set the window type
  221268. setWindowType();
  221269. // Define decoration
  221270. if ((styleFlags & windowHasTitleBar) == 0)
  221271. removeWindowDecorations (windowH);
  221272. else
  221273. addWindowButtons (windowH);
  221274. // Set window name
  221275. setWindowTitle (windowH, getComponent()->getName());
  221276. // Associate the PID, allowing to be shut down when something goes wrong
  221277. unsigned long pid = getpid();
  221278. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221279. (unsigned char*) &pid, 1);
  221280. // Set window manager protocols
  221281. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221282. (unsigned char*) Atoms::ProtocolList, 2);
  221283. // Set drag and drop flags
  221284. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221285. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221286. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221287. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221288. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221289. (const unsigned char*) "", 0);
  221290. unsigned long dndVersion = Atoms::DndVersion;
  221291. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221292. (const unsigned char*) &dndVersion, 1);
  221293. // Initialise the pointer and keyboard mapping
  221294. // This is not the same as the logical pointer mapping the X server uses:
  221295. // we don't mess with this.
  221296. static bool mappingInitialised = false;
  221297. if (! mappingInitialised)
  221298. {
  221299. mappingInitialised = true;
  221300. const int numButtons = XGetPointerMapping (display, 0, 0);
  221301. if (numButtons == 2)
  221302. {
  221303. pointerMap[0] = Keys::LeftButton;
  221304. pointerMap[1] = Keys::RightButton;
  221305. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221306. }
  221307. else if (numButtons >= 3)
  221308. {
  221309. pointerMap[0] = Keys::LeftButton;
  221310. pointerMap[1] = Keys::MiddleButton;
  221311. pointerMap[2] = Keys::RightButton;
  221312. if (numButtons >= 5)
  221313. {
  221314. pointerMap[3] = Keys::WheelUp;
  221315. pointerMap[4] = Keys::WheelDown;
  221316. }
  221317. }
  221318. updateModifierMappings();
  221319. }
  221320. }
  221321. void destroyWindow()
  221322. {
  221323. ScopedXLock xlock;
  221324. XPointer handlePointer;
  221325. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221326. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221327. XDestroyWindow (display, windowH);
  221328. // Wait for it to complete and then remove any events for this
  221329. // window from the event queue.
  221330. XSync (display, false);
  221331. XEvent event;
  221332. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221333. {}
  221334. }
  221335. static int getAllEventsMask() throw()
  221336. {
  221337. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221338. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221339. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221340. }
  221341. static int64 getEventTime (::Time t)
  221342. {
  221343. static int64 eventTimeOffset = 0x12345678;
  221344. const int64 thisMessageTime = t;
  221345. if (eventTimeOffset == 0x12345678)
  221346. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221347. return eventTimeOffset + thisMessageTime;
  221348. }
  221349. static void setWindowTitle (Window xwin, const String& title)
  221350. {
  221351. XTextProperty nameProperty;
  221352. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221353. ScopedXLock xlock;
  221354. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221355. {
  221356. XSetWMName (display, xwin, &nameProperty);
  221357. XSetWMIconName (display, xwin, &nameProperty);
  221358. XFree (nameProperty.value);
  221359. }
  221360. }
  221361. void updateBorderSize()
  221362. {
  221363. if ((styleFlags & windowHasTitleBar) == 0)
  221364. {
  221365. windowBorder = BorderSize (0);
  221366. }
  221367. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221368. {
  221369. ScopedXLock xlock;
  221370. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221371. if (hints != None)
  221372. {
  221373. unsigned char* data = 0;
  221374. unsigned long nitems, bytesLeft;
  221375. Atom actualType;
  221376. int actualFormat;
  221377. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221378. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221379. &data) == Success)
  221380. {
  221381. const unsigned long* const sizes = (const unsigned long*) data;
  221382. if (actualFormat == 32)
  221383. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221384. (int) sizes[3], (int) sizes[1]);
  221385. XFree (data);
  221386. }
  221387. }
  221388. }
  221389. }
  221390. void updateBounds()
  221391. {
  221392. jassert (windowH != 0);
  221393. if (windowH != 0)
  221394. {
  221395. Window root, child;
  221396. unsigned int bw, depth;
  221397. ScopedXLock xlock;
  221398. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221399. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221400. &bw, &depth))
  221401. {
  221402. wx = wy = ww = wh = 0;
  221403. }
  221404. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221405. {
  221406. wx = wy = 0;
  221407. }
  221408. }
  221409. }
  221410. void resetDragAndDrop()
  221411. {
  221412. dragAndDropFiles.clear();
  221413. lastDropPos = Point<int> (-1, -1);
  221414. dragAndDropCurrentMimeType = 0;
  221415. dragAndDropSourceWindow = 0;
  221416. srcMimeTypeAtomList.clear();
  221417. }
  221418. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221419. {
  221420. msg.type = ClientMessage;
  221421. msg.display = display;
  221422. msg.window = dragAndDropSourceWindow;
  221423. msg.format = 32;
  221424. msg.data.l[0] = windowH;
  221425. ScopedXLock xlock;
  221426. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221427. }
  221428. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221429. {
  221430. XClientMessageEvent msg;
  221431. zerostruct (msg);
  221432. msg.message_type = Atoms::XdndStatus;
  221433. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221434. msg.data.l[4] = dropAction;
  221435. sendDragAndDropMessage (msg);
  221436. }
  221437. void sendDragAndDropLeave()
  221438. {
  221439. XClientMessageEvent msg;
  221440. zerostruct (msg);
  221441. msg.message_type = Atoms::XdndLeave;
  221442. sendDragAndDropMessage (msg);
  221443. }
  221444. void sendDragAndDropFinish()
  221445. {
  221446. XClientMessageEvent msg;
  221447. zerostruct (msg);
  221448. msg.message_type = Atoms::XdndFinished;
  221449. sendDragAndDropMessage (msg);
  221450. }
  221451. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221452. {
  221453. if ((clientMsg->data.l[1] & 1) == 0)
  221454. {
  221455. sendDragAndDropLeave();
  221456. if (dragAndDropFiles.size() > 0)
  221457. handleFileDragExit (dragAndDropFiles);
  221458. dragAndDropFiles.clear();
  221459. }
  221460. }
  221461. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221462. {
  221463. if (dragAndDropSourceWindow == 0)
  221464. return;
  221465. dragAndDropSourceWindow = clientMsg->data.l[0];
  221466. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221467. (int) clientMsg->data.l[2] & 0xffff);
  221468. dropPos -= getScreenPosition();
  221469. if (lastDropPos != dropPos)
  221470. {
  221471. lastDropPos = dropPos;
  221472. dragAndDropTimestamp = clientMsg->data.l[3];
  221473. Atom targetAction = Atoms::XdndActionCopy;
  221474. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221475. {
  221476. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221477. {
  221478. targetAction = Atoms::allowedActions[i];
  221479. break;
  221480. }
  221481. }
  221482. sendDragAndDropStatus (true, targetAction);
  221483. if (dragAndDropFiles.size() == 0)
  221484. updateDraggedFileList (clientMsg);
  221485. if (dragAndDropFiles.size() > 0)
  221486. handleFileDragMove (dragAndDropFiles, dropPos);
  221487. }
  221488. }
  221489. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221490. {
  221491. if (dragAndDropFiles.size() == 0)
  221492. updateDraggedFileList (clientMsg);
  221493. const StringArray files (dragAndDropFiles);
  221494. const Point<int> lastPos (lastDropPos);
  221495. sendDragAndDropFinish();
  221496. resetDragAndDrop();
  221497. if (files.size() > 0)
  221498. handleFileDragDrop (files, lastPos);
  221499. }
  221500. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221501. {
  221502. dragAndDropFiles.clear();
  221503. srcMimeTypeAtomList.clear();
  221504. dragAndDropCurrentMimeType = 0;
  221505. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221506. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221507. {
  221508. dragAndDropSourceWindow = 0;
  221509. return;
  221510. }
  221511. dragAndDropSourceWindow = clientMsg->data.l[0];
  221512. if ((clientMsg->data.l[1] & 1) != 0)
  221513. {
  221514. Atom actual;
  221515. int format;
  221516. unsigned long count = 0, remaining = 0;
  221517. unsigned char* data = 0;
  221518. ScopedXLock xlock;
  221519. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221520. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221521. &count, &remaining, &data);
  221522. if (data != 0)
  221523. {
  221524. if (actual == XA_ATOM && format == 32 && count != 0)
  221525. {
  221526. const unsigned long* const types = (const unsigned long*) data;
  221527. for (unsigned int i = 0; i < count; ++i)
  221528. if (types[i] != None)
  221529. srcMimeTypeAtomList.add (types[i]);
  221530. }
  221531. XFree (data);
  221532. }
  221533. }
  221534. if (srcMimeTypeAtomList.size() == 0)
  221535. {
  221536. for (int i = 2; i < 5; ++i)
  221537. if (clientMsg->data.l[i] != None)
  221538. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221539. if (srcMimeTypeAtomList.size() == 0)
  221540. {
  221541. dragAndDropSourceWindow = 0;
  221542. return;
  221543. }
  221544. }
  221545. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221546. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221547. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221548. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221549. handleDragAndDropPosition (clientMsg);
  221550. }
  221551. void handleDragAndDropSelection (const XEvent* const evt)
  221552. {
  221553. dragAndDropFiles.clear();
  221554. if (evt->xselection.property != 0)
  221555. {
  221556. StringArray lines;
  221557. {
  221558. MemoryBlock dropData;
  221559. for (;;)
  221560. {
  221561. Atom actual;
  221562. uint8* data = 0;
  221563. unsigned long count = 0, remaining = 0;
  221564. int format = 0;
  221565. ScopedXLock xlock;
  221566. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221567. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221568. &format, &count, &remaining, &data) == Success)
  221569. {
  221570. dropData.append (data, count * format / 8);
  221571. XFree (data);
  221572. if (remaining == 0)
  221573. break;
  221574. }
  221575. else
  221576. {
  221577. XFree (data);
  221578. break;
  221579. }
  221580. }
  221581. lines.addLines (dropData.toString());
  221582. }
  221583. for (int i = 0; i < lines.size(); ++i)
  221584. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221585. dragAndDropFiles.trim();
  221586. dragAndDropFiles.removeEmptyStrings();
  221587. }
  221588. }
  221589. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221590. {
  221591. dragAndDropFiles.clear();
  221592. if (dragAndDropSourceWindow != None
  221593. && dragAndDropCurrentMimeType != 0)
  221594. {
  221595. dragAndDropTimestamp = clientMsg->data.l[2];
  221596. ScopedXLock xlock;
  221597. XConvertSelection (display,
  221598. Atoms::XdndSelection,
  221599. dragAndDropCurrentMimeType,
  221600. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221601. windowH,
  221602. dragAndDropTimestamp);
  221603. }
  221604. }
  221605. StringArray dragAndDropFiles;
  221606. int dragAndDropTimestamp;
  221607. Point<int> lastDropPos;
  221608. Atom dragAndDropCurrentMimeType;
  221609. Window dragAndDropSourceWindow;
  221610. Array <Atom> srcMimeTypeAtomList;
  221611. static int pointerMap[5];
  221612. static Point<int> lastMousePos;
  221613. static void clearLastMousePos() throw()
  221614. {
  221615. lastMousePos = Point<int> (0x100000, 0x100000);
  221616. }
  221617. };
  221618. ModifierKeys LinuxComponentPeer::currentModifiers;
  221619. bool LinuxComponentPeer::isActiveApplication = false;
  221620. int LinuxComponentPeer::pointerMap[5];
  221621. Point<int> LinuxComponentPeer::lastMousePos;
  221622. bool Process::isForegroundProcess()
  221623. {
  221624. return LinuxComponentPeer::isActiveApplication;
  221625. }
  221626. void ModifierKeys::updateCurrentModifiers() throw()
  221627. {
  221628. currentModifiers = LinuxComponentPeer::currentModifiers;
  221629. }
  221630. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221631. {
  221632. Window root, child;
  221633. int x, y, winx, winy;
  221634. unsigned int mask;
  221635. int mouseMods = 0;
  221636. ScopedXLock xlock;
  221637. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221638. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221639. {
  221640. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221641. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221642. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221643. }
  221644. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221645. return LinuxComponentPeer::currentModifiers;
  221646. }
  221647. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221648. {
  221649. if (enableOrDisable)
  221650. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221651. }
  221652. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221653. {
  221654. return new LinuxComponentPeer (this, styleFlags);
  221655. }
  221656. // (this callback is hooked up in the messaging code)
  221657. void juce_windowMessageReceive (XEvent* event)
  221658. {
  221659. if (event->xany.window != None)
  221660. {
  221661. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221662. if (ComponentPeer::isValidPeer (peer))
  221663. peer->handleWindowMessage (event);
  221664. }
  221665. else
  221666. {
  221667. switch (event->xany.type)
  221668. {
  221669. case KeymapNotify:
  221670. {
  221671. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221672. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221673. break;
  221674. }
  221675. default:
  221676. break;
  221677. }
  221678. }
  221679. }
  221680. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221681. {
  221682. if (display == 0)
  221683. return;
  221684. #if JUCE_USE_XINERAMA
  221685. int major_opcode, first_event, first_error;
  221686. ScopedXLock xlock;
  221687. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221688. {
  221689. typedef Bool (*tXineramaIsActive) (Display*);
  221690. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221691. static tXineramaIsActive xXineramaIsActive = 0;
  221692. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221693. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221694. {
  221695. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221696. if (h == 0)
  221697. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221698. if (h != 0)
  221699. {
  221700. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221701. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221702. }
  221703. }
  221704. if (xXineramaIsActive != 0
  221705. && xXineramaQueryScreens != 0
  221706. && xXineramaIsActive (display))
  221707. {
  221708. int numMonitors = 0;
  221709. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221710. if (screens != 0)
  221711. {
  221712. for (int i = numMonitors; --i >= 0;)
  221713. {
  221714. int index = screens[i].screen_number;
  221715. if (index >= 0)
  221716. {
  221717. while (monitorCoords.size() < index)
  221718. monitorCoords.add (Rectangle<int>());
  221719. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221720. screens[i].y_org,
  221721. screens[i].width,
  221722. screens[i].height));
  221723. }
  221724. }
  221725. XFree (screens);
  221726. }
  221727. }
  221728. }
  221729. if (monitorCoords.size() == 0)
  221730. #endif
  221731. {
  221732. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221733. if (hints != None)
  221734. {
  221735. const int numMonitors = ScreenCount (display);
  221736. for (int i = 0; i < numMonitors; ++i)
  221737. {
  221738. Window root = RootWindow (display, i);
  221739. unsigned long nitems, bytesLeft;
  221740. Atom actualType;
  221741. int actualFormat;
  221742. unsigned char* data = 0;
  221743. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221744. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221745. &data) == Success)
  221746. {
  221747. const long* const position = (const long*) data;
  221748. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221749. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221750. position[2], position[3]));
  221751. XFree (data);
  221752. }
  221753. }
  221754. }
  221755. if (monitorCoords.size() == 0)
  221756. {
  221757. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221758. DisplayHeight (display, DefaultScreen (display))));
  221759. }
  221760. }
  221761. }
  221762. void Desktop::createMouseInputSources()
  221763. {
  221764. mouseSources.add (new MouseInputSource (0, true));
  221765. }
  221766. bool Desktop::canUseSemiTransparentWindows() throw()
  221767. {
  221768. int matchedDepth = 0;
  221769. const int desiredDepth = 32;
  221770. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221771. && (matchedDepth == desiredDepth);
  221772. }
  221773. const Point<int> Desktop::getMousePosition()
  221774. {
  221775. Window root, child;
  221776. int x, y, winx, winy;
  221777. unsigned int mask;
  221778. ScopedXLock xlock;
  221779. if (XQueryPointer (display,
  221780. RootWindow (display, DefaultScreen (display)),
  221781. &root, &child,
  221782. &x, &y, &winx, &winy, &mask) == False)
  221783. {
  221784. // Pointer not on the default screen
  221785. x = y = -1;
  221786. }
  221787. return Point<int> (x, y);
  221788. }
  221789. void Desktop::setMousePosition (const Point<int>& newPosition)
  221790. {
  221791. ScopedXLock xlock;
  221792. Window root = RootWindow (display, DefaultScreen (display));
  221793. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221794. }
  221795. static bool screenSaverAllowed = true;
  221796. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221797. {
  221798. if (screenSaverAllowed != isEnabled)
  221799. {
  221800. screenSaverAllowed = isEnabled;
  221801. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221802. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221803. if (xScreenSaverSuspend == 0)
  221804. {
  221805. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221806. if (h != 0)
  221807. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221808. }
  221809. ScopedXLock xlock;
  221810. if (xScreenSaverSuspend != 0)
  221811. xScreenSaverSuspend (display, ! isEnabled);
  221812. }
  221813. }
  221814. bool Desktop::isScreenSaverEnabled()
  221815. {
  221816. return screenSaverAllowed;
  221817. }
  221818. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221819. {
  221820. ScopedXLock xlock;
  221821. const unsigned int imageW = image.getWidth();
  221822. const unsigned int imageH = image.getHeight();
  221823. #if JUCE_USE_XCURSOR
  221824. {
  221825. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221826. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221827. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221828. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221829. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221830. static tXcursorImageCreate xXcursorImageCreate = 0;
  221831. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221832. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221833. static bool hasBeenLoaded = false;
  221834. if (! hasBeenLoaded)
  221835. {
  221836. hasBeenLoaded = true;
  221837. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221838. if (h != 0)
  221839. {
  221840. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221841. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221842. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221843. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221844. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221845. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221846. || ! xXcursorSupportsARGB (display))
  221847. xXcursorSupportsARGB = 0;
  221848. }
  221849. }
  221850. if (xXcursorSupportsARGB != 0)
  221851. {
  221852. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221853. if (xcImage != 0)
  221854. {
  221855. xcImage->xhot = hotspotX;
  221856. xcImage->yhot = hotspotY;
  221857. XcursorPixel* dest = xcImage->pixels;
  221858. for (int y = 0; y < (int) imageH; ++y)
  221859. for (int x = 0; x < (int) imageW; ++x)
  221860. *dest++ = image.getPixelAt (x, y).getARGB();
  221861. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221862. xXcursorImageDestroy (xcImage);
  221863. if (result != 0)
  221864. return result;
  221865. }
  221866. }
  221867. }
  221868. #endif
  221869. Window root = RootWindow (display, DefaultScreen (display));
  221870. unsigned int cursorW, cursorH;
  221871. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221872. return 0;
  221873. Image im (Image::ARGB, cursorW, cursorH, true);
  221874. {
  221875. Graphics g (im);
  221876. if (imageW > cursorW || imageH > cursorH)
  221877. {
  221878. hotspotX = (hotspotX * cursorW) / imageW;
  221879. hotspotY = (hotspotY * cursorH) / imageH;
  221880. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221881. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221882. false);
  221883. }
  221884. else
  221885. {
  221886. g.drawImageAt (image, 0, 0);
  221887. }
  221888. }
  221889. const int stride = (cursorW + 7) >> 3;
  221890. HeapBlock <char> maskPlane, sourcePlane;
  221891. maskPlane.calloc (stride * cursorH);
  221892. sourcePlane.calloc (stride * cursorH);
  221893. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221894. for (int y = cursorH; --y >= 0;)
  221895. {
  221896. for (int x = cursorW; --x >= 0;)
  221897. {
  221898. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221899. const int offset = y * stride + (x >> 3);
  221900. const Colour c (im.getPixelAt (x, y));
  221901. if (c.getAlpha() >= 128)
  221902. maskPlane[offset] |= mask;
  221903. if (c.getBrightness() >= 0.5f)
  221904. sourcePlane[offset] |= mask;
  221905. }
  221906. }
  221907. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221908. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221909. XColor white, black;
  221910. black.red = black.green = black.blue = 0;
  221911. white.red = white.green = white.blue = 0xffff;
  221912. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221913. XFreePixmap (display, sourcePixmap);
  221914. XFreePixmap (display, maskPixmap);
  221915. return result;
  221916. }
  221917. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221918. {
  221919. ScopedXLock xlock;
  221920. if (cursorHandle != 0)
  221921. XFreeCursor (display, (Cursor) cursorHandle);
  221922. }
  221923. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221924. {
  221925. unsigned int shape;
  221926. switch (type)
  221927. {
  221928. case NormalCursor: return None; // Use parent cursor
  221929. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221930. case WaitCursor: shape = XC_watch; break;
  221931. case IBeamCursor: shape = XC_xterm; break;
  221932. case PointingHandCursor: shape = XC_hand2; break;
  221933. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221934. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221935. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221936. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221937. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221938. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221939. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221940. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221941. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221942. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221943. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221944. case CrosshairCursor: shape = XC_crosshair; break;
  221945. case DraggingHandCursor:
  221946. {
  221947. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221948. 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,
  221949. 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 };
  221950. const int dragHandDataSize = 99;
  221951. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221952. }
  221953. case CopyingCursor:
  221954. {
  221955. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221956. 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,
  221957. 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,
  221958. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221959. const int copyCursorSize = 119;
  221960. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221961. }
  221962. default:
  221963. jassertfalse;
  221964. return None;
  221965. }
  221966. ScopedXLock xlock;
  221967. return (void*) XCreateFontCursor (display, shape);
  221968. }
  221969. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221970. {
  221971. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221972. if (lp != 0)
  221973. lp->showMouseCursor ((Cursor) getHandle());
  221974. }
  221975. void MouseCursor::showInAllWindows() const
  221976. {
  221977. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221978. showInWindow (ComponentPeer::getPeer (i));
  221979. }
  221980. const Image juce_createIconForFile (const File& file)
  221981. {
  221982. return Image::null;
  221983. }
  221984. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221985. {
  221986. return createSoftwareImage (format, width, height, clearImage);
  221987. }
  221988. #if JUCE_OPENGL
  221989. class WindowedGLContext : public OpenGLContext
  221990. {
  221991. public:
  221992. WindowedGLContext (Component* const component,
  221993. const OpenGLPixelFormat& pixelFormat_,
  221994. GLXContext sharedContext)
  221995. : renderContext (0),
  221996. embeddedWindow (0),
  221997. pixelFormat (pixelFormat_),
  221998. swapInterval (0)
  221999. {
  222000. jassert (component != 0);
  222001. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222002. if (peer == 0)
  222003. return;
  222004. ScopedXLock xlock;
  222005. XSync (display, False);
  222006. GLint attribs [64];
  222007. int n = 0;
  222008. attribs[n++] = GLX_RGBA;
  222009. attribs[n++] = GLX_DOUBLEBUFFER;
  222010. attribs[n++] = GLX_RED_SIZE;
  222011. attribs[n++] = pixelFormat.redBits;
  222012. attribs[n++] = GLX_GREEN_SIZE;
  222013. attribs[n++] = pixelFormat.greenBits;
  222014. attribs[n++] = GLX_BLUE_SIZE;
  222015. attribs[n++] = pixelFormat.blueBits;
  222016. attribs[n++] = GLX_ALPHA_SIZE;
  222017. attribs[n++] = pixelFormat.alphaBits;
  222018. attribs[n++] = GLX_DEPTH_SIZE;
  222019. attribs[n++] = pixelFormat.depthBufferBits;
  222020. attribs[n++] = GLX_STENCIL_SIZE;
  222021. attribs[n++] = pixelFormat.stencilBufferBits;
  222022. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222023. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222024. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222025. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222026. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222027. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222028. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222029. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222030. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222031. attribs[n++] = None;
  222032. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222033. if (bestVisual == 0)
  222034. return;
  222035. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222036. Window windowH = (Window) peer->getNativeHandle();
  222037. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222038. XSetWindowAttributes swa;
  222039. swa.colormap = colourMap;
  222040. swa.border_pixel = 0;
  222041. swa.event_mask = ExposureMask | StructureNotifyMask;
  222042. embeddedWindow = XCreateWindow (display, windowH,
  222043. 0, 0, 1, 1, 0,
  222044. bestVisual->depth,
  222045. InputOutput,
  222046. bestVisual->visual,
  222047. CWBorderPixel | CWColormap | CWEventMask,
  222048. &swa);
  222049. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222050. XMapWindow (display, embeddedWindow);
  222051. XFreeColormap (display, colourMap);
  222052. XFree (bestVisual);
  222053. XSync (display, False);
  222054. }
  222055. ~WindowedGLContext()
  222056. {
  222057. ScopedXLock xlock;
  222058. deleteContext();
  222059. XUnmapWindow (display, embeddedWindow);
  222060. XDestroyWindow (display, embeddedWindow);
  222061. }
  222062. void deleteContext()
  222063. {
  222064. makeInactive();
  222065. if (renderContext != 0)
  222066. {
  222067. ScopedXLock xlock;
  222068. glXDestroyContext (display, renderContext);
  222069. renderContext = 0;
  222070. }
  222071. }
  222072. bool makeActive() const throw()
  222073. {
  222074. jassert (renderContext != 0);
  222075. ScopedXLock xlock;
  222076. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222077. && XSync (display, False);
  222078. }
  222079. bool makeInactive() const throw()
  222080. {
  222081. ScopedXLock xlock;
  222082. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222083. }
  222084. bool isActive() const throw()
  222085. {
  222086. ScopedXLock xlock;
  222087. return glXGetCurrentContext() == renderContext;
  222088. }
  222089. const OpenGLPixelFormat getPixelFormat() const
  222090. {
  222091. return pixelFormat;
  222092. }
  222093. void* getRawContext() const throw()
  222094. {
  222095. return renderContext;
  222096. }
  222097. void updateWindowPosition (int x, int y, int w, int h, int)
  222098. {
  222099. ScopedXLock xlock;
  222100. XMoveResizeWindow (display, embeddedWindow,
  222101. x, y, jmax (1, w), jmax (1, h));
  222102. }
  222103. void swapBuffers()
  222104. {
  222105. ScopedXLock xlock;
  222106. glXSwapBuffers (display, embeddedWindow);
  222107. }
  222108. bool setSwapInterval (const int numFramesPerSwap)
  222109. {
  222110. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222111. if (GLXSwapIntervalSGI != 0)
  222112. {
  222113. swapInterval = numFramesPerSwap;
  222114. GLXSwapIntervalSGI (numFramesPerSwap);
  222115. return true;
  222116. }
  222117. return false;
  222118. }
  222119. int getSwapInterval() const
  222120. {
  222121. return swapInterval;
  222122. }
  222123. void repaint()
  222124. {
  222125. }
  222126. juce_UseDebuggingNewOperator
  222127. GLXContext renderContext;
  222128. private:
  222129. Window embeddedWindow;
  222130. OpenGLPixelFormat pixelFormat;
  222131. int swapInterval;
  222132. WindowedGLContext (const WindowedGLContext&);
  222133. WindowedGLContext& operator= (const WindowedGLContext&);
  222134. };
  222135. OpenGLContext* OpenGLComponent::createContext()
  222136. {
  222137. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222138. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222139. return (c->renderContext != 0) ? c.release() : 0;
  222140. }
  222141. void juce_glViewport (const int w, const int h)
  222142. {
  222143. glViewport (0, 0, w, h);
  222144. }
  222145. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222146. OwnedArray <OpenGLPixelFormat>& results)
  222147. {
  222148. results.add (new OpenGLPixelFormat()); // xxx
  222149. }
  222150. #endif
  222151. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222152. {
  222153. jassertfalse; // not implemented!
  222154. return false;
  222155. }
  222156. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222157. {
  222158. jassertfalse; // not implemented!
  222159. return false;
  222160. }
  222161. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222162. {
  222163. if (! isOnDesktop ())
  222164. addToDesktop (0);
  222165. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222166. if (wp != 0)
  222167. {
  222168. wp->setTaskBarIcon (newImage);
  222169. setVisible (true);
  222170. toFront (false);
  222171. repaint();
  222172. }
  222173. }
  222174. void SystemTrayIconComponent::paint (Graphics& g)
  222175. {
  222176. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222177. if (wp != 0)
  222178. {
  222179. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222180. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222181. false);
  222182. }
  222183. }
  222184. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222185. {
  222186. // xxx not yet implemented!
  222187. }
  222188. void PlatformUtilities::beep()
  222189. {
  222190. std::cout << "\a" << std::flush;
  222191. }
  222192. bool AlertWindow::showNativeDialogBox (const String& title,
  222193. const String& bodyText,
  222194. bool isOkCancel)
  222195. {
  222196. // use a non-native one for the time being..
  222197. if (isOkCancel)
  222198. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222199. else
  222200. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222201. return true;
  222202. }
  222203. const int KeyPress::spaceKey = XK_space & 0xff;
  222204. const int KeyPress::returnKey = XK_Return & 0xff;
  222205. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222206. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222207. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222208. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222209. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222210. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222211. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222212. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222213. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222214. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222215. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222216. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222217. const int KeyPress::tabKey = XK_Tab & 0xff;
  222218. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222219. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222220. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222221. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222222. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222223. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222224. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222225. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222226. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222227. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222228. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222229. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222230. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222231. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222232. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222233. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222234. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222235. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222236. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222237. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222238. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222239. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222240. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222241. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222242. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222243. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222244. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222245. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222246. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222247. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222248. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222249. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222250. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222251. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222252. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222253. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222254. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222255. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222256. #endif
  222257. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222258. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222259. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222260. // compiled on its own).
  222261. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222262. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222263. {
  222264. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222265. snd_pcm_hw_params_t* hwParams;
  222266. snd_pcm_hw_params_alloca (&hwParams);
  222267. for (int i = 0; ratesToTry[i] != 0; ++i)
  222268. {
  222269. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222270. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222271. {
  222272. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222273. }
  222274. }
  222275. }
  222276. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222277. {
  222278. snd_pcm_hw_params_t *params;
  222279. snd_pcm_hw_params_alloca (&params);
  222280. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222281. {
  222282. snd_pcm_hw_params_get_channels_min (params, minChans);
  222283. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222284. }
  222285. }
  222286. static void getDeviceProperties (const String& deviceID,
  222287. unsigned int& minChansOut,
  222288. unsigned int& maxChansOut,
  222289. unsigned int& minChansIn,
  222290. unsigned int& maxChansIn,
  222291. Array <int>& rates)
  222292. {
  222293. if (deviceID.isEmpty())
  222294. return;
  222295. snd_ctl_t* handle;
  222296. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222297. {
  222298. snd_pcm_info_t* info;
  222299. snd_pcm_info_alloca (&info);
  222300. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222301. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222302. snd_pcm_info_set_subdevice (info, 0);
  222303. if (snd_ctl_pcm_info (handle, info) >= 0)
  222304. {
  222305. snd_pcm_t* pcmHandle;
  222306. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222307. {
  222308. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222309. getDeviceSampleRates (pcmHandle, rates);
  222310. snd_pcm_close (pcmHandle);
  222311. }
  222312. }
  222313. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222314. if (snd_ctl_pcm_info (handle, info) >= 0)
  222315. {
  222316. snd_pcm_t* pcmHandle;
  222317. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222318. {
  222319. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222320. if (rates.size() == 0)
  222321. getDeviceSampleRates (pcmHandle, rates);
  222322. snd_pcm_close (pcmHandle);
  222323. }
  222324. }
  222325. snd_ctl_close (handle);
  222326. }
  222327. }
  222328. class ALSADevice
  222329. {
  222330. public:
  222331. ALSADevice (const String& deviceID,
  222332. const bool forInput)
  222333. : handle (0),
  222334. bitDepth (16),
  222335. numChannelsRunning (0),
  222336. latency (0),
  222337. isInput (forInput),
  222338. sampleFormat (AudioDataConverters::int16LE)
  222339. {
  222340. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222341. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222342. SND_PCM_ASYNC));
  222343. }
  222344. ~ALSADevice()
  222345. {
  222346. if (handle != 0)
  222347. snd_pcm_close (handle);
  222348. }
  222349. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222350. {
  222351. if (handle == 0)
  222352. return false;
  222353. snd_pcm_hw_params_t* hwParams;
  222354. snd_pcm_hw_params_alloca (&hwParams);
  222355. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222356. return false;
  222357. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222358. isInterleaved = false;
  222359. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222360. isInterleaved = true;
  222361. else
  222362. {
  222363. jassertfalse;
  222364. return false;
  222365. }
  222366. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  222367. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  222368. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  222369. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  222370. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  222371. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  222372. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  222373. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  222374. bitDepth = 0;
  222375. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  222376. {
  222377. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222378. {
  222379. bitDepth = formatsToTry [i + 1];
  222380. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  222381. break;
  222382. }
  222383. }
  222384. if (bitDepth == 0)
  222385. {
  222386. error = "device doesn't support a compatible PCM format";
  222387. DBG ("ALSA error: " + error + "\n");
  222388. return false;
  222389. }
  222390. int dir = 0;
  222391. unsigned int periods = 4;
  222392. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222393. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222394. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222395. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222396. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222397. || failed (snd_pcm_hw_params (handle, hwParams)))
  222398. {
  222399. return false;
  222400. }
  222401. snd_pcm_uframes_t frames = 0;
  222402. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222403. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222404. latency = 0;
  222405. else
  222406. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222407. snd_pcm_sw_params_t* swParams;
  222408. snd_pcm_sw_params_alloca (&swParams);
  222409. snd_pcm_uframes_t boundary;
  222410. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222411. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222412. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222413. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222414. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222415. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222416. || failed (snd_pcm_sw_params (handle, swParams)))
  222417. {
  222418. return false;
  222419. }
  222420. /*
  222421. #if JUCE_DEBUG
  222422. // enable this to dump the config of the devices that get opened
  222423. snd_output_t* out;
  222424. snd_output_stdio_attach (&out, stderr, 0);
  222425. snd_pcm_hw_params_dump (hwParams, out);
  222426. snd_pcm_sw_params_dump (swParams, out);
  222427. #endif
  222428. */
  222429. numChannelsRunning = numChannels;
  222430. return true;
  222431. }
  222432. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222433. {
  222434. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222435. float** const data = outputChannelBuffer.getArrayOfChannels();
  222436. if (isInterleaved)
  222437. {
  222438. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222439. float* interleaved = static_cast <float*> (scratch.getData());
  222440. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  222441. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222442. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  222443. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222444. return false;
  222445. }
  222446. else
  222447. {
  222448. for (int i = 0; i < numChannelsRunning; ++i)
  222449. if (data[i] != 0)
  222450. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  222451. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  222452. if (failed (num))
  222453. {
  222454. if (num == -EPIPE)
  222455. {
  222456. if (failed (snd_pcm_prepare (handle)))
  222457. return false;
  222458. }
  222459. else if (num != -ESTRPIPE)
  222460. return false;
  222461. }
  222462. }
  222463. return true;
  222464. }
  222465. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222466. {
  222467. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222468. float** const data = inputChannelBuffer.getArrayOfChannels();
  222469. if (isInterleaved)
  222470. {
  222471. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222472. float* interleaved = static_cast <float*> (scratch.getData());
  222473. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  222474. if (failed (num))
  222475. {
  222476. if (num == -EPIPE)
  222477. {
  222478. if (failed (snd_pcm_prepare (handle)))
  222479. return false;
  222480. }
  222481. else if (num != -ESTRPIPE)
  222482. return false;
  222483. }
  222484. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222485. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  222486. }
  222487. else
  222488. {
  222489. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222490. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222491. return false;
  222492. for (int i = 0; i < numChannelsRunning; ++i)
  222493. if (data[i] != 0)
  222494. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  222495. }
  222496. return true;
  222497. }
  222498. juce_UseDebuggingNewOperator
  222499. snd_pcm_t* handle;
  222500. String error;
  222501. int bitDepth, numChannelsRunning, latency;
  222502. private:
  222503. const bool isInput;
  222504. bool isInterleaved;
  222505. MemoryBlock scratch;
  222506. AudioDataConverters::DataFormat sampleFormat;
  222507. bool failed (const int errorNum)
  222508. {
  222509. if (errorNum >= 0)
  222510. return false;
  222511. error = snd_strerror (errorNum);
  222512. DBG ("ALSA error: " + error + "\n");
  222513. return true;
  222514. }
  222515. };
  222516. class ALSAThread : public Thread
  222517. {
  222518. public:
  222519. ALSAThread (const String& inputId_,
  222520. const String& outputId_)
  222521. : Thread ("Juce ALSA"),
  222522. sampleRate (0),
  222523. bufferSize (0),
  222524. outputLatency (0),
  222525. inputLatency (0),
  222526. callback (0),
  222527. inputId (inputId_),
  222528. outputId (outputId_),
  222529. numCallbacks (0),
  222530. inputChannelBuffer (1, 1),
  222531. outputChannelBuffer (1, 1)
  222532. {
  222533. initialiseRatesAndChannels();
  222534. }
  222535. ~ALSAThread()
  222536. {
  222537. close();
  222538. }
  222539. void open (BigInteger inputChannels,
  222540. BigInteger outputChannels,
  222541. const double sampleRate_,
  222542. const int bufferSize_)
  222543. {
  222544. close();
  222545. error = String::empty;
  222546. sampleRate = sampleRate_;
  222547. bufferSize = bufferSize_;
  222548. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222549. inputChannelBuffer.clear();
  222550. inputChannelDataForCallback.clear();
  222551. currentInputChans.clear();
  222552. if (inputChannels.getHighestBit() >= 0)
  222553. {
  222554. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222555. {
  222556. if (inputChannels[i])
  222557. {
  222558. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222559. currentInputChans.setBit (i);
  222560. }
  222561. }
  222562. }
  222563. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222564. outputChannelBuffer.clear();
  222565. outputChannelDataForCallback.clear();
  222566. currentOutputChans.clear();
  222567. if (outputChannels.getHighestBit() >= 0)
  222568. {
  222569. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222570. {
  222571. if (outputChannels[i])
  222572. {
  222573. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222574. currentOutputChans.setBit (i);
  222575. }
  222576. }
  222577. }
  222578. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222579. {
  222580. outputDevice = new ALSADevice (outputId, false);
  222581. if (outputDevice->error.isNotEmpty())
  222582. {
  222583. error = outputDevice->error;
  222584. outputDevice = 0;
  222585. return;
  222586. }
  222587. currentOutputChans.setRange (0, minChansOut, true);
  222588. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222589. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222590. bufferSize))
  222591. {
  222592. error = outputDevice->error;
  222593. outputDevice = 0;
  222594. return;
  222595. }
  222596. outputLatency = outputDevice->latency;
  222597. }
  222598. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222599. {
  222600. inputDevice = new ALSADevice (inputId, true);
  222601. if (inputDevice->error.isNotEmpty())
  222602. {
  222603. error = inputDevice->error;
  222604. inputDevice = 0;
  222605. return;
  222606. }
  222607. currentInputChans.setRange (0, minChansIn, true);
  222608. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222609. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222610. bufferSize))
  222611. {
  222612. error = inputDevice->error;
  222613. inputDevice = 0;
  222614. return;
  222615. }
  222616. inputLatency = inputDevice->latency;
  222617. }
  222618. if (outputDevice == 0 && inputDevice == 0)
  222619. {
  222620. error = "no channels";
  222621. return;
  222622. }
  222623. if (outputDevice != 0 && inputDevice != 0)
  222624. {
  222625. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222626. }
  222627. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222628. return;
  222629. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222630. return;
  222631. startThread (9);
  222632. int count = 1000;
  222633. while (numCallbacks == 0)
  222634. {
  222635. sleep (5);
  222636. if (--count < 0 || ! isThreadRunning())
  222637. {
  222638. error = "device didn't start";
  222639. break;
  222640. }
  222641. }
  222642. }
  222643. void close()
  222644. {
  222645. stopThread (6000);
  222646. inputDevice = 0;
  222647. outputDevice = 0;
  222648. inputChannelBuffer.setSize (1, 1);
  222649. outputChannelBuffer.setSize (1, 1);
  222650. numCallbacks = 0;
  222651. }
  222652. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222653. {
  222654. const ScopedLock sl (callbackLock);
  222655. callback = newCallback;
  222656. }
  222657. void run()
  222658. {
  222659. while (! threadShouldExit())
  222660. {
  222661. if (inputDevice != 0)
  222662. {
  222663. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  222664. {
  222665. DBG ("ALSA: read failure");
  222666. break;
  222667. }
  222668. }
  222669. if (threadShouldExit())
  222670. break;
  222671. {
  222672. const ScopedLock sl (callbackLock);
  222673. ++numCallbacks;
  222674. if (callback != 0)
  222675. {
  222676. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222677. inputChannelDataForCallback.size(),
  222678. outputChannelDataForCallback.getRawDataPointer(),
  222679. outputChannelDataForCallback.size(),
  222680. bufferSize);
  222681. }
  222682. else
  222683. {
  222684. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222685. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222686. }
  222687. }
  222688. if (outputDevice != 0)
  222689. {
  222690. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222691. if (threadShouldExit())
  222692. break;
  222693. failed (snd_pcm_avail_update (outputDevice->handle));
  222694. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  222695. {
  222696. DBG ("ALSA: write failure");
  222697. break;
  222698. }
  222699. }
  222700. }
  222701. }
  222702. int getBitDepth() const throw()
  222703. {
  222704. if (outputDevice != 0)
  222705. return outputDevice->bitDepth;
  222706. if (inputDevice != 0)
  222707. return inputDevice->bitDepth;
  222708. return 16;
  222709. }
  222710. juce_UseDebuggingNewOperator
  222711. String error;
  222712. double sampleRate;
  222713. int bufferSize, outputLatency, inputLatency;
  222714. BigInteger currentInputChans, currentOutputChans;
  222715. Array <int> sampleRates;
  222716. StringArray channelNamesOut, channelNamesIn;
  222717. AudioIODeviceCallback* callback;
  222718. private:
  222719. const String inputId, outputId;
  222720. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222721. int numCallbacks;
  222722. CriticalSection callbackLock;
  222723. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222724. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222725. unsigned int minChansOut, maxChansOut;
  222726. unsigned int minChansIn, maxChansIn;
  222727. bool failed (const int errorNum)
  222728. {
  222729. if (errorNum >= 0)
  222730. return false;
  222731. error = snd_strerror (errorNum);
  222732. DBG ("ALSA error: " + error + "\n");
  222733. return true;
  222734. }
  222735. void initialiseRatesAndChannels()
  222736. {
  222737. sampleRates.clear();
  222738. channelNamesOut.clear();
  222739. channelNamesIn.clear();
  222740. minChansOut = 0;
  222741. maxChansOut = 0;
  222742. minChansIn = 0;
  222743. maxChansIn = 0;
  222744. unsigned int dummy = 0;
  222745. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222746. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222747. unsigned int i;
  222748. for (i = 0; i < maxChansOut; ++i)
  222749. channelNamesOut.add ("channel " + String ((int) i + 1));
  222750. for (i = 0; i < maxChansIn; ++i)
  222751. channelNamesIn.add ("channel " + String ((int) i + 1));
  222752. }
  222753. };
  222754. class ALSAAudioIODevice : public AudioIODevice
  222755. {
  222756. public:
  222757. ALSAAudioIODevice (const String& deviceName,
  222758. const String& inputId_,
  222759. const String& outputId_)
  222760. : AudioIODevice (deviceName, "ALSA"),
  222761. inputId (inputId_),
  222762. outputId (outputId_),
  222763. isOpen_ (false),
  222764. isStarted (false),
  222765. internal (inputId_, outputId_)
  222766. {
  222767. }
  222768. ~ALSAAudioIODevice()
  222769. {
  222770. }
  222771. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222772. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222773. int getNumSampleRates() { return internal.sampleRates.size(); }
  222774. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222775. int getDefaultBufferSize() { return 512; }
  222776. int getNumBufferSizesAvailable() { return 50; }
  222777. int getBufferSizeSamples (int index)
  222778. {
  222779. int n = 16;
  222780. for (int i = 0; i < index; ++i)
  222781. n += n < 64 ? 16
  222782. : (n < 512 ? 32
  222783. : (n < 1024 ? 64
  222784. : (n < 2048 ? 128 : 256)));
  222785. return n;
  222786. }
  222787. const String open (const BigInteger& inputChannels,
  222788. const BigInteger& outputChannels,
  222789. double sampleRate,
  222790. int bufferSizeSamples)
  222791. {
  222792. close();
  222793. if (bufferSizeSamples <= 0)
  222794. bufferSizeSamples = getDefaultBufferSize();
  222795. if (sampleRate <= 0)
  222796. {
  222797. for (int i = 0; i < getNumSampleRates(); ++i)
  222798. {
  222799. if (getSampleRate (i) >= 44100)
  222800. {
  222801. sampleRate = getSampleRate (i);
  222802. break;
  222803. }
  222804. }
  222805. }
  222806. internal.open (inputChannels, outputChannels,
  222807. sampleRate, bufferSizeSamples);
  222808. isOpen_ = internal.error.isEmpty();
  222809. return internal.error;
  222810. }
  222811. void close()
  222812. {
  222813. stop();
  222814. internal.close();
  222815. isOpen_ = false;
  222816. }
  222817. bool isOpen() { return isOpen_; }
  222818. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222819. const String getLastError() { return internal.error; }
  222820. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222821. double getCurrentSampleRate() { return internal.sampleRate; }
  222822. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222823. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222824. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222825. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222826. int getInputLatencyInSamples() { return internal.inputLatency; }
  222827. void start (AudioIODeviceCallback* callback)
  222828. {
  222829. if (! isOpen_)
  222830. callback = 0;
  222831. if (callback != 0)
  222832. callback->audioDeviceAboutToStart (this);
  222833. internal.setCallback (callback);
  222834. isStarted = (callback != 0);
  222835. }
  222836. void stop()
  222837. {
  222838. AudioIODeviceCallback* const oldCallback = internal.callback;
  222839. start (0);
  222840. if (oldCallback != 0)
  222841. oldCallback->audioDeviceStopped();
  222842. }
  222843. String inputId, outputId;
  222844. private:
  222845. bool isOpen_, isStarted;
  222846. ALSAThread internal;
  222847. };
  222848. class ALSAAudioIODeviceType : public AudioIODeviceType
  222849. {
  222850. public:
  222851. ALSAAudioIODeviceType()
  222852. : AudioIODeviceType ("ALSA"),
  222853. hasScanned (false)
  222854. {
  222855. }
  222856. ~ALSAAudioIODeviceType()
  222857. {
  222858. }
  222859. void scanForDevices()
  222860. {
  222861. if (hasScanned)
  222862. return;
  222863. hasScanned = true;
  222864. inputNames.clear();
  222865. inputIds.clear();
  222866. outputNames.clear();
  222867. outputIds.clear();
  222868. snd_ctl_t* handle = 0;
  222869. snd_ctl_card_info_t* info = 0;
  222870. snd_ctl_card_info_alloca (&info);
  222871. int cardNum = -1;
  222872. while (outputIds.size() + inputIds.size() <= 32)
  222873. {
  222874. snd_card_next (&cardNum);
  222875. if (cardNum < 0)
  222876. break;
  222877. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222878. {
  222879. if (snd_ctl_card_info (handle, info) >= 0)
  222880. {
  222881. String cardId (snd_ctl_card_info_get_id (info));
  222882. if (cardId.removeCharacters ("0123456789").isEmpty())
  222883. cardId = String (cardNum);
  222884. int device = -1;
  222885. for (;;)
  222886. {
  222887. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222888. break;
  222889. String id, name;
  222890. id << "hw:" << cardId << ',' << device;
  222891. bool isInput, isOutput;
  222892. if (testDevice (id, isInput, isOutput))
  222893. {
  222894. name << snd_ctl_card_info_get_name (info);
  222895. if (name.isEmpty())
  222896. name = id;
  222897. if (isInput)
  222898. {
  222899. inputNames.add (name);
  222900. inputIds.add (id);
  222901. }
  222902. if (isOutput)
  222903. {
  222904. outputNames.add (name);
  222905. outputIds.add (id);
  222906. }
  222907. }
  222908. }
  222909. }
  222910. snd_ctl_close (handle);
  222911. }
  222912. }
  222913. inputNames.appendNumbersToDuplicates (false, true);
  222914. outputNames.appendNumbersToDuplicates (false, true);
  222915. }
  222916. const StringArray getDeviceNames (bool wantInputNames) const
  222917. {
  222918. jassert (hasScanned); // need to call scanForDevices() before doing this
  222919. return wantInputNames ? inputNames : outputNames;
  222920. }
  222921. int getDefaultDeviceIndex (bool forInput) const
  222922. {
  222923. jassert (hasScanned); // need to call scanForDevices() before doing this
  222924. return 0;
  222925. }
  222926. bool hasSeparateInputsAndOutputs() const { return true; }
  222927. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222928. {
  222929. jassert (hasScanned); // need to call scanForDevices() before doing this
  222930. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222931. if (d == 0)
  222932. return -1;
  222933. return asInput ? inputIds.indexOf (d->inputId)
  222934. : outputIds.indexOf (d->outputId);
  222935. }
  222936. AudioIODevice* createDevice (const String& outputDeviceName,
  222937. const String& inputDeviceName)
  222938. {
  222939. jassert (hasScanned); // need to call scanForDevices() before doing this
  222940. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222941. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222942. String deviceName (outputIndex >= 0 ? outputDeviceName
  222943. : inputDeviceName);
  222944. if (inputIndex >= 0 || outputIndex >= 0)
  222945. return new ALSAAudioIODevice (deviceName,
  222946. inputIds [inputIndex],
  222947. outputIds [outputIndex]);
  222948. return 0;
  222949. }
  222950. juce_UseDebuggingNewOperator
  222951. private:
  222952. StringArray inputNames, outputNames, inputIds, outputIds;
  222953. bool hasScanned;
  222954. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222955. {
  222956. unsigned int minChansOut = 0, maxChansOut = 0;
  222957. unsigned int minChansIn = 0, maxChansIn = 0;
  222958. Array <int> rates;
  222959. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222960. DBG ("ALSA device: " + id
  222961. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222962. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222963. + " rates=" + String (rates.size()));
  222964. isInput = maxChansIn > 0;
  222965. isOutput = maxChansOut > 0;
  222966. return (isInput || isOutput) && rates.size() > 0;
  222967. }
  222968. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  222969. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  222970. };
  222971. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222972. {
  222973. return new ALSAAudioIODeviceType();
  222974. }
  222975. #endif
  222976. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222977. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222978. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222979. // compiled on its own).
  222980. #ifdef JUCE_INCLUDED_FILE
  222981. #if JUCE_JACK
  222982. static void* juce_libjack_handle = 0;
  222983. void* juce_load_jack_function (const char* const name)
  222984. {
  222985. if (juce_libjack_handle == 0)
  222986. return 0;
  222987. return dlsym (juce_libjack_handle, name);
  222988. }
  222989. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222990. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222991. return_type fn_name argument_types { \
  222992. static fn_name##_ptr_t fn = 0; \
  222993. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222994. if (fn) return (*fn)arguments; \
  222995. else return 0; \
  222996. }
  222997. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222998. typedef void (*fn_name##_ptr_t)argument_types; \
  222999. void fn_name argument_types { \
  223000. static fn_name##_ptr_t fn = 0; \
  223001. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223002. if (fn) (*fn)arguments; \
  223003. }
  223004. 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));
  223005. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223006. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223007. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223008. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223009. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223010. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223011. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223012. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223013. 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));
  223014. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223015. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223016. 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));
  223017. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223018. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223019. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223020. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223021. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223022. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223023. #if JUCE_DEBUG
  223024. #define JACK_LOGGING_ENABLED 1
  223025. #endif
  223026. #if JACK_LOGGING_ENABLED
  223027. static void jack_Log (const String& s)
  223028. {
  223029. std::cerr << s << std::endl;
  223030. }
  223031. static void dumpJackErrorMessage (const jack_status_t status)
  223032. {
  223033. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223034. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223035. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223036. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223037. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223038. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223039. }
  223040. #else
  223041. #define dumpJackErrorMessage(a) {}
  223042. #define jack_Log(...) {}
  223043. #endif
  223044. #ifndef JUCE_JACK_CLIENT_NAME
  223045. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223046. #endif
  223047. class JackAudioIODevice : public AudioIODevice
  223048. {
  223049. public:
  223050. JackAudioIODevice (const String& deviceName,
  223051. const String& inputId_,
  223052. const String& outputId_)
  223053. : AudioIODevice (deviceName, "JACK"),
  223054. inputId (inputId_),
  223055. outputId (outputId_),
  223056. isOpen_ (false),
  223057. callback (0),
  223058. totalNumberOfInputChannels (0),
  223059. totalNumberOfOutputChannels (0)
  223060. {
  223061. jassert (deviceName.isNotEmpty());
  223062. jack_status_t status;
  223063. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223064. if (client == 0)
  223065. {
  223066. dumpJackErrorMessage (status);
  223067. }
  223068. else
  223069. {
  223070. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223071. // open input ports
  223072. const StringArray inputChannels (getInputChannelNames());
  223073. for (int i = 0; i < inputChannels.size(); i++)
  223074. {
  223075. String inputName;
  223076. inputName << "in_" << ++totalNumberOfInputChannels;
  223077. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223078. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223079. }
  223080. // open output ports
  223081. const StringArray outputChannels (getOutputChannelNames());
  223082. for (int i = 0; i < outputChannels.size (); i++)
  223083. {
  223084. String outputName;
  223085. outputName << "out_" << ++totalNumberOfOutputChannels;
  223086. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223087. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223088. }
  223089. inChans.calloc (totalNumberOfInputChannels + 2);
  223090. outChans.calloc (totalNumberOfOutputChannels + 2);
  223091. }
  223092. }
  223093. ~JackAudioIODevice()
  223094. {
  223095. close();
  223096. if (client != 0)
  223097. {
  223098. JUCE_NAMESPACE::jack_client_close (client);
  223099. client = 0;
  223100. }
  223101. }
  223102. const StringArray getChannelNames (bool forInput) const
  223103. {
  223104. StringArray names;
  223105. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223106. forInput ? JackPortIsInput : JackPortIsOutput);
  223107. if (ports != 0)
  223108. {
  223109. int j = 0;
  223110. while (ports[j] != 0)
  223111. {
  223112. const String portName (ports [j++]);
  223113. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223114. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223115. }
  223116. free (ports);
  223117. }
  223118. return names;
  223119. }
  223120. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223121. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223122. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223123. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223124. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223125. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223126. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223127. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223128. double sampleRate, int bufferSizeSamples)
  223129. {
  223130. if (client == 0)
  223131. {
  223132. lastError = "No JACK client running";
  223133. return lastError;
  223134. }
  223135. lastError = String::empty;
  223136. close();
  223137. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223138. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223139. JUCE_NAMESPACE::jack_activate (client);
  223140. isOpen_ = true;
  223141. if (! inputChannels.isZero())
  223142. {
  223143. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223144. if (ports != 0)
  223145. {
  223146. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223147. for (int i = 0; i < numInputChannels; ++i)
  223148. {
  223149. const String portName (ports[i]);
  223150. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223151. {
  223152. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223153. if (error != 0)
  223154. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223155. }
  223156. }
  223157. free (ports);
  223158. }
  223159. }
  223160. if (! outputChannels.isZero())
  223161. {
  223162. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223163. if (ports != 0)
  223164. {
  223165. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223166. for (int i = 0; i < numOutputChannels; ++i)
  223167. {
  223168. const String portName (ports[i]);
  223169. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223170. {
  223171. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223172. if (error != 0)
  223173. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223174. }
  223175. }
  223176. free (ports);
  223177. }
  223178. }
  223179. return lastError;
  223180. }
  223181. void close()
  223182. {
  223183. stop();
  223184. if (client != 0)
  223185. {
  223186. JUCE_NAMESPACE::jack_deactivate (client);
  223187. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223188. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223189. }
  223190. isOpen_ = false;
  223191. }
  223192. void start (AudioIODeviceCallback* newCallback)
  223193. {
  223194. if (isOpen_ && newCallback != callback)
  223195. {
  223196. if (newCallback != 0)
  223197. newCallback->audioDeviceAboutToStart (this);
  223198. AudioIODeviceCallback* const oldCallback = callback;
  223199. {
  223200. const ScopedLock sl (callbackLock);
  223201. callback = newCallback;
  223202. }
  223203. if (oldCallback != 0)
  223204. oldCallback->audioDeviceStopped();
  223205. }
  223206. }
  223207. void stop()
  223208. {
  223209. start (0);
  223210. }
  223211. bool isOpen() { return isOpen_; }
  223212. bool isPlaying() { return callback != 0; }
  223213. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223214. double getCurrentSampleRate() { return getSampleRate (0); }
  223215. int getCurrentBitDepth() { return 32; }
  223216. const String getLastError() { return lastError; }
  223217. const BigInteger getActiveOutputChannels() const
  223218. {
  223219. BigInteger outputBits;
  223220. for (int i = 0; i < outputPorts.size(); i++)
  223221. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223222. outputBits.setBit (i);
  223223. return outputBits;
  223224. }
  223225. const BigInteger getActiveInputChannels() const
  223226. {
  223227. BigInteger inputBits;
  223228. for (int i = 0; i < inputPorts.size(); i++)
  223229. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223230. inputBits.setBit (i);
  223231. return inputBits;
  223232. }
  223233. int getOutputLatencyInSamples()
  223234. {
  223235. int latency = 0;
  223236. for (int i = 0; i < outputPorts.size(); i++)
  223237. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223238. return latency;
  223239. }
  223240. int getInputLatencyInSamples()
  223241. {
  223242. int latency = 0;
  223243. for (int i = 0; i < inputPorts.size(); i++)
  223244. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223245. return latency;
  223246. }
  223247. String inputId, outputId;
  223248. private:
  223249. void process (const int numSamples)
  223250. {
  223251. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223252. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223253. {
  223254. jack_default_audio_sample_t* in
  223255. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223256. if (in != 0)
  223257. inChans [numActiveInChans++] = (float*) in;
  223258. }
  223259. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223260. {
  223261. jack_default_audio_sample_t* out
  223262. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223263. if (out != 0)
  223264. outChans [numActiveOutChans++] = (float*) out;
  223265. }
  223266. const ScopedLock sl (callbackLock);
  223267. if (callback != 0)
  223268. {
  223269. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223270. outChans, numActiveOutChans, numSamples);
  223271. }
  223272. else
  223273. {
  223274. for (i = 0; i < numActiveOutChans; ++i)
  223275. zeromem (outChans[i], sizeof (float) * numSamples);
  223276. }
  223277. }
  223278. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223279. {
  223280. if (callbackArgument != 0)
  223281. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223282. return 0;
  223283. }
  223284. static void threadInitCallback (void* callbackArgument)
  223285. {
  223286. jack_Log ("JackAudioIODevice::initialise");
  223287. }
  223288. static void shutdownCallback (void* callbackArgument)
  223289. {
  223290. jack_Log ("JackAudioIODevice::shutdown");
  223291. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223292. if (device != 0)
  223293. {
  223294. device->client = 0;
  223295. device->close();
  223296. }
  223297. }
  223298. static void errorCallback (const char* msg)
  223299. {
  223300. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223301. }
  223302. bool isOpen_;
  223303. jack_client_t* client;
  223304. String lastError;
  223305. AudioIODeviceCallback* callback;
  223306. CriticalSection callbackLock;
  223307. HeapBlock <float*> inChans, outChans;
  223308. int totalNumberOfInputChannels;
  223309. int totalNumberOfOutputChannels;
  223310. Array<void*> inputPorts, outputPorts;
  223311. };
  223312. class JackAudioIODeviceType : public AudioIODeviceType
  223313. {
  223314. public:
  223315. JackAudioIODeviceType()
  223316. : AudioIODeviceType ("JACK"),
  223317. hasScanned (false)
  223318. {
  223319. }
  223320. ~JackAudioIODeviceType()
  223321. {
  223322. }
  223323. void scanForDevices()
  223324. {
  223325. hasScanned = true;
  223326. inputNames.clear();
  223327. inputIds.clear();
  223328. outputNames.clear();
  223329. outputIds.clear();
  223330. if (juce_libjack_handle == 0)
  223331. {
  223332. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223333. if (juce_libjack_handle == 0)
  223334. return;
  223335. }
  223336. // open a dummy client
  223337. jack_status_t status;
  223338. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223339. if (client == 0)
  223340. {
  223341. dumpJackErrorMessage (status);
  223342. }
  223343. else
  223344. {
  223345. // scan for output devices
  223346. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223347. if (ports != 0)
  223348. {
  223349. int j = 0;
  223350. while (ports[j] != 0)
  223351. {
  223352. String clientName (ports[j]);
  223353. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223354. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223355. && ! inputNames.contains (clientName))
  223356. {
  223357. inputNames.add (clientName);
  223358. inputIds.add (ports [j]);
  223359. }
  223360. ++j;
  223361. }
  223362. free (ports);
  223363. }
  223364. // scan for input devices
  223365. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223366. if (ports != 0)
  223367. {
  223368. int j = 0;
  223369. while (ports[j] != 0)
  223370. {
  223371. String clientName (ports[j]);
  223372. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223373. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223374. && ! outputNames.contains (clientName))
  223375. {
  223376. outputNames.add (clientName);
  223377. outputIds.add (ports [j]);
  223378. }
  223379. ++j;
  223380. }
  223381. free (ports);
  223382. }
  223383. JUCE_NAMESPACE::jack_client_close (client);
  223384. }
  223385. }
  223386. const StringArray getDeviceNames (bool wantInputNames) const
  223387. {
  223388. jassert (hasScanned); // need to call scanForDevices() before doing this
  223389. return wantInputNames ? inputNames : outputNames;
  223390. }
  223391. int getDefaultDeviceIndex (bool forInput) const
  223392. {
  223393. jassert (hasScanned); // need to call scanForDevices() before doing this
  223394. return 0;
  223395. }
  223396. bool hasSeparateInputsAndOutputs() const { return true; }
  223397. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223398. {
  223399. jassert (hasScanned); // need to call scanForDevices() before doing this
  223400. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223401. if (d == 0)
  223402. return -1;
  223403. return asInput ? inputIds.indexOf (d->inputId)
  223404. : outputIds.indexOf (d->outputId);
  223405. }
  223406. AudioIODevice* createDevice (const String& outputDeviceName,
  223407. const String& inputDeviceName)
  223408. {
  223409. jassert (hasScanned); // need to call scanForDevices() before doing this
  223410. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223411. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223412. if (inputIndex >= 0 || outputIndex >= 0)
  223413. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223414. : inputDeviceName,
  223415. inputIds [inputIndex],
  223416. outputIds [outputIndex]);
  223417. return 0;
  223418. }
  223419. juce_UseDebuggingNewOperator
  223420. private:
  223421. StringArray inputNames, outputNames, inputIds, outputIds;
  223422. bool hasScanned;
  223423. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223424. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223425. };
  223426. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223427. {
  223428. return new JackAudioIODeviceType();
  223429. }
  223430. #else // if JACK is turned off..
  223431. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223432. #endif
  223433. #endif
  223434. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223435. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223436. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223437. // compiled on its own).
  223438. #if JUCE_INCLUDED_FILE
  223439. #if JUCE_ALSA
  223440. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223441. StringArray& deviceNamesFound,
  223442. const int deviceIndexToOpen)
  223443. {
  223444. snd_seq_t* returnedHandle = 0;
  223445. snd_seq_t* seqHandle;
  223446. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223447. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223448. {
  223449. snd_seq_system_info_t* systemInfo;
  223450. snd_seq_client_info_t* clientInfo;
  223451. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223452. {
  223453. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223454. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223455. {
  223456. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223457. while (--numClients >= 0 && returnedHandle == 0)
  223458. {
  223459. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223460. {
  223461. snd_seq_port_info_t* portInfo;
  223462. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223463. {
  223464. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223465. const int client = snd_seq_client_info_get_client (clientInfo);
  223466. snd_seq_port_info_set_client (portInfo, client);
  223467. snd_seq_port_info_set_port (portInfo, -1);
  223468. while (--numPorts >= 0)
  223469. {
  223470. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223471. && (snd_seq_port_info_get_capability (portInfo)
  223472. & (forInput ? SND_SEQ_PORT_CAP_READ
  223473. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223474. {
  223475. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223476. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223477. {
  223478. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223479. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223480. if (sourcePort != -1)
  223481. {
  223482. snd_seq_set_client_name (seqHandle,
  223483. forInput ? "Juce Midi Input"
  223484. : "Juce Midi Output");
  223485. const int portId
  223486. = snd_seq_create_simple_port (seqHandle,
  223487. forInput ? "Juce Midi In Port"
  223488. : "Juce Midi Out Port",
  223489. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223490. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223491. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223492. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223493. returnedHandle = seqHandle;
  223494. }
  223495. }
  223496. }
  223497. }
  223498. snd_seq_port_info_free (portInfo);
  223499. }
  223500. }
  223501. }
  223502. snd_seq_client_info_free (clientInfo);
  223503. }
  223504. snd_seq_system_info_free (systemInfo);
  223505. }
  223506. if (returnedHandle == 0)
  223507. snd_seq_close (seqHandle);
  223508. }
  223509. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223510. return returnedHandle;
  223511. }
  223512. static snd_seq_t* createMidiDevice (const bool forInput,
  223513. const String& deviceNameToOpen)
  223514. {
  223515. snd_seq_t* seqHandle = 0;
  223516. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223517. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223518. {
  223519. snd_seq_set_client_name (seqHandle,
  223520. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223521. const int portId
  223522. = snd_seq_create_simple_port (seqHandle,
  223523. forInput ? "in"
  223524. : "out",
  223525. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223526. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223527. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223528. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223529. if (portId < 0)
  223530. {
  223531. snd_seq_close (seqHandle);
  223532. seqHandle = 0;
  223533. }
  223534. }
  223535. return seqHandle;
  223536. }
  223537. class MidiOutputDevice
  223538. {
  223539. public:
  223540. MidiOutputDevice (MidiOutput* const midiOutput_,
  223541. snd_seq_t* const seqHandle_)
  223542. :
  223543. midiOutput (midiOutput_),
  223544. seqHandle (seqHandle_),
  223545. maxEventSize (16 * 1024)
  223546. {
  223547. jassert (seqHandle != 0 && midiOutput != 0);
  223548. snd_midi_event_new (maxEventSize, &midiParser);
  223549. }
  223550. ~MidiOutputDevice()
  223551. {
  223552. snd_midi_event_free (midiParser);
  223553. snd_seq_close (seqHandle);
  223554. }
  223555. void sendMessageNow (const MidiMessage& message)
  223556. {
  223557. if (message.getRawDataSize() > maxEventSize)
  223558. {
  223559. maxEventSize = message.getRawDataSize();
  223560. snd_midi_event_free (midiParser);
  223561. snd_midi_event_new (maxEventSize, &midiParser);
  223562. }
  223563. snd_seq_event_t event;
  223564. snd_seq_ev_clear (&event);
  223565. snd_midi_event_encode (midiParser,
  223566. message.getRawData(),
  223567. message.getRawDataSize(),
  223568. &event);
  223569. snd_midi_event_reset_encode (midiParser);
  223570. snd_seq_ev_set_source (&event, 0);
  223571. snd_seq_ev_set_subs (&event);
  223572. snd_seq_ev_set_direct (&event);
  223573. snd_seq_event_output (seqHandle, &event);
  223574. snd_seq_drain_output (seqHandle);
  223575. }
  223576. juce_UseDebuggingNewOperator
  223577. private:
  223578. MidiOutput* const midiOutput;
  223579. snd_seq_t* const seqHandle;
  223580. snd_midi_event_t* midiParser;
  223581. int maxEventSize;
  223582. };
  223583. const StringArray MidiOutput::getDevices()
  223584. {
  223585. StringArray devices;
  223586. iterateMidiDevices (false, devices, -1);
  223587. return devices;
  223588. }
  223589. int MidiOutput::getDefaultDeviceIndex()
  223590. {
  223591. return 0;
  223592. }
  223593. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223594. {
  223595. MidiOutput* newDevice = 0;
  223596. StringArray devices;
  223597. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223598. if (handle != 0)
  223599. {
  223600. newDevice = new MidiOutput();
  223601. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223602. }
  223603. return newDevice;
  223604. }
  223605. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223606. {
  223607. MidiOutput* newDevice = 0;
  223608. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223609. if (handle != 0)
  223610. {
  223611. newDevice = new MidiOutput();
  223612. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223613. }
  223614. return newDevice;
  223615. }
  223616. MidiOutput::~MidiOutput()
  223617. {
  223618. delete static_cast <MidiOutputDevice*> (internal);
  223619. }
  223620. void MidiOutput::reset()
  223621. {
  223622. }
  223623. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223624. {
  223625. return false;
  223626. }
  223627. void MidiOutput::setVolume (float leftVol, float rightVol)
  223628. {
  223629. }
  223630. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223631. {
  223632. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223633. }
  223634. class MidiInputThread : public Thread
  223635. {
  223636. public:
  223637. MidiInputThread (MidiInput* const midiInput_,
  223638. snd_seq_t* const seqHandle_,
  223639. MidiInputCallback* const callback_)
  223640. : Thread ("Juce MIDI Input"),
  223641. midiInput (midiInput_),
  223642. seqHandle (seqHandle_),
  223643. callback (callback_)
  223644. {
  223645. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223646. }
  223647. ~MidiInputThread()
  223648. {
  223649. snd_seq_close (seqHandle);
  223650. }
  223651. void run()
  223652. {
  223653. const int maxEventSize = 16 * 1024;
  223654. snd_midi_event_t* midiParser;
  223655. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223656. {
  223657. HeapBlock <uint8> buffer (maxEventSize);
  223658. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223659. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223660. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223661. while (! threadShouldExit())
  223662. {
  223663. if (poll (pfd, numPfds, 500) > 0)
  223664. {
  223665. snd_seq_event_t* inputEvent = 0;
  223666. snd_seq_nonblock (seqHandle, 1);
  223667. do
  223668. {
  223669. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223670. {
  223671. // xxx what about SYSEXes that are too big for the buffer?
  223672. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223673. snd_midi_event_reset_decode (midiParser);
  223674. if (numBytes > 0)
  223675. {
  223676. const MidiMessage message ((const uint8*) buffer,
  223677. numBytes,
  223678. Time::getMillisecondCounter() * 0.001);
  223679. callback->handleIncomingMidiMessage (midiInput, message);
  223680. }
  223681. snd_seq_free_event (inputEvent);
  223682. }
  223683. }
  223684. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223685. snd_seq_free_event (inputEvent);
  223686. }
  223687. }
  223688. snd_midi_event_free (midiParser);
  223689. }
  223690. };
  223691. juce_UseDebuggingNewOperator
  223692. private:
  223693. MidiInput* const midiInput;
  223694. snd_seq_t* const seqHandle;
  223695. MidiInputCallback* const callback;
  223696. };
  223697. MidiInput::MidiInput (const String& name_)
  223698. : name (name_),
  223699. internal (0)
  223700. {
  223701. }
  223702. MidiInput::~MidiInput()
  223703. {
  223704. stop();
  223705. delete static_cast <MidiInputThread*> (internal);
  223706. }
  223707. void MidiInput::start()
  223708. {
  223709. static_cast <MidiInputThread*> (internal)->startThread();
  223710. }
  223711. void MidiInput::stop()
  223712. {
  223713. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223714. }
  223715. int MidiInput::getDefaultDeviceIndex()
  223716. {
  223717. return 0;
  223718. }
  223719. const StringArray MidiInput::getDevices()
  223720. {
  223721. StringArray devices;
  223722. iterateMidiDevices (true, devices, -1);
  223723. return devices;
  223724. }
  223725. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223726. {
  223727. MidiInput* newDevice = 0;
  223728. StringArray devices;
  223729. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223730. if (handle != 0)
  223731. {
  223732. newDevice = new MidiInput (devices [deviceIndex]);
  223733. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223734. }
  223735. return newDevice;
  223736. }
  223737. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223738. {
  223739. MidiInput* newDevice = 0;
  223740. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223741. if (handle != 0)
  223742. {
  223743. newDevice = new MidiInput (deviceName);
  223744. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223745. }
  223746. return newDevice;
  223747. }
  223748. #else
  223749. // (These are just stub functions if ALSA is unavailable...)
  223750. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223751. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223752. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223753. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223754. MidiOutput::~MidiOutput() {}
  223755. void MidiOutput::reset() {}
  223756. bool MidiOutput::getVolume (float&, float&) { return false; }
  223757. void MidiOutput::setVolume (float, float) {}
  223758. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223759. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223760. MidiInput::~MidiInput() {}
  223761. void MidiInput::start() {}
  223762. void MidiInput::stop() {}
  223763. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223764. const StringArray MidiInput::getDevices() { return StringArray(); }
  223765. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223766. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223767. #endif
  223768. #endif
  223769. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223770. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223771. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223772. // compiled on its own).
  223773. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223774. AudioCDReader::AudioCDReader()
  223775. : AudioFormatReader (0, "CD Audio")
  223776. {
  223777. }
  223778. const StringArray AudioCDReader::getAvailableCDNames()
  223779. {
  223780. StringArray names;
  223781. return names;
  223782. }
  223783. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223784. {
  223785. return 0;
  223786. }
  223787. AudioCDReader::~AudioCDReader()
  223788. {
  223789. }
  223790. void AudioCDReader::refreshTrackLengths()
  223791. {
  223792. }
  223793. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223794. int64 startSampleInFile, int numSamples)
  223795. {
  223796. return false;
  223797. }
  223798. bool AudioCDReader::isCDStillPresent() const
  223799. {
  223800. return false;
  223801. }
  223802. bool AudioCDReader::isTrackAudio (int trackNum) const
  223803. {
  223804. return false;
  223805. }
  223806. void AudioCDReader::enableIndexScanning (bool b)
  223807. {
  223808. }
  223809. int AudioCDReader::getLastIndex() const
  223810. {
  223811. return 0;
  223812. }
  223813. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223814. {
  223815. return Array<int>();
  223816. }
  223817. #endif
  223818. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223819. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223820. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223821. // compiled on its own).
  223822. #if JUCE_INCLUDED_FILE
  223823. void FileChooser::showPlatformDialog (Array<File>& results,
  223824. const String& title,
  223825. const File& file,
  223826. const String& filters,
  223827. bool isDirectory,
  223828. bool selectsFiles,
  223829. bool isSave,
  223830. bool warnAboutOverwritingExistingFiles,
  223831. bool selectMultipleFiles,
  223832. FilePreviewComponent* previewComponent)
  223833. {
  223834. const String separator (":");
  223835. String command ("zenity --file-selection");
  223836. if (title.isNotEmpty())
  223837. command << " --title=\"" << title << "\"";
  223838. if (file != File::nonexistent)
  223839. command << " --filename=\"" << file.getFullPathName () << "\"";
  223840. if (isDirectory)
  223841. command << " --directory";
  223842. if (isSave)
  223843. command << " --save";
  223844. if (selectMultipleFiles)
  223845. command << " --multiple --separator=\"" << separator << "\"";
  223846. command << " 2>&1";
  223847. MemoryOutputStream result;
  223848. int status = -1;
  223849. FILE* stream = popen (command.toUTF8(), "r");
  223850. if (stream != 0)
  223851. {
  223852. for (;;)
  223853. {
  223854. char buffer [1024];
  223855. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223856. if (bytesRead <= 0)
  223857. break;
  223858. result.write (buffer, bytesRead);
  223859. }
  223860. status = pclose (stream);
  223861. }
  223862. if (status == 0)
  223863. {
  223864. StringArray tokens;
  223865. if (selectMultipleFiles)
  223866. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223867. else
  223868. tokens.add (result.toUTF8());
  223869. for (int i = 0; i < tokens.size(); i++)
  223870. results.add (File (tokens[i]));
  223871. return;
  223872. }
  223873. //xxx ain't got one!
  223874. jassertfalse;
  223875. }
  223876. #endif
  223877. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223878. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223879. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223880. // compiled on its own).
  223881. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223882. /*
  223883. Sorry.. This class isn't implemented on Linux!
  223884. */
  223885. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223886. : browser (0),
  223887. blankPageShown (false),
  223888. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223889. {
  223890. setOpaque (true);
  223891. }
  223892. WebBrowserComponent::~WebBrowserComponent()
  223893. {
  223894. }
  223895. void WebBrowserComponent::goToURL (const String& url,
  223896. const StringArray* headers,
  223897. const MemoryBlock* postData)
  223898. {
  223899. lastURL = url;
  223900. lastHeaders.clear();
  223901. if (headers != 0)
  223902. lastHeaders = *headers;
  223903. lastPostData.setSize (0);
  223904. if (postData != 0)
  223905. lastPostData = *postData;
  223906. blankPageShown = false;
  223907. }
  223908. void WebBrowserComponent::stop()
  223909. {
  223910. }
  223911. void WebBrowserComponent::goBack()
  223912. {
  223913. lastURL = String::empty;
  223914. blankPageShown = false;
  223915. }
  223916. void WebBrowserComponent::goForward()
  223917. {
  223918. lastURL = String::empty;
  223919. }
  223920. void WebBrowserComponent::refresh()
  223921. {
  223922. }
  223923. void WebBrowserComponent::paint (Graphics& g)
  223924. {
  223925. g.fillAll (Colours::white);
  223926. }
  223927. void WebBrowserComponent::checkWindowAssociation()
  223928. {
  223929. }
  223930. void WebBrowserComponent::reloadLastURL()
  223931. {
  223932. if (lastURL.isNotEmpty())
  223933. {
  223934. goToURL (lastURL, &lastHeaders, &lastPostData);
  223935. lastURL = String::empty;
  223936. }
  223937. }
  223938. void WebBrowserComponent::parentHierarchyChanged()
  223939. {
  223940. checkWindowAssociation();
  223941. }
  223942. void WebBrowserComponent::resized()
  223943. {
  223944. }
  223945. void WebBrowserComponent::visibilityChanged()
  223946. {
  223947. checkWindowAssociation();
  223948. }
  223949. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223950. {
  223951. return true;
  223952. }
  223953. #endif
  223954. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223955. #endif
  223956. END_JUCE_NAMESPACE
  223957. #endif
  223958. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223959. #endif
  223960. #if JUCE_MAC || JUCE_IPHONE
  223961. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223962. /*
  223963. This file wraps together all the mac-specific code, so that
  223964. we can include all the native headers just once, and compile all our
  223965. platform-specific stuff in one big lump, keeping it out of the way of
  223966. the rest of the codebase.
  223967. */
  223968. #if JUCE_MAC || JUCE_IOS
  223969. BEGIN_JUCE_NAMESPACE
  223970. #undef Point
  223971. #define JUCE_INCLUDED_FILE 1
  223972. // Now include the actual code files..
  223973. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223974. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223975. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223976. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223977. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223978. actually calling into a similarly named class in the other module's address space.
  223979. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223980. have unique names, and should avoid this problem.
  223981. If you're using the amalgamated version, you can just set this macro to something unique before
  223982. you include juce_amalgamated.cpp.
  223983. */
  223984. #ifndef JUCE_ObjCExtraSuffix
  223985. #define JUCE_ObjCExtraSuffix 3
  223986. #endif
  223987. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223988. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223989. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223990. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223991. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223992. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223993. // compiled on its own).
  223994. #if JUCE_INCLUDED_FILE
  223995. static const String nsStringToJuce (NSString* s)
  223996. {
  223997. return String::fromUTF8 ([s UTF8String]);
  223998. }
  223999. static NSString* juceStringToNS (const String& s)
  224000. {
  224001. return [NSString stringWithUTF8String: s.toUTF8()];
  224002. }
  224003. static const String convertUTF16ToString (const UniChar* utf16)
  224004. {
  224005. String s;
  224006. while (*utf16 != 0)
  224007. s += (juce_wchar) *utf16++;
  224008. return s;
  224009. }
  224010. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224011. {
  224012. String result;
  224013. if (cfString != 0)
  224014. {
  224015. CFRange range = { 0, CFStringGetLength (cfString) };
  224016. HeapBlock <UniChar> u (range.length + 1);
  224017. CFStringGetCharacters (cfString, range, u);
  224018. u[range.length] = 0;
  224019. result = convertUTF16ToString (u);
  224020. }
  224021. return result;
  224022. }
  224023. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224024. {
  224025. const int len = s.length();
  224026. HeapBlock <UniChar> temp (len + 2);
  224027. for (int i = 0; i <= len; ++i)
  224028. temp[i] = s[i];
  224029. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224030. }
  224031. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224032. {
  224033. #if JUCE_IOS
  224034. const ScopedAutoReleasePool pool;
  224035. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224036. #else
  224037. UnicodeMapping map;
  224038. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224039. kUnicodeNoSubset,
  224040. kTextEncodingDefaultFormat);
  224041. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224042. kUnicodeCanonicalCompVariant,
  224043. kTextEncodingDefaultFormat);
  224044. map.mappingVersion = kUnicodeUseLatestMapping;
  224045. UnicodeToTextInfo conversionInfo = 0;
  224046. String result;
  224047. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224048. {
  224049. const int len = s.length();
  224050. HeapBlock <UniChar> tempIn, tempOut;
  224051. tempIn.calloc (len + 2);
  224052. tempOut.calloc (len + 2);
  224053. for (int i = 0; i <= len; ++i)
  224054. tempIn[i] = s[i];
  224055. ByteCount bytesRead = 0;
  224056. ByteCount outputBufferSize = 0;
  224057. if (ConvertFromUnicodeToText (conversionInfo,
  224058. len * sizeof (UniChar), tempIn,
  224059. kUnicodeDefaultDirectionMask,
  224060. 0, 0, 0, 0,
  224061. len * sizeof (UniChar), &bytesRead,
  224062. &outputBufferSize, tempOut) == noErr)
  224063. {
  224064. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224065. juce_wchar* t = result;
  224066. unsigned int i;
  224067. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224068. t[i] = (juce_wchar) tempOut[i];
  224069. t[i] = 0;
  224070. }
  224071. DisposeUnicodeToTextInfo (&conversionInfo);
  224072. }
  224073. return result;
  224074. #endif
  224075. }
  224076. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224077. void SystemClipboard::copyTextToClipboard (const String& text)
  224078. {
  224079. #if JUCE_IOS
  224080. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224081. forPasteboardType: @"public.text"];
  224082. #else
  224083. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224084. owner: nil];
  224085. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224086. forType: NSStringPboardType];
  224087. #endif
  224088. }
  224089. const String SystemClipboard::getTextFromClipboard()
  224090. {
  224091. #if JUCE_IOS
  224092. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224093. #else
  224094. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224095. #endif
  224096. return text == 0 ? String::empty
  224097. : nsStringToJuce (text);
  224098. }
  224099. #endif
  224100. #endif
  224101. /*** End of inlined file: juce_mac_Strings.mm ***/
  224102. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224103. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224104. // compiled on its own).
  224105. #if JUCE_INCLUDED_FILE
  224106. namespace SystemStatsHelpers
  224107. {
  224108. static int64 highResTimerFrequency = 0;
  224109. static double highResTimerToMillisecRatio = 0;
  224110. #if JUCE_INTEL
  224111. static void juce_getCpuVendor (char* const v) throw()
  224112. {
  224113. int vendor[4];
  224114. zerostruct (vendor);
  224115. int dummy = 0;
  224116. asm ("mov %%ebx, %%esi \n\t"
  224117. "cpuid \n\t"
  224118. "xchg %%esi, %%ebx"
  224119. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224120. memcpy (v, vendor, 16);
  224121. }
  224122. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224123. {
  224124. unsigned int cpu = 0;
  224125. unsigned int ext = 0;
  224126. unsigned int family = 0;
  224127. unsigned int dummy = 0;
  224128. asm ("mov %%ebx, %%esi \n\t"
  224129. "cpuid \n\t"
  224130. "xchg %%esi, %%ebx"
  224131. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224132. familyModel = family;
  224133. extFeatures = ext;
  224134. return cpu;
  224135. }
  224136. #endif
  224137. }
  224138. void SystemStats::initialiseStats()
  224139. {
  224140. using namespace SystemStatsHelpers;
  224141. static bool initialised = false;
  224142. if (! initialised)
  224143. {
  224144. initialised = true;
  224145. #if JUCE_MAC
  224146. [NSApplication sharedApplication];
  224147. #endif
  224148. #if JUCE_INTEL
  224149. unsigned int familyModel, extFeatures;
  224150. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224151. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224152. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224153. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224154. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224155. #else
  224156. cpuFlags.hasMMX = false;
  224157. cpuFlags.hasSSE = false;
  224158. cpuFlags.hasSSE2 = false;
  224159. cpuFlags.has3DNow = false;
  224160. #endif
  224161. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224162. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224163. #else
  224164. cpuFlags.numCpus = (int) MPProcessors();
  224165. #endif
  224166. mach_timebase_info_data_t timebase;
  224167. (void) mach_timebase_info (&timebase);
  224168. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224169. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224170. String s (SystemStats::getJUCEVersion());
  224171. rlimit lim;
  224172. getrlimit (RLIMIT_NOFILE, &lim);
  224173. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224174. setrlimit (RLIMIT_NOFILE, &lim);
  224175. }
  224176. }
  224177. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224178. {
  224179. return MacOSX;
  224180. }
  224181. const String SystemStats::getOperatingSystemName()
  224182. {
  224183. return "Mac OS X";
  224184. }
  224185. #if ! JUCE_IOS
  224186. int PlatformUtilities::getOSXMinorVersionNumber()
  224187. {
  224188. SInt32 versionMinor = 0;
  224189. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224190. (void) err;
  224191. jassert (err == noErr);
  224192. return (int) versionMinor;
  224193. }
  224194. #endif
  224195. bool SystemStats::isOperatingSystem64Bit()
  224196. {
  224197. #if JUCE_IOS
  224198. return false;
  224199. #elif JUCE_64BIT
  224200. return true;
  224201. #else
  224202. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224203. #endif
  224204. }
  224205. int SystemStats::getMemorySizeInMegabytes()
  224206. {
  224207. uint64 mem = 0;
  224208. size_t memSize = sizeof (mem);
  224209. int mib[] = { CTL_HW, HW_MEMSIZE };
  224210. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224211. return (int) (mem / (1024 * 1024));
  224212. }
  224213. const String SystemStats::getCpuVendor()
  224214. {
  224215. #if JUCE_INTEL
  224216. char v [16];
  224217. SystemStatsHelpers::juce_getCpuVendor (v);
  224218. return String (v, 16);
  224219. #else
  224220. return String::empty;
  224221. #endif
  224222. }
  224223. int SystemStats::getCpuSpeedInMegaherz()
  224224. {
  224225. uint64 speedHz = 0;
  224226. size_t speedSize = sizeof (speedHz);
  224227. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224228. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224229. #if JUCE_BIG_ENDIAN
  224230. if (speedSize == 4)
  224231. speedHz >>= 32;
  224232. #endif
  224233. return (int) (speedHz / 1000000);
  224234. }
  224235. const String SystemStats::getLogonName()
  224236. {
  224237. return nsStringToJuce (NSUserName());
  224238. }
  224239. const String SystemStats::getFullUserName()
  224240. {
  224241. return nsStringToJuce (NSFullUserName());
  224242. }
  224243. uint32 juce_millisecondsSinceStartup() throw()
  224244. {
  224245. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224246. }
  224247. double Time::getMillisecondCounterHiRes() throw()
  224248. {
  224249. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224250. }
  224251. int64 Time::getHighResolutionTicks() throw()
  224252. {
  224253. return (int64) mach_absolute_time();
  224254. }
  224255. int64 Time::getHighResolutionTicksPerSecond() throw()
  224256. {
  224257. return SystemStatsHelpers::highResTimerFrequency;
  224258. }
  224259. bool Time::setSystemTimeToThisTime() const
  224260. {
  224261. jassertfalse;
  224262. return false;
  224263. }
  224264. int SystemStats::getPageSize()
  224265. {
  224266. return (int) NSPageSize();
  224267. }
  224268. void PlatformUtilities::fpuReset()
  224269. {
  224270. }
  224271. #endif
  224272. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224273. /*** Start of inlined file: juce_mac_Network.mm ***/
  224274. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224275. // compiled on its own).
  224276. #if JUCE_INCLUDED_FILE
  224277. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224278. {
  224279. #ifndef IFT_ETHER
  224280. #define IFT_ETHER 6
  224281. #endif
  224282. ifaddrs* addrs = 0;
  224283. int numResults = 0;
  224284. if (getifaddrs (&addrs) == 0)
  224285. {
  224286. const ifaddrs* cursor = addrs;
  224287. while (cursor != 0 && numResults < maxNum)
  224288. {
  224289. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224290. if (sto->ss_family == AF_LINK)
  224291. {
  224292. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224293. if (sadd->sdl_type == IFT_ETHER)
  224294. {
  224295. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224296. uint64 a = 0;
  224297. for (int i = 6; --i >= 0;)
  224298. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224299. *addresses++ = (int64) a;
  224300. ++numResults;
  224301. }
  224302. }
  224303. cursor = cursor->ifa_next;
  224304. }
  224305. freeifaddrs (addrs);
  224306. }
  224307. return numResults;
  224308. }
  224309. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224310. const String& emailSubject,
  224311. const String& bodyText,
  224312. const StringArray& filesToAttach)
  224313. {
  224314. #if JUCE_IOS
  224315. //xxx probably need to use MFMailComposeViewController
  224316. jassertfalse;
  224317. return false;
  224318. #else
  224319. const ScopedAutoReleasePool pool;
  224320. String script;
  224321. script << "tell application \"Mail\"\r\n"
  224322. "set newMessage to make new outgoing message with properties {subject:\""
  224323. << emailSubject.replace ("\"", "\\\"")
  224324. << "\", content:\""
  224325. << bodyText.replace ("\"", "\\\"")
  224326. << "\" & return & return}\r\n"
  224327. "tell newMessage\r\n"
  224328. "set visible to true\r\n"
  224329. "set sender to \"sdfsdfsdfewf\"\r\n"
  224330. "make new to recipient at end of to recipients with properties {address:\""
  224331. << targetEmailAddress
  224332. << "\"}\r\n";
  224333. for (int i = 0; i < filesToAttach.size(); ++i)
  224334. {
  224335. script << "tell content\r\n"
  224336. "make new attachment with properties {file name:\""
  224337. << filesToAttach[i].replace ("\"", "\\\"")
  224338. << "\"} at after the last paragraph\r\n"
  224339. "end tell\r\n";
  224340. }
  224341. script << "end tell\r\n"
  224342. "end tell\r\n";
  224343. NSAppleScript* s = [[NSAppleScript alloc]
  224344. initWithSource: juceStringToNS (script)];
  224345. NSDictionary* error = 0;
  224346. const bool ok = [s executeAndReturnError: &error] != nil;
  224347. [s release];
  224348. return ok;
  224349. #endif
  224350. }
  224351. END_JUCE_NAMESPACE
  224352. using namespace JUCE_NAMESPACE;
  224353. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224354. @interface JuceURLConnection : NSObject
  224355. {
  224356. @public
  224357. NSURLRequest* request;
  224358. NSURLConnection* connection;
  224359. NSMutableData* data;
  224360. Thread* runLoopThread;
  224361. bool initialised, hasFailed, hasFinished;
  224362. int position;
  224363. int64 contentLength;
  224364. NSDictionary* headers;
  224365. NSLock* dataLock;
  224366. }
  224367. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224368. - (void) dealloc;
  224369. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224370. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224371. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224372. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224373. - (BOOL) isOpen;
  224374. - (int) read: (char*) dest numBytes: (int) num;
  224375. - (int) readPosition;
  224376. - (void) stop;
  224377. - (void) createConnection;
  224378. @end
  224379. class JuceURLConnectionMessageThread : public Thread
  224380. {
  224381. JuceURLConnection* owner;
  224382. public:
  224383. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224384. : Thread ("http connection"),
  224385. owner (owner_)
  224386. {
  224387. }
  224388. ~JuceURLConnectionMessageThread()
  224389. {
  224390. stopThread (10000);
  224391. }
  224392. void run()
  224393. {
  224394. [owner createConnection];
  224395. while (! threadShouldExit())
  224396. {
  224397. const ScopedAutoReleasePool pool;
  224398. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224399. }
  224400. }
  224401. };
  224402. @implementation JuceURLConnection
  224403. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224404. withCallback: (URL::OpenStreamProgressCallback*) callback
  224405. withContext: (void*) context;
  224406. {
  224407. [super init];
  224408. request = req;
  224409. [request retain];
  224410. data = [[NSMutableData data] retain];
  224411. dataLock = [[NSLock alloc] init];
  224412. connection = 0;
  224413. initialised = false;
  224414. hasFailed = false;
  224415. hasFinished = false;
  224416. contentLength = -1;
  224417. headers = 0;
  224418. runLoopThread = new JuceURLConnectionMessageThread (self);
  224419. runLoopThread->startThread();
  224420. while (runLoopThread->isThreadRunning() && ! initialised)
  224421. {
  224422. if (callback != 0)
  224423. callback (context, -1, (int) [[request HTTPBody] length]);
  224424. Thread::sleep (1);
  224425. }
  224426. return self;
  224427. }
  224428. - (void) dealloc
  224429. {
  224430. [self stop];
  224431. deleteAndZero (runLoopThread);
  224432. [connection release];
  224433. [data release];
  224434. [dataLock release];
  224435. [request release];
  224436. [headers release];
  224437. [super dealloc];
  224438. }
  224439. - (void) createConnection
  224440. {
  224441. NSUInteger oldRetainCount = [self retainCount];
  224442. connection = [[NSURLConnection alloc] initWithRequest: request
  224443. delegate: self];
  224444. if (oldRetainCount == [self retainCount])
  224445. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224446. if (connection == nil)
  224447. runLoopThread->signalThreadShouldExit();
  224448. }
  224449. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224450. {
  224451. (void) conn;
  224452. [dataLock lock];
  224453. [data setLength: 0];
  224454. [dataLock unlock];
  224455. initialised = true;
  224456. contentLength = [response expectedContentLength];
  224457. [headers release];
  224458. headers = 0;
  224459. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224460. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224461. }
  224462. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224463. {
  224464. (void) conn;
  224465. DBG (nsStringToJuce ([error description]));
  224466. hasFailed = true;
  224467. initialised = true;
  224468. if (runLoopThread != 0)
  224469. runLoopThread->signalThreadShouldExit();
  224470. }
  224471. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224472. {
  224473. (void) conn;
  224474. [dataLock lock];
  224475. [data appendData: newData];
  224476. [dataLock unlock];
  224477. initialised = true;
  224478. }
  224479. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224480. {
  224481. (void) conn;
  224482. hasFinished = true;
  224483. initialised = true;
  224484. if (runLoopThread != 0)
  224485. runLoopThread->signalThreadShouldExit();
  224486. }
  224487. - (BOOL) isOpen
  224488. {
  224489. return connection != 0 && ! hasFailed;
  224490. }
  224491. - (int) readPosition
  224492. {
  224493. return position;
  224494. }
  224495. - (int) read: (char*) dest numBytes: (int) numNeeded
  224496. {
  224497. int numDone = 0;
  224498. while (numNeeded > 0)
  224499. {
  224500. int available = jmin (numNeeded, (int) [data length]);
  224501. if (available > 0)
  224502. {
  224503. [dataLock lock];
  224504. [data getBytes: dest length: available];
  224505. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224506. [dataLock unlock];
  224507. numDone += available;
  224508. numNeeded -= available;
  224509. dest += available;
  224510. }
  224511. else
  224512. {
  224513. if (hasFailed || hasFinished)
  224514. break;
  224515. Thread::sleep (1);
  224516. }
  224517. }
  224518. position += numDone;
  224519. return numDone;
  224520. }
  224521. - (void) stop
  224522. {
  224523. [connection cancel];
  224524. if (runLoopThread != 0)
  224525. runLoopThread->stopThread (10000);
  224526. }
  224527. @end
  224528. BEGIN_JUCE_NAMESPACE
  224529. void* juce_openInternetFile (const String& url,
  224530. const String& headers,
  224531. const MemoryBlock& postData,
  224532. const bool isPost,
  224533. URL::OpenStreamProgressCallback* callback,
  224534. void* callbackContext,
  224535. int timeOutMs)
  224536. {
  224537. const ScopedAutoReleasePool pool;
  224538. NSMutableURLRequest* req = [NSMutableURLRequest
  224539. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224540. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224541. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224542. if (req == nil)
  224543. return 0;
  224544. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224545. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224546. StringArray headerLines;
  224547. headerLines.addLines (headers);
  224548. headerLines.removeEmptyStrings (true);
  224549. for (int i = 0; i < headerLines.size(); ++i)
  224550. {
  224551. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224552. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224553. if (key.isNotEmpty() && value.isNotEmpty())
  224554. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224555. }
  224556. if (isPost && postData.getSize() > 0)
  224557. {
  224558. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224559. length: postData.getSize()]];
  224560. }
  224561. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224562. withCallback: callback
  224563. withContext: callbackContext];
  224564. if ([s isOpen])
  224565. return s;
  224566. [s release];
  224567. return 0;
  224568. }
  224569. void juce_closeInternetFile (void* handle)
  224570. {
  224571. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224572. if (s != 0)
  224573. {
  224574. const ScopedAutoReleasePool pool;
  224575. [s stop];
  224576. [s release];
  224577. }
  224578. }
  224579. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224580. {
  224581. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224582. if (s != 0)
  224583. {
  224584. const ScopedAutoReleasePool pool;
  224585. return [s read: (char*) buffer numBytes: bytesToRead];
  224586. }
  224587. return 0;
  224588. }
  224589. int64 juce_getInternetFileContentLength (void* handle)
  224590. {
  224591. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224592. if (s != 0)
  224593. return s->contentLength;
  224594. return -1;
  224595. }
  224596. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224597. {
  224598. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224599. if (s != 0 && s->headers != 0)
  224600. {
  224601. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224602. NSString* key;
  224603. while ((key = [enumerator nextObject]) != nil)
  224604. headers.set (nsStringToJuce (key),
  224605. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224606. }
  224607. }
  224608. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224609. {
  224610. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224611. if (s != 0)
  224612. return [s readPosition];
  224613. return 0;
  224614. }
  224615. #endif
  224616. /*** End of inlined file: juce_mac_Network.mm ***/
  224617. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224618. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224619. // compiled on its own).
  224620. #if JUCE_INCLUDED_FILE
  224621. struct NamedPipeInternal
  224622. {
  224623. String pipeInName, pipeOutName;
  224624. int pipeIn, pipeOut;
  224625. bool volatile createdPipe, blocked, stopReadOperation;
  224626. static void signalHandler (int) {}
  224627. };
  224628. void NamedPipe::cancelPendingReads()
  224629. {
  224630. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224631. {
  224632. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224633. intern->stopReadOperation = true;
  224634. char buffer [1] = { 0 };
  224635. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224636. (void) bytesWritten;
  224637. int timeout = 2000;
  224638. while (intern->blocked && --timeout >= 0)
  224639. Thread::sleep (2);
  224640. intern->stopReadOperation = false;
  224641. }
  224642. }
  224643. void NamedPipe::close()
  224644. {
  224645. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224646. if (intern != 0)
  224647. {
  224648. internal = 0;
  224649. if (intern->pipeIn != -1)
  224650. ::close (intern->pipeIn);
  224651. if (intern->pipeOut != -1)
  224652. ::close (intern->pipeOut);
  224653. if (intern->createdPipe)
  224654. {
  224655. unlink (intern->pipeInName.toUTF8());
  224656. unlink (intern->pipeOutName.toUTF8());
  224657. }
  224658. delete intern;
  224659. }
  224660. }
  224661. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224662. {
  224663. close();
  224664. NamedPipeInternal* const intern = new NamedPipeInternal();
  224665. internal = intern;
  224666. intern->createdPipe = createPipe;
  224667. intern->blocked = false;
  224668. intern->stopReadOperation = false;
  224669. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224670. siginterrupt (SIGPIPE, 1);
  224671. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224672. intern->pipeInName = pipePath + "_in";
  224673. intern->pipeOutName = pipePath + "_out";
  224674. intern->pipeIn = -1;
  224675. intern->pipeOut = -1;
  224676. if (createPipe)
  224677. {
  224678. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224679. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224680. {
  224681. delete intern;
  224682. internal = 0;
  224683. return false;
  224684. }
  224685. }
  224686. return true;
  224687. }
  224688. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224689. {
  224690. int bytesRead = -1;
  224691. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224692. if (intern != 0)
  224693. {
  224694. intern->blocked = true;
  224695. if (intern->pipeIn == -1)
  224696. {
  224697. if (intern->createdPipe)
  224698. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224699. else
  224700. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224701. if (intern->pipeIn == -1)
  224702. {
  224703. intern->blocked = false;
  224704. return -1;
  224705. }
  224706. }
  224707. bytesRead = 0;
  224708. char* p = (char*) destBuffer;
  224709. while (bytesRead < maxBytesToRead)
  224710. {
  224711. const int bytesThisTime = maxBytesToRead - bytesRead;
  224712. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224713. if (numRead <= 0 || intern->stopReadOperation)
  224714. {
  224715. bytesRead = -1;
  224716. break;
  224717. }
  224718. bytesRead += numRead;
  224719. p += bytesRead;
  224720. }
  224721. intern->blocked = false;
  224722. }
  224723. return bytesRead;
  224724. }
  224725. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224726. {
  224727. int bytesWritten = -1;
  224728. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224729. if (intern != 0)
  224730. {
  224731. if (intern->pipeOut == -1)
  224732. {
  224733. if (intern->createdPipe)
  224734. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224735. else
  224736. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224737. if (intern->pipeOut == -1)
  224738. {
  224739. return -1;
  224740. }
  224741. }
  224742. const char* p = (const char*) sourceBuffer;
  224743. bytesWritten = 0;
  224744. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224745. while (bytesWritten < numBytesToWrite
  224746. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224747. {
  224748. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224749. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224750. if (numWritten <= 0)
  224751. {
  224752. bytesWritten = -1;
  224753. break;
  224754. }
  224755. bytesWritten += numWritten;
  224756. p += bytesWritten;
  224757. }
  224758. }
  224759. return bytesWritten;
  224760. }
  224761. #endif
  224762. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224763. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224764. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224765. // compiled on its own).
  224766. #if JUCE_INCLUDED_FILE
  224767. /*
  224768. Note that a lot of methods that you'd expect to find in this file actually
  224769. live in juce_posix_SharedCode.h!
  224770. */
  224771. bool Process::isForegroundProcess()
  224772. {
  224773. #if JUCE_MAC
  224774. return [NSApp isActive];
  224775. #else
  224776. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224777. #endif
  224778. }
  224779. void Process::raisePrivilege()
  224780. {
  224781. jassertfalse;
  224782. }
  224783. void Process::lowerPrivilege()
  224784. {
  224785. jassertfalse;
  224786. }
  224787. void Process::terminate()
  224788. {
  224789. exit (0);
  224790. }
  224791. void Process::setPriority (ProcessPriority)
  224792. {
  224793. // xxx
  224794. }
  224795. #endif
  224796. /*** End of inlined file: juce_mac_Threads.mm ***/
  224797. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224798. /*
  224799. This file contains posix routines that are common to both the Linux and Mac builds.
  224800. It gets included directly in the cpp files for these platforms.
  224801. */
  224802. CriticalSection::CriticalSection() throw()
  224803. {
  224804. pthread_mutexattr_t atts;
  224805. pthread_mutexattr_init (&atts);
  224806. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224807. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224808. pthread_mutex_init (&internal, &atts);
  224809. }
  224810. CriticalSection::~CriticalSection() throw()
  224811. {
  224812. pthread_mutex_destroy (&internal);
  224813. }
  224814. void CriticalSection::enter() const throw()
  224815. {
  224816. pthread_mutex_lock (&internal);
  224817. }
  224818. bool CriticalSection::tryEnter() const throw()
  224819. {
  224820. return pthread_mutex_trylock (&internal) == 0;
  224821. }
  224822. void CriticalSection::exit() const throw()
  224823. {
  224824. pthread_mutex_unlock (&internal);
  224825. }
  224826. class WaitableEventImpl
  224827. {
  224828. public:
  224829. WaitableEventImpl (const bool manualReset_)
  224830. : triggered (false),
  224831. manualReset (manualReset_)
  224832. {
  224833. pthread_cond_init (&condition, 0);
  224834. pthread_mutexattr_t atts;
  224835. pthread_mutexattr_init (&atts);
  224836. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224837. pthread_mutex_init (&mutex, &atts);
  224838. }
  224839. ~WaitableEventImpl()
  224840. {
  224841. pthread_cond_destroy (&condition);
  224842. pthread_mutex_destroy (&mutex);
  224843. }
  224844. bool wait (const int timeOutMillisecs) throw()
  224845. {
  224846. pthread_mutex_lock (&mutex);
  224847. if (! triggered)
  224848. {
  224849. if (timeOutMillisecs < 0)
  224850. {
  224851. do
  224852. {
  224853. pthread_cond_wait (&condition, &mutex);
  224854. }
  224855. while (! triggered);
  224856. }
  224857. else
  224858. {
  224859. struct timeval now;
  224860. gettimeofday (&now, 0);
  224861. struct timespec time;
  224862. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224863. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224864. if (time.tv_nsec >= 1000000000)
  224865. {
  224866. time.tv_nsec -= 1000000000;
  224867. time.tv_sec++;
  224868. }
  224869. do
  224870. {
  224871. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224872. {
  224873. pthread_mutex_unlock (&mutex);
  224874. return false;
  224875. }
  224876. }
  224877. while (! triggered);
  224878. }
  224879. }
  224880. if (! manualReset)
  224881. triggered = false;
  224882. pthread_mutex_unlock (&mutex);
  224883. return true;
  224884. }
  224885. void signal() throw()
  224886. {
  224887. pthread_mutex_lock (&mutex);
  224888. triggered = true;
  224889. pthread_cond_broadcast (&condition);
  224890. pthread_mutex_unlock (&mutex);
  224891. }
  224892. void reset() throw()
  224893. {
  224894. pthread_mutex_lock (&mutex);
  224895. triggered = false;
  224896. pthread_mutex_unlock (&mutex);
  224897. }
  224898. private:
  224899. pthread_cond_t condition;
  224900. pthread_mutex_t mutex;
  224901. bool triggered;
  224902. const bool manualReset;
  224903. WaitableEventImpl (const WaitableEventImpl&);
  224904. WaitableEventImpl& operator= (const WaitableEventImpl&);
  224905. };
  224906. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224907. : internal (new WaitableEventImpl (manualReset))
  224908. {
  224909. }
  224910. WaitableEvent::~WaitableEvent() throw()
  224911. {
  224912. delete static_cast <WaitableEventImpl*> (internal);
  224913. }
  224914. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224915. {
  224916. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224917. }
  224918. void WaitableEvent::signal() const throw()
  224919. {
  224920. static_cast <WaitableEventImpl*> (internal)->signal();
  224921. }
  224922. void WaitableEvent::reset() const throw()
  224923. {
  224924. static_cast <WaitableEventImpl*> (internal)->reset();
  224925. }
  224926. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224927. {
  224928. struct timespec time;
  224929. time.tv_sec = millisecs / 1000;
  224930. time.tv_nsec = (millisecs % 1000) * 1000000;
  224931. nanosleep (&time, 0);
  224932. }
  224933. const juce_wchar File::separator = '/';
  224934. const String File::separatorString ("/");
  224935. const File File::getCurrentWorkingDirectory()
  224936. {
  224937. HeapBlock<char> heapBuffer;
  224938. char localBuffer [1024];
  224939. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224940. int bufferSize = 4096;
  224941. while (cwd == 0 && errno == ERANGE)
  224942. {
  224943. heapBuffer.malloc (bufferSize);
  224944. cwd = getcwd (heapBuffer, bufferSize - 1);
  224945. bufferSize += 1024;
  224946. }
  224947. return File (String::fromUTF8 (cwd));
  224948. }
  224949. bool File::setAsCurrentWorkingDirectory() const
  224950. {
  224951. return chdir (getFullPathName().toUTF8()) == 0;
  224952. }
  224953. static bool juce_stat (const String& fileName, struct stat& info)
  224954. {
  224955. return fileName.isNotEmpty()
  224956. && (stat (fileName.toUTF8(), &info) == 0);
  224957. }
  224958. bool File::isDirectory() const
  224959. {
  224960. struct stat info;
  224961. return fullPath.isEmpty()
  224962. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224963. }
  224964. bool File::exists() const
  224965. {
  224966. return fullPath.isNotEmpty()
  224967. && access (fullPath.toUTF8(), F_OK) == 0;
  224968. }
  224969. bool File::existsAsFile() const
  224970. {
  224971. return exists() && ! isDirectory();
  224972. }
  224973. int64 File::getSize() const
  224974. {
  224975. struct stat info;
  224976. return juce_stat (fullPath, info) ? info.st_size : 0;
  224977. }
  224978. bool File::hasWriteAccess() const
  224979. {
  224980. if (exists())
  224981. return access (fullPath.toUTF8(), W_OK) == 0;
  224982. if ((! isDirectory()) && fullPath.containsChar (separator))
  224983. return getParentDirectory().hasWriteAccess();
  224984. return false;
  224985. }
  224986. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224987. {
  224988. struct stat info;
  224989. const int res = stat (fullPath.toUTF8(), &info);
  224990. if (res != 0)
  224991. return false;
  224992. info.st_mode &= 0777; // Just permissions
  224993. if (shouldBeReadOnly)
  224994. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224995. else
  224996. // Give everybody write permission?
  224997. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224998. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224999. }
  225000. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225001. {
  225002. modificationTime = 0;
  225003. accessTime = 0;
  225004. creationTime = 0;
  225005. struct stat info;
  225006. const int res = stat (fullPath.toUTF8(), &info);
  225007. if (res == 0)
  225008. {
  225009. modificationTime = (int64) info.st_mtime * 1000;
  225010. accessTime = (int64) info.st_atime * 1000;
  225011. creationTime = (int64) info.st_ctime * 1000;
  225012. }
  225013. }
  225014. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225015. {
  225016. struct utimbuf times;
  225017. times.actime = (time_t) (accessTime / 1000);
  225018. times.modtime = (time_t) (modificationTime / 1000);
  225019. return utime (fullPath.toUTF8(), &times) == 0;
  225020. }
  225021. bool File::deleteFile() const
  225022. {
  225023. if (! exists())
  225024. return true;
  225025. else if (isDirectory())
  225026. return rmdir (fullPath.toUTF8()) == 0;
  225027. else
  225028. return remove (fullPath.toUTF8()) == 0;
  225029. }
  225030. bool File::moveInternal (const File& dest) const
  225031. {
  225032. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225033. return true;
  225034. if (hasWriteAccess() && copyInternal (dest))
  225035. {
  225036. if (deleteFile())
  225037. return true;
  225038. dest.deleteFile();
  225039. }
  225040. return false;
  225041. }
  225042. void File::createDirectoryInternal (const String& fileName) const
  225043. {
  225044. mkdir (fileName.toUTF8(), 0777);
  225045. }
  225046. int64 juce_fileSetPosition (void* handle, int64 pos)
  225047. {
  225048. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225049. return pos;
  225050. return -1;
  225051. }
  225052. void FileInputStream::openHandle()
  225053. {
  225054. totalSize = file.getSize();
  225055. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225056. if (f != -1)
  225057. fileHandle = (void*) f;
  225058. }
  225059. void FileInputStream::closeHandle()
  225060. {
  225061. if (fileHandle != 0)
  225062. {
  225063. close ((int) (pointer_sized_int) fileHandle);
  225064. fileHandle = 0;
  225065. }
  225066. }
  225067. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225068. {
  225069. if (fileHandle != 0)
  225070. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225071. return 0;
  225072. }
  225073. void FileOutputStream::openHandle()
  225074. {
  225075. if (file.exists())
  225076. {
  225077. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225078. if (f != -1)
  225079. {
  225080. currentPosition = lseek (f, 0, SEEK_END);
  225081. if (currentPosition >= 0)
  225082. fileHandle = (void*) f;
  225083. else
  225084. close (f);
  225085. }
  225086. }
  225087. else
  225088. {
  225089. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225090. if (f != -1)
  225091. fileHandle = (void*) f;
  225092. }
  225093. }
  225094. void FileOutputStream::closeHandle()
  225095. {
  225096. if (fileHandle != 0)
  225097. {
  225098. close ((int) (pointer_sized_int) fileHandle);
  225099. fileHandle = 0;
  225100. }
  225101. }
  225102. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225103. {
  225104. if (fileHandle != 0)
  225105. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225106. return 0;
  225107. }
  225108. void FileOutputStream::flushInternal()
  225109. {
  225110. if (fileHandle != 0)
  225111. fsync ((int) (pointer_sized_int) fileHandle);
  225112. }
  225113. const File juce_getExecutableFile()
  225114. {
  225115. Dl_info exeInfo;
  225116. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225117. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225118. }
  225119. // if this file doesn't exist, find a parent of it that does..
  225120. static bool juce_doStatFS (File f, struct statfs& result)
  225121. {
  225122. for (int i = 5; --i >= 0;)
  225123. {
  225124. if (f.exists())
  225125. break;
  225126. f = f.getParentDirectory();
  225127. }
  225128. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225129. }
  225130. int64 File::getBytesFreeOnVolume() const
  225131. {
  225132. struct statfs buf;
  225133. if (juce_doStatFS (*this, buf))
  225134. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225135. return 0;
  225136. }
  225137. int64 File::getVolumeTotalSize() const
  225138. {
  225139. struct statfs buf;
  225140. if (juce_doStatFS (*this, buf))
  225141. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225142. return 0;
  225143. }
  225144. const String File::getVolumeLabel() const
  225145. {
  225146. #if JUCE_MAC
  225147. struct VolAttrBuf
  225148. {
  225149. u_int32_t length;
  225150. attrreference_t mountPointRef;
  225151. char mountPointSpace [MAXPATHLEN];
  225152. } attrBuf;
  225153. struct attrlist attrList;
  225154. zerostruct (attrList);
  225155. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225156. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225157. File f (*this);
  225158. for (;;)
  225159. {
  225160. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225161. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225162. (int) attrBuf.mountPointRef.attr_length);
  225163. const File parent (f.getParentDirectory());
  225164. if (f == parent)
  225165. break;
  225166. f = parent;
  225167. }
  225168. #endif
  225169. return String::empty;
  225170. }
  225171. int File::getVolumeSerialNumber() const
  225172. {
  225173. return 0; // xxx
  225174. }
  225175. void juce_runSystemCommand (const String& command)
  225176. {
  225177. int result = system (command.toUTF8());
  225178. (void) result;
  225179. }
  225180. const String juce_getOutputFromCommand (const String& command)
  225181. {
  225182. // slight bodge here, as we just pipe the output into a temp file and read it...
  225183. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225184. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225185. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225186. String result (tempFile.loadFileAsString());
  225187. tempFile.deleteFile();
  225188. return result;
  225189. }
  225190. class InterProcessLock::Pimpl
  225191. {
  225192. public:
  225193. Pimpl (const String& name, const int timeOutMillisecs)
  225194. : handle (0), refCount (1)
  225195. {
  225196. #if JUCE_MAC
  225197. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225198. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225199. #else
  225200. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225201. #endif
  225202. temp.create();
  225203. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225204. if (handle != 0)
  225205. {
  225206. struct flock fl;
  225207. zerostruct (fl);
  225208. fl.l_whence = SEEK_SET;
  225209. fl.l_type = F_WRLCK;
  225210. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225211. for (;;)
  225212. {
  225213. const int result = fcntl (handle, F_SETLK, &fl);
  225214. if (result >= 0)
  225215. return;
  225216. if (errno != EINTR)
  225217. {
  225218. if (timeOutMillisecs == 0
  225219. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225220. break;
  225221. Thread::sleep (10);
  225222. }
  225223. }
  225224. }
  225225. closeFile();
  225226. }
  225227. ~Pimpl()
  225228. {
  225229. closeFile();
  225230. }
  225231. void closeFile()
  225232. {
  225233. if (handle != 0)
  225234. {
  225235. struct flock fl;
  225236. zerostruct (fl);
  225237. fl.l_whence = SEEK_SET;
  225238. fl.l_type = F_UNLCK;
  225239. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225240. {}
  225241. close (handle);
  225242. handle = 0;
  225243. }
  225244. }
  225245. int handle, refCount;
  225246. };
  225247. InterProcessLock::InterProcessLock (const String& name_)
  225248. : name (name_)
  225249. {
  225250. }
  225251. InterProcessLock::~InterProcessLock()
  225252. {
  225253. }
  225254. bool InterProcessLock::enter (const int timeOutMillisecs)
  225255. {
  225256. const ScopedLock sl (lock);
  225257. if (pimpl == 0)
  225258. {
  225259. pimpl = new Pimpl (name, timeOutMillisecs);
  225260. if (pimpl->handle == 0)
  225261. pimpl = 0;
  225262. }
  225263. else
  225264. {
  225265. pimpl->refCount++;
  225266. }
  225267. return pimpl != 0;
  225268. }
  225269. void InterProcessLock::exit()
  225270. {
  225271. const ScopedLock sl (lock);
  225272. // Trying to release the lock too many times!
  225273. jassert (pimpl != 0);
  225274. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225275. pimpl = 0;
  225276. }
  225277. void JUCE_API juce_threadEntryPoint (void*);
  225278. void* threadEntryProc (void* userData)
  225279. {
  225280. JUCE_AUTORELEASEPOOL
  225281. juce_threadEntryPoint (userData);
  225282. return 0;
  225283. }
  225284. void* juce_createThread (void* userData)
  225285. {
  225286. pthread_t handle = 0;
  225287. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225288. {
  225289. pthread_detach (handle);
  225290. return (void*) handle;
  225291. }
  225292. return 0;
  225293. }
  225294. void juce_killThread (void* handle)
  225295. {
  225296. if (handle != 0)
  225297. pthread_cancel ((pthread_t) handle);
  225298. }
  225299. void juce_setCurrentThreadName (const String& /*name*/)
  225300. {
  225301. }
  225302. bool juce_setThreadPriority (void* handle, int priority)
  225303. {
  225304. struct sched_param param;
  225305. int policy;
  225306. priority = jlimit (0, 10, priority);
  225307. if (handle == 0)
  225308. handle = (void*) pthread_self();
  225309. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225310. return false;
  225311. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225312. const int minPriority = sched_get_priority_min (policy);
  225313. const int maxPriority = sched_get_priority_max (policy);
  225314. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225315. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225316. }
  225317. Thread::ThreadID Thread::getCurrentThreadId()
  225318. {
  225319. return (ThreadID) pthread_self();
  225320. }
  225321. void Thread::yield()
  225322. {
  225323. sched_yield();
  225324. }
  225325. /* Remove this macro if you're having problems compiling the cpu affinity
  225326. calls (the API for these has changed about quite a bit in various Linux
  225327. versions, and a lot of distros seem to ship with obsolete versions)
  225328. */
  225329. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225330. #define SUPPORT_AFFINITIES 1
  225331. #endif
  225332. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225333. {
  225334. #if SUPPORT_AFFINITIES
  225335. cpu_set_t affinity;
  225336. CPU_ZERO (&affinity);
  225337. for (int i = 0; i < 32; ++i)
  225338. if ((affinityMask & (1 << i)) != 0)
  225339. CPU_SET (i, &affinity);
  225340. /*
  225341. N.B. If this line causes a compile error, then you've probably not got the latest
  225342. version of glibc installed.
  225343. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225344. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225345. */
  225346. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225347. sched_yield();
  225348. #else
  225349. /* affinities aren't supported because either the appropriate header files weren't found,
  225350. or the SUPPORT_AFFINITIES macro was turned off
  225351. */
  225352. jassertfalse;
  225353. #endif
  225354. }
  225355. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225356. /*** Start of inlined file: juce_mac_Files.mm ***/
  225357. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225358. // compiled on its own).
  225359. #if JUCE_INCLUDED_FILE
  225360. /*
  225361. Note that a lot of methods that you'd expect to find in this file actually
  225362. live in juce_posix_SharedCode.h!
  225363. */
  225364. bool File::copyInternal (const File& dest) const
  225365. {
  225366. const ScopedAutoReleasePool pool;
  225367. NSFileManager* fm = [NSFileManager defaultManager];
  225368. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225369. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225370. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225371. toPath: juceStringToNS (dest.getFullPathName())
  225372. error: nil];
  225373. #else
  225374. && [fm copyPath: juceStringToNS (fullPath)
  225375. toPath: juceStringToNS (dest.getFullPathName())
  225376. handler: nil];
  225377. #endif
  225378. }
  225379. void File::findFileSystemRoots (Array<File>& destArray)
  225380. {
  225381. destArray.add (File ("/"));
  225382. }
  225383. static bool isFileOnDriveType (const File& f, const char* const* types)
  225384. {
  225385. struct statfs buf;
  225386. if (juce_doStatFS (f, buf))
  225387. {
  225388. const String type (buf.f_fstypename);
  225389. while (*types != 0)
  225390. if (type.equalsIgnoreCase (*types++))
  225391. return true;
  225392. }
  225393. return false;
  225394. }
  225395. bool File::isOnCDRomDrive() const
  225396. {
  225397. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225398. return isFileOnDriveType (*this, cdTypes);
  225399. }
  225400. bool File::isOnHardDisk() const
  225401. {
  225402. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225403. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225404. }
  225405. bool File::isOnRemovableDrive() const
  225406. {
  225407. #if JUCE_IOS
  225408. return false; // xxx is this possible?
  225409. #else
  225410. const ScopedAutoReleasePool pool;
  225411. BOOL removable = false;
  225412. [[NSWorkspace sharedWorkspace]
  225413. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225414. isRemovable: &removable
  225415. isWritable: nil
  225416. isUnmountable: nil
  225417. description: nil
  225418. type: nil];
  225419. return removable;
  225420. #endif
  225421. }
  225422. static bool juce_isHiddenFile (const String& path)
  225423. {
  225424. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225425. const ScopedAutoReleasePool pool;
  225426. NSNumber* hidden = nil;
  225427. NSError* err = nil;
  225428. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225429. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225430. && [hidden boolValue];
  225431. #else
  225432. #if JUCE_IOS
  225433. return File (path).getFileName().startsWithChar ('.');
  225434. #else
  225435. FSRef ref;
  225436. LSItemInfoRecord info;
  225437. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225438. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225439. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225440. #endif
  225441. #endif
  225442. }
  225443. bool File::isHidden() const
  225444. {
  225445. return juce_isHiddenFile (getFullPathName());
  225446. }
  225447. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225448. const File File::getSpecialLocation (const SpecialLocationType type)
  225449. {
  225450. const ScopedAutoReleasePool pool;
  225451. String resultPath;
  225452. switch (type)
  225453. {
  225454. case userHomeDirectory:
  225455. resultPath = nsStringToJuce (NSHomeDirectory());
  225456. break;
  225457. case userDocumentsDirectory:
  225458. resultPath = "~/Documents";
  225459. break;
  225460. case userDesktopDirectory:
  225461. resultPath = "~/Desktop";
  225462. break;
  225463. case userApplicationDataDirectory:
  225464. resultPath = "~/Library";
  225465. break;
  225466. case commonApplicationDataDirectory:
  225467. resultPath = "/Library";
  225468. break;
  225469. case globalApplicationsDirectory:
  225470. resultPath = "/Applications";
  225471. break;
  225472. case userMusicDirectory:
  225473. resultPath = "~/Music";
  225474. break;
  225475. case userMoviesDirectory:
  225476. resultPath = "~/Movies";
  225477. break;
  225478. case tempDirectory:
  225479. {
  225480. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225481. tmp.createDirectory();
  225482. return tmp.getFullPathName();
  225483. }
  225484. case invokedExecutableFile:
  225485. if (juce_Argv0 != 0)
  225486. return File (String::fromUTF8 (juce_Argv0));
  225487. // deliberate fall-through...
  225488. case currentExecutableFile:
  225489. return juce_getExecutableFile();
  225490. case currentApplicationFile:
  225491. {
  225492. const File exe (juce_getExecutableFile());
  225493. const File parent (exe.getParentDirectory());
  225494. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225495. ? parent.getParentDirectory().getParentDirectory()
  225496. : exe;
  225497. }
  225498. case hostApplicationPath:
  225499. {
  225500. unsigned int size = 8192;
  225501. HeapBlock<char> buffer;
  225502. buffer.calloc (size + 8);
  225503. _NSGetExecutablePath (buffer.getData(), &size);
  225504. return String::fromUTF8 (buffer, size);
  225505. }
  225506. default:
  225507. jassertfalse; // unknown type?
  225508. break;
  225509. }
  225510. if (resultPath.isNotEmpty())
  225511. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225512. return File::nonexistent;
  225513. }
  225514. const String File::getVersion() const
  225515. {
  225516. const ScopedAutoReleasePool pool;
  225517. String result;
  225518. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225519. if (bundle != 0)
  225520. {
  225521. NSDictionary* info = [bundle infoDictionary];
  225522. if (info != 0)
  225523. {
  225524. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225525. if (name != nil)
  225526. result = nsStringToJuce (name);
  225527. }
  225528. }
  225529. return result;
  225530. }
  225531. const File File::getLinkedTarget() const
  225532. {
  225533. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225534. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225535. #else
  225536. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225537. #endif
  225538. if (dest != nil)
  225539. return File (nsStringToJuce (dest));
  225540. return *this;
  225541. }
  225542. bool File::moveToTrash() const
  225543. {
  225544. if (! exists())
  225545. return true;
  225546. #if JUCE_IOS
  225547. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225548. #else
  225549. const ScopedAutoReleasePool pool;
  225550. NSString* p = juceStringToNS (getFullPathName());
  225551. return [[NSWorkspace sharedWorkspace]
  225552. performFileOperation: NSWorkspaceRecycleOperation
  225553. source: [p stringByDeletingLastPathComponent]
  225554. destination: @""
  225555. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225556. tag: nil ];
  225557. #endif
  225558. }
  225559. class DirectoryIterator::NativeIterator::Pimpl
  225560. {
  225561. public:
  225562. Pimpl (const File& directory, const String& wildCard_)
  225563. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225564. wildCard (wildCard_),
  225565. enumerator (0)
  225566. {
  225567. const ScopedAutoReleasePool pool;
  225568. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225569. wildcardUTF8 = wildCard.toUTF8();
  225570. }
  225571. ~Pimpl()
  225572. {
  225573. [enumerator release];
  225574. }
  225575. bool next (String& filenameFound,
  225576. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225577. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225578. {
  225579. const ScopedAutoReleasePool pool;
  225580. for (;;)
  225581. {
  225582. NSString* file;
  225583. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225584. return false;
  225585. [enumerator skipDescendents];
  225586. filenameFound = nsStringToJuce (file);
  225587. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225588. continue;
  225589. const String path (parentDir + filenameFound);
  225590. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225591. {
  225592. struct stat info;
  225593. const bool statOk = juce_stat (path, info);
  225594. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225595. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225596. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225597. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225598. }
  225599. if (isHidden != 0)
  225600. *isHidden = juce_isHiddenFile (path);
  225601. if (isReadOnly != 0)
  225602. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225603. return true;
  225604. }
  225605. }
  225606. private:
  225607. String parentDir, wildCard;
  225608. const char* wildcardUTF8;
  225609. NSDirectoryEnumerator* enumerator;
  225610. Pimpl (const Pimpl&);
  225611. Pimpl& operator= (const Pimpl&);
  225612. };
  225613. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225614. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225615. {
  225616. }
  225617. DirectoryIterator::NativeIterator::~NativeIterator()
  225618. {
  225619. }
  225620. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225621. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225622. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225623. {
  225624. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225625. }
  225626. bool juce_launchExecutable (const String& pathAndArguments)
  225627. {
  225628. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225629. const int cpid = fork();
  225630. if (cpid == 0)
  225631. {
  225632. // Child process
  225633. if (execve (argv[0], (char**) argv, 0) < 0)
  225634. exit (0);
  225635. }
  225636. else
  225637. {
  225638. if (cpid < 0)
  225639. return false;
  225640. }
  225641. return true;
  225642. }
  225643. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225644. {
  225645. #if JUCE_IOS
  225646. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225647. #else
  225648. const ScopedAutoReleasePool pool;
  225649. if (parameters.isEmpty())
  225650. {
  225651. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225652. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225653. }
  225654. bool ok = false;
  225655. if (PlatformUtilities::isBundle (fileName))
  225656. {
  225657. NSMutableArray* urls = [NSMutableArray array];
  225658. StringArray docs;
  225659. docs.addTokens (parameters, true);
  225660. for (int i = 0; i < docs.size(); ++i)
  225661. [urls addObject: juceStringToNS (docs[i])];
  225662. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225663. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225664. options: 0
  225665. additionalEventParamDescriptor: nil
  225666. launchIdentifiers: nil];
  225667. }
  225668. else if (File (fileName).exists())
  225669. {
  225670. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225671. }
  225672. return ok;
  225673. #endif
  225674. }
  225675. void File::revealToUser() const
  225676. {
  225677. #if ! JUCE_IOS
  225678. if (exists())
  225679. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225680. else if (getParentDirectory().exists())
  225681. getParentDirectory().revealToUser();
  225682. #endif
  225683. }
  225684. #if ! JUCE_IOS
  225685. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225686. {
  225687. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225688. }
  225689. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225690. {
  225691. char path [2048];
  225692. zerostruct (path);
  225693. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225694. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225695. return String::empty;
  225696. }
  225697. #endif
  225698. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225699. {
  225700. const ScopedAutoReleasePool pool;
  225701. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225702. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225703. #else
  225704. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225705. #endif
  225706. return [fileDict fileHFSTypeCode];
  225707. }
  225708. bool PlatformUtilities::isBundle (const String& filename)
  225709. {
  225710. #if JUCE_IOS
  225711. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225712. #else
  225713. const ScopedAutoReleasePool pool;
  225714. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225715. #endif
  225716. }
  225717. #endif
  225718. /*** End of inlined file: juce_mac_Files.mm ***/
  225719. #if JUCE_IOS
  225720. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225721. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225722. // compiled on its own).
  225723. #if JUCE_INCLUDED_FILE
  225724. END_JUCE_NAMESPACE
  225725. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225726. {
  225727. }
  225728. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225729. - (void) applicationWillTerminate: (UIApplication*) application;
  225730. @end
  225731. @implementation JuceAppStartupDelegate
  225732. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225733. {
  225734. initialiseJuce_GUI();
  225735. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225736. exit (0);
  225737. }
  225738. - (void) applicationWillTerminate: (UIApplication*) application
  225739. {
  225740. jassert (JUCEApplication::getInstance() != 0);
  225741. JUCEApplication::getInstance()->shutdownApp();
  225742. delete JUCEApplication::getInstance();
  225743. shutdownJuce_GUI();
  225744. }
  225745. @end
  225746. BEGIN_JUCE_NAMESPACE
  225747. int juce_iOSMain (int argc, const char* argv[])
  225748. {
  225749. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225750. }
  225751. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225752. {
  225753. pool = [[NSAutoreleasePool alloc] init];
  225754. }
  225755. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225756. {
  225757. [((NSAutoreleasePool*) pool) release];
  225758. }
  225759. void PlatformUtilities::beep()
  225760. {
  225761. //xxx
  225762. //AudioServicesPlaySystemSound ();
  225763. }
  225764. void PlatformUtilities::addItemToDock (const File& file)
  225765. {
  225766. }
  225767. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225768. END_JUCE_NAMESPACE
  225769. @interface JuceAlertBoxDelegate : NSObject
  225770. {
  225771. @public
  225772. bool clickedOk;
  225773. }
  225774. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225775. @end
  225776. @implementation JuceAlertBoxDelegate
  225777. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225778. {
  225779. clickedOk = (buttonIndex == 0);
  225780. alertView.hidden = true;
  225781. }
  225782. @end
  225783. BEGIN_JUCE_NAMESPACE
  225784. // (This function is used directly by other bits of code)
  225785. bool juce_iPhoneShowModalAlert (const String& title,
  225786. const String& bodyText,
  225787. NSString* okButtonText,
  225788. NSString* cancelButtonText)
  225789. {
  225790. const ScopedAutoReleasePool pool;
  225791. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225792. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225793. message: juceStringToNS (bodyText)
  225794. delegate: callback
  225795. cancelButtonTitle: okButtonText
  225796. otherButtonTitles: cancelButtonText, nil];
  225797. [alert retain];
  225798. [alert show];
  225799. while (! alert.hidden && alert.superview != nil)
  225800. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225801. const bool result = callback->clickedOk;
  225802. [alert release];
  225803. [callback release];
  225804. return result;
  225805. }
  225806. bool AlertWindow::showNativeDialogBox (const String& title,
  225807. const String& bodyText,
  225808. bool isOkCancel)
  225809. {
  225810. return juce_iPhoneShowModalAlert (title, bodyText,
  225811. @"OK",
  225812. isOkCancel ? @"Cancel" : nil);
  225813. }
  225814. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225815. {
  225816. jassertfalse; // no such thing on the iphone!
  225817. return false;
  225818. }
  225819. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225820. {
  225821. jassertfalse; // no such thing on the iphone!
  225822. return false;
  225823. }
  225824. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225825. {
  225826. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225827. }
  225828. bool Desktop::isScreenSaverEnabled()
  225829. {
  225830. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225831. }
  225832. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  225833. {
  225834. const ScopedAutoReleasePool pool;
  225835. monitorCoords.clear();
  225836. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  225837. : [[UIScreen mainScreen] bounds];
  225838. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  225839. (int) r.origin.y,
  225840. (int) r.size.width,
  225841. (int) r.size.height));
  225842. }
  225843. #endif
  225844. #endif
  225845. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225846. #else
  225847. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225848. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225849. // compiled on its own).
  225850. #if JUCE_INCLUDED_FILE
  225851. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225852. {
  225853. pool = [[NSAutoreleasePool alloc] init];
  225854. }
  225855. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225856. {
  225857. [((NSAutoreleasePool*) pool) release];
  225858. }
  225859. void PlatformUtilities::beep()
  225860. {
  225861. NSBeep();
  225862. }
  225863. void PlatformUtilities::addItemToDock (const File& file)
  225864. {
  225865. // check that it's not already there...
  225866. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225867. .containsIgnoreCase (file.getFullPathName()))
  225868. {
  225869. 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>"
  225870. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225871. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225872. }
  225873. }
  225874. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225875. bool AlertWindow::showNativeDialogBox (const String& title,
  225876. const String& bodyText,
  225877. bool isOkCancel)
  225878. {
  225879. const ScopedAutoReleasePool pool;
  225880. return NSRunAlertPanel (juceStringToNS (title),
  225881. juceStringToNS (bodyText),
  225882. @"Ok",
  225883. isOkCancel ? @"Cancel" : nil,
  225884. nil) == NSAlertDefaultReturn;
  225885. }
  225886. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225887. {
  225888. if (files.size() == 0)
  225889. return false;
  225890. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225891. if (draggingSource == 0)
  225892. {
  225893. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225894. return false;
  225895. }
  225896. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225897. if (sourceComp == 0)
  225898. {
  225899. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225900. return false;
  225901. }
  225902. const ScopedAutoReleasePool pool;
  225903. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225904. if (view == 0)
  225905. return false;
  225906. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225907. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225908. owner: nil];
  225909. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225910. for (int i = 0; i < files.size(); ++i)
  225911. [filesArray addObject: juceStringToNS (files[i])];
  225912. [pboard setPropertyList: filesArray
  225913. forType: NSFilenamesPboardType];
  225914. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225915. fromView: nil];
  225916. dragPosition.x -= 16;
  225917. dragPosition.y -= 16;
  225918. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225919. at: dragPosition
  225920. offset: NSMakeSize (0, 0)
  225921. event: [[view window] currentEvent]
  225922. pasteboard: pboard
  225923. source: view
  225924. slideBack: YES];
  225925. return true;
  225926. }
  225927. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225928. {
  225929. jassertfalse; // not implemented!
  225930. return false;
  225931. }
  225932. bool Desktop::canUseSemiTransparentWindows() throw()
  225933. {
  225934. return true;
  225935. }
  225936. const Point<int> Desktop::getMousePosition()
  225937. {
  225938. const ScopedAutoReleasePool pool;
  225939. const NSPoint p ([NSEvent mouseLocation]);
  225940. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225941. }
  225942. void Desktop::setMousePosition (const Point<int>& newPosition)
  225943. {
  225944. // this rubbish needs to be done around the warp call, to avoid causing a
  225945. // bizarre glitch..
  225946. CGAssociateMouseAndMouseCursorPosition (false);
  225947. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225948. CGAssociateMouseAndMouseCursorPosition (true);
  225949. }
  225950. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225951. class ScreenSaverDefeater : public Timer,
  225952. public DeletedAtShutdown
  225953. {
  225954. public:
  225955. ScreenSaverDefeater()
  225956. {
  225957. startTimer (10000);
  225958. timerCallback();
  225959. }
  225960. ~ScreenSaverDefeater() {}
  225961. void timerCallback()
  225962. {
  225963. if (Process::isForegroundProcess())
  225964. UpdateSystemActivity (UsrActivity);
  225965. }
  225966. };
  225967. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225968. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225969. {
  225970. if (isEnabled)
  225971. deleteAndZero (screenSaverDefeater);
  225972. else if (screenSaverDefeater == 0)
  225973. screenSaverDefeater = new ScreenSaverDefeater();
  225974. }
  225975. bool Desktop::isScreenSaverEnabled()
  225976. {
  225977. return screenSaverDefeater == 0;
  225978. }
  225979. #else
  225980. static IOPMAssertionID screenSaverDisablerID = 0;
  225981. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225982. {
  225983. if (isEnabled)
  225984. {
  225985. if (screenSaverDisablerID != 0)
  225986. {
  225987. IOPMAssertionRelease (screenSaverDisablerID);
  225988. screenSaverDisablerID = 0;
  225989. }
  225990. }
  225991. else
  225992. {
  225993. if (screenSaverDisablerID == 0)
  225994. {
  225995. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225996. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225997. CFSTR ("Juce"), &screenSaverDisablerID);
  225998. #else
  225999. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226000. &screenSaverDisablerID);
  226001. #endif
  226002. }
  226003. }
  226004. }
  226005. bool Desktop::isScreenSaverEnabled()
  226006. {
  226007. return screenSaverDisablerID == 0;
  226008. }
  226009. #endif
  226010. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226011. {
  226012. const ScopedAutoReleasePool pool;
  226013. monitorCoords.clear();
  226014. NSArray* screens = [NSScreen screens];
  226015. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226016. for (unsigned int i = 0; i < [screens count]; ++i)
  226017. {
  226018. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226019. NSRect r = clipToWorkArea ? [s visibleFrame]
  226020. : [s frame];
  226021. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226022. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226023. (int) r.size.width,
  226024. (int) r.size.height));
  226025. }
  226026. jassert (monitorCoords.size() > 0);
  226027. }
  226028. #endif
  226029. #endif
  226030. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226031. #endif
  226032. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226033. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226034. // compiled on its own).
  226035. #if JUCE_INCLUDED_FILE
  226036. void Logger::outputDebugString (const String& text)
  226037. {
  226038. std::cerr << text << std::endl;
  226039. }
  226040. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226041. {
  226042. static char testResult = 0;
  226043. if (testResult == 0)
  226044. {
  226045. struct kinfo_proc info;
  226046. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226047. size_t sz = sizeof (info);
  226048. sysctl (m, 4, &info, &sz, 0, 0);
  226049. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226050. }
  226051. return testResult > 0;
  226052. }
  226053. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226054. {
  226055. return juce_isRunningUnderDebugger();
  226056. }
  226057. #endif
  226058. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226059. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226060. #if JUCE_IOS
  226061. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226062. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226063. // compiled on its own).
  226064. #if JUCE_INCLUDED_FILE
  226065. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226066. #define SUPPORT_10_4_FONTS 1
  226067. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226068. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226069. #define SUPPORT_ONLY_10_4_FONTS 1
  226070. #endif
  226071. END_JUCE_NAMESPACE
  226072. @interface NSFont (PrivateHack)
  226073. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226074. @end
  226075. BEGIN_JUCE_NAMESPACE
  226076. #endif
  226077. class MacTypeface : public Typeface
  226078. {
  226079. public:
  226080. MacTypeface (const Font& font)
  226081. : Typeface (font.getTypefaceName())
  226082. {
  226083. const ScopedAutoReleasePool pool;
  226084. renderingTransform = CGAffineTransformIdentity;
  226085. bool needsItalicTransform = false;
  226086. #if JUCE_IOS
  226087. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226088. if (font.isItalic() || font.isBold())
  226089. {
  226090. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226091. for (NSString* i in familyFonts)
  226092. {
  226093. const String fn (nsStringToJuce (i));
  226094. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226095. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226096. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226097. || afterDash.containsIgnoreCase ("italic")
  226098. || fn.endsWithIgnoreCase ("oblique")
  226099. || fn.endsWithIgnoreCase ("italic");
  226100. if (probablyBold == font.isBold()
  226101. && probablyItalic == font.isItalic())
  226102. {
  226103. fontName = i;
  226104. needsItalicTransform = false;
  226105. break;
  226106. }
  226107. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226108. {
  226109. fontName = i;
  226110. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226111. }
  226112. }
  226113. if (needsItalicTransform)
  226114. renderingTransform.c = 0.15f;
  226115. }
  226116. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226117. const int ascender = abs (CGFontGetAscent (fontRef));
  226118. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226119. ascent = ascender / totalHeight;
  226120. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226121. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226122. #else
  226123. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226124. if (font.isItalic())
  226125. {
  226126. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226127. toHaveTrait: NSItalicFontMask];
  226128. if (newFont == nsFont)
  226129. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226130. nsFont = newFont;
  226131. }
  226132. if (font.isBold())
  226133. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226134. [nsFont retain];
  226135. ascent = std::abs ((float) [nsFont ascender]);
  226136. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226137. ascent /= totalSize;
  226138. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226139. if (needsItalicTransform)
  226140. {
  226141. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226142. renderingTransform.c = 0.15f;
  226143. }
  226144. #if SUPPORT_ONLY_10_4_FONTS
  226145. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226146. if (atsFont == 0)
  226147. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226148. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226149. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226150. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226151. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226152. #else
  226153. #if SUPPORT_10_4_FONTS
  226154. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226155. {
  226156. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226157. if (atsFont == 0)
  226158. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226159. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226160. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226161. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226162. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226163. }
  226164. else
  226165. #endif
  226166. {
  226167. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226168. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226169. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226170. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226171. }
  226172. #endif
  226173. #endif
  226174. }
  226175. ~MacTypeface()
  226176. {
  226177. #if ! JUCE_IOS
  226178. [nsFont release];
  226179. #endif
  226180. if (fontRef != 0)
  226181. CGFontRelease (fontRef);
  226182. }
  226183. float getAscent() const
  226184. {
  226185. return ascent;
  226186. }
  226187. float getDescent() const
  226188. {
  226189. return 1.0f - ascent;
  226190. }
  226191. float getStringWidth (const String& text)
  226192. {
  226193. if (fontRef == 0 || text.isEmpty())
  226194. return 0;
  226195. const int length = text.length();
  226196. HeapBlock <CGGlyph> glyphs;
  226197. createGlyphsForString (text, length, glyphs);
  226198. float x = 0;
  226199. #if SUPPORT_ONLY_10_4_FONTS
  226200. HeapBlock <NSSize> advances (length);
  226201. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226202. for (int i = 0; i < length; ++i)
  226203. x += advances[i].width;
  226204. #else
  226205. #if SUPPORT_10_4_FONTS
  226206. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226207. {
  226208. HeapBlock <NSSize> advances (length);
  226209. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226210. for (int i = 0; i < length; ++i)
  226211. x += advances[i].width;
  226212. }
  226213. else
  226214. #endif
  226215. {
  226216. HeapBlock <int> advances (length);
  226217. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226218. for (int i = 0; i < length; ++i)
  226219. x += advances[i];
  226220. }
  226221. #endif
  226222. return x * unitsToHeightScaleFactor;
  226223. }
  226224. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226225. {
  226226. xOffsets.add (0);
  226227. if (fontRef == 0 || text.isEmpty())
  226228. return;
  226229. const int length = text.length();
  226230. HeapBlock <CGGlyph> glyphs;
  226231. createGlyphsForString (text, length, glyphs);
  226232. #if SUPPORT_ONLY_10_4_FONTS
  226233. HeapBlock <NSSize> advances (length);
  226234. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226235. int x = 0;
  226236. for (int i = 0; i < length; ++i)
  226237. {
  226238. x += advances[i].width;
  226239. xOffsets.add (x * unitsToHeightScaleFactor);
  226240. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226241. }
  226242. #else
  226243. #if SUPPORT_10_4_FONTS
  226244. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226245. {
  226246. HeapBlock <NSSize> advances (length);
  226247. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226248. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226249. float x = 0;
  226250. for (int i = 0; i < length; ++i)
  226251. {
  226252. x += advances[i].width;
  226253. xOffsets.add (x * unitsToHeightScaleFactor);
  226254. resultGlyphs.add (nsGlyphs[i]);
  226255. }
  226256. }
  226257. else
  226258. #endif
  226259. {
  226260. HeapBlock <int> advances (length);
  226261. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226262. {
  226263. int x = 0;
  226264. for (int i = 0; i < length; ++i)
  226265. {
  226266. x += advances [i];
  226267. xOffsets.add (x * unitsToHeightScaleFactor);
  226268. resultGlyphs.add (glyphs[i]);
  226269. }
  226270. }
  226271. }
  226272. #endif
  226273. }
  226274. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226275. {
  226276. #if JUCE_IOS
  226277. return false;
  226278. #else
  226279. if (nsFont == 0)
  226280. return false;
  226281. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226282. jassert (path.isEmpty());
  226283. const ScopedAutoReleasePool pool;
  226284. NSBezierPath* bez = [NSBezierPath bezierPath];
  226285. [bez moveToPoint: NSMakePoint (0, 0)];
  226286. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226287. inFont: nsFont];
  226288. for (int i = 0; i < [bez elementCount]; ++i)
  226289. {
  226290. NSPoint p[3];
  226291. switch ([bez elementAtIndex: i associatedPoints: p])
  226292. {
  226293. case NSMoveToBezierPathElement:
  226294. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226295. break;
  226296. case NSLineToBezierPathElement:
  226297. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226298. break;
  226299. case NSCurveToBezierPathElement:
  226300. 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);
  226301. break;
  226302. case NSClosePathBezierPathElement:
  226303. path.closeSubPath();
  226304. break;
  226305. default:
  226306. jassertfalse;
  226307. break;
  226308. }
  226309. }
  226310. path.applyTransform (pathTransform);
  226311. return true;
  226312. #endif
  226313. }
  226314. juce_UseDebuggingNewOperator
  226315. CGFontRef fontRef;
  226316. float fontHeightToCGSizeFactor;
  226317. CGAffineTransform renderingTransform;
  226318. private:
  226319. float ascent, unitsToHeightScaleFactor;
  226320. #if JUCE_IOS
  226321. #else
  226322. NSFont* nsFont;
  226323. AffineTransform pathTransform;
  226324. #endif
  226325. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226326. {
  226327. #if SUPPORT_10_4_FONTS
  226328. #if ! SUPPORT_ONLY_10_4_FONTS
  226329. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226330. #endif
  226331. {
  226332. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226333. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226334. for (int i = 0; i < length; ++i)
  226335. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226336. return;
  226337. }
  226338. #endif
  226339. #if ! SUPPORT_ONLY_10_4_FONTS
  226340. if (charToGlyphMapper == 0)
  226341. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226342. glyphs.malloc (length);
  226343. for (int i = 0; i < length; ++i)
  226344. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226345. #endif
  226346. }
  226347. #if ! SUPPORT_ONLY_10_4_FONTS
  226348. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226349. class CharToGlyphMapper
  226350. {
  226351. public:
  226352. CharToGlyphMapper (CGFontRef fontRef)
  226353. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226354. idRangeOffset (0), glyphIndexes (0)
  226355. {
  226356. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226357. if (cmapTable != 0)
  226358. {
  226359. const int numSubtables = getValue16 (cmapTable, 2);
  226360. for (int i = 0; i < numSubtables; ++i)
  226361. {
  226362. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226363. {
  226364. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226365. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226366. {
  226367. const int length = getValue16 (cmapTable, offset + 2);
  226368. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226369. segCount = segCountX2 / 2;
  226370. const int endCodeOffset = offset + 14;
  226371. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226372. const int idDeltaOffset = startCodeOffset + segCountX2;
  226373. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226374. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226375. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226376. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226377. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226378. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226379. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226380. }
  226381. break;
  226382. }
  226383. }
  226384. CFRelease (cmapTable);
  226385. }
  226386. }
  226387. ~CharToGlyphMapper()
  226388. {
  226389. if (endCode != 0)
  226390. {
  226391. CFRelease (endCode);
  226392. CFRelease (startCode);
  226393. CFRelease (idDelta);
  226394. CFRelease (idRangeOffset);
  226395. CFRelease (glyphIndexes);
  226396. }
  226397. }
  226398. int getGlyphForCharacter (const juce_wchar c) const
  226399. {
  226400. for (int i = 0; i < segCount; ++i)
  226401. {
  226402. if (getValue16 (endCode, i * 2) >= c)
  226403. {
  226404. const int start = getValue16 (startCode, i * 2);
  226405. if (start > c)
  226406. break;
  226407. const int delta = getValue16 (idDelta, i * 2);
  226408. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226409. if (rangeOffset == 0)
  226410. return delta + c;
  226411. else
  226412. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226413. }
  226414. }
  226415. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226416. return jmax (-1, c - 29);
  226417. }
  226418. private:
  226419. int segCount;
  226420. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226421. static uint16 getValue16 (CFDataRef data, const int index)
  226422. {
  226423. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226424. }
  226425. static uint32 getValue32 (CFDataRef data, const int index)
  226426. {
  226427. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226428. }
  226429. };
  226430. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226431. #endif
  226432. MacTypeface (const MacTypeface&);
  226433. MacTypeface& operator= (const MacTypeface&);
  226434. };
  226435. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226436. {
  226437. return new MacTypeface (font);
  226438. }
  226439. const StringArray Font::findAllTypefaceNames()
  226440. {
  226441. StringArray names;
  226442. const ScopedAutoReleasePool pool;
  226443. #if JUCE_IOS
  226444. NSArray* fonts = [UIFont familyNames];
  226445. #else
  226446. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226447. #endif
  226448. for (unsigned int i = 0; i < [fonts count]; ++i)
  226449. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226450. names.sort (true);
  226451. return names;
  226452. }
  226453. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226454. {
  226455. #if JUCE_IOS
  226456. defaultSans = "Helvetica";
  226457. defaultSerif = "Times New Roman";
  226458. defaultFixed = "Courier New";
  226459. #else
  226460. defaultSans = "Lucida Grande";
  226461. defaultSerif = "Times New Roman";
  226462. defaultFixed = "Monaco";
  226463. #endif
  226464. }
  226465. #endif
  226466. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226467. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226468. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226469. // compiled on its own).
  226470. #if JUCE_INCLUDED_FILE
  226471. class CoreGraphicsImage : public Image::SharedImage
  226472. {
  226473. public:
  226474. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226475. : Image::SharedImage (format_, width_, height_)
  226476. {
  226477. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226478. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226479. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226480. imageData = imageDataAllocated;
  226481. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226482. : CGColorSpaceCreateDeviceRGB();
  226483. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226484. colourSpace, getCGImageFlags (format_));
  226485. CGColorSpaceRelease (colourSpace);
  226486. }
  226487. ~CoreGraphicsImage()
  226488. {
  226489. CGContextRelease (context);
  226490. }
  226491. Image::ImageType getType() const { return Image::NativeImage; }
  226492. LowLevelGraphicsContext* createLowLevelContext();
  226493. SharedImage* clone()
  226494. {
  226495. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226496. memcpy (im->imageData, imageData, lineStride * height);
  226497. return im;
  226498. }
  226499. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226500. {
  226501. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226502. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226503. {
  226504. return CGBitmapContextCreateImage (nativeImage->context);
  226505. }
  226506. else
  226507. {
  226508. const Image::BitmapData srcData (juceImage, false);
  226509. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226510. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226511. 8, srcData.pixelStride * 8, srcData.lineStride,
  226512. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226513. 0, true, kCGRenderingIntentDefault);
  226514. CGDataProviderRelease (provider);
  226515. return imageRef;
  226516. }
  226517. }
  226518. #if JUCE_MAC
  226519. static NSImage* createNSImage (const Image& image)
  226520. {
  226521. const ScopedAutoReleasePool pool;
  226522. NSImage* im = [[NSImage alloc] init];
  226523. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226524. [im lockFocus];
  226525. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226526. CGImageRef imageRef = createImage (image, false, colourSpace);
  226527. CGColorSpaceRelease (colourSpace);
  226528. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226529. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226530. CGImageRelease (imageRef);
  226531. [im unlockFocus];
  226532. return im;
  226533. }
  226534. #endif
  226535. CGContextRef context;
  226536. HeapBlock<uint8> imageDataAllocated;
  226537. private:
  226538. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226539. {
  226540. #if JUCE_BIG_ENDIAN
  226541. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226542. #else
  226543. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226544. #endif
  226545. }
  226546. };
  226547. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226548. {
  226549. #if USE_COREGRAPHICS_RENDERING
  226550. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226551. #else
  226552. return createSoftwareImage (format, width, height, clearImage);
  226553. #endif
  226554. }
  226555. class CoreGraphicsContext : public LowLevelGraphicsContext
  226556. {
  226557. public:
  226558. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226559. : context (context_),
  226560. flipHeight (flipHeight_),
  226561. state (new SavedState()),
  226562. numGradientLookupEntries (0),
  226563. lastClipRectIsValid (false)
  226564. {
  226565. CGContextRetain (context);
  226566. CGContextSaveGState(context);
  226567. CGContextSetShouldSmoothFonts (context, true);
  226568. CGContextSetShouldAntialias (context, true);
  226569. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226570. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226571. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226572. gradientCallbacks.version = 0;
  226573. gradientCallbacks.evaluate = gradientCallback;
  226574. gradientCallbacks.releaseInfo = 0;
  226575. setFont (Font());
  226576. }
  226577. ~CoreGraphicsContext()
  226578. {
  226579. CGContextRestoreGState (context);
  226580. CGContextRelease (context);
  226581. CGColorSpaceRelease (rgbColourSpace);
  226582. CGColorSpaceRelease (greyColourSpace);
  226583. }
  226584. bool isVectorDevice() const { return false; }
  226585. void setOrigin (int x, int y)
  226586. {
  226587. CGContextTranslateCTM (context, x, -y);
  226588. if (lastClipRectIsValid)
  226589. lastClipRect.translate (-x, -y);
  226590. }
  226591. bool clipToRectangle (const Rectangle<int>& r)
  226592. {
  226593. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226594. if (lastClipRectIsValid)
  226595. {
  226596. // This is actually incorrect, because the actual clip region may be complex, and
  226597. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226598. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226599. // when calculating the resultant clip bounds, and makes the same mistake!
  226600. lastClipRect = lastClipRect.getIntersection (r);
  226601. return ! lastClipRect.isEmpty();
  226602. }
  226603. return ! isClipEmpty();
  226604. }
  226605. bool clipToRectangleList (const RectangleList& clipRegion)
  226606. {
  226607. if (clipRegion.isEmpty())
  226608. {
  226609. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226610. lastClipRectIsValid = true;
  226611. lastClipRect = Rectangle<int>();
  226612. return false;
  226613. }
  226614. else
  226615. {
  226616. const int numRects = clipRegion.getNumRectangles();
  226617. HeapBlock <CGRect> rects (numRects);
  226618. for (int i = 0; i < numRects; ++i)
  226619. {
  226620. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226621. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226622. }
  226623. CGContextClipToRects (context, rects, numRects);
  226624. lastClipRectIsValid = false;
  226625. return ! isClipEmpty();
  226626. }
  226627. }
  226628. void excludeClipRectangle (const Rectangle<int>& r)
  226629. {
  226630. RectangleList remaining (getClipBounds());
  226631. remaining.subtract (r);
  226632. clipToRectangleList (remaining);
  226633. lastClipRectIsValid = false;
  226634. }
  226635. void clipToPath (const Path& path, const AffineTransform& transform)
  226636. {
  226637. createPath (path, transform);
  226638. CGContextClip (context);
  226639. lastClipRectIsValid = false;
  226640. }
  226641. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226642. {
  226643. if (! transform.isSingularity())
  226644. {
  226645. Image singleChannelImage (sourceImage);
  226646. if (sourceImage.getFormat() != Image::SingleChannel)
  226647. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226648. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226649. flip();
  226650. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226651. applyTransform (t);
  226652. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226653. CGContextClipToMask (context, r, image);
  226654. applyTransform (t.inverted());
  226655. flip();
  226656. CGImageRelease (image);
  226657. lastClipRectIsValid = false;
  226658. }
  226659. }
  226660. bool clipRegionIntersects (const Rectangle<int>& r)
  226661. {
  226662. return getClipBounds().intersects (r);
  226663. }
  226664. const Rectangle<int> getClipBounds() const
  226665. {
  226666. if (! lastClipRectIsValid)
  226667. {
  226668. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226669. lastClipRectIsValid = true;
  226670. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226671. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226672. roundToInt (bounds.size.width),
  226673. roundToInt (bounds.size.height));
  226674. }
  226675. return lastClipRect;
  226676. }
  226677. bool isClipEmpty() const
  226678. {
  226679. return getClipBounds().isEmpty();
  226680. }
  226681. void saveState()
  226682. {
  226683. CGContextSaveGState (context);
  226684. stateStack.add (new SavedState (*state));
  226685. }
  226686. void restoreState()
  226687. {
  226688. CGContextRestoreGState (context);
  226689. SavedState* const top = stateStack.getLast();
  226690. if (top != 0)
  226691. {
  226692. state = top;
  226693. stateStack.removeLast (1, false);
  226694. lastClipRectIsValid = false;
  226695. }
  226696. else
  226697. {
  226698. jassertfalse; // trying to pop with an empty stack!
  226699. }
  226700. }
  226701. void setFill (const FillType& fillType)
  226702. {
  226703. state->fillType = fillType;
  226704. if (fillType.isColour())
  226705. {
  226706. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226707. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226708. CGContextSetAlpha (context, 1.0f);
  226709. }
  226710. }
  226711. void setOpacity (float newOpacity)
  226712. {
  226713. state->fillType.setOpacity (newOpacity);
  226714. setFill (state->fillType);
  226715. }
  226716. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226717. {
  226718. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226719. ? kCGInterpolationLow
  226720. : kCGInterpolationHigh);
  226721. }
  226722. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226723. {
  226724. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226725. }
  226726. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226727. {
  226728. if (replaceExistingContents)
  226729. {
  226730. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226731. CGContextClearRect (context, cgRect);
  226732. #else
  226733. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226734. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226735. CGContextClearRect (context, cgRect);
  226736. else
  226737. #endif
  226738. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226739. #endif
  226740. fillCGRect (cgRect, false);
  226741. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226742. }
  226743. else
  226744. {
  226745. if (state->fillType.isColour())
  226746. {
  226747. CGContextFillRect (context, cgRect);
  226748. }
  226749. else if (state->fillType.isGradient())
  226750. {
  226751. CGContextSaveGState (context);
  226752. CGContextClipToRect (context, cgRect);
  226753. drawGradient();
  226754. CGContextRestoreGState (context);
  226755. }
  226756. else
  226757. {
  226758. CGContextSaveGState (context);
  226759. CGContextClipToRect (context, cgRect);
  226760. drawImage (state->fillType.image, state->fillType.transform, true);
  226761. CGContextRestoreGState (context);
  226762. }
  226763. }
  226764. }
  226765. void fillPath (const Path& path, const AffineTransform& transform)
  226766. {
  226767. CGContextSaveGState (context);
  226768. if (state->fillType.isColour())
  226769. {
  226770. flip();
  226771. applyTransform (transform);
  226772. createPath (path);
  226773. if (path.isUsingNonZeroWinding())
  226774. CGContextFillPath (context);
  226775. else
  226776. CGContextEOFillPath (context);
  226777. }
  226778. else
  226779. {
  226780. createPath (path, transform);
  226781. if (path.isUsingNonZeroWinding())
  226782. CGContextClip (context);
  226783. else
  226784. CGContextEOClip (context);
  226785. if (state->fillType.isGradient())
  226786. drawGradient();
  226787. else
  226788. drawImage (state->fillType.image, state->fillType.transform, true);
  226789. }
  226790. CGContextRestoreGState (context);
  226791. }
  226792. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226793. {
  226794. const int iw = sourceImage.getWidth();
  226795. const int ih = sourceImage.getHeight();
  226796. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226797. CGContextSaveGState (context);
  226798. CGContextSetAlpha (context, state->fillType.getOpacity());
  226799. flip();
  226800. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226801. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226802. if (fillEntireClipAsTiles)
  226803. {
  226804. #if JUCE_IOS
  226805. CGContextDrawTiledImage (context, imageRect, image);
  226806. #else
  226807. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226808. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226809. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226810. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226811. CGContextDrawTiledImage (context, imageRect, image);
  226812. else
  226813. #endif
  226814. {
  226815. // Fallback to manually doing a tiled fill on 10.4
  226816. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226817. int x = 0, y = 0;
  226818. while (x > clip.origin.x) x -= iw;
  226819. while (y > clip.origin.y) y -= ih;
  226820. const int right = (int) (clip.origin.x + clip.size.width);
  226821. const int bottom = (int) (clip.origin.y + clip.size.height);
  226822. while (y < bottom)
  226823. {
  226824. for (int x2 = x; x2 < right; x2 += iw)
  226825. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226826. y += ih;
  226827. }
  226828. }
  226829. #endif
  226830. }
  226831. else
  226832. {
  226833. CGContextDrawImage (context, imageRect, image);
  226834. }
  226835. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226836. CGContextRestoreGState (context);
  226837. }
  226838. void drawLine (const Line<float>& line)
  226839. {
  226840. if (state->fillType.isColour())
  226841. {
  226842. CGContextSetLineCap (context, kCGLineCapSquare);
  226843. CGContextSetLineWidth (context, 1.0f);
  226844. CGContextSetRGBStrokeColor (context,
  226845. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226846. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226847. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226848. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226849. CGContextStrokeLineSegments (context, cgLine, 1);
  226850. }
  226851. else
  226852. {
  226853. Path p;
  226854. p.addLineSegment (line, 1.0f);
  226855. fillPath (p, AffineTransform::identity);
  226856. }
  226857. }
  226858. void drawVerticalLine (const int x, float top, float bottom)
  226859. {
  226860. if (state->fillType.isColour())
  226861. {
  226862. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226863. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226864. #else
  226865. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226866. // the x co-ord slightly to trick it..
  226867. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226868. #endif
  226869. }
  226870. else
  226871. {
  226872. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226873. }
  226874. }
  226875. void drawHorizontalLine (const int y, float left, float right)
  226876. {
  226877. if (state->fillType.isColour())
  226878. {
  226879. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226880. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226881. #else
  226882. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226883. // the x co-ord slightly to trick it..
  226884. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226885. #endif
  226886. }
  226887. else
  226888. {
  226889. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226890. }
  226891. }
  226892. void setFont (const Font& newFont)
  226893. {
  226894. if (state->font != newFont)
  226895. {
  226896. state->fontRef = 0;
  226897. state->font = newFont;
  226898. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226899. if (mf != 0)
  226900. {
  226901. state->fontRef = mf->fontRef;
  226902. CGContextSetFont (context, state->fontRef);
  226903. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226904. state->fontTransform = mf->renderingTransform;
  226905. state->fontTransform.a *= state->font.getHorizontalScale();
  226906. CGContextSetTextMatrix (context, state->fontTransform);
  226907. }
  226908. }
  226909. }
  226910. const Font getFont()
  226911. {
  226912. return state->font;
  226913. }
  226914. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226915. {
  226916. if (state->fontRef != 0 && state->fillType.isColour())
  226917. {
  226918. if (transform.isOnlyTranslation())
  226919. {
  226920. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226921. CGGlyph g = glyphNumber;
  226922. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226923. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226924. }
  226925. else
  226926. {
  226927. CGContextSaveGState (context);
  226928. flip();
  226929. applyTransform (transform);
  226930. CGAffineTransform t = state->fontTransform;
  226931. t.d = -t.d;
  226932. CGContextSetTextMatrix (context, t);
  226933. CGGlyph g = glyphNumber;
  226934. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226935. CGContextRestoreGState (context);
  226936. }
  226937. }
  226938. else
  226939. {
  226940. Path p;
  226941. Font& f = state->font;
  226942. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226943. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226944. .followedBy (transform));
  226945. }
  226946. }
  226947. private:
  226948. CGContextRef context;
  226949. const CGFloat flipHeight;
  226950. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226951. CGFunctionCallbacks gradientCallbacks;
  226952. mutable Rectangle<int> lastClipRect;
  226953. mutable bool lastClipRectIsValid;
  226954. struct SavedState
  226955. {
  226956. SavedState()
  226957. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226958. {
  226959. }
  226960. SavedState (const SavedState& other)
  226961. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226962. fontTransform (other.fontTransform)
  226963. {
  226964. }
  226965. ~SavedState()
  226966. {
  226967. }
  226968. FillType fillType;
  226969. Font font;
  226970. CGFontRef fontRef;
  226971. CGAffineTransform fontTransform;
  226972. };
  226973. ScopedPointer <SavedState> state;
  226974. OwnedArray <SavedState> stateStack;
  226975. HeapBlock <PixelARGB> gradientLookupTable;
  226976. int numGradientLookupEntries;
  226977. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226978. {
  226979. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226980. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226981. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226982. colour.unpremultiply();
  226983. outData[0] = colour.getRed() / 255.0f;
  226984. outData[1] = colour.getGreen() / 255.0f;
  226985. outData[2] = colour.getBlue() / 255.0f;
  226986. outData[3] = colour.getAlpha() / 255.0f;
  226987. }
  226988. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226989. {
  226990. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  226991. --numGradientLookupEntries;
  226992. CGShadingRef result = 0;
  226993. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226994. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226995. if (gradient.isRadial)
  226996. {
  226997. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226998. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226999. function, true, true);
  227000. }
  227001. else
  227002. {
  227003. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227004. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227005. function, true, true);
  227006. }
  227007. CGFunctionRelease (function);
  227008. return result;
  227009. }
  227010. void drawGradient()
  227011. {
  227012. flip();
  227013. applyTransform (state->fillType.transform);
  227014. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227015. // you draw a gradient with high quality interp enabled).
  227016. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227017. CGContextSetAlpha (context, state->fillType.getOpacity());
  227018. CGContextDrawShading (context, shading);
  227019. CGShadingRelease (shading);
  227020. }
  227021. void createPath (const Path& path) const
  227022. {
  227023. CGContextBeginPath (context);
  227024. Path::Iterator i (path);
  227025. while (i.next())
  227026. {
  227027. switch (i.elementType)
  227028. {
  227029. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227030. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227031. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227032. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227033. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227034. default: jassertfalse; break;
  227035. }
  227036. }
  227037. }
  227038. void createPath (const Path& path, const AffineTransform& transform) const
  227039. {
  227040. CGContextBeginPath (context);
  227041. Path::Iterator i (path);
  227042. while (i.next())
  227043. {
  227044. switch (i.elementType)
  227045. {
  227046. case Path::Iterator::startNewSubPath:
  227047. transform.transformPoint (i.x1, i.y1);
  227048. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227049. break;
  227050. case Path::Iterator::lineTo:
  227051. transform.transformPoint (i.x1, i.y1);
  227052. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227053. break;
  227054. case Path::Iterator::quadraticTo:
  227055. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227056. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227057. break;
  227058. case Path::Iterator::cubicTo:
  227059. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227060. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227061. break;
  227062. case Path::Iterator::closePath:
  227063. CGContextClosePath (context); break;
  227064. default:
  227065. jassertfalse;
  227066. break;
  227067. }
  227068. }
  227069. }
  227070. void flip() const
  227071. {
  227072. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227073. }
  227074. void applyTransform (const AffineTransform& transform) const
  227075. {
  227076. CGAffineTransform t;
  227077. t.a = transform.mat00;
  227078. t.b = transform.mat10;
  227079. t.c = transform.mat01;
  227080. t.d = transform.mat11;
  227081. t.tx = transform.mat02;
  227082. t.ty = transform.mat12;
  227083. CGContextConcatCTM (context, t);
  227084. }
  227085. CoreGraphicsContext (const CoreGraphicsContext&);
  227086. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227087. };
  227088. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227089. {
  227090. return new CoreGraphicsContext (context, height);
  227091. }
  227092. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227093. const Image juce_loadWithCoreImage (InputStream& input)
  227094. {
  227095. MemoryBlock data;
  227096. input.readIntoMemoryBlock (data, -1);
  227097. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227098. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227099. CGDataProviderRelease (provider);
  227100. if (imageSource != 0)
  227101. {
  227102. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227103. CFRelease (imageSource);
  227104. if (loadedImage != 0)
  227105. {
  227106. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227107. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227108. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227109. hasAlphaChan, Image::NativeImage);
  227110. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227111. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227112. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227113. CGContextFlush (cgImage->context);
  227114. CFRelease (loadedImage);
  227115. return image;
  227116. }
  227117. }
  227118. return Image::null;
  227119. }
  227120. #endif
  227121. #endif
  227122. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227123. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227124. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227125. // compiled on its own).
  227126. #if JUCE_INCLUDED_FILE
  227127. class UIViewComponentPeer;
  227128. END_JUCE_NAMESPACE
  227129. #define JuceUIView MakeObjCClassName(JuceUIView)
  227130. @interface JuceUIView : UIView <UITextViewDelegate>
  227131. {
  227132. @public
  227133. UIViewComponentPeer* owner;
  227134. UITextView* hiddenTextView;
  227135. }
  227136. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227137. - (void) dealloc;
  227138. - (void) drawRect: (CGRect) r;
  227139. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227140. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227141. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227142. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227143. - (BOOL) becomeFirstResponder;
  227144. - (BOOL) resignFirstResponder;
  227145. - (BOOL) canBecomeFirstResponder;
  227146. - (void) asyncRepaint: (id) rect;
  227147. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227148. @end
  227149. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227150. @interface JuceUIWindow : UIWindow
  227151. {
  227152. @private
  227153. UIViewComponentPeer* owner;
  227154. bool isZooming;
  227155. }
  227156. - (void) setOwner: (UIViewComponentPeer*) owner;
  227157. - (void) becomeKeyWindow;
  227158. @end
  227159. BEGIN_JUCE_NAMESPACE
  227160. class UIViewComponentPeer : public ComponentPeer,
  227161. public FocusChangeListener
  227162. {
  227163. public:
  227164. UIViewComponentPeer (Component* const component,
  227165. const int windowStyleFlags,
  227166. UIView* viewToAttachTo);
  227167. ~UIViewComponentPeer();
  227168. void* getNativeHandle() const;
  227169. void setVisible (bool shouldBeVisible);
  227170. void setTitle (const String& title);
  227171. void setPosition (int x, int y);
  227172. void setSize (int w, int h);
  227173. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227174. const Rectangle<int> getBounds() const;
  227175. const Rectangle<int> getBounds (const bool global) const;
  227176. const Point<int> getScreenPosition() const;
  227177. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227178. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227179. void setMinimised (bool shouldBeMinimised);
  227180. bool isMinimised() const;
  227181. void setFullScreen (bool shouldBeFullScreen);
  227182. bool isFullScreen() const;
  227183. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227184. const BorderSize getFrameSize() const;
  227185. bool setAlwaysOnTop (bool alwaysOnTop);
  227186. void toFront (bool makeActiveWindow);
  227187. void toBehind (ComponentPeer* other);
  227188. void setIcon (const Image& newIcon);
  227189. virtual void drawRect (CGRect r);
  227190. virtual bool canBecomeKeyWindow();
  227191. virtual bool windowShouldClose();
  227192. virtual void redirectMovedOrResized();
  227193. virtual CGRect constrainRect (CGRect r);
  227194. virtual void viewFocusGain();
  227195. virtual void viewFocusLoss();
  227196. bool isFocused() const;
  227197. void grabFocus();
  227198. void textInputRequired (const Point<int>& position);
  227199. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227200. void updateHiddenTextContent (TextInputTarget* target);
  227201. void globalFocusChanged (Component*);
  227202. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227203. void repaint (const Rectangle<int>& area);
  227204. void performAnyPendingRepaintsNow();
  227205. juce_UseDebuggingNewOperator
  227206. UIWindow* window;
  227207. JuceUIView* view;
  227208. bool isSharedWindow, fullScreen, insideDrawRect;
  227209. static ModifierKeys currentModifiers;
  227210. static int64 getMouseTime (UIEvent* e)
  227211. {
  227212. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227213. + (int64) ([e timestamp] * 1000.0);
  227214. }
  227215. Array <UITouch*> currentTouches;
  227216. };
  227217. END_JUCE_NAMESPACE
  227218. @implementation JuceUIView
  227219. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227220. withFrame: (CGRect) frame
  227221. {
  227222. [super initWithFrame: frame];
  227223. owner = owner_;
  227224. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227225. [self addSubview: hiddenTextView];
  227226. hiddenTextView.delegate = self;
  227227. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227228. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227229. return self;
  227230. }
  227231. - (void) dealloc
  227232. {
  227233. [hiddenTextView removeFromSuperview];
  227234. [hiddenTextView release];
  227235. [super dealloc];
  227236. }
  227237. - (void) drawRect: (CGRect) r
  227238. {
  227239. if (owner != 0)
  227240. owner->drawRect (r);
  227241. }
  227242. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227243. {
  227244. return false;
  227245. }
  227246. ModifierKeys UIViewComponentPeer::currentModifiers;
  227247. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227248. {
  227249. return UIViewComponentPeer::currentModifiers;
  227250. }
  227251. void ModifierKeys::updateCurrentModifiers() throw()
  227252. {
  227253. currentModifiers = UIViewComponentPeer::currentModifiers;
  227254. }
  227255. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227256. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227257. {
  227258. if (owner != 0)
  227259. owner->handleTouches (event, true, false, false);
  227260. }
  227261. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227262. {
  227263. if (owner != 0)
  227264. owner->handleTouches (event, false, false, false);
  227265. }
  227266. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227267. {
  227268. if (owner != 0)
  227269. owner->handleTouches (event, false, true, false);
  227270. }
  227271. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227272. {
  227273. if (owner != 0)
  227274. owner->handleTouches (event, false, true, true);
  227275. [self touchesEnded: touches withEvent: event];
  227276. }
  227277. - (BOOL) becomeFirstResponder
  227278. {
  227279. if (owner != 0)
  227280. owner->viewFocusGain();
  227281. return true;
  227282. }
  227283. - (BOOL) resignFirstResponder
  227284. {
  227285. if (owner != 0)
  227286. owner->viewFocusLoss();
  227287. return true;
  227288. }
  227289. - (BOOL) canBecomeFirstResponder
  227290. {
  227291. return owner != 0 && owner->canBecomeKeyWindow();
  227292. }
  227293. - (void) asyncRepaint: (id) rect
  227294. {
  227295. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227296. [self setNeedsDisplayInRect: *r];
  227297. }
  227298. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227299. {
  227300. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227301. nsStringToJuce (text));
  227302. }
  227303. @end
  227304. @implementation JuceUIWindow
  227305. - (void) setOwner: (UIViewComponentPeer*) owner_
  227306. {
  227307. owner = owner_;
  227308. isZooming = false;
  227309. }
  227310. - (void) becomeKeyWindow
  227311. {
  227312. [super becomeKeyWindow];
  227313. if (owner != 0)
  227314. owner->grabFocus();
  227315. }
  227316. @end
  227317. BEGIN_JUCE_NAMESPACE
  227318. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227319. const int windowStyleFlags,
  227320. UIView* viewToAttachTo)
  227321. : ComponentPeer (component, windowStyleFlags),
  227322. window (0),
  227323. view (0),
  227324. isSharedWindow (viewToAttachTo != 0),
  227325. fullScreen (false),
  227326. insideDrawRect (false)
  227327. {
  227328. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227329. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227330. if (isSharedWindow)
  227331. {
  227332. window = [viewToAttachTo window];
  227333. [viewToAttachTo addSubview: view];
  227334. setVisible (component->isVisible());
  227335. }
  227336. else
  227337. {
  227338. r.origin.x = (float) component->getX();
  227339. r.origin.y = (float) component->getY();
  227340. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227341. window = [[JuceUIWindow alloc] init];
  227342. window.frame = r;
  227343. window.opaque = component->isOpaque();
  227344. view.opaque = component->isOpaque();
  227345. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227346. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227347. [((JuceUIWindow*) window) setOwner: this];
  227348. if (component->isAlwaysOnTop())
  227349. window.windowLevel = UIWindowLevelAlert;
  227350. [window addSubview: view];
  227351. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227352. view.hidden = ! component->isVisible();
  227353. window.hidden = ! component->isVisible();
  227354. view.multipleTouchEnabled = YES;
  227355. }
  227356. setTitle (component->getName());
  227357. Desktop::getInstance().addFocusChangeListener (this);
  227358. }
  227359. UIViewComponentPeer::~UIViewComponentPeer()
  227360. {
  227361. Desktop::getInstance().removeFocusChangeListener (this);
  227362. view->owner = 0;
  227363. [view removeFromSuperview];
  227364. [view release];
  227365. if (! isSharedWindow)
  227366. {
  227367. [((JuceUIWindow*) window) setOwner: 0];
  227368. [window release];
  227369. }
  227370. }
  227371. void* UIViewComponentPeer::getNativeHandle() const
  227372. {
  227373. return view;
  227374. }
  227375. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227376. {
  227377. view.hidden = ! shouldBeVisible;
  227378. if (! isSharedWindow)
  227379. window.hidden = ! shouldBeVisible;
  227380. }
  227381. void UIViewComponentPeer::setTitle (const String& title)
  227382. {
  227383. // xxx is this possible?
  227384. }
  227385. void UIViewComponentPeer::setPosition (int x, int y)
  227386. {
  227387. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227388. }
  227389. void UIViewComponentPeer::setSize (int w, int h)
  227390. {
  227391. setBounds (component->getX(), component->getY(), w, h, false);
  227392. }
  227393. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227394. {
  227395. fullScreen = isNowFullScreen;
  227396. w = jmax (0, w);
  227397. h = jmax (0, h);
  227398. CGRect r;
  227399. r.origin.x = (float) x;
  227400. r.origin.y = (float) y;
  227401. r.size.width = (float) w;
  227402. r.size.height = (float) h;
  227403. if (isSharedWindow)
  227404. {
  227405. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227406. if ([view frame].size.width != r.size.width
  227407. || [view frame].size.height != r.size.height)
  227408. [view setNeedsDisplay];
  227409. view.frame = r;
  227410. }
  227411. else
  227412. {
  227413. window.frame = r;
  227414. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227415. }
  227416. }
  227417. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227418. {
  227419. CGRect r = [view frame];
  227420. if (global && [view window] != 0)
  227421. {
  227422. r = [view convertRect: r toView: nil];
  227423. CGRect wr = [[view window] frame];
  227424. r.origin.x += wr.origin.x;
  227425. r.origin.y += wr.origin.y;
  227426. }
  227427. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227428. (int) r.size.width, (int) r.size.height);
  227429. }
  227430. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227431. {
  227432. return getBounds (! isSharedWindow);
  227433. }
  227434. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227435. {
  227436. return getBounds (true).getPosition();
  227437. }
  227438. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227439. {
  227440. return relativePosition + getScreenPosition();
  227441. }
  227442. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227443. {
  227444. return screenPosition - getScreenPosition();
  227445. }
  227446. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227447. {
  227448. if (constrainer != 0)
  227449. {
  227450. CGRect current = [window frame];
  227451. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227452. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227453. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227454. (int) r.size.width, (int) r.size.height);
  227455. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227456. (int) current.size.width, (int) current.size.height);
  227457. constrainer->checkBounds (pos, original,
  227458. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227459. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227460. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227461. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227462. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227463. r.origin.x = pos.getX();
  227464. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227465. r.size.width = pos.getWidth();
  227466. r.size.height = pos.getHeight();
  227467. }
  227468. return r;
  227469. }
  227470. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227471. {
  227472. // xxx
  227473. }
  227474. bool UIViewComponentPeer::isMinimised() const
  227475. {
  227476. return false;
  227477. }
  227478. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227479. {
  227480. if (! isSharedWindow)
  227481. {
  227482. Rectangle<int> r (lastNonFullscreenBounds);
  227483. setMinimised (false);
  227484. if (fullScreen != shouldBeFullScreen)
  227485. {
  227486. if (shouldBeFullScreen)
  227487. r = Desktop::getInstance().getMainMonitorArea();
  227488. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227489. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227490. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227491. }
  227492. }
  227493. }
  227494. bool UIViewComponentPeer::isFullScreen() const
  227495. {
  227496. return fullScreen;
  227497. }
  227498. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227499. {
  227500. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227501. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227502. return false;
  227503. CGPoint p;
  227504. p.x = (float) position.getX();
  227505. p.y = (float) position.getY();
  227506. UIView* v = [view hitTest: p withEvent: nil];
  227507. if (trueIfInAChildWindow)
  227508. return v != nil;
  227509. return v == view;
  227510. }
  227511. const BorderSize UIViewComponentPeer::getFrameSize() const
  227512. {
  227513. BorderSize b;
  227514. if (! isSharedWindow)
  227515. {
  227516. CGRect v = [view convertRect: [view frame] toView: nil];
  227517. CGRect w = [window frame];
  227518. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227519. b.setBottom ((int) v.origin.y);
  227520. b.setLeft ((int) v.origin.x);
  227521. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227522. }
  227523. return b;
  227524. }
  227525. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227526. {
  227527. if (! isSharedWindow)
  227528. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227529. return true;
  227530. }
  227531. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227532. {
  227533. if (isSharedWindow)
  227534. [[view superview] bringSubviewToFront: view];
  227535. if (window != 0 && component->isVisible())
  227536. [window makeKeyAndVisible];
  227537. }
  227538. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227539. {
  227540. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227541. jassert (otherPeer != 0); // wrong type of window?
  227542. if (otherPeer != 0)
  227543. {
  227544. if (isSharedWindow)
  227545. {
  227546. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227547. }
  227548. else
  227549. {
  227550. jassertfalse; // don't know how to do this
  227551. }
  227552. }
  227553. }
  227554. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227555. {
  227556. // to do..
  227557. }
  227558. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227559. {
  227560. NSArray* touches = [[event touchesForView: view] allObjects];
  227561. for (unsigned int i = 0; i < [touches count]; ++i)
  227562. {
  227563. UITouch* touch = [touches objectAtIndex: i];
  227564. CGPoint p = [touch locationInView: view];
  227565. const Point<int> pos ((int) p.x, (int) p.y);
  227566. juce_lastMousePos = pos + getScreenPosition();
  227567. const int64 time = getMouseTime (event);
  227568. int touchIndex = currentTouches.indexOf (touch);
  227569. if (touchIndex < 0)
  227570. {
  227571. touchIndex = currentTouches.size();
  227572. currentTouches.add (touch);
  227573. }
  227574. if (isDown)
  227575. {
  227576. currentModifiers = currentModifiers.withoutMouseButtons();
  227577. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227578. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227579. }
  227580. else if (isUp)
  227581. {
  227582. currentModifiers = currentModifiers.withoutMouseButtons();
  227583. currentTouches.remove (touchIndex);
  227584. }
  227585. if (isCancel)
  227586. currentTouches.clear();
  227587. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227588. }
  227589. }
  227590. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227591. void UIViewComponentPeer::viewFocusGain()
  227592. {
  227593. if (currentlyFocusedPeer != this)
  227594. {
  227595. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227596. currentlyFocusedPeer->handleFocusLoss();
  227597. currentlyFocusedPeer = this;
  227598. handleFocusGain();
  227599. }
  227600. }
  227601. void UIViewComponentPeer::viewFocusLoss()
  227602. {
  227603. if (currentlyFocusedPeer == this)
  227604. {
  227605. currentlyFocusedPeer = 0;
  227606. handleFocusLoss();
  227607. }
  227608. }
  227609. void juce_HandleProcessFocusChange()
  227610. {
  227611. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227612. {
  227613. if (Process::isForegroundProcess())
  227614. {
  227615. currentlyFocusedPeer->handleFocusGain();
  227616. ComponentPeer::bringModalComponentToFront();
  227617. }
  227618. else
  227619. {
  227620. currentlyFocusedPeer->handleFocusLoss();
  227621. // turn kiosk mode off if we lose focus..
  227622. Desktop::getInstance().setKioskModeComponent (0);
  227623. }
  227624. }
  227625. }
  227626. bool UIViewComponentPeer::isFocused() const
  227627. {
  227628. return isSharedWindow ? this == currentlyFocusedPeer
  227629. : (window != 0 && [window isKeyWindow]);
  227630. }
  227631. void UIViewComponentPeer::grabFocus()
  227632. {
  227633. if (window != 0)
  227634. {
  227635. [window makeKeyWindow];
  227636. viewFocusGain();
  227637. }
  227638. }
  227639. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227640. {
  227641. }
  227642. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227643. {
  227644. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227645. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227646. }
  227647. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227648. {
  227649. TextInputTarget* const target = findCurrentTextInputTarget();
  227650. if (target != 0)
  227651. {
  227652. const Range<int> currentSelection (target->getHighlightedRegion());
  227653. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227654. if (currentSelection.isEmpty())
  227655. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227656. target->insertTextAtCaret (text);
  227657. updateHiddenTextContent (target);
  227658. }
  227659. return NO;
  227660. }
  227661. void UIViewComponentPeer::globalFocusChanged (Component*)
  227662. {
  227663. TextInputTarget* const target = findCurrentTextInputTarget();
  227664. if (target != 0)
  227665. {
  227666. Component* comp = dynamic_cast<Component*> (target);
  227667. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227668. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227669. updateHiddenTextContent (target);
  227670. [view->hiddenTextView becomeFirstResponder];
  227671. }
  227672. else
  227673. {
  227674. [view->hiddenTextView resignFirstResponder];
  227675. }
  227676. }
  227677. void UIViewComponentPeer::drawRect (CGRect r)
  227678. {
  227679. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227680. return;
  227681. CGContextRef cg = UIGraphicsGetCurrentContext();
  227682. if (! component->isOpaque())
  227683. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227684. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227685. CoreGraphicsContext g (cg, view.bounds.size.height);
  227686. insideDrawRect = true;
  227687. handlePaint (g);
  227688. insideDrawRect = false;
  227689. }
  227690. bool UIViewComponentPeer::canBecomeKeyWindow()
  227691. {
  227692. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227693. }
  227694. bool UIViewComponentPeer::windowShouldClose()
  227695. {
  227696. if (! isValidPeer (this))
  227697. return YES;
  227698. handleUserClosingWindow();
  227699. return NO;
  227700. }
  227701. void UIViewComponentPeer::redirectMovedOrResized()
  227702. {
  227703. handleMovedOrResized();
  227704. }
  227705. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227706. {
  227707. }
  227708. class AsyncRepaintMessage : public CallbackMessage
  227709. {
  227710. public:
  227711. UIViewComponentPeer* const peer;
  227712. const Rectangle<int> rect;
  227713. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227714. : peer (peer_), rect (rect_)
  227715. {
  227716. }
  227717. void messageCallback()
  227718. {
  227719. if (ComponentPeer::isValidPeer (peer))
  227720. peer->repaint (rect);
  227721. }
  227722. };
  227723. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227724. {
  227725. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227726. {
  227727. (new AsyncRepaintMessage (this, area))->post();
  227728. }
  227729. else
  227730. {
  227731. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  227732. (float) area.getWidth(), (float) area.getHeight())];
  227733. }
  227734. }
  227735. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227736. {
  227737. }
  227738. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227739. {
  227740. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227741. }
  227742. const Image juce_createIconForFile (const File& file)
  227743. {
  227744. return Image::null;
  227745. }
  227746. void Desktop::createMouseInputSources()
  227747. {
  227748. for (int i = 0; i < 10; ++i)
  227749. mouseSources.add (new MouseInputSource (i, false));
  227750. }
  227751. bool Desktop::canUseSemiTransparentWindows() throw()
  227752. {
  227753. return true;
  227754. }
  227755. const Point<int> Desktop::getMousePosition()
  227756. {
  227757. return juce_lastMousePos;
  227758. }
  227759. void Desktop::setMousePosition (const Point<int>&)
  227760. {
  227761. }
  227762. const int KeyPress::spaceKey = ' ';
  227763. const int KeyPress::returnKey = 0x0d;
  227764. const int KeyPress::escapeKey = 0x1b;
  227765. const int KeyPress::backspaceKey = 0x7f;
  227766. const int KeyPress::leftKey = 0x1000;
  227767. const int KeyPress::rightKey = 0x1001;
  227768. const int KeyPress::upKey = 0x1002;
  227769. const int KeyPress::downKey = 0x1003;
  227770. const int KeyPress::pageUpKey = 0x1004;
  227771. const int KeyPress::pageDownKey = 0x1005;
  227772. const int KeyPress::endKey = 0x1006;
  227773. const int KeyPress::homeKey = 0x1007;
  227774. const int KeyPress::deleteKey = 0x1008;
  227775. const int KeyPress::insertKey = -1;
  227776. const int KeyPress::tabKey = 9;
  227777. const int KeyPress::F1Key = 0x2001;
  227778. const int KeyPress::F2Key = 0x2002;
  227779. const int KeyPress::F3Key = 0x2003;
  227780. const int KeyPress::F4Key = 0x2004;
  227781. const int KeyPress::F5Key = 0x2005;
  227782. const int KeyPress::F6Key = 0x2006;
  227783. const int KeyPress::F7Key = 0x2007;
  227784. const int KeyPress::F8Key = 0x2008;
  227785. const int KeyPress::F9Key = 0x2009;
  227786. const int KeyPress::F10Key = 0x200a;
  227787. const int KeyPress::F11Key = 0x200b;
  227788. const int KeyPress::F12Key = 0x200c;
  227789. const int KeyPress::F13Key = 0x200d;
  227790. const int KeyPress::F14Key = 0x200e;
  227791. const int KeyPress::F15Key = 0x200f;
  227792. const int KeyPress::F16Key = 0x2010;
  227793. const int KeyPress::numberPad0 = 0x30020;
  227794. const int KeyPress::numberPad1 = 0x30021;
  227795. const int KeyPress::numberPad2 = 0x30022;
  227796. const int KeyPress::numberPad3 = 0x30023;
  227797. const int KeyPress::numberPad4 = 0x30024;
  227798. const int KeyPress::numberPad5 = 0x30025;
  227799. const int KeyPress::numberPad6 = 0x30026;
  227800. const int KeyPress::numberPad7 = 0x30027;
  227801. const int KeyPress::numberPad8 = 0x30028;
  227802. const int KeyPress::numberPad9 = 0x30029;
  227803. const int KeyPress::numberPadAdd = 0x3002a;
  227804. const int KeyPress::numberPadSubtract = 0x3002b;
  227805. const int KeyPress::numberPadMultiply = 0x3002c;
  227806. const int KeyPress::numberPadDivide = 0x3002d;
  227807. const int KeyPress::numberPadSeparator = 0x3002e;
  227808. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227809. const int KeyPress::numberPadEquals = 0x30030;
  227810. const int KeyPress::numberPadDelete = 0x30031;
  227811. const int KeyPress::playKey = 0x30000;
  227812. const int KeyPress::stopKey = 0x30001;
  227813. const int KeyPress::fastForwardKey = 0x30002;
  227814. const int KeyPress::rewindKey = 0x30003;
  227815. #endif
  227816. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227817. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227818. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227819. // compiled on its own).
  227820. #if JUCE_INCLUDED_FILE
  227821. struct CallbackMessagePayload
  227822. {
  227823. MessageCallbackFunction* function;
  227824. void* parameter;
  227825. void* volatile result;
  227826. bool volatile hasBeenExecuted;
  227827. };
  227828. END_JUCE_NAMESPACE
  227829. @interface JuceCustomMessageHandler : NSObject
  227830. {
  227831. }
  227832. - (void) performCallback: (id) info;
  227833. @end
  227834. @implementation JuceCustomMessageHandler
  227835. - (void) performCallback: (id) info
  227836. {
  227837. if ([info isKindOfClass: [NSData class]])
  227838. {
  227839. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227840. if (pl != 0)
  227841. {
  227842. pl->result = (*pl->function) (pl->parameter);
  227843. pl->hasBeenExecuted = true;
  227844. }
  227845. }
  227846. else
  227847. {
  227848. jassertfalse; // should never get here!
  227849. }
  227850. }
  227851. @end
  227852. BEGIN_JUCE_NAMESPACE
  227853. void MessageManager::runDispatchLoop()
  227854. {
  227855. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227856. runDispatchLoopUntil (-1);
  227857. }
  227858. void MessageManager::stopDispatchLoop()
  227859. {
  227860. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227861. exit (0); // iPhone apps get no mercy..
  227862. }
  227863. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227864. {
  227865. const ScopedAutoReleasePool pool;
  227866. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227867. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227868. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227869. while (! quitMessagePosted)
  227870. {
  227871. const ScopedAutoReleasePool pool;
  227872. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227873. beforeDate: endDate];
  227874. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227875. break;
  227876. }
  227877. return ! quitMessagePosted;
  227878. }
  227879. static CFRunLoopRef runLoop = 0;
  227880. static CFRunLoopSourceRef runLoopSource = 0;
  227881. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  227882. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  227883. static void runLoopSourceCallback (void*)
  227884. {
  227885. if (pendingMessages != 0)
  227886. {
  227887. int numDispatched = 0;
  227888. do
  227889. {
  227890. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  227891. if (nextMessage == 0)
  227892. return;
  227893. const ScopedAutoReleasePool pool;
  227894. MessageManager::getInstance()->deliverMessage (nextMessage);
  227895. } while (++numDispatched <= 4);
  227896. CFRunLoopSourceSignal (runLoopSource);
  227897. CFRunLoopWakeUp (runLoop);
  227898. }
  227899. }
  227900. void MessageManager::doPlatformSpecificInitialisation()
  227901. {
  227902. pendingMessages = new OwnedArray <Message, CriticalSection>();
  227903. runLoop = CFRunLoopGetCurrent();
  227904. CFRunLoopSourceContext sourceContext;
  227905. zerostruct (sourceContext);
  227906. sourceContext.perform = runLoopSourceCallback;
  227907. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  227908. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  227909. if (juceCustomMessageHandler == 0)
  227910. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227911. }
  227912. void MessageManager::doPlatformSpecificShutdown()
  227913. {
  227914. CFRunLoopSourceInvalidate (runLoopSource);
  227915. CFRelease (runLoopSource);
  227916. runLoopSource = 0;
  227917. deleteAndZero (pendingMessages);
  227918. if (juceCustomMessageHandler != 0)
  227919. {
  227920. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227921. [juceCustomMessageHandler release];
  227922. juceCustomMessageHandler = 0;
  227923. }
  227924. }
  227925. bool juce_postMessageToSystemQueue (Message* message)
  227926. {
  227927. if (pendingMessages != 0)
  227928. {
  227929. pendingMessages->add (message);
  227930. CFRunLoopSourceSignal (runLoopSource);
  227931. CFRunLoopWakeUp (runLoop);
  227932. }
  227933. return true;
  227934. }
  227935. void MessageManager::broadcastMessage (const String& value)
  227936. {
  227937. }
  227938. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227939. {
  227940. if (isThisTheMessageThread())
  227941. {
  227942. return (*callback) (data);
  227943. }
  227944. else
  227945. {
  227946. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227947. // deadlock because the message manager is blocked from running, so can never
  227948. // call your function..
  227949. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227950. const ScopedAutoReleasePool pool;
  227951. CallbackMessagePayload cmp;
  227952. cmp.function = callback;
  227953. cmp.parameter = data;
  227954. cmp.result = 0;
  227955. cmp.hasBeenExecuted = false;
  227956. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227957. withObject: [NSData dataWithBytesNoCopy: &cmp
  227958. length: sizeof (cmp)
  227959. freeWhenDone: NO]
  227960. waitUntilDone: YES];
  227961. return cmp.result;
  227962. }
  227963. }
  227964. #endif
  227965. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227966. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227967. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227968. // compiled on its own).
  227969. #if JUCE_INCLUDED_FILE
  227970. #if JUCE_MAC
  227971. END_JUCE_NAMESPACE
  227972. using namespace JUCE_NAMESPACE;
  227973. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227974. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227975. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227976. #else
  227977. @interface JuceFileChooserDelegate : NSObject
  227978. #endif
  227979. {
  227980. StringArray* filters;
  227981. }
  227982. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227983. - (void) dealloc;
  227984. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227985. @end
  227986. @implementation JuceFileChooserDelegate
  227987. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227988. {
  227989. [super init];
  227990. filters = filters_;
  227991. return self;
  227992. }
  227993. - (void) dealloc
  227994. {
  227995. delete filters;
  227996. [super dealloc];
  227997. }
  227998. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227999. {
  228000. (void) sender;
  228001. const File f (nsStringToJuce (filename));
  228002. for (int i = filters->size(); --i >= 0;)
  228003. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228004. return true;
  228005. return f.isDirectory();
  228006. }
  228007. @end
  228008. BEGIN_JUCE_NAMESPACE
  228009. void FileChooser::showPlatformDialog (Array<File>& results,
  228010. const String& title,
  228011. const File& currentFileOrDirectory,
  228012. const String& filter,
  228013. bool selectsDirectory,
  228014. bool selectsFiles,
  228015. bool isSaveDialogue,
  228016. bool warnAboutOverwritingExistingFiles,
  228017. bool selectMultipleFiles,
  228018. FilePreviewComponent* extraInfoComponent)
  228019. {
  228020. const ScopedAutoReleasePool pool;
  228021. StringArray* filters = new StringArray();
  228022. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228023. filters->trim();
  228024. filters->removeEmptyStrings();
  228025. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228026. [delegate autorelease];
  228027. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228028. : [NSOpenPanel openPanel];
  228029. [panel setTitle: juceStringToNS (title)];
  228030. if (! isSaveDialogue)
  228031. {
  228032. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228033. [openPanel setCanChooseDirectories: selectsDirectory];
  228034. [openPanel setCanChooseFiles: selectsFiles];
  228035. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228036. }
  228037. [panel setDelegate: delegate];
  228038. if (isSaveDialogue || selectsDirectory)
  228039. [panel setCanCreateDirectories: YES];
  228040. String directory, filename;
  228041. if (currentFileOrDirectory.isDirectory())
  228042. {
  228043. directory = currentFileOrDirectory.getFullPathName();
  228044. }
  228045. else
  228046. {
  228047. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228048. filename = currentFileOrDirectory.getFileName();
  228049. }
  228050. if ([panel runModalForDirectory: juceStringToNS (directory)
  228051. file: juceStringToNS (filename)]
  228052. == NSOKButton)
  228053. {
  228054. if (isSaveDialogue)
  228055. {
  228056. results.add (File (nsStringToJuce ([panel filename])));
  228057. }
  228058. else
  228059. {
  228060. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228061. NSArray* urls = [openPanel filenames];
  228062. for (unsigned int i = 0; i < [urls count]; ++i)
  228063. {
  228064. NSString* f = [urls objectAtIndex: i];
  228065. results.add (File (nsStringToJuce (f)));
  228066. }
  228067. }
  228068. }
  228069. [panel setDelegate: nil];
  228070. }
  228071. #else
  228072. void FileChooser::showPlatformDialog (Array<File>& results,
  228073. const String& title,
  228074. const File& currentFileOrDirectory,
  228075. const String& filter,
  228076. bool selectsDirectory,
  228077. bool selectsFiles,
  228078. bool isSaveDialogue,
  228079. bool warnAboutOverwritingExistingFiles,
  228080. bool selectMultipleFiles,
  228081. FilePreviewComponent* extraInfoComponent)
  228082. {
  228083. const ScopedAutoReleasePool pool;
  228084. jassertfalse; //xxx to do
  228085. }
  228086. #endif
  228087. #endif
  228088. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228089. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228090. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228091. // compiled on its own).
  228092. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228093. #if JUCE_MAC
  228094. END_JUCE_NAMESPACE
  228095. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228096. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228097. {
  228098. CriticalSection* contextLock;
  228099. bool needsUpdate;
  228100. }
  228101. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228102. - (bool) makeActive;
  228103. - (void) makeInactive;
  228104. - (void) reshape;
  228105. @end
  228106. @implementation ThreadSafeNSOpenGLView
  228107. - (id) initWithFrame: (NSRect) frameRect
  228108. pixelFormat: (NSOpenGLPixelFormat*) format
  228109. {
  228110. contextLock = new CriticalSection();
  228111. self = [super initWithFrame: frameRect pixelFormat: format];
  228112. if (self != nil)
  228113. [[NSNotificationCenter defaultCenter] addObserver: self
  228114. selector: @selector (_surfaceNeedsUpdate:)
  228115. name: NSViewGlobalFrameDidChangeNotification
  228116. object: self];
  228117. return self;
  228118. }
  228119. - (void) dealloc
  228120. {
  228121. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228122. delete contextLock;
  228123. [super dealloc];
  228124. }
  228125. - (bool) makeActive
  228126. {
  228127. const ScopedLock sl (*contextLock);
  228128. if ([self openGLContext] == 0)
  228129. return false;
  228130. [[self openGLContext] makeCurrentContext];
  228131. if (needsUpdate)
  228132. {
  228133. [super update];
  228134. needsUpdate = false;
  228135. }
  228136. return true;
  228137. }
  228138. - (void) makeInactive
  228139. {
  228140. const ScopedLock sl (*contextLock);
  228141. [NSOpenGLContext clearCurrentContext];
  228142. }
  228143. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228144. {
  228145. const ScopedLock sl (*contextLock);
  228146. needsUpdate = true;
  228147. }
  228148. - (void) update
  228149. {
  228150. const ScopedLock sl (*contextLock);
  228151. needsUpdate = true;
  228152. }
  228153. - (void) reshape
  228154. {
  228155. const ScopedLock sl (*contextLock);
  228156. needsUpdate = true;
  228157. }
  228158. @end
  228159. BEGIN_JUCE_NAMESPACE
  228160. class WindowedGLContext : public OpenGLContext
  228161. {
  228162. public:
  228163. WindowedGLContext (Component* const component,
  228164. const OpenGLPixelFormat& pixelFormat_,
  228165. NSOpenGLContext* sharedContext)
  228166. : renderContext (0),
  228167. pixelFormat (pixelFormat_)
  228168. {
  228169. jassert (component != 0);
  228170. NSOpenGLPixelFormatAttribute attribs [64];
  228171. int n = 0;
  228172. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228173. attribs[n++] = NSOpenGLPFAAccelerated;
  228174. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228175. attribs[n++] = NSOpenGLPFAColorSize;
  228176. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228177. pixelFormat.greenBits,
  228178. pixelFormat.blueBits);
  228179. attribs[n++] = NSOpenGLPFAAlphaSize;
  228180. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228181. attribs[n++] = NSOpenGLPFADepthSize;
  228182. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228183. attribs[n++] = NSOpenGLPFAStencilSize;
  228184. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228185. attribs[n++] = NSOpenGLPFAAccumSize;
  228186. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228187. pixelFormat.accumulationBufferGreenBits,
  228188. pixelFormat.accumulationBufferBlueBits,
  228189. pixelFormat.accumulationBufferAlphaBits);
  228190. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228191. attribs[n++] = NSOpenGLPFASampleBuffers;
  228192. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228193. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228194. attribs[n++] = NSOpenGLPFANoRecovery;
  228195. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228196. NSOpenGLPixelFormat* format
  228197. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228198. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228199. pixelFormat: format];
  228200. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228201. shareContext: sharedContext] autorelease];
  228202. const GLint swapInterval = 1;
  228203. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228204. [view setOpenGLContext: renderContext];
  228205. [format release];
  228206. viewHolder = new NSViewComponentInternal (view, component);
  228207. }
  228208. ~WindowedGLContext()
  228209. {
  228210. deleteContext();
  228211. viewHolder = 0;
  228212. }
  228213. void deleteContext()
  228214. {
  228215. makeInactive();
  228216. [renderContext clearDrawable];
  228217. [renderContext setView: nil];
  228218. [view setOpenGLContext: nil];
  228219. renderContext = nil;
  228220. }
  228221. bool makeActive() const throw()
  228222. {
  228223. jassert (renderContext != 0);
  228224. if ([renderContext view] != view)
  228225. [renderContext setView: view];
  228226. [view makeActive];
  228227. return isActive();
  228228. }
  228229. bool makeInactive() const throw()
  228230. {
  228231. [view makeInactive];
  228232. return true;
  228233. }
  228234. bool isActive() const throw()
  228235. {
  228236. return [NSOpenGLContext currentContext] == renderContext;
  228237. }
  228238. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228239. void* getRawContext() const throw() { return renderContext; }
  228240. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228241. {
  228242. }
  228243. void swapBuffers()
  228244. {
  228245. [renderContext flushBuffer];
  228246. }
  228247. bool setSwapInterval (const int numFramesPerSwap)
  228248. {
  228249. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228250. forParameter: NSOpenGLCPSwapInterval];
  228251. return true;
  228252. }
  228253. int getSwapInterval() const
  228254. {
  228255. GLint numFrames = 0;
  228256. [renderContext getValues: &numFrames
  228257. forParameter: NSOpenGLCPSwapInterval];
  228258. return numFrames;
  228259. }
  228260. void repaint()
  228261. {
  228262. // we need to invalidate the juce view that holds this gl view, to make it
  228263. // cause a repaint callback
  228264. NSView* v = (NSView*) viewHolder->view;
  228265. NSRect r = [v frame];
  228266. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228267. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228268. // repaint message, thus never causing our paint() callback, and never repainting
  228269. // the comp. So invalidating just a little bit around the edge helps..
  228270. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228271. }
  228272. void* getNativeWindowHandle() const { return viewHolder->view; }
  228273. juce_UseDebuggingNewOperator
  228274. NSOpenGLContext* renderContext;
  228275. ThreadSafeNSOpenGLView* view;
  228276. private:
  228277. OpenGLPixelFormat pixelFormat;
  228278. ScopedPointer <NSViewComponentInternal> viewHolder;
  228279. WindowedGLContext (const WindowedGLContext&);
  228280. WindowedGLContext& operator= (const WindowedGLContext&);
  228281. };
  228282. OpenGLContext* OpenGLComponent::createContext()
  228283. {
  228284. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228285. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228286. return (c->renderContext != 0) ? c.release() : 0;
  228287. }
  228288. void* OpenGLComponent::getNativeWindowHandle() const
  228289. {
  228290. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228291. : 0;
  228292. }
  228293. void juce_glViewport (const int w, const int h)
  228294. {
  228295. glViewport (0, 0, w, h);
  228296. }
  228297. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228298. OwnedArray <OpenGLPixelFormat>& results)
  228299. {
  228300. /* GLint attribs [64];
  228301. int n = 0;
  228302. attribs[n++] = AGL_RGBA;
  228303. attribs[n++] = AGL_DOUBLEBUFFER;
  228304. attribs[n++] = AGL_ACCELERATED;
  228305. attribs[n++] = AGL_NO_RECOVERY;
  228306. attribs[n++] = AGL_NONE;
  228307. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228308. while (p != 0)
  228309. {
  228310. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228311. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228312. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228313. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228314. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228315. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228316. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228317. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228318. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228319. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228320. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228321. results.add (pf);
  228322. p = aglNextPixelFormat (p);
  228323. }*/
  228324. //jassertfalse // can't see how you do this in cocoa!
  228325. }
  228326. #else
  228327. END_JUCE_NAMESPACE
  228328. @interface JuceGLView : UIView
  228329. {
  228330. }
  228331. + (Class) layerClass;
  228332. @end
  228333. @implementation JuceGLView
  228334. + (Class) layerClass
  228335. {
  228336. return [CAEAGLLayer class];
  228337. }
  228338. @end
  228339. BEGIN_JUCE_NAMESPACE
  228340. class GLESContext : public OpenGLContext
  228341. {
  228342. public:
  228343. GLESContext (UIViewComponentPeer* peer,
  228344. Component* const component_,
  228345. const OpenGLPixelFormat& pixelFormat_,
  228346. const GLESContext* const sharedContext,
  228347. NSUInteger apiType)
  228348. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228349. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228350. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228351. {
  228352. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228353. view.opaque = YES;
  228354. view.hidden = NO;
  228355. view.backgroundColor = [UIColor blackColor];
  228356. view.userInteractionEnabled = NO;
  228357. glLayer = (CAEAGLLayer*) [view layer];
  228358. [peer->view addSubview: view];
  228359. if (sharedContext != 0)
  228360. context = [[EAGLContext alloc] initWithAPI: apiType
  228361. sharegroup: [sharedContext->context sharegroup]];
  228362. else
  228363. context = [[EAGLContext alloc] initWithAPI: apiType];
  228364. createGLBuffers();
  228365. }
  228366. ~GLESContext()
  228367. {
  228368. deleteContext();
  228369. [view removeFromSuperview];
  228370. [view release];
  228371. freeGLBuffers();
  228372. }
  228373. void deleteContext()
  228374. {
  228375. makeInactive();
  228376. [context release];
  228377. context = nil;
  228378. }
  228379. bool makeActive() const throw()
  228380. {
  228381. jassert (context != 0);
  228382. [EAGLContext setCurrentContext: context];
  228383. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228384. return true;
  228385. }
  228386. void swapBuffers()
  228387. {
  228388. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228389. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228390. }
  228391. bool makeInactive() const throw()
  228392. {
  228393. return [EAGLContext setCurrentContext: nil];
  228394. }
  228395. bool isActive() const throw()
  228396. {
  228397. return [EAGLContext currentContext] == context;
  228398. }
  228399. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228400. void* getRawContext() const throw() { return glLayer; }
  228401. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228402. {
  228403. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228404. if (lastWidth != w || lastHeight != h)
  228405. {
  228406. lastWidth = w;
  228407. lastHeight = h;
  228408. freeGLBuffers();
  228409. createGLBuffers();
  228410. }
  228411. }
  228412. bool setSwapInterval (const int numFramesPerSwap)
  228413. {
  228414. numFrames = numFramesPerSwap;
  228415. return true;
  228416. }
  228417. int getSwapInterval() const
  228418. {
  228419. return numFrames;
  228420. }
  228421. void repaint()
  228422. {
  228423. }
  228424. void createGLBuffers()
  228425. {
  228426. makeActive();
  228427. glGenFramebuffersOES (1, &frameBufferHandle);
  228428. glGenRenderbuffersOES (1, &colorBufferHandle);
  228429. glGenRenderbuffersOES (1, &depthBufferHandle);
  228430. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228431. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228432. GLint width, height;
  228433. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228434. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228435. if (useDepthBuffer)
  228436. {
  228437. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228438. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228439. }
  228440. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228441. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228442. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228443. if (useDepthBuffer)
  228444. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228445. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228446. }
  228447. void freeGLBuffers()
  228448. {
  228449. if (frameBufferHandle != 0)
  228450. {
  228451. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228452. frameBufferHandle = 0;
  228453. }
  228454. if (colorBufferHandle != 0)
  228455. {
  228456. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228457. colorBufferHandle = 0;
  228458. }
  228459. if (depthBufferHandle != 0)
  228460. {
  228461. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228462. depthBufferHandle = 0;
  228463. }
  228464. }
  228465. juce_UseDebuggingNewOperator
  228466. private:
  228467. Component::SafePointer<Component> component;
  228468. OpenGLPixelFormat pixelFormat;
  228469. JuceGLView* view;
  228470. CAEAGLLayer* glLayer;
  228471. EAGLContext* context;
  228472. bool useDepthBuffer;
  228473. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228474. int numFrames;
  228475. int lastWidth, lastHeight;
  228476. GLESContext (const GLESContext&);
  228477. GLESContext& operator= (const GLESContext&);
  228478. };
  228479. OpenGLContext* OpenGLComponent::createContext()
  228480. {
  228481. ScopedAutoReleasePool pool;
  228482. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228483. if (peer != 0)
  228484. return new GLESContext (peer, this, preferredPixelFormat,
  228485. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228486. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228487. return 0;
  228488. }
  228489. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228490. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228491. {
  228492. }
  228493. void juce_glViewport (const int w, const int h)
  228494. {
  228495. glViewport (0, 0, w, h);
  228496. }
  228497. #endif
  228498. #endif
  228499. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228500. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228501. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228502. // compiled on its own).
  228503. #if JUCE_INCLUDED_FILE
  228504. #if JUCE_MAC
  228505. namespace MouseCursorHelpers
  228506. {
  228507. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228508. {
  228509. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228510. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228511. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228512. [im release];
  228513. return c;
  228514. }
  228515. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228516. {
  228517. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228518. BufferedInputStream buf (&fileStream, 4096, false);
  228519. PNGImageFormat pngFormat;
  228520. Image im (pngFormat.decodeImage (buf));
  228521. if (im.isValid())
  228522. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228523. jassertfalse;
  228524. return 0;
  228525. }
  228526. }
  228527. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228528. {
  228529. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228530. }
  228531. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228532. {
  228533. const ScopedAutoReleasePool pool;
  228534. NSCursor* c = 0;
  228535. switch (type)
  228536. {
  228537. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228538. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228539. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228540. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228541. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228542. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228543. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228544. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228545. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228546. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228547. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228548. case UpDownResizeCursor:
  228549. case TopEdgeResizeCursor:
  228550. case BottomEdgeResizeCursor:
  228551. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228552. case TopLeftCornerResizeCursor:
  228553. case BottomRightCornerResizeCursor:
  228554. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228555. case TopRightCornerResizeCursor:
  228556. case BottomLeftCornerResizeCursor:
  228557. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228558. case UpDownLeftRightResizeCursor:
  228559. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228560. default:
  228561. jassertfalse;
  228562. break;
  228563. }
  228564. [c retain];
  228565. return c;
  228566. }
  228567. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228568. {
  228569. [((NSCursor*) cursorHandle) release];
  228570. }
  228571. void MouseCursor::showInAllWindows() const
  228572. {
  228573. showInWindow (0);
  228574. }
  228575. void MouseCursor::showInWindow (ComponentPeer*) const
  228576. {
  228577. [((NSCursor*) getHandle()) set];
  228578. }
  228579. #else
  228580. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228581. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228582. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228583. void MouseCursor::showInAllWindows() const {}
  228584. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228585. #endif
  228586. #endif
  228587. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228588. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228589. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228590. // compiled on its own).
  228591. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228592. #if JUCE_MAC
  228593. END_JUCE_NAMESPACE
  228594. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228595. @interface DownloadClickDetector : NSObject
  228596. {
  228597. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228598. }
  228599. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228600. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228601. request: (NSURLRequest*) request
  228602. frame: (WebFrame*) frame
  228603. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228604. @end
  228605. @implementation DownloadClickDetector
  228606. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228607. {
  228608. [super init];
  228609. ownerComponent = ownerComponent_;
  228610. return self;
  228611. }
  228612. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228613. request: (NSURLRequest*) request
  228614. frame: (WebFrame*) frame
  228615. decisionListener: (id <WebPolicyDecisionListener>) listener
  228616. {
  228617. (void) sender;
  228618. (void) request;
  228619. (void) frame;
  228620. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228621. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228622. [listener use];
  228623. else
  228624. [listener ignore];
  228625. }
  228626. @end
  228627. BEGIN_JUCE_NAMESPACE
  228628. class WebBrowserComponentInternal : public NSViewComponent
  228629. {
  228630. public:
  228631. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228632. {
  228633. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228634. frameName: @""
  228635. groupName: @""];
  228636. setView (webView);
  228637. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228638. [webView setPolicyDelegate: clickListener];
  228639. }
  228640. ~WebBrowserComponentInternal()
  228641. {
  228642. [webView setPolicyDelegate: nil];
  228643. [clickListener release];
  228644. setView (0);
  228645. }
  228646. void goToURL (const String& url,
  228647. const StringArray* headers,
  228648. const MemoryBlock* postData)
  228649. {
  228650. NSMutableURLRequest* r
  228651. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228652. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228653. timeoutInterval: 30.0];
  228654. if (postData != 0 && postData->getSize() > 0)
  228655. {
  228656. [r setHTTPMethod: @"POST"];
  228657. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228658. length: postData->getSize()]];
  228659. }
  228660. if (headers != 0)
  228661. {
  228662. for (int i = 0; i < headers->size(); ++i)
  228663. {
  228664. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228665. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228666. [r setValue: juceStringToNS (headerValue)
  228667. forHTTPHeaderField: juceStringToNS (headerName)];
  228668. }
  228669. }
  228670. stop();
  228671. [[webView mainFrame] loadRequest: r];
  228672. }
  228673. void goBack()
  228674. {
  228675. [webView goBack];
  228676. }
  228677. void goForward()
  228678. {
  228679. [webView goForward];
  228680. }
  228681. void stop()
  228682. {
  228683. [webView stopLoading: nil];
  228684. }
  228685. void refresh()
  228686. {
  228687. [webView reload: nil];
  228688. }
  228689. private:
  228690. WebView* webView;
  228691. DownloadClickDetector* clickListener;
  228692. };
  228693. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228694. : browser (0),
  228695. blankPageShown (false),
  228696. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228697. {
  228698. setOpaque (true);
  228699. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228700. }
  228701. WebBrowserComponent::~WebBrowserComponent()
  228702. {
  228703. deleteAndZero (browser);
  228704. }
  228705. void WebBrowserComponent::goToURL (const String& url,
  228706. const StringArray* headers,
  228707. const MemoryBlock* postData)
  228708. {
  228709. lastURL = url;
  228710. lastHeaders.clear();
  228711. if (headers != 0)
  228712. lastHeaders = *headers;
  228713. lastPostData.setSize (0);
  228714. if (postData != 0)
  228715. lastPostData = *postData;
  228716. blankPageShown = false;
  228717. browser->goToURL (url, headers, postData);
  228718. }
  228719. void WebBrowserComponent::stop()
  228720. {
  228721. browser->stop();
  228722. }
  228723. void WebBrowserComponent::goBack()
  228724. {
  228725. lastURL = String::empty;
  228726. blankPageShown = false;
  228727. browser->goBack();
  228728. }
  228729. void WebBrowserComponent::goForward()
  228730. {
  228731. lastURL = String::empty;
  228732. browser->goForward();
  228733. }
  228734. void WebBrowserComponent::refresh()
  228735. {
  228736. browser->refresh();
  228737. }
  228738. void WebBrowserComponent::paint (Graphics&)
  228739. {
  228740. }
  228741. void WebBrowserComponent::checkWindowAssociation()
  228742. {
  228743. if (isShowing())
  228744. {
  228745. if (blankPageShown)
  228746. goBack();
  228747. }
  228748. else
  228749. {
  228750. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228751. {
  228752. // when the component becomes invisible, some stuff like flash
  228753. // carries on playing audio, so we need to force it onto a blank
  228754. // page to avoid this, (and send it back when it's made visible again).
  228755. blankPageShown = true;
  228756. browser->goToURL ("about:blank", 0, 0);
  228757. }
  228758. }
  228759. }
  228760. void WebBrowserComponent::reloadLastURL()
  228761. {
  228762. if (lastURL.isNotEmpty())
  228763. {
  228764. goToURL (lastURL, &lastHeaders, &lastPostData);
  228765. lastURL = String::empty;
  228766. }
  228767. }
  228768. void WebBrowserComponent::parentHierarchyChanged()
  228769. {
  228770. checkWindowAssociation();
  228771. }
  228772. void WebBrowserComponent::resized()
  228773. {
  228774. browser->setSize (getWidth(), getHeight());
  228775. }
  228776. void WebBrowserComponent::visibilityChanged()
  228777. {
  228778. checkWindowAssociation();
  228779. }
  228780. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228781. {
  228782. return true;
  228783. }
  228784. #else
  228785. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228786. {
  228787. }
  228788. WebBrowserComponent::~WebBrowserComponent()
  228789. {
  228790. }
  228791. void WebBrowserComponent::goToURL (const String& url,
  228792. const StringArray* headers,
  228793. const MemoryBlock* postData)
  228794. {
  228795. }
  228796. void WebBrowserComponent::stop()
  228797. {
  228798. }
  228799. void WebBrowserComponent::goBack()
  228800. {
  228801. }
  228802. void WebBrowserComponent::goForward()
  228803. {
  228804. }
  228805. void WebBrowserComponent::refresh()
  228806. {
  228807. }
  228808. void WebBrowserComponent::paint (Graphics& g)
  228809. {
  228810. }
  228811. void WebBrowserComponent::checkWindowAssociation()
  228812. {
  228813. }
  228814. void WebBrowserComponent::reloadLastURL()
  228815. {
  228816. }
  228817. void WebBrowserComponent::parentHierarchyChanged()
  228818. {
  228819. }
  228820. void WebBrowserComponent::resized()
  228821. {
  228822. }
  228823. void WebBrowserComponent::visibilityChanged()
  228824. {
  228825. }
  228826. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228827. {
  228828. return true;
  228829. }
  228830. #endif
  228831. #endif
  228832. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228833. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228834. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228835. // compiled on its own).
  228836. #if JUCE_INCLUDED_FILE
  228837. class IPhoneAudioIODevice : public AudioIODevice
  228838. {
  228839. public:
  228840. IPhoneAudioIODevice (const String& deviceName)
  228841. : AudioIODevice (deviceName, "Audio"),
  228842. audioUnit (0),
  228843. isRunning (false),
  228844. callback (0),
  228845. actualBufferSize (0),
  228846. floatData (1, 2)
  228847. {
  228848. numInputChannels = 2;
  228849. numOutputChannels = 2;
  228850. preferredBufferSize = 0;
  228851. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228852. updateDeviceInfo();
  228853. }
  228854. ~IPhoneAudioIODevice()
  228855. {
  228856. close();
  228857. }
  228858. const StringArray getOutputChannelNames()
  228859. {
  228860. StringArray s;
  228861. s.add ("Left");
  228862. s.add ("Right");
  228863. return s;
  228864. }
  228865. const StringArray getInputChannelNames()
  228866. {
  228867. StringArray s;
  228868. if (audioInputIsAvailable)
  228869. {
  228870. s.add ("Left");
  228871. s.add ("Right");
  228872. }
  228873. return s;
  228874. }
  228875. int getNumSampleRates()
  228876. {
  228877. return 1;
  228878. }
  228879. double getSampleRate (int index)
  228880. {
  228881. return sampleRate;
  228882. }
  228883. int getNumBufferSizesAvailable()
  228884. {
  228885. return 1;
  228886. }
  228887. int getBufferSizeSamples (int index)
  228888. {
  228889. return getDefaultBufferSize();
  228890. }
  228891. int getDefaultBufferSize()
  228892. {
  228893. return 1024;
  228894. }
  228895. const String open (const BigInteger& inputChannels,
  228896. const BigInteger& outputChannels,
  228897. double sampleRate,
  228898. int bufferSize)
  228899. {
  228900. close();
  228901. lastError = String::empty;
  228902. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228903. // xxx set up channel mapping
  228904. activeOutputChans = outputChannels;
  228905. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228906. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228907. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228908. activeInputChans = inputChannels;
  228909. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228910. numInputChannels = activeInputChans.countNumberOfSetBits();
  228911. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228912. AudioSessionSetActive (true);
  228913. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228914. : kAudioSessionCategory_MediaPlayback;
  228915. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228916. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228917. fixAudioRouteIfSetToReceiver();
  228918. updateDeviceInfo();
  228919. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228920. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228921. actualBufferSize = preferredBufferSize;
  228922. prepareFloatBuffers();
  228923. isRunning = true;
  228924. propertyChanged (0, 0, 0); // creates and starts the AU
  228925. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228926. return lastError;
  228927. }
  228928. void close()
  228929. {
  228930. if (isRunning)
  228931. {
  228932. isRunning = false;
  228933. AudioSessionSetActive (false);
  228934. if (audioUnit != 0)
  228935. {
  228936. AudioComponentInstanceDispose (audioUnit);
  228937. audioUnit = 0;
  228938. }
  228939. }
  228940. }
  228941. bool isOpen()
  228942. {
  228943. return isRunning;
  228944. }
  228945. int getCurrentBufferSizeSamples()
  228946. {
  228947. return actualBufferSize;
  228948. }
  228949. double getCurrentSampleRate()
  228950. {
  228951. return sampleRate;
  228952. }
  228953. int getCurrentBitDepth()
  228954. {
  228955. return 16;
  228956. }
  228957. const BigInteger getActiveOutputChannels() const
  228958. {
  228959. return activeOutputChans;
  228960. }
  228961. const BigInteger getActiveInputChannels() const
  228962. {
  228963. return activeInputChans;
  228964. }
  228965. int getOutputLatencyInSamples()
  228966. {
  228967. return 0; //xxx
  228968. }
  228969. int getInputLatencyInSamples()
  228970. {
  228971. return 0; //xxx
  228972. }
  228973. void start (AudioIODeviceCallback* callback_)
  228974. {
  228975. if (isRunning && callback != callback_)
  228976. {
  228977. if (callback_ != 0)
  228978. callback_->audioDeviceAboutToStart (this);
  228979. const ScopedLock sl (callbackLock);
  228980. callback = callback_;
  228981. }
  228982. }
  228983. void stop()
  228984. {
  228985. if (isRunning)
  228986. {
  228987. AudioIODeviceCallback* lastCallback;
  228988. {
  228989. const ScopedLock sl (callbackLock);
  228990. lastCallback = callback;
  228991. callback = 0;
  228992. }
  228993. if (lastCallback != 0)
  228994. lastCallback->audioDeviceStopped();
  228995. }
  228996. }
  228997. bool isPlaying()
  228998. {
  228999. return isRunning && callback != 0;
  229000. }
  229001. const String getLastError()
  229002. {
  229003. return lastError;
  229004. }
  229005. private:
  229006. CriticalSection callbackLock;
  229007. Float64 sampleRate;
  229008. int numInputChannels, numOutputChannels;
  229009. int preferredBufferSize;
  229010. int actualBufferSize;
  229011. bool isRunning;
  229012. String lastError;
  229013. AudioStreamBasicDescription format;
  229014. AudioUnit audioUnit;
  229015. UInt32 audioInputIsAvailable;
  229016. AudioIODeviceCallback* callback;
  229017. BigInteger activeOutputChans, activeInputChans;
  229018. AudioSampleBuffer floatData;
  229019. float* inputChannels[3];
  229020. float* outputChannels[3];
  229021. bool monoInputChannelNumber, monoOutputChannelNumber;
  229022. void prepareFloatBuffers()
  229023. {
  229024. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229025. zerostruct (inputChannels);
  229026. zerostruct (outputChannels);
  229027. for (int i = 0; i < numInputChannels; ++i)
  229028. inputChannels[i] = floatData.getSampleData (i);
  229029. for (int i = 0; i < numOutputChannels; ++i)
  229030. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229031. }
  229032. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229033. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229034. {
  229035. OSStatus err = noErr;
  229036. if (audioInputIsAvailable)
  229037. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229038. const ScopedLock sl (callbackLock);
  229039. if (callback != 0)
  229040. {
  229041. if (audioInputIsAvailable && numInputChannels > 0)
  229042. {
  229043. short* shortData = (short*) ioData->mBuffers[0].mData;
  229044. if (numInputChannels >= 2)
  229045. {
  229046. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229047. {
  229048. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229049. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229050. }
  229051. }
  229052. else
  229053. {
  229054. if (monoInputChannelNumber > 0)
  229055. ++shortData;
  229056. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229057. {
  229058. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229059. ++shortData;
  229060. }
  229061. }
  229062. }
  229063. else
  229064. {
  229065. for (int i = numInputChannels; --i >= 0;)
  229066. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229067. }
  229068. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229069. outputChannels, numOutputChannels,
  229070. (int) inNumberFrames);
  229071. short* shortData = (short*) ioData->mBuffers[0].mData;
  229072. int n = 0;
  229073. if (numOutputChannels >= 2)
  229074. {
  229075. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229076. {
  229077. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229078. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229079. }
  229080. }
  229081. else if (numOutputChannels == 1)
  229082. {
  229083. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229084. {
  229085. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229086. shortData [n++] = s;
  229087. shortData [n++] = s;
  229088. }
  229089. }
  229090. else
  229091. {
  229092. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229093. }
  229094. }
  229095. else
  229096. {
  229097. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229098. }
  229099. return err;
  229100. }
  229101. void updateDeviceInfo()
  229102. {
  229103. UInt32 size = sizeof (sampleRate);
  229104. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229105. size = sizeof (audioInputIsAvailable);
  229106. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229107. }
  229108. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229109. {
  229110. if (! isRunning)
  229111. return;
  229112. if (inPropertyValue != 0)
  229113. {
  229114. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229115. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229116. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229117. SInt32 routeChangeReason;
  229118. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229119. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229120. fixAudioRouteIfSetToReceiver();
  229121. }
  229122. updateDeviceInfo();
  229123. createAudioUnit();
  229124. AudioSessionSetActive (true);
  229125. if (audioUnit != 0)
  229126. {
  229127. UInt32 formatSize = sizeof (format);
  229128. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229129. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229130. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229131. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229132. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229133. AudioOutputUnitStart (audioUnit);
  229134. }
  229135. }
  229136. void interruptionListener (UInt32 inInterruption)
  229137. {
  229138. /*if (inInterruption == kAudioSessionBeginInterruption)
  229139. {
  229140. isRunning = false;
  229141. AudioOutputUnitStop (audioUnit);
  229142. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229143. "This could have been interrupted by another application or by unplugging a headset",
  229144. @"Resume",
  229145. @"Cancel"))
  229146. {
  229147. isRunning = true;
  229148. propertyChanged (0, 0, 0);
  229149. }
  229150. }*/
  229151. if (inInterruption == kAudioSessionEndInterruption)
  229152. {
  229153. isRunning = true;
  229154. AudioSessionSetActive (true);
  229155. AudioOutputUnitStart (audioUnit);
  229156. }
  229157. }
  229158. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229159. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229160. {
  229161. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229162. }
  229163. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229164. {
  229165. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229166. }
  229167. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229168. {
  229169. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229170. }
  229171. void resetFormat (const int numChannels)
  229172. {
  229173. memset (&format, 0, sizeof (format));
  229174. format.mFormatID = kAudioFormatLinearPCM;
  229175. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229176. format.mBitsPerChannel = 8 * sizeof (short);
  229177. format.mChannelsPerFrame = 2;
  229178. format.mFramesPerPacket = 1;
  229179. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229180. }
  229181. bool createAudioUnit()
  229182. {
  229183. if (audioUnit != 0)
  229184. {
  229185. AudioComponentInstanceDispose (audioUnit);
  229186. audioUnit = 0;
  229187. }
  229188. resetFormat (2);
  229189. AudioComponentDescription desc;
  229190. desc.componentType = kAudioUnitType_Output;
  229191. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229192. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229193. desc.componentFlags = 0;
  229194. desc.componentFlagsMask = 0;
  229195. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229196. AudioComponentInstanceNew (comp, &audioUnit);
  229197. if (audioUnit == 0)
  229198. return false;
  229199. const UInt32 one = 1;
  229200. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229201. AudioChannelLayout layout;
  229202. layout.mChannelBitmap = 0;
  229203. layout.mNumberChannelDescriptions = 0;
  229204. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229205. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229206. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229207. AURenderCallbackStruct inputProc;
  229208. inputProc.inputProc = processStatic;
  229209. inputProc.inputProcRefCon = this;
  229210. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229211. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229212. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229213. AudioUnitInitialize (audioUnit);
  229214. return true;
  229215. }
  229216. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229217. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229218. static void fixAudioRouteIfSetToReceiver()
  229219. {
  229220. CFStringRef audioRoute = 0;
  229221. UInt32 propertySize = sizeof (audioRoute);
  229222. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229223. {
  229224. NSString* route = (NSString*) audioRoute;
  229225. //DBG ("audio route: " + nsStringToJuce (route));
  229226. if ([route hasPrefix: @"Receiver"])
  229227. {
  229228. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229229. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229230. }
  229231. CFRelease (audioRoute);
  229232. }
  229233. }
  229234. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229235. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229236. };
  229237. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229238. {
  229239. public:
  229240. IPhoneAudioIODeviceType()
  229241. : AudioIODeviceType ("iPhone Audio")
  229242. {
  229243. }
  229244. ~IPhoneAudioIODeviceType()
  229245. {
  229246. }
  229247. void scanForDevices()
  229248. {
  229249. }
  229250. const StringArray getDeviceNames (bool wantInputNames) const
  229251. {
  229252. StringArray s;
  229253. s.add ("iPhone Audio");
  229254. return s;
  229255. }
  229256. int getDefaultDeviceIndex (bool forInput) const
  229257. {
  229258. return 0;
  229259. }
  229260. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229261. {
  229262. return device != 0 ? 0 : -1;
  229263. }
  229264. bool hasSeparateInputsAndOutputs() const { return false; }
  229265. AudioIODevice* createDevice (const String& outputDeviceName,
  229266. const String& inputDeviceName)
  229267. {
  229268. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229269. {
  229270. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229271. : inputDeviceName);
  229272. }
  229273. return 0;
  229274. }
  229275. juce_UseDebuggingNewOperator
  229276. private:
  229277. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229278. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229279. };
  229280. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229281. {
  229282. return new IPhoneAudioIODeviceType();
  229283. }
  229284. #endif
  229285. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229286. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229287. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229288. // compiled on its own).
  229289. #if JUCE_INCLUDED_FILE
  229290. #if JUCE_MAC
  229291. #undef log
  229292. #define log(a) Logger::writeToLog(a)
  229293. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  229294. {
  229295. if (err == noErr)
  229296. return true;
  229297. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229298. jassertfalse;
  229299. return false;
  229300. }
  229301. #undef OK
  229302. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  229303. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229304. {
  229305. String result;
  229306. CFStringRef str = 0;
  229307. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229308. if (str != 0)
  229309. {
  229310. result = PlatformUtilities::cfStringToJuceString (str);
  229311. CFRelease (str);
  229312. str = 0;
  229313. }
  229314. MIDIEntityRef entity = 0;
  229315. MIDIEndpointGetEntity (endpoint, &entity);
  229316. if (entity == 0)
  229317. return result; // probably virtual
  229318. if (result.isEmpty())
  229319. {
  229320. // endpoint name has zero length - try the entity
  229321. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229322. if (str != 0)
  229323. {
  229324. result += PlatformUtilities::cfStringToJuceString (str);
  229325. CFRelease (str);
  229326. str = 0;
  229327. }
  229328. }
  229329. // now consider the device's name
  229330. MIDIDeviceRef device = 0;
  229331. MIDIEntityGetDevice (entity, &device);
  229332. if (device == 0)
  229333. return result;
  229334. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229335. if (str != 0)
  229336. {
  229337. const String s (PlatformUtilities::cfStringToJuceString (str));
  229338. CFRelease (str);
  229339. // if an external device has only one entity, throw away
  229340. // the endpoint name and just use the device name
  229341. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229342. {
  229343. result = s;
  229344. }
  229345. else if (! result.startsWithIgnoreCase (s))
  229346. {
  229347. // prepend the device name to the entity name
  229348. result = (s + " " + result).trimEnd();
  229349. }
  229350. }
  229351. return result;
  229352. }
  229353. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229354. {
  229355. String result;
  229356. // Does the endpoint have connections?
  229357. CFDataRef connections = 0;
  229358. int numConnections = 0;
  229359. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229360. if (connections != 0)
  229361. {
  229362. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229363. if (numConnections > 0)
  229364. {
  229365. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229366. for (int i = 0; i < numConnections; ++i, ++pid)
  229367. {
  229368. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229369. MIDIObjectRef connObject;
  229370. MIDIObjectType connObjectType;
  229371. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229372. if (err == noErr)
  229373. {
  229374. String s;
  229375. if (connObjectType == kMIDIObjectType_ExternalSource
  229376. || connObjectType == kMIDIObjectType_ExternalDestination)
  229377. {
  229378. // Connected to an external device's endpoint (10.3 and later).
  229379. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229380. }
  229381. else
  229382. {
  229383. // Connected to an external device (10.2) (or something else, catch-all)
  229384. CFStringRef str = 0;
  229385. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229386. if (str != 0)
  229387. {
  229388. s = PlatformUtilities::cfStringToJuceString (str);
  229389. CFRelease (str);
  229390. }
  229391. }
  229392. if (s.isNotEmpty())
  229393. {
  229394. if (result.isNotEmpty())
  229395. result += ", ";
  229396. result += s;
  229397. }
  229398. }
  229399. }
  229400. }
  229401. CFRelease (connections);
  229402. }
  229403. if (result.isNotEmpty())
  229404. return result;
  229405. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229406. return getEndpointName (endpoint, false);
  229407. }
  229408. const StringArray MidiOutput::getDevices()
  229409. {
  229410. StringArray s;
  229411. const ItemCount num = MIDIGetNumberOfDestinations();
  229412. for (ItemCount i = 0; i < num; ++i)
  229413. {
  229414. MIDIEndpointRef dest = MIDIGetDestination (i);
  229415. if (dest != 0)
  229416. {
  229417. String name (getConnectedEndpointName (dest));
  229418. if (name.isEmpty())
  229419. name = "<error>";
  229420. s.add (name);
  229421. }
  229422. else
  229423. {
  229424. s.add ("<error>");
  229425. }
  229426. }
  229427. return s;
  229428. }
  229429. int MidiOutput::getDefaultDeviceIndex()
  229430. {
  229431. return 0;
  229432. }
  229433. static MIDIClientRef globalMidiClient;
  229434. static bool hasGlobalClientBeenCreated = false;
  229435. static bool makeSureClientExists()
  229436. {
  229437. if (! hasGlobalClientBeenCreated)
  229438. {
  229439. String name ("JUCE");
  229440. if (JUCEApplication::getInstance() != 0)
  229441. name = JUCEApplication::getInstance()->getApplicationName();
  229442. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229443. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229444. CFRelease (appName);
  229445. }
  229446. return hasGlobalClientBeenCreated;
  229447. }
  229448. class MidiPortAndEndpoint
  229449. {
  229450. public:
  229451. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229452. : port (port_), endPoint (endPoint_)
  229453. {
  229454. }
  229455. ~MidiPortAndEndpoint()
  229456. {
  229457. if (port != 0)
  229458. MIDIPortDispose (port);
  229459. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229460. MIDIEndpointDispose (endPoint);
  229461. }
  229462. MIDIPortRef port;
  229463. MIDIEndpointRef endPoint;
  229464. };
  229465. MidiOutput* MidiOutput::openDevice (int index)
  229466. {
  229467. MidiOutput* mo = 0;
  229468. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229469. {
  229470. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229471. CFStringRef pname;
  229472. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229473. {
  229474. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  229475. if (makeSureClientExists())
  229476. {
  229477. MIDIPortRef port;
  229478. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  229479. {
  229480. mo = new MidiOutput();
  229481. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  229482. }
  229483. }
  229484. CFRelease (pname);
  229485. }
  229486. }
  229487. return mo;
  229488. }
  229489. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229490. {
  229491. MidiOutput* mo = 0;
  229492. if (makeSureClientExists())
  229493. {
  229494. MIDIEndpointRef endPoint;
  229495. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229496. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  229497. {
  229498. mo = new MidiOutput();
  229499. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  229500. }
  229501. CFRelease (name);
  229502. }
  229503. return mo;
  229504. }
  229505. MidiOutput::~MidiOutput()
  229506. {
  229507. delete static_cast<MidiPortAndEndpoint*> (internal);
  229508. }
  229509. void MidiOutput::reset()
  229510. {
  229511. }
  229512. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229513. {
  229514. return false;
  229515. }
  229516. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229517. {
  229518. }
  229519. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229520. {
  229521. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  229522. if (message.isSysEx())
  229523. {
  229524. const int maxPacketSize = 256;
  229525. int pos = 0, bytesLeft = message.getRawDataSize();
  229526. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229527. HeapBlock <MIDIPacketList> packets;
  229528. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229529. packets->numPackets = numPackets;
  229530. MIDIPacket* p = packets->packet;
  229531. for (int i = 0; i < numPackets; ++i)
  229532. {
  229533. p->timeStamp = 0;
  229534. p->length = jmin (maxPacketSize, bytesLeft);
  229535. memcpy (p->data, message.getRawData() + pos, p->length);
  229536. pos += p->length;
  229537. bytesLeft -= p->length;
  229538. p = MIDIPacketNext (p);
  229539. }
  229540. if (mpe->port != 0)
  229541. MIDISend (mpe->port, mpe->endPoint, packets);
  229542. else
  229543. MIDIReceived (mpe->endPoint, packets);
  229544. }
  229545. else
  229546. {
  229547. MIDIPacketList packets;
  229548. packets.numPackets = 1;
  229549. packets.packet[0].timeStamp = 0;
  229550. packets.packet[0].length = message.getRawDataSize();
  229551. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229552. if (mpe->port != 0)
  229553. MIDISend (mpe->port, mpe->endPoint, &packets);
  229554. else
  229555. MIDIReceived (mpe->endPoint, &packets);
  229556. }
  229557. }
  229558. const StringArray MidiInput::getDevices()
  229559. {
  229560. StringArray s;
  229561. const ItemCount num = MIDIGetNumberOfSources();
  229562. for (ItemCount i = 0; i < num; ++i)
  229563. {
  229564. MIDIEndpointRef source = MIDIGetSource (i);
  229565. if (source != 0)
  229566. {
  229567. String name (getConnectedEndpointName (source));
  229568. if (name.isEmpty())
  229569. name = "<error>";
  229570. s.add (name);
  229571. }
  229572. else
  229573. {
  229574. s.add ("<error>");
  229575. }
  229576. }
  229577. return s;
  229578. }
  229579. int MidiInput::getDefaultDeviceIndex()
  229580. {
  229581. return 0;
  229582. }
  229583. struct MidiPortAndCallback
  229584. {
  229585. MidiInput* input;
  229586. MidiPortAndEndpoint* portAndEndpoint;
  229587. MidiInputCallback* callback;
  229588. MemoryBlock pendingData;
  229589. int pendingBytes;
  229590. double pendingDataTime;
  229591. bool active;
  229592. void processSysex (const uint8*& d, int& size, const double time)
  229593. {
  229594. if (*d == 0xf0)
  229595. {
  229596. pendingBytes = 0;
  229597. pendingDataTime = time;
  229598. }
  229599. pendingData.ensureSize (pendingBytes + size, false);
  229600. uint8* totalMessage = (uint8*) pendingData.getData();
  229601. uint8* dest = totalMessage + pendingBytes;
  229602. while (size > 0)
  229603. {
  229604. if (pendingBytes > 0 && *d >= 0x80)
  229605. {
  229606. if (*d >= 0xfa || *d == 0xf8)
  229607. {
  229608. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  229609. ++d;
  229610. --size;
  229611. }
  229612. else
  229613. {
  229614. if (*d == 0xf7)
  229615. {
  229616. *dest++ = *d++;
  229617. pendingBytes++;
  229618. --size;
  229619. }
  229620. break;
  229621. }
  229622. }
  229623. else
  229624. {
  229625. *dest++ = *d++;
  229626. pendingBytes++;
  229627. --size;
  229628. }
  229629. }
  229630. if (totalMessage [pendingBytes - 1] == 0xf7)
  229631. {
  229632. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  229633. pendingBytes = 0;
  229634. }
  229635. else
  229636. {
  229637. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  229638. }
  229639. }
  229640. };
  229641. namespace CoreMidiCallbacks
  229642. {
  229643. static CriticalSection callbackLock;
  229644. static Array<void*> activeCallbacks;
  229645. }
  229646. static void midiInputProc (const MIDIPacketList* pktlist,
  229647. void* readProcRefCon,
  229648. void* /*srcConnRefCon*/)
  229649. {
  229650. double time = Time::getMillisecondCounterHiRes() * 0.001;
  229651. const double originalTime = time;
  229652. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  229653. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229654. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  229655. {
  229656. const MIDIPacket* packet = &pktlist->packet[0];
  229657. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229658. {
  229659. const uint8* d = (const uint8*) (packet->data);
  229660. int size = packet->length;
  229661. while (size > 0)
  229662. {
  229663. time = originalTime;
  229664. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  229665. {
  229666. mpc->processSysex (d, size, time);
  229667. }
  229668. else
  229669. {
  229670. int used = 0;
  229671. const MidiMessage m (d, size, used, 0, time);
  229672. if (used <= 0)
  229673. {
  229674. jassertfalse; // malformed midi message
  229675. break;
  229676. }
  229677. else
  229678. {
  229679. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  229680. }
  229681. size -= used;
  229682. d += used;
  229683. }
  229684. }
  229685. packet = MIDIPacketNext (packet);
  229686. }
  229687. }
  229688. }
  229689. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229690. {
  229691. MidiInput* mi = 0;
  229692. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229693. {
  229694. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229695. if (endPoint != 0)
  229696. {
  229697. CFStringRef pname;
  229698. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229699. {
  229700. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  229701. if (makeSureClientExists())
  229702. {
  229703. MIDIPortRef port;
  229704. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  229705. mpc->active = false;
  229706. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  229707. {
  229708. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  229709. {
  229710. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229711. mpc->callback = callback;
  229712. mpc->pendingBytes = 0;
  229713. mpc->pendingData.ensureSize (128);
  229714. mi = new MidiInput (getDevices() [index]);
  229715. mpc->input = mi;
  229716. mi->internal = mpc;
  229717. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229718. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  229719. }
  229720. else
  229721. {
  229722. OK (MIDIPortDispose (port));
  229723. }
  229724. }
  229725. }
  229726. }
  229727. CFRelease (pname);
  229728. }
  229729. }
  229730. return mi;
  229731. }
  229732. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229733. {
  229734. MidiInput* mi = 0;
  229735. if (makeSureClientExists())
  229736. {
  229737. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  229738. mpc->active = false;
  229739. MIDIEndpointRef endPoint;
  229740. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229741. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  229742. {
  229743. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229744. mpc->callback = callback;
  229745. mpc->pendingBytes = 0;
  229746. mpc->pendingData.ensureSize (128);
  229747. mi = new MidiInput (deviceName);
  229748. mpc->input = mi;
  229749. mi->internal = mpc;
  229750. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229751. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  229752. }
  229753. CFRelease (name);
  229754. }
  229755. return mi;
  229756. }
  229757. MidiInput::MidiInput (const String& name_)
  229758. : name (name_)
  229759. {
  229760. }
  229761. MidiInput::~MidiInput()
  229762. {
  229763. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  229764. mpc->active = false;
  229765. {
  229766. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229767. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  229768. }
  229769. if (mpc->portAndEndpoint->port != 0)
  229770. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  229771. delete mpc->portAndEndpoint;
  229772. delete mpc;
  229773. }
  229774. void MidiInput::start()
  229775. {
  229776. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229777. static_cast<MidiPortAndCallback*> (internal)->active = true;
  229778. }
  229779. void MidiInput::stop()
  229780. {
  229781. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229782. static_cast<MidiPortAndCallback*> (internal)->active = false;
  229783. }
  229784. #undef log
  229785. #else
  229786. MidiOutput::~MidiOutput()
  229787. {
  229788. }
  229789. void MidiOutput::reset()
  229790. {
  229791. }
  229792. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229793. {
  229794. return false;
  229795. }
  229796. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229797. {
  229798. }
  229799. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229800. {
  229801. }
  229802. const StringArray MidiOutput::getDevices()
  229803. {
  229804. return StringArray();
  229805. }
  229806. MidiOutput* MidiOutput::openDevice (int index)
  229807. {
  229808. return 0;
  229809. }
  229810. const StringArray MidiInput::getDevices()
  229811. {
  229812. return StringArray();
  229813. }
  229814. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229815. {
  229816. return 0;
  229817. }
  229818. #endif
  229819. #endif
  229820. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229821. #else
  229822. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229823. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229824. // compiled on its own).
  229825. #if JUCE_INCLUDED_FILE
  229826. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229827. #define SUPPORT_10_4_FONTS 1
  229828. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229829. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229830. #define SUPPORT_ONLY_10_4_FONTS 1
  229831. #endif
  229832. END_JUCE_NAMESPACE
  229833. @interface NSFont (PrivateHack)
  229834. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229835. @end
  229836. BEGIN_JUCE_NAMESPACE
  229837. #endif
  229838. class MacTypeface : public Typeface
  229839. {
  229840. public:
  229841. MacTypeface (const Font& font)
  229842. : Typeface (font.getTypefaceName())
  229843. {
  229844. const ScopedAutoReleasePool pool;
  229845. renderingTransform = CGAffineTransformIdentity;
  229846. bool needsItalicTransform = false;
  229847. #if JUCE_IOS
  229848. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229849. if (font.isItalic() || font.isBold())
  229850. {
  229851. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229852. for (NSString* i in familyFonts)
  229853. {
  229854. const String fn (nsStringToJuce (i));
  229855. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229856. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229857. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229858. || afterDash.containsIgnoreCase ("italic")
  229859. || fn.endsWithIgnoreCase ("oblique")
  229860. || fn.endsWithIgnoreCase ("italic");
  229861. if (probablyBold == font.isBold()
  229862. && probablyItalic == font.isItalic())
  229863. {
  229864. fontName = i;
  229865. needsItalicTransform = false;
  229866. break;
  229867. }
  229868. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229869. {
  229870. fontName = i;
  229871. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229872. }
  229873. }
  229874. if (needsItalicTransform)
  229875. renderingTransform.c = 0.15f;
  229876. }
  229877. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229878. const int ascender = abs (CGFontGetAscent (fontRef));
  229879. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229880. ascent = ascender / totalHeight;
  229881. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229882. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229883. #else
  229884. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229885. if (font.isItalic())
  229886. {
  229887. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229888. toHaveTrait: NSItalicFontMask];
  229889. if (newFont == nsFont)
  229890. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229891. nsFont = newFont;
  229892. }
  229893. if (font.isBold())
  229894. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229895. [nsFont retain];
  229896. ascent = std::abs ((float) [nsFont ascender]);
  229897. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229898. ascent /= totalSize;
  229899. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229900. if (needsItalicTransform)
  229901. {
  229902. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229903. renderingTransform.c = 0.15f;
  229904. }
  229905. #if SUPPORT_ONLY_10_4_FONTS
  229906. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229907. if (atsFont == 0)
  229908. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229909. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229910. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229911. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229912. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229913. #else
  229914. #if SUPPORT_10_4_FONTS
  229915. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229916. {
  229917. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229918. if (atsFont == 0)
  229919. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229920. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229921. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229922. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229923. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229924. }
  229925. else
  229926. #endif
  229927. {
  229928. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229929. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229930. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229931. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229932. }
  229933. #endif
  229934. #endif
  229935. }
  229936. ~MacTypeface()
  229937. {
  229938. #if ! JUCE_IOS
  229939. [nsFont release];
  229940. #endif
  229941. if (fontRef != 0)
  229942. CGFontRelease (fontRef);
  229943. }
  229944. float getAscent() const
  229945. {
  229946. return ascent;
  229947. }
  229948. float getDescent() const
  229949. {
  229950. return 1.0f - ascent;
  229951. }
  229952. float getStringWidth (const String& text)
  229953. {
  229954. if (fontRef == 0 || text.isEmpty())
  229955. return 0;
  229956. const int length = text.length();
  229957. HeapBlock <CGGlyph> glyphs;
  229958. createGlyphsForString (text, length, glyphs);
  229959. float x = 0;
  229960. #if SUPPORT_ONLY_10_4_FONTS
  229961. HeapBlock <NSSize> advances (length);
  229962. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229963. for (int i = 0; i < length; ++i)
  229964. x += advances[i].width;
  229965. #else
  229966. #if SUPPORT_10_4_FONTS
  229967. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229968. {
  229969. HeapBlock <NSSize> advances (length);
  229970. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229971. for (int i = 0; i < length; ++i)
  229972. x += advances[i].width;
  229973. }
  229974. else
  229975. #endif
  229976. {
  229977. HeapBlock <int> advances (length);
  229978. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229979. for (int i = 0; i < length; ++i)
  229980. x += advances[i];
  229981. }
  229982. #endif
  229983. return x * unitsToHeightScaleFactor;
  229984. }
  229985. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229986. {
  229987. xOffsets.add (0);
  229988. if (fontRef == 0 || text.isEmpty())
  229989. return;
  229990. const int length = text.length();
  229991. HeapBlock <CGGlyph> glyphs;
  229992. createGlyphsForString (text, length, glyphs);
  229993. #if SUPPORT_ONLY_10_4_FONTS
  229994. HeapBlock <NSSize> advances (length);
  229995. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229996. int x = 0;
  229997. for (int i = 0; i < length; ++i)
  229998. {
  229999. x += advances[i].width;
  230000. xOffsets.add (x * unitsToHeightScaleFactor);
  230001. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230002. }
  230003. #else
  230004. #if SUPPORT_10_4_FONTS
  230005. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230006. {
  230007. HeapBlock <NSSize> advances (length);
  230008. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230009. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230010. float x = 0;
  230011. for (int i = 0; i < length; ++i)
  230012. {
  230013. x += advances[i].width;
  230014. xOffsets.add (x * unitsToHeightScaleFactor);
  230015. resultGlyphs.add (nsGlyphs[i]);
  230016. }
  230017. }
  230018. else
  230019. #endif
  230020. {
  230021. HeapBlock <int> advances (length);
  230022. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230023. {
  230024. int x = 0;
  230025. for (int i = 0; i < length; ++i)
  230026. {
  230027. x += advances [i];
  230028. xOffsets.add (x * unitsToHeightScaleFactor);
  230029. resultGlyphs.add (glyphs[i]);
  230030. }
  230031. }
  230032. }
  230033. #endif
  230034. }
  230035. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230036. {
  230037. #if JUCE_IOS
  230038. return false;
  230039. #else
  230040. if (nsFont == 0)
  230041. return false;
  230042. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230043. jassert (path.isEmpty());
  230044. const ScopedAutoReleasePool pool;
  230045. NSBezierPath* bez = [NSBezierPath bezierPath];
  230046. [bez moveToPoint: NSMakePoint (0, 0)];
  230047. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230048. inFont: nsFont];
  230049. for (int i = 0; i < [bez elementCount]; ++i)
  230050. {
  230051. NSPoint p[3];
  230052. switch ([bez elementAtIndex: i associatedPoints: p])
  230053. {
  230054. case NSMoveToBezierPathElement:
  230055. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230056. break;
  230057. case NSLineToBezierPathElement:
  230058. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230059. break;
  230060. case NSCurveToBezierPathElement:
  230061. 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);
  230062. break;
  230063. case NSClosePathBezierPathElement:
  230064. path.closeSubPath();
  230065. break;
  230066. default:
  230067. jassertfalse;
  230068. break;
  230069. }
  230070. }
  230071. path.applyTransform (pathTransform);
  230072. return true;
  230073. #endif
  230074. }
  230075. juce_UseDebuggingNewOperator
  230076. CGFontRef fontRef;
  230077. float fontHeightToCGSizeFactor;
  230078. CGAffineTransform renderingTransform;
  230079. private:
  230080. float ascent, unitsToHeightScaleFactor;
  230081. #if JUCE_IOS
  230082. #else
  230083. NSFont* nsFont;
  230084. AffineTransform pathTransform;
  230085. #endif
  230086. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230087. {
  230088. #if SUPPORT_10_4_FONTS
  230089. #if ! SUPPORT_ONLY_10_4_FONTS
  230090. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230091. #endif
  230092. {
  230093. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230094. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230095. for (int i = 0; i < length; ++i)
  230096. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230097. return;
  230098. }
  230099. #endif
  230100. #if ! SUPPORT_ONLY_10_4_FONTS
  230101. if (charToGlyphMapper == 0)
  230102. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230103. glyphs.malloc (length);
  230104. for (int i = 0; i < length; ++i)
  230105. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230106. #endif
  230107. }
  230108. #if ! SUPPORT_ONLY_10_4_FONTS
  230109. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230110. class CharToGlyphMapper
  230111. {
  230112. public:
  230113. CharToGlyphMapper (CGFontRef fontRef)
  230114. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230115. idRangeOffset (0), glyphIndexes (0)
  230116. {
  230117. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230118. if (cmapTable != 0)
  230119. {
  230120. const int numSubtables = getValue16 (cmapTable, 2);
  230121. for (int i = 0; i < numSubtables; ++i)
  230122. {
  230123. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230124. {
  230125. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230126. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230127. {
  230128. const int length = getValue16 (cmapTable, offset + 2);
  230129. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230130. segCount = segCountX2 / 2;
  230131. const int endCodeOffset = offset + 14;
  230132. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230133. const int idDeltaOffset = startCodeOffset + segCountX2;
  230134. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230135. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230136. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230137. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230138. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230139. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230140. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230141. }
  230142. break;
  230143. }
  230144. }
  230145. CFRelease (cmapTable);
  230146. }
  230147. }
  230148. ~CharToGlyphMapper()
  230149. {
  230150. if (endCode != 0)
  230151. {
  230152. CFRelease (endCode);
  230153. CFRelease (startCode);
  230154. CFRelease (idDelta);
  230155. CFRelease (idRangeOffset);
  230156. CFRelease (glyphIndexes);
  230157. }
  230158. }
  230159. int getGlyphForCharacter (const juce_wchar c) const
  230160. {
  230161. for (int i = 0; i < segCount; ++i)
  230162. {
  230163. if (getValue16 (endCode, i * 2) >= c)
  230164. {
  230165. const int start = getValue16 (startCode, i * 2);
  230166. if (start > c)
  230167. break;
  230168. const int delta = getValue16 (idDelta, i * 2);
  230169. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230170. if (rangeOffset == 0)
  230171. return delta + c;
  230172. else
  230173. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230174. }
  230175. }
  230176. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230177. return jmax (-1, c - 29);
  230178. }
  230179. private:
  230180. int segCount;
  230181. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230182. static uint16 getValue16 (CFDataRef data, const int index)
  230183. {
  230184. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230185. }
  230186. static uint32 getValue32 (CFDataRef data, const int index)
  230187. {
  230188. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230189. }
  230190. };
  230191. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230192. #endif
  230193. MacTypeface (const MacTypeface&);
  230194. MacTypeface& operator= (const MacTypeface&);
  230195. };
  230196. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230197. {
  230198. return new MacTypeface (font);
  230199. }
  230200. const StringArray Font::findAllTypefaceNames()
  230201. {
  230202. StringArray names;
  230203. const ScopedAutoReleasePool pool;
  230204. #if JUCE_IOS
  230205. NSArray* fonts = [UIFont familyNames];
  230206. #else
  230207. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230208. #endif
  230209. for (unsigned int i = 0; i < [fonts count]; ++i)
  230210. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230211. names.sort (true);
  230212. return names;
  230213. }
  230214. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230215. {
  230216. #if JUCE_IOS
  230217. defaultSans = "Helvetica";
  230218. defaultSerif = "Times New Roman";
  230219. defaultFixed = "Courier New";
  230220. #else
  230221. defaultSans = "Lucida Grande";
  230222. defaultSerif = "Times New Roman";
  230223. defaultFixed = "Monaco";
  230224. #endif
  230225. }
  230226. #endif
  230227. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230228. // (must go before juce_mac_CoreGraphicsContext.mm)
  230229. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230230. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230231. // compiled on its own).
  230232. #if JUCE_INCLUDED_FILE
  230233. class CoreGraphicsImage : public Image::SharedImage
  230234. {
  230235. public:
  230236. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230237. : Image::SharedImage (format_, width_, height_)
  230238. {
  230239. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230240. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230241. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230242. imageData = imageDataAllocated;
  230243. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230244. : CGColorSpaceCreateDeviceRGB();
  230245. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230246. colourSpace, getCGImageFlags (format_));
  230247. CGColorSpaceRelease (colourSpace);
  230248. }
  230249. ~CoreGraphicsImage()
  230250. {
  230251. CGContextRelease (context);
  230252. }
  230253. Image::ImageType getType() const { return Image::NativeImage; }
  230254. LowLevelGraphicsContext* createLowLevelContext();
  230255. SharedImage* clone()
  230256. {
  230257. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230258. memcpy (im->imageData, imageData, lineStride * height);
  230259. return im;
  230260. }
  230261. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230262. {
  230263. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230264. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230265. {
  230266. return CGBitmapContextCreateImage (nativeImage->context);
  230267. }
  230268. else
  230269. {
  230270. const Image::BitmapData srcData (juceImage, false);
  230271. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230272. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230273. 8, srcData.pixelStride * 8, srcData.lineStride,
  230274. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230275. 0, true, kCGRenderingIntentDefault);
  230276. CGDataProviderRelease (provider);
  230277. return imageRef;
  230278. }
  230279. }
  230280. #if JUCE_MAC
  230281. static NSImage* createNSImage (const Image& image)
  230282. {
  230283. const ScopedAutoReleasePool pool;
  230284. NSImage* im = [[NSImage alloc] init];
  230285. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230286. [im lockFocus];
  230287. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230288. CGImageRef imageRef = createImage (image, false, colourSpace);
  230289. CGColorSpaceRelease (colourSpace);
  230290. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230291. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230292. CGImageRelease (imageRef);
  230293. [im unlockFocus];
  230294. return im;
  230295. }
  230296. #endif
  230297. CGContextRef context;
  230298. HeapBlock<uint8> imageDataAllocated;
  230299. private:
  230300. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230301. {
  230302. #if JUCE_BIG_ENDIAN
  230303. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230304. #else
  230305. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230306. #endif
  230307. }
  230308. };
  230309. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230310. {
  230311. #if USE_COREGRAPHICS_RENDERING
  230312. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230313. #else
  230314. return createSoftwareImage (format, width, height, clearImage);
  230315. #endif
  230316. }
  230317. class CoreGraphicsContext : public LowLevelGraphicsContext
  230318. {
  230319. public:
  230320. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230321. : context (context_),
  230322. flipHeight (flipHeight_),
  230323. state (new SavedState()),
  230324. numGradientLookupEntries (0),
  230325. lastClipRectIsValid (false)
  230326. {
  230327. CGContextRetain (context);
  230328. CGContextSaveGState(context);
  230329. CGContextSetShouldSmoothFonts (context, true);
  230330. CGContextSetShouldAntialias (context, true);
  230331. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230332. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230333. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230334. gradientCallbacks.version = 0;
  230335. gradientCallbacks.evaluate = gradientCallback;
  230336. gradientCallbacks.releaseInfo = 0;
  230337. setFont (Font());
  230338. }
  230339. ~CoreGraphicsContext()
  230340. {
  230341. CGContextRestoreGState (context);
  230342. CGContextRelease (context);
  230343. CGColorSpaceRelease (rgbColourSpace);
  230344. CGColorSpaceRelease (greyColourSpace);
  230345. }
  230346. bool isVectorDevice() const { return false; }
  230347. void setOrigin (int x, int y)
  230348. {
  230349. CGContextTranslateCTM (context, x, -y);
  230350. if (lastClipRectIsValid)
  230351. lastClipRect.translate (-x, -y);
  230352. }
  230353. bool clipToRectangle (const Rectangle<int>& r)
  230354. {
  230355. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230356. if (lastClipRectIsValid)
  230357. {
  230358. // This is actually incorrect, because the actual clip region may be complex, and
  230359. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230360. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230361. // when calculating the resultant clip bounds, and makes the same mistake!
  230362. lastClipRect = lastClipRect.getIntersection (r);
  230363. return ! lastClipRect.isEmpty();
  230364. }
  230365. return ! isClipEmpty();
  230366. }
  230367. bool clipToRectangleList (const RectangleList& clipRegion)
  230368. {
  230369. if (clipRegion.isEmpty())
  230370. {
  230371. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230372. lastClipRectIsValid = true;
  230373. lastClipRect = Rectangle<int>();
  230374. return false;
  230375. }
  230376. else
  230377. {
  230378. const int numRects = clipRegion.getNumRectangles();
  230379. HeapBlock <CGRect> rects (numRects);
  230380. for (int i = 0; i < numRects; ++i)
  230381. {
  230382. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230383. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230384. }
  230385. CGContextClipToRects (context, rects, numRects);
  230386. lastClipRectIsValid = false;
  230387. return ! isClipEmpty();
  230388. }
  230389. }
  230390. void excludeClipRectangle (const Rectangle<int>& r)
  230391. {
  230392. RectangleList remaining (getClipBounds());
  230393. remaining.subtract (r);
  230394. clipToRectangleList (remaining);
  230395. lastClipRectIsValid = false;
  230396. }
  230397. void clipToPath (const Path& path, const AffineTransform& transform)
  230398. {
  230399. createPath (path, transform);
  230400. CGContextClip (context);
  230401. lastClipRectIsValid = false;
  230402. }
  230403. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230404. {
  230405. if (! transform.isSingularity())
  230406. {
  230407. Image singleChannelImage (sourceImage);
  230408. if (sourceImage.getFormat() != Image::SingleChannel)
  230409. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230410. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230411. flip();
  230412. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230413. applyTransform (t);
  230414. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230415. CGContextClipToMask (context, r, image);
  230416. applyTransform (t.inverted());
  230417. flip();
  230418. CGImageRelease (image);
  230419. lastClipRectIsValid = false;
  230420. }
  230421. }
  230422. bool clipRegionIntersects (const Rectangle<int>& r)
  230423. {
  230424. return getClipBounds().intersects (r);
  230425. }
  230426. const Rectangle<int> getClipBounds() const
  230427. {
  230428. if (! lastClipRectIsValid)
  230429. {
  230430. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230431. lastClipRectIsValid = true;
  230432. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230433. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230434. roundToInt (bounds.size.width),
  230435. roundToInt (bounds.size.height));
  230436. }
  230437. return lastClipRect;
  230438. }
  230439. bool isClipEmpty() const
  230440. {
  230441. return getClipBounds().isEmpty();
  230442. }
  230443. void saveState()
  230444. {
  230445. CGContextSaveGState (context);
  230446. stateStack.add (new SavedState (*state));
  230447. }
  230448. void restoreState()
  230449. {
  230450. CGContextRestoreGState (context);
  230451. SavedState* const top = stateStack.getLast();
  230452. if (top != 0)
  230453. {
  230454. state = top;
  230455. stateStack.removeLast (1, false);
  230456. lastClipRectIsValid = false;
  230457. }
  230458. else
  230459. {
  230460. jassertfalse; // trying to pop with an empty stack!
  230461. }
  230462. }
  230463. void setFill (const FillType& fillType)
  230464. {
  230465. state->fillType = fillType;
  230466. if (fillType.isColour())
  230467. {
  230468. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230469. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230470. CGContextSetAlpha (context, 1.0f);
  230471. }
  230472. }
  230473. void setOpacity (float newOpacity)
  230474. {
  230475. state->fillType.setOpacity (newOpacity);
  230476. setFill (state->fillType);
  230477. }
  230478. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230479. {
  230480. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230481. ? kCGInterpolationLow
  230482. : kCGInterpolationHigh);
  230483. }
  230484. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230485. {
  230486. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230487. }
  230488. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230489. {
  230490. if (replaceExistingContents)
  230491. {
  230492. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230493. CGContextClearRect (context, cgRect);
  230494. #else
  230495. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230496. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230497. CGContextClearRect (context, cgRect);
  230498. else
  230499. #endif
  230500. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230501. #endif
  230502. fillCGRect (cgRect, false);
  230503. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230504. }
  230505. else
  230506. {
  230507. if (state->fillType.isColour())
  230508. {
  230509. CGContextFillRect (context, cgRect);
  230510. }
  230511. else if (state->fillType.isGradient())
  230512. {
  230513. CGContextSaveGState (context);
  230514. CGContextClipToRect (context, cgRect);
  230515. drawGradient();
  230516. CGContextRestoreGState (context);
  230517. }
  230518. else
  230519. {
  230520. CGContextSaveGState (context);
  230521. CGContextClipToRect (context, cgRect);
  230522. drawImage (state->fillType.image, state->fillType.transform, true);
  230523. CGContextRestoreGState (context);
  230524. }
  230525. }
  230526. }
  230527. void fillPath (const Path& path, const AffineTransform& transform)
  230528. {
  230529. CGContextSaveGState (context);
  230530. if (state->fillType.isColour())
  230531. {
  230532. flip();
  230533. applyTransform (transform);
  230534. createPath (path);
  230535. if (path.isUsingNonZeroWinding())
  230536. CGContextFillPath (context);
  230537. else
  230538. CGContextEOFillPath (context);
  230539. }
  230540. else
  230541. {
  230542. createPath (path, transform);
  230543. if (path.isUsingNonZeroWinding())
  230544. CGContextClip (context);
  230545. else
  230546. CGContextEOClip (context);
  230547. if (state->fillType.isGradient())
  230548. drawGradient();
  230549. else
  230550. drawImage (state->fillType.image, state->fillType.transform, true);
  230551. }
  230552. CGContextRestoreGState (context);
  230553. }
  230554. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230555. {
  230556. const int iw = sourceImage.getWidth();
  230557. const int ih = sourceImage.getHeight();
  230558. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230559. CGContextSaveGState (context);
  230560. CGContextSetAlpha (context, state->fillType.getOpacity());
  230561. flip();
  230562. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230563. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230564. if (fillEntireClipAsTiles)
  230565. {
  230566. #if JUCE_IOS
  230567. CGContextDrawTiledImage (context, imageRect, image);
  230568. #else
  230569. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230570. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230571. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230572. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230573. CGContextDrawTiledImage (context, imageRect, image);
  230574. else
  230575. #endif
  230576. {
  230577. // Fallback to manually doing a tiled fill on 10.4
  230578. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230579. int x = 0, y = 0;
  230580. while (x > clip.origin.x) x -= iw;
  230581. while (y > clip.origin.y) y -= ih;
  230582. const int right = (int) (clip.origin.x + clip.size.width);
  230583. const int bottom = (int) (clip.origin.y + clip.size.height);
  230584. while (y < bottom)
  230585. {
  230586. for (int x2 = x; x2 < right; x2 += iw)
  230587. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230588. y += ih;
  230589. }
  230590. }
  230591. #endif
  230592. }
  230593. else
  230594. {
  230595. CGContextDrawImage (context, imageRect, image);
  230596. }
  230597. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230598. CGContextRestoreGState (context);
  230599. }
  230600. void drawLine (const Line<float>& line)
  230601. {
  230602. if (state->fillType.isColour())
  230603. {
  230604. CGContextSetLineCap (context, kCGLineCapSquare);
  230605. CGContextSetLineWidth (context, 1.0f);
  230606. CGContextSetRGBStrokeColor (context,
  230607. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230608. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230609. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230610. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230611. CGContextStrokeLineSegments (context, cgLine, 1);
  230612. }
  230613. else
  230614. {
  230615. Path p;
  230616. p.addLineSegment (line, 1.0f);
  230617. fillPath (p, AffineTransform::identity);
  230618. }
  230619. }
  230620. void drawVerticalLine (const int x, float top, float bottom)
  230621. {
  230622. if (state->fillType.isColour())
  230623. {
  230624. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230625. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230626. #else
  230627. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230628. // the x co-ord slightly to trick it..
  230629. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230630. #endif
  230631. }
  230632. else
  230633. {
  230634. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230635. }
  230636. }
  230637. void drawHorizontalLine (const int y, float left, float right)
  230638. {
  230639. if (state->fillType.isColour())
  230640. {
  230641. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230642. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230643. #else
  230644. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230645. // the x co-ord slightly to trick it..
  230646. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230647. #endif
  230648. }
  230649. else
  230650. {
  230651. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230652. }
  230653. }
  230654. void setFont (const Font& newFont)
  230655. {
  230656. if (state->font != newFont)
  230657. {
  230658. state->fontRef = 0;
  230659. state->font = newFont;
  230660. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230661. if (mf != 0)
  230662. {
  230663. state->fontRef = mf->fontRef;
  230664. CGContextSetFont (context, state->fontRef);
  230665. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230666. state->fontTransform = mf->renderingTransform;
  230667. state->fontTransform.a *= state->font.getHorizontalScale();
  230668. CGContextSetTextMatrix (context, state->fontTransform);
  230669. }
  230670. }
  230671. }
  230672. const Font getFont()
  230673. {
  230674. return state->font;
  230675. }
  230676. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230677. {
  230678. if (state->fontRef != 0 && state->fillType.isColour())
  230679. {
  230680. if (transform.isOnlyTranslation())
  230681. {
  230682. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230683. CGGlyph g = glyphNumber;
  230684. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230685. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230686. }
  230687. else
  230688. {
  230689. CGContextSaveGState (context);
  230690. flip();
  230691. applyTransform (transform);
  230692. CGAffineTransform t = state->fontTransform;
  230693. t.d = -t.d;
  230694. CGContextSetTextMatrix (context, t);
  230695. CGGlyph g = glyphNumber;
  230696. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230697. CGContextRestoreGState (context);
  230698. }
  230699. }
  230700. else
  230701. {
  230702. Path p;
  230703. Font& f = state->font;
  230704. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230705. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230706. .followedBy (transform));
  230707. }
  230708. }
  230709. private:
  230710. CGContextRef context;
  230711. const CGFloat flipHeight;
  230712. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230713. CGFunctionCallbacks gradientCallbacks;
  230714. mutable Rectangle<int> lastClipRect;
  230715. mutable bool lastClipRectIsValid;
  230716. struct SavedState
  230717. {
  230718. SavedState()
  230719. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230720. {
  230721. }
  230722. SavedState (const SavedState& other)
  230723. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230724. fontTransform (other.fontTransform)
  230725. {
  230726. }
  230727. ~SavedState()
  230728. {
  230729. }
  230730. FillType fillType;
  230731. Font font;
  230732. CGFontRef fontRef;
  230733. CGAffineTransform fontTransform;
  230734. };
  230735. ScopedPointer <SavedState> state;
  230736. OwnedArray <SavedState> stateStack;
  230737. HeapBlock <PixelARGB> gradientLookupTable;
  230738. int numGradientLookupEntries;
  230739. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230740. {
  230741. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230742. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230743. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230744. colour.unpremultiply();
  230745. outData[0] = colour.getRed() / 255.0f;
  230746. outData[1] = colour.getGreen() / 255.0f;
  230747. outData[2] = colour.getBlue() / 255.0f;
  230748. outData[3] = colour.getAlpha() / 255.0f;
  230749. }
  230750. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230751. {
  230752. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230753. --numGradientLookupEntries;
  230754. CGShadingRef result = 0;
  230755. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230756. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230757. if (gradient.isRadial)
  230758. {
  230759. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230760. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230761. function, true, true);
  230762. }
  230763. else
  230764. {
  230765. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230766. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230767. function, true, true);
  230768. }
  230769. CGFunctionRelease (function);
  230770. return result;
  230771. }
  230772. void drawGradient()
  230773. {
  230774. flip();
  230775. applyTransform (state->fillType.transform);
  230776. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230777. // you draw a gradient with high quality interp enabled).
  230778. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230779. CGContextSetAlpha (context, state->fillType.getOpacity());
  230780. CGContextDrawShading (context, shading);
  230781. CGShadingRelease (shading);
  230782. }
  230783. void createPath (const Path& path) const
  230784. {
  230785. CGContextBeginPath (context);
  230786. Path::Iterator i (path);
  230787. while (i.next())
  230788. {
  230789. switch (i.elementType)
  230790. {
  230791. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230792. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230793. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230794. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230795. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230796. default: jassertfalse; break;
  230797. }
  230798. }
  230799. }
  230800. void createPath (const Path& path, const AffineTransform& transform) const
  230801. {
  230802. CGContextBeginPath (context);
  230803. Path::Iterator i (path);
  230804. while (i.next())
  230805. {
  230806. switch (i.elementType)
  230807. {
  230808. case Path::Iterator::startNewSubPath:
  230809. transform.transformPoint (i.x1, i.y1);
  230810. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230811. break;
  230812. case Path::Iterator::lineTo:
  230813. transform.transformPoint (i.x1, i.y1);
  230814. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230815. break;
  230816. case Path::Iterator::quadraticTo:
  230817. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230818. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230819. break;
  230820. case Path::Iterator::cubicTo:
  230821. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230822. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230823. break;
  230824. case Path::Iterator::closePath:
  230825. CGContextClosePath (context); break;
  230826. default:
  230827. jassertfalse;
  230828. break;
  230829. }
  230830. }
  230831. }
  230832. void flip() const
  230833. {
  230834. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230835. }
  230836. void applyTransform (const AffineTransform& transform) const
  230837. {
  230838. CGAffineTransform t;
  230839. t.a = transform.mat00;
  230840. t.b = transform.mat10;
  230841. t.c = transform.mat01;
  230842. t.d = transform.mat11;
  230843. t.tx = transform.mat02;
  230844. t.ty = transform.mat12;
  230845. CGContextConcatCTM (context, t);
  230846. }
  230847. CoreGraphicsContext (const CoreGraphicsContext&);
  230848. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  230849. };
  230850. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230851. {
  230852. return new CoreGraphicsContext (context, height);
  230853. }
  230854. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230855. const Image juce_loadWithCoreImage (InputStream& input)
  230856. {
  230857. MemoryBlock data;
  230858. input.readIntoMemoryBlock (data, -1);
  230859. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230860. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230861. CGDataProviderRelease (provider);
  230862. if (imageSource != 0)
  230863. {
  230864. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230865. CFRelease (imageSource);
  230866. if (loadedImage != 0)
  230867. {
  230868. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  230869. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  230870. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230871. hasAlphaChan, Image::NativeImage);
  230872. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230873. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230874. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230875. CGContextFlush (cgImage->context);
  230876. CFRelease (loadedImage);
  230877. return image;
  230878. }
  230879. }
  230880. return Image::null;
  230881. }
  230882. #endif
  230883. #endif
  230884. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230885. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230886. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230887. // compiled on its own).
  230888. #if JUCE_INCLUDED_FILE
  230889. class NSViewComponentPeer;
  230890. END_JUCE_NAMESPACE
  230891. @interface NSEvent (JuceDeviceDelta)
  230892. - (float) deviceDeltaX;
  230893. - (float) deviceDeltaY;
  230894. @end
  230895. #define JuceNSView MakeObjCClassName(JuceNSView)
  230896. @interface JuceNSView : NSView<NSTextInput>
  230897. {
  230898. @public
  230899. NSViewComponentPeer* owner;
  230900. NSNotificationCenter* notificationCenter;
  230901. String* stringBeingComposed;
  230902. bool textWasInserted;
  230903. }
  230904. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230905. - (void) dealloc;
  230906. - (BOOL) isOpaque;
  230907. - (void) drawRect: (NSRect) r;
  230908. - (void) mouseDown: (NSEvent*) ev;
  230909. - (void) asyncMouseDown: (NSEvent*) ev;
  230910. - (void) mouseUp: (NSEvent*) ev;
  230911. - (void) asyncMouseUp: (NSEvent*) ev;
  230912. - (void) mouseDragged: (NSEvent*) ev;
  230913. - (void) mouseMoved: (NSEvent*) ev;
  230914. - (void) mouseEntered: (NSEvent*) ev;
  230915. - (void) mouseExited: (NSEvent*) ev;
  230916. - (void) rightMouseDown: (NSEvent*) ev;
  230917. - (void) rightMouseDragged: (NSEvent*) ev;
  230918. - (void) rightMouseUp: (NSEvent*) ev;
  230919. - (void) otherMouseDown: (NSEvent*) ev;
  230920. - (void) otherMouseDragged: (NSEvent*) ev;
  230921. - (void) otherMouseUp: (NSEvent*) ev;
  230922. - (void) scrollWheel: (NSEvent*) ev;
  230923. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230924. - (void) frameChanged: (NSNotification*) n;
  230925. - (void) viewDidMoveToWindow;
  230926. - (void) keyDown: (NSEvent*) ev;
  230927. - (void) keyUp: (NSEvent*) ev;
  230928. // NSTextInput Methods
  230929. - (void) insertText: (id) aString;
  230930. - (void) doCommandBySelector: (SEL) aSelector;
  230931. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230932. - (void) unmarkText;
  230933. - (BOOL) hasMarkedText;
  230934. - (long) conversationIdentifier;
  230935. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230936. - (NSRange) markedRange;
  230937. - (NSRange) selectedRange;
  230938. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230939. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230940. - (NSArray*) validAttributesForMarkedText;
  230941. - (void) flagsChanged: (NSEvent*) ev;
  230942. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230943. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230944. #endif
  230945. - (BOOL) becomeFirstResponder;
  230946. - (BOOL) resignFirstResponder;
  230947. - (BOOL) acceptsFirstResponder;
  230948. - (void) asyncRepaint: (id) rect;
  230949. - (NSArray*) getSupportedDragTypes;
  230950. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230951. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230952. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230953. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230954. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230955. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230956. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230957. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230958. @end
  230959. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230960. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230961. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230962. #else
  230963. @interface JuceNSWindow : NSWindow
  230964. #endif
  230965. {
  230966. @private
  230967. NSViewComponentPeer* owner;
  230968. bool isZooming;
  230969. }
  230970. - (void) setOwner: (NSViewComponentPeer*) owner;
  230971. - (BOOL) canBecomeKeyWindow;
  230972. - (void) becomeKeyWindow;
  230973. - (BOOL) windowShouldClose: (id) window;
  230974. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230975. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230976. - (void) zoom: (id) sender;
  230977. @end
  230978. BEGIN_JUCE_NAMESPACE
  230979. class NSViewComponentPeer : public ComponentPeer
  230980. {
  230981. public:
  230982. NSViewComponentPeer (Component* const component,
  230983. const int windowStyleFlags,
  230984. NSView* viewToAttachTo);
  230985. ~NSViewComponentPeer();
  230986. void* getNativeHandle() const;
  230987. void setVisible (bool shouldBeVisible);
  230988. void setTitle (const String& title);
  230989. void setPosition (int x, int y);
  230990. void setSize (int w, int h);
  230991. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230992. const Rectangle<int> getBounds (const bool global) const;
  230993. const Rectangle<int> getBounds() const;
  230994. const Point<int> getScreenPosition() const;
  230995. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  230996. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  230997. void setMinimised (bool shouldBeMinimised);
  230998. bool isMinimised() const;
  230999. void setFullScreen (bool shouldBeFullScreen);
  231000. bool isFullScreen() const;
  231001. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231002. const BorderSize getFrameSize() const;
  231003. bool setAlwaysOnTop (bool alwaysOnTop);
  231004. void toFront (bool makeActiveWindow);
  231005. void toBehind (ComponentPeer* other);
  231006. void setIcon (const Image& newIcon);
  231007. const StringArray getAvailableRenderingEngines();
  231008. int getCurrentRenderingEngine() throw();
  231009. void setCurrentRenderingEngine (int index);
  231010. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231011. for example having more than one juce plugin loaded into a host, then when a
  231012. method is called, the actual code that runs might actually be in a different module
  231013. than the one you expect... So any calls to library functions or statics that are
  231014. made inside obj-c methods will probably end up getting executed in a different DLL's
  231015. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231016. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231017. virtual methods of an object that's known to live inside the right module's space.
  231018. */
  231019. virtual void redirectMouseDown (NSEvent* ev);
  231020. virtual void redirectMouseUp (NSEvent* ev);
  231021. virtual void redirectMouseDrag (NSEvent* ev);
  231022. virtual void redirectMouseMove (NSEvent* ev);
  231023. virtual void redirectMouseEnter (NSEvent* ev);
  231024. virtual void redirectMouseExit (NSEvent* ev);
  231025. virtual void redirectMouseWheel (NSEvent* ev);
  231026. void sendMouseEvent (NSEvent* ev);
  231027. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231028. virtual bool redirectKeyDown (NSEvent* ev);
  231029. virtual bool redirectKeyUp (NSEvent* ev);
  231030. virtual void redirectModKeyChange (NSEvent* ev);
  231031. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231032. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231033. #endif
  231034. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231035. virtual bool isOpaque();
  231036. virtual void drawRect (NSRect r);
  231037. virtual bool canBecomeKeyWindow();
  231038. virtual bool windowShouldClose();
  231039. virtual void redirectMovedOrResized();
  231040. virtual void viewMovedToWindow();
  231041. virtual NSRect constrainRect (NSRect r);
  231042. static void showArrowCursorIfNeeded();
  231043. static void updateModifiers (NSEvent* e);
  231044. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231045. static int getKeyCodeFromEvent (NSEvent* ev)
  231046. {
  231047. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231048. int keyCode = unmodified[0];
  231049. if (keyCode == 0x19) // (backwards-tab)
  231050. keyCode = '\t';
  231051. else if (keyCode == 0x03) // (enter)
  231052. keyCode = '\r';
  231053. else
  231054. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231055. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231056. {
  231057. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231058. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231059. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231060. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231061. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231062. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231063. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231064. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231065. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231066. if (keyCode == numPadConversions [i])
  231067. keyCode = numPadConversions [i + 1];
  231068. }
  231069. return keyCode;
  231070. }
  231071. static int64 getMouseTime (NSEvent* e)
  231072. {
  231073. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231074. + (int64) ([e timestamp] * 1000.0);
  231075. }
  231076. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231077. {
  231078. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231079. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231080. }
  231081. static int getModifierForButtonNumber (const NSInteger num)
  231082. {
  231083. return num == 0 ? ModifierKeys::leftButtonModifier
  231084. : (num == 1 ? ModifierKeys::rightButtonModifier
  231085. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231086. }
  231087. virtual void viewFocusGain();
  231088. virtual void viewFocusLoss();
  231089. bool isFocused() const;
  231090. void grabFocus();
  231091. void textInputRequired (const Point<int>& position);
  231092. void repaint (const Rectangle<int>& area);
  231093. void performAnyPendingRepaintsNow();
  231094. juce_UseDebuggingNewOperator
  231095. NSWindow* window;
  231096. JuceNSView* view;
  231097. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231098. static ModifierKeys currentModifiers;
  231099. static ComponentPeer* currentlyFocusedPeer;
  231100. static Array<int> keysCurrentlyDown;
  231101. };
  231102. END_JUCE_NAMESPACE
  231103. @implementation JuceNSView
  231104. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231105. withFrame: (NSRect) frame
  231106. {
  231107. [super initWithFrame: frame];
  231108. owner = owner_;
  231109. stringBeingComposed = 0;
  231110. textWasInserted = false;
  231111. notificationCenter = [NSNotificationCenter defaultCenter];
  231112. [notificationCenter addObserver: self
  231113. selector: @selector (frameChanged:)
  231114. name: NSViewFrameDidChangeNotification
  231115. object: self];
  231116. if (! owner_->isSharedWindow)
  231117. {
  231118. [notificationCenter addObserver: self
  231119. selector: @selector (frameChanged:)
  231120. name: NSWindowDidMoveNotification
  231121. object: owner_->window];
  231122. }
  231123. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231124. return self;
  231125. }
  231126. - (void) dealloc
  231127. {
  231128. [notificationCenter removeObserver: self];
  231129. delete stringBeingComposed;
  231130. [super dealloc];
  231131. }
  231132. - (void) drawRect: (NSRect) r
  231133. {
  231134. if (owner != 0)
  231135. owner->drawRect (r);
  231136. }
  231137. - (BOOL) isOpaque
  231138. {
  231139. return owner == 0 || owner->isOpaque();
  231140. }
  231141. - (void) mouseDown: (NSEvent*) ev
  231142. {
  231143. if (JUCEApplication::isStandaloneApp())
  231144. [self asyncMouseDown: ev];
  231145. else
  231146. // In some host situations, the host will stop modal loops from working
  231147. // correctly if they're called from a mouse event, so we'll trigger
  231148. // the event asynchronously..
  231149. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231150. withObject: ev
  231151. waitUntilDone: NO];
  231152. }
  231153. - (void) asyncMouseDown: (NSEvent*) ev
  231154. {
  231155. if (owner != 0)
  231156. owner->redirectMouseDown (ev);
  231157. }
  231158. - (void) mouseUp: (NSEvent*) ev
  231159. {
  231160. if (! JUCEApplication::isStandaloneApp())
  231161. [self asyncMouseUp: ev];
  231162. else
  231163. // In some host situations, the host will stop modal loops from working
  231164. // correctly if they're called from a mouse event, so we'll trigger
  231165. // the event asynchronously..
  231166. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231167. withObject: ev
  231168. waitUntilDone: NO];
  231169. }
  231170. - (void) asyncMouseUp: (NSEvent*) ev
  231171. {
  231172. if (owner != 0)
  231173. owner->redirectMouseUp (ev);
  231174. }
  231175. - (void) mouseDragged: (NSEvent*) ev
  231176. {
  231177. if (owner != 0)
  231178. owner->redirectMouseDrag (ev);
  231179. }
  231180. - (void) mouseMoved: (NSEvent*) ev
  231181. {
  231182. if (owner != 0)
  231183. owner->redirectMouseMove (ev);
  231184. }
  231185. - (void) mouseEntered: (NSEvent*) ev
  231186. {
  231187. if (owner != 0)
  231188. owner->redirectMouseEnter (ev);
  231189. }
  231190. - (void) mouseExited: (NSEvent*) ev
  231191. {
  231192. if (owner != 0)
  231193. owner->redirectMouseExit (ev);
  231194. }
  231195. - (void) rightMouseDown: (NSEvent*) ev
  231196. {
  231197. [self mouseDown: ev];
  231198. }
  231199. - (void) rightMouseDragged: (NSEvent*) ev
  231200. {
  231201. [self mouseDragged: ev];
  231202. }
  231203. - (void) rightMouseUp: (NSEvent*) ev
  231204. {
  231205. [self mouseUp: ev];
  231206. }
  231207. - (void) otherMouseDown: (NSEvent*) ev
  231208. {
  231209. [self mouseDown: ev];
  231210. }
  231211. - (void) otherMouseDragged: (NSEvent*) ev
  231212. {
  231213. [self mouseDragged: ev];
  231214. }
  231215. - (void) otherMouseUp: (NSEvent*) ev
  231216. {
  231217. [self mouseUp: ev];
  231218. }
  231219. - (void) scrollWheel: (NSEvent*) ev
  231220. {
  231221. if (owner != 0)
  231222. owner->redirectMouseWheel (ev);
  231223. }
  231224. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231225. {
  231226. (void) ev;
  231227. return YES;
  231228. }
  231229. - (void) frameChanged: (NSNotification*) n
  231230. {
  231231. (void) n;
  231232. if (owner != 0)
  231233. owner->redirectMovedOrResized();
  231234. }
  231235. - (void) viewDidMoveToWindow
  231236. {
  231237. if (owner != 0)
  231238. owner->viewMovedToWindow();
  231239. }
  231240. - (void) asyncRepaint: (id) rect
  231241. {
  231242. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231243. [self setNeedsDisplayInRect: *r];
  231244. }
  231245. - (void) keyDown: (NSEvent*) ev
  231246. {
  231247. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231248. textWasInserted = false;
  231249. if (target != 0)
  231250. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231251. else
  231252. deleteAndZero (stringBeingComposed);
  231253. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231254. [super keyDown: ev];
  231255. }
  231256. - (void) keyUp: (NSEvent*) ev
  231257. {
  231258. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231259. [super keyUp: ev];
  231260. }
  231261. - (void) insertText: (id) aString
  231262. {
  231263. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231264. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231265. if ([newText length] > 0)
  231266. {
  231267. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231268. if (target != 0)
  231269. {
  231270. target->insertTextAtCaret (nsStringToJuce (newText));
  231271. textWasInserted = true;
  231272. }
  231273. }
  231274. deleteAndZero (stringBeingComposed);
  231275. }
  231276. - (void) doCommandBySelector: (SEL) aSelector
  231277. {
  231278. (void) aSelector;
  231279. }
  231280. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231281. {
  231282. (void) selectionRange;
  231283. if (stringBeingComposed == 0)
  231284. stringBeingComposed = new String();
  231285. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231286. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231287. if (target != 0)
  231288. {
  231289. const Range<int> currentHighlight (target->getHighlightedRegion());
  231290. target->insertTextAtCaret (*stringBeingComposed);
  231291. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231292. textWasInserted = true;
  231293. }
  231294. }
  231295. - (void) unmarkText
  231296. {
  231297. if (stringBeingComposed != 0)
  231298. {
  231299. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231300. if (target != 0)
  231301. {
  231302. target->insertTextAtCaret (*stringBeingComposed);
  231303. textWasInserted = true;
  231304. }
  231305. }
  231306. deleteAndZero (stringBeingComposed);
  231307. }
  231308. - (BOOL) hasMarkedText
  231309. {
  231310. return stringBeingComposed != 0;
  231311. }
  231312. - (long) conversationIdentifier
  231313. {
  231314. return (long) (pointer_sized_int) self;
  231315. }
  231316. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231317. {
  231318. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231319. if (target != 0)
  231320. {
  231321. const Range<int> r ((int) theRange.location,
  231322. (int) (theRange.location + theRange.length));
  231323. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231324. }
  231325. return nil;
  231326. }
  231327. - (NSRange) markedRange
  231328. {
  231329. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231330. : NSMakeRange (NSNotFound, 0);
  231331. }
  231332. - (NSRange) selectedRange
  231333. {
  231334. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231335. if (target != 0)
  231336. {
  231337. const Range<int> highlight (target->getHighlightedRegion());
  231338. if (! highlight.isEmpty())
  231339. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231340. }
  231341. return NSMakeRange (NSNotFound, 0);
  231342. }
  231343. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231344. {
  231345. (void) theRange;
  231346. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231347. if (comp == 0)
  231348. return NSMakeRect (0, 0, 0, 0);
  231349. const Rectangle<int> bounds (comp->getScreenBounds());
  231350. return NSMakeRect (bounds.getX(),
  231351. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231352. bounds.getWidth(),
  231353. bounds.getHeight());
  231354. }
  231355. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231356. {
  231357. (void) thePoint;
  231358. return NSNotFound;
  231359. }
  231360. - (NSArray*) validAttributesForMarkedText
  231361. {
  231362. return [NSArray array];
  231363. }
  231364. - (void) flagsChanged: (NSEvent*) ev
  231365. {
  231366. if (owner != 0)
  231367. owner->redirectModKeyChange (ev);
  231368. }
  231369. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231370. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231371. {
  231372. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231373. return true;
  231374. return [super performKeyEquivalent: ev];
  231375. }
  231376. #endif
  231377. - (BOOL) becomeFirstResponder
  231378. {
  231379. if (owner != 0)
  231380. owner->viewFocusGain();
  231381. return true;
  231382. }
  231383. - (BOOL) resignFirstResponder
  231384. {
  231385. if (owner != 0)
  231386. owner->viewFocusLoss();
  231387. return true;
  231388. }
  231389. - (BOOL) acceptsFirstResponder
  231390. {
  231391. return owner != 0 && owner->canBecomeKeyWindow();
  231392. }
  231393. - (NSArray*) getSupportedDragTypes
  231394. {
  231395. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231396. }
  231397. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231398. {
  231399. return owner != 0 && owner->sendDragCallback (type, sender);
  231400. }
  231401. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231402. {
  231403. if ([self sendDragCallback: 0 sender: sender])
  231404. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231405. else
  231406. return NSDragOperationNone;
  231407. }
  231408. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231409. {
  231410. if ([self sendDragCallback: 0 sender: sender])
  231411. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231412. else
  231413. return NSDragOperationNone;
  231414. }
  231415. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231416. {
  231417. [self sendDragCallback: 1 sender: sender];
  231418. }
  231419. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231420. {
  231421. [self sendDragCallback: 1 sender: sender];
  231422. }
  231423. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231424. {
  231425. (void) sender;
  231426. return YES;
  231427. }
  231428. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231429. {
  231430. return [self sendDragCallback: 2 sender: sender];
  231431. }
  231432. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231433. {
  231434. (void) sender;
  231435. }
  231436. @end
  231437. @implementation JuceNSWindow
  231438. - (void) setOwner: (NSViewComponentPeer*) owner_
  231439. {
  231440. owner = owner_;
  231441. isZooming = false;
  231442. }
  231443. - (BOOL) canBecomeKeyWindow
  231444. {
  231445. return owner != 0 && owner->canBecomeKeyWindow();
  231446. }
  231447. - (void) becomeKeyWindow
  231448. {
  231449. [super becomeKeyWindow];
  231450. if (owner != 0)
  231451. owner->grabFocus();
  231452. }
  231453. - (BOOL) windowShouldClose: (id) window
  231454. {
  231455. (void) window;
  231456. return owner == 0 || owner->windowShouldClose();
  231457. }
  231458. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231459. {
  231460. (void) screen;
  231461. if (owner != 0)
  231462. frameRect = owner->constrainRect (frameRect);
  231463. return frameRect;
  231464. }
  231465. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231466. {
  231467. (void) window;
  231468. if (isZooming)
  231469. return proposedFrameSize;
  231470. NSRect frameRect = [self frame];
  231471. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231472. frameRect.size = proposedFrameSize;
  231473. if (owner != 0)
  231474. frameRect = owner->constrainRect (frameRect);
  231475. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231476. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231477. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231478. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231479. return frameRect.size;
  231480. }
  231481. - (void) zoom: (id) sender
  231482. {
  231483. isZooming = true;
  231484. [super zoom: sender];
  231485. isZooming = false;
  231486. }
  231487. - (void) windowWillMove: (NSNotification*) notification
  231488. {
  231489. (void) notification;
  231490. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231491. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231492. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231493. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231494. }
  231495. @end
  231496. BEGIN_JUCE_NAMESPACE
  231497. ModifierKeys NSViewComponentPeer::currentModifiers;
  231498. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231499. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231500. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231501. {
  231502. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231503. return true;
  231504. if (keyCode >= 'A' && keyCode <= 'Z'
  231505. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231506. return true;
  231507. if (keyCode >= 'a' && keyCode <= 'z'
  231508. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231509. return true;
  231510. return false;
  231511. }
  231512. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231513. {
  231514. int m = 0;
  231515. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231516. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231517. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231518. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231519. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231520. }
  231521. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231522. {
  231523. updateModifiers (ev);
  231524. int keyCode = getKeyCodeFromEvent (ev);
  231525. if (keyCode != 0)
  231526. {
  231527. if (isKeyDown)
  231528. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231529. else
  231530. keysCurrentlyDown.removeValue (keyCode);
  231531. }
  231532. }
  231533. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231534. {
  231535. return NSViewComponentPeer::currentModifiers;
  231536. }
  231537. void ModifierKeys::updateCurrentModifiers() throw()
  231538. {
  231539. currentModifiers = NSViewComponentPeer::currentModifiers;
  231540. }
  231541. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231542. const int windowStyleFlags,
  231543. NSView* viewToAttachTo)
  231544. : ComponentPeer (component_, windowStyleFlags),
  231545. window (0),
  231546. view (0),
  231547. isSharedWindow (viewToAttachTo != 0),
  231548. fullScreen (false),
  231549. insideDrawRect (false),
  231550. #if USE_COREGRAPHICS_RENDERING
  231551. usingCoreGraphics (true),
  231552. #else
  231553. usingCoreGraphics (false),
  231554. #endif
  231555. recursiveToFrontCall (false)
  231556. {
  231557. NSRect r;
  231558. r.origin.x = 0;
  231559. r.origin.y = 0;
  231560. r.size.width = (float) component->getWidth();
  231561. r.size.height = (float) component->getHeight();
  231562. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231563. [view setPostsFrameChangedNotifications: YES];
  231564. if (isSharedWindow)
  231565. {
  231566. window = [viewToAttachTo window];
  231567. [viewToAttachTo addSubview: view];
  231568. setVisible (component->isVisible());
  231569. }
  231570. else
  231571. {
  231572. r.origin.x = (float) component->getX();
  231573. r.origin.y = (float) component->getY();
  231574. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231575. unsigned int style = 0;
  231576. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231577. style = NSBorderlessWindowMask;
  231578. else
  231579. style = NSTitledWindowMask;
  231580. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231581. style |= NSMiniaturizableWindowMask;
  231582. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231583. style |= NSClosableWindowMask;
  231584. if ((windowStyleFlags & windowIsResizable) != 0)
  231585. style |= NSResizableWindowMask;
  231586. window = [[JuceNSWindow alloc] initWithContentRect: r
  231587. styleMask: style
  231588. backing: NSBackingStoreBuffered
  231589. defer: YES];
  231590. [((JuceNSWindow*) window) setOwner: this];
  231591. [window orderOut: nil];
  231592. [window setDelegate: (JuceNSWindow*) window];
  231593. [window setOpaque: component->isOpaque()];
  231594. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231595. if (component->isAlwaysOnTop())
  231596. [window setLevel: NSFloatingWindowLevel];
  231597. [window setContentView: view];
  231598. [window setAutodisplay: YES];
  231599. [window setAcceptsMouseMovedEvents: YES];
  231600. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231601. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231602. [window setReleasedWhenClosed: YES];
  231603. [window retain];
  231604. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231605. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231606. }
  231607. setTitle (component->getName());
  231608. }
  231609. NSViewComponentPeer::~NSViewComponentPeer()
  231610. {
  231611. view->owner = 0;
  231612. [view removeFromSuperview];
  231613. [view release];
  231614. if (! isSharedWindow)
  231615. {
  231616. [((JuceNSWindow*) window) setOwner: 0];
  231617. [window close];
  231618. [window release];
  231619. }
  231620. }
  231621. void* NSViewComponentPeer::getNativeHandle() const
  231622. {
  231623. return view;
  231624. }
  231625. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231626. {
  231627. if (isSharedWindow)
  231628. {
  231629. [view setHidden: ! shouldBeVisible];
  231630. }
  231631. else
  231632. {
  231633. if (shouldBeVisible)
  231634. {
  231635. [window orderFront: nil];
  231636. handleBroughtToFront();
  231637. }
  231638. else
  231639. {
  231640. [window orderOut: nil];
  231641. }
  231642. }
  231643. }
  231644. void NSViewComponentPeer::setTitle (const String& title)
  231645. {
  231646. const ScopedAutoReleasePool pool;
  231647. if (! isSharedWindow)
  231648. [window setTitle: juceStringToNS (title)];
  231649. }
  231650. void NSViewComponentPeer::setPosition (int x, int y)
  231651. {
  231652. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231653. }
  231654. void NSViewComponentPeer::setSize (int w, int h)
  231655. {
  231656. setBounds (component->getX(), component->getY(), w, h, false);
  231657. }
  231658. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231659. {
  231660. fullScreen = isNowFullScreen;
  231661. w = jmax (0, w);
  231662. h = jmax (0, h);
  231663. NSRect r;
  231664. r.origin.x = (float) x;
  231665. r.origin.y = (float) y;
  231666. r.size.width = (float) w;
  231667. r.size.height = (float) h;
  231668. if (isSharedWindow)
  231669. {
  231670. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231671. if ([view frame].size.width != r.size.width
  231672. || [view frame].size.height != r.size.height)
  231673. [view setNeedsDisplay: true];
  231674. [view setFrame: r];
  231675. }
  231676. else
  231677. {
  231678. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231679. [window setFrame: [window frameRectForContentRect: r]
  231680. display: true];
  231681. }
  231682. }
  231683. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231684. {
  231685. NSRect r = [view frame];
  231686. if (global && [view window] != 0)
  231687. {
  231688. r = [view convertRect: r toView: nil];
  231689. NSRect wr = [[view window] frame];
  231690. r.origin.x += wr.origin.x;
  231691. r.origin.y += wr.origin.y;
  231692. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231693. }
  231694. else
  231695. {
  231696. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231697. }
  231698. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  231699. }
  231700. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231701. {
  231702. return getBounds (! isSharedWindow);
  231703. }
  231704. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231705. {
  231706. return getBounds (true).getPosition();
  231707. }
  231708. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  231709. {
  231710. return relativePosition + getScreenPosition();
  231711. }
  231712. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  231713. {
  231714. return screenPosition - getScreenPosition();
  231715. }
  231716. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231717. {
  231718. if (constrainer != 0)
  231719. {
  231720. NSRect current = [window frame];
  231721. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231722. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231723. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  231724. (int) r.size.width, (int) r.size.height);
  231725. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  231726. (int) current.size.width, (int) current.size.height);
  231727. constrainer->checkBounds (pos, original,
  231728. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231729. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231730. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231731. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231732. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231733. r.origin.x = pos.getX();
  231734. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231735. r.size.width = pos.getWidth();
  231736. r.size.height = pos.getHeight();
  231737. }
  231738. return r;
  231739. }
  231740. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231741. {
  231742. if (! isSharedWindow)
  231743. {
  231744. if (shouldBeMinimised)
  231745. [window miniaturize: nil];
  231746. else
  231747. [window deminiaturize: nil];
  231748. }
  231749. }
  231750. bool NSViewComponentPeer::isMinimised() const
  231751. {
  231752. return window != 0 && [window isMiniaturized];
  231753. }
  231754. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231755. {
  231756. if (! isSharedWindow)
  231757. {
  231758. Rectangle<int> r (lastNonFullscreenBounds);
  231759. setMinimised (false);
  231760. if (fullScreen != shouldBeFullScreen)
  231761. {
  231762. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231763. {
  231764. fullScreen = true;
  231765. [window performZoom: nil];
  231766. }
  231767. else
  231768. {
  231769. if (shouldBeFullScreen)
  231770. r = Desktop::getInstance().getMainMonitorArea();
  231771. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231772. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231773. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231774. }
  231775. }
  231776. }
  231777. }
  231778. bool NSViewComponentPeer::isFullScreen() const
  231779. {
  231780. return fullScreen;
  231781. }
  231782. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231783. {
  231784. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  231785. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  231786. return false;
  231787. NSPoint p;
  231788. p.x = (float) position.getX();
  231789. p.y = (float) position.getY();
  231790. NSView* v = [view hitTest: p];
  231791. if (trueIfInAChildWindow)
  231792. return v != nil;
  231793. return v == view;
  231794. }
  231795. const BorderSize NSViewComponentPeer::getFrameSize() const
  231796. {
  231797. BorderSize b;
  231798. if (! isSharedWindow)
  231799. {
  231800. NSRect v = [view convertRect: [view frame] toView: nil];
  231801. NSRect w = [window frame];
  231802. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231803. b.setBottom ((int) v.origin.y);
  231804. b.setLeft ((int) v.origin.x);
  231805. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231806. }
  231807. return b;
  231808. }
  231809. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231810. {
  231811. if (! isSharedWindow)
  231812. {
  231813. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231814. : NSNormalWindowLevel];
  231815. }
  231816. return true;
  231817. }
  231818. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231819. {
  231820. if (isSharedWindow)
  231821. {
  231822. [[view superview] addSubview: view
  231823. positioned: NSWindowAbove
  231824. relativeTo: nil];
  231825. }
  231826. if (window != 0 && component->isVisible())
  231827. {
  231828. if (makeActiveWindow)
  231829. [window makeKeyAndOrderFront: nil];
  231830. else
  231831. [window orderFront: nil];
  231832. if (! recursiveToFrontCall)
  231833. {
  231834. recursiveToFrontCall = true;
  231835. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231836. handleBroughtToFront();
  231837. recursiveToFrontCall = false;
  231838. }
  231839. }
  231840. }
  231841. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231842. {
  231843. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231844. jassert (otherPeer != 0); // wrong type of window?
  231845. if (otherPeer != 0)
  231846. {
  231847. if (isSharedWindow)
  231848. {
  231849. [[view superview] addSubview: view
  231850. positioned: NSWindowBelow
  231851. relativeTo: otherPeer->view];
  231852. }
  231853. else
  231854. {
  231855. [window orderWindow: NSWindowBelow
  231856. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231857. : nil ];
  231858. }
  231859. }
  231860. }
  231861. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231862. {
  231863. // to do..
  231864. }
  231865. void NSViewComponentPeer::viewFocusGain()
  231866. {
  231867. if (currentlyFocusedPeer != this)
  231868. {
  231869. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231870. currentlyFocusedPeer->handleFocusLoss();
  231871. currentlyFocusedPeer = this;
  231872. handleFocusGain();
  231873. }
  231874. }
  231875. void NSViewComponentPeer::viewFocusLoss()
  231876. {
  231877. if (currentlyFocusedPeer == this)
  231878. {
  231879. currentlyFocusedPeer = 0;
  231880. handleFocusLoss();
  231881. }
  231882. }
  231883. void juce_HandleProcessFocusChange()
  231884. {
  231885. NSViewComponentPeer::keysCurrentlyDown.clear();
  231886. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231887. {
  231888. if (Process::isForegroundProcess())
  231889. {
  231890. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231891. ComponentPeer::bringModalComponentToFront();
  231892. }
  231893. else
  231894. {
  231895. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231896. // turn kiosk mode off if we lose focus..
  231897. Desktop::getInstance().setKioskModeComponent (0);
  231898. }
  231899. }
  231900. }
  231901. bool NSViewComponentPeer::isFocused() const
  231902. {
  231903. return isSharedWindow ? this == currentlyFocusedPeer
  231904. : (window != 0 && [window isKeyWindow]);
  231905. }
  231906. void NSViewComponentPeer::grabFocus()
  231907. {
  231908. if (window != 0)
  231909. {
  231910. [window makeKeyWindow];
  231911. [window makeFirstResponder: view];
  231912. viewFocusGain();
  231913. }
  231914. }
  231915. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231916. {
  231917. }
  231918. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231919. {
  231920. String unicode (nsStringToJuce ([ev characters]));
  231921. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231922. int keyCode = getKeyCodeFromEvent (ev);
  231923. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231924. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231925. if (unicode.isNotEmpty() || keyCode != 0)
  231926. {
  231927. if (isKeyDown)
  231928. {
  231929. bool used = false;
  231930. while (unicode.length() > 0)
  231931. {
  231932. juce_wchar textCharacter = unicode[0];
  231933. unicode = unicode.substring (1);
  231934. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231935. textCharacter = 0;
  231936. used = handleKeyUpOrDown (true) || used;
  231937. used = handleKeyPress (keyCode, textCharacter) || used;
  231938. }
  231939. return used;
  231940. }
  231941. else
  231942. {
  231943. if (handleKeyUpOrDown (false))
  231944. return true;
  231945. }
  231946. }
  231947. return false;
  231948. }
  231949. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231950. {
  231951. updateKeysDown (ev, true);
  231952. bool used = handleKeyEvent (ev, true);
  231953. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231954. {
  231955. // for command keys, the key-up event is thrown away, so simulate one..
  231956. updateKeysDown (ev, false);
  231957. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231958. }
  231959. // (If we're running modally, don't allow unused keystrokes to be passed
  231960. // along to other blocked views..)
  231961. if (Component::getCurrentlyModalComponent() != 0)
  231962. used = true;
  231963. return used;
  231964. }
  231965. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231966. {
  231967. updateKeysDown (ev, false);
  231968. return handleKeyEvent (ev, false)
  231969. || Component::getCurrentlyModalComponent() != 0;
  231970. }
  231971. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231972. {
  231973. keysCurrentlyDown.clear();
  231974. handleKeyUpOrDown (true);
  231975. updateModifiers (ev);
  231976. handleModifierKeysChange();
  231977. }
  231978. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231979. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231980. {
  231981. if ([ev type] == NSKeyDown)
  231982. return redirectKeyDown (ev);
  231983. else if ([ev type] == NSKeyUp)
  231984. return redirectKeyUp (ev);
  231985. return false;
  231986. }
  231987. #endif
  231988. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231989. {
  231990. updateModifiers (ev);
  231991. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231992. }
  231993. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231994. {
  231995. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231996. sendMouseEvent (ev);
  231997. }
  231998. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231999. {
  232000. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232001. sendMouseEvent (ev);
  232002. showArrowCursorIfNeeded();
  232003. }
  232004. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232005. {
  232006. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232007. sendMouseEvent (ev);
  232008. }
  232009. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232010. {
  232011. currentModifiers = currentModifiers.withoutMouseButtons();
  232012. sendMouseEvent (ev);
  232013. showArrowCursorIfNeeded();
  232014. }
  232015. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232016. {
  232017. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232018. currentModifiers = currentModifiers.withoutMouseButtons();
  232019. sendMouseEvent (ev);
  232020. }
  232021. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232022. {
  232023. currentModifiers = currentModifiers.withoutMouseButtons();
  232024. sendMouseEvent (ev);
  232025. }
  232026. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232027. {
  232028. updateModifiers (ev);
  232029. float x = 0, y = 0;
  232030. @try
  232031. {
  232032. x = [ev deviceDeltaX] * 0.5f;
  232033. y = [ev deviceDeltaY] * 0.5f;
  232034. }
  232035. @catch (...)
  232036. {}
  232037. if (x == 0 && y == 0)
  232038. {
  232039. x = [ev deltaX] * 10.0f;
  232040. y = [ev deltaY] * 10.0f;
  232041. }
  232042. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232043. }
  232044. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232045. {
  232046. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232047. if (mouse.getComponentUnderMouse() == 0
  232048. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232049. {
  232050. [[NSCursor arrowCursor] set];
  232051. }
  232052. }
  232053. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232054. {
  232055. NSString* bestType
  232056. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232057. if (bestType == nil)
  232058. return false;
  232059. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232060. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232061. StringArray files;
  232062. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232063. if (list == nil)
  232064. return false;
  232065. if ([list isKindOfClass: [NSArray class]])
  232066. {
  232067. NSArray* items = (NSArray*) list;
  232068. for (unsigned int i = 0; i < [items count]; ++i)
  232069. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232070. }
  232071. if (files.size() == 0)
  232072. return false;
  232073. if (type == 0)
  232074. handleFileDragMove (files, pos);
  232075. else if (type == 1)
  232076. handleFileDragExit (files);
  232077. else if (type == 2)
  232078. handleFileDragDrop (files, pos);
  232079. return true;
  232080. }
  232081. bool NSViewComponentPeer::isOpaque()
  232082. {
  232083. return component == 0 || component->isOpaque();
  232084. }
  232085. void NSViewComponentPeer::drawRect (NSRect r)
  232086. {
  232087. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232088. return;
  232089. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232090. if (! component->isOpaque())
  232091. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232092. #if USE_COREGRAPHICS_RENDERING
  232093. if (usingCoreGraphics)
  232094. {
  232095. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232096. insideDrawRect = true;
  232097. handlePaint (context);
  232098. insideDrawRect = false;
  232099. }
  232100. else
  232101. #endif
  232102. {
  232103. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232104. (int) (r.size.width + 0.5f),
  232105. (int) (r.size.height + 0.5f),
  232106. ! getComponent()->isOpaque());
  232107. const int xOffset = -roundToInt (r.origin.x);
  232108. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232109. const NSRect* rects = 0;
  232110. NSInteger numRects = 0;
  232111. [view getRectsBeingDrawn: &rects count: &numRects];
  232112. const Rectangle<int> clipBounds (temp.getBounds());
  232113. RectangleList clip;
  232114. for (int i = 0; i < numRects; ++i)
  232115. {
  232116. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232117. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232118. roundToInt (rects[i].size.width),
  232119. roundToInt (rects[i].size.height))));
  232120. }
  232121. if (! clip.isEmpty())
  232122. {
  232123. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232124. insideDrawRect = true;
  232125. handlePaint (context);
  232126. insideDrawRect = false;
  232127. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232128. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232129. CGColorSpaceRelease (colourSpace);
  232130. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232131. CGImageRelease (image);
  232132. }
  232133. }
  232134. }
  232135. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232136. {
  232137. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232138. #if USE_COREGRAPHICS_RENDERING
  232139. s.add ("CoreGraphics Renderer");
  232140. #endif
  232141. return s;
  232142. }
  232143. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232144. {
  232145. return usingCoreGraphics ? 1 : 0;
  232146. }
  232147. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232148. {
  232149. #if USE_COREGRAPHICS_RENDERING
  232150. if (usingCoreGraphics != (index > 0))
  232151. {
  232152. usingCoreGraphics = index > 0;
  232153. [view setNeedsDisplay: true];
  232154. }
  232155. #endif
  232156. }
  232157. bool NSViewComponentPeer::canBecomeKeyWindow()
  232158. {
  232159. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232160. }
  232161. bool NSViewComponentPeer::windowShouldClose()
  232162. {
  232163. if (! isValidPeer (this))
  232164. return YES;
  232165. handleUserClosingWindow();
  232166. return NO;
  232167. }
  232168. void NSViewComponentPeer::redirectMovedOrResized()
  232169. {
  232170. handleMovedOrResized();
  232171. }
  232172. void NSViewComponentPeer::viewMovedToWindow()
  232173. {
  232174. if (isSharedWindow)
  232175. window = [view window];
  232176. }
  232177. void Desktop::createMouseInputSources()
  232178. {
  232179. mouseSources.add (new MouseInputSource (0, true));
  232180. }
  232181. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232182. {
  232183. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232184. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232185. // is apparently still available in 64-bit apps..
  232186. if (enableOrDisable)
  232187. {
  232188. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232189. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232190. }
  232191. else
  232192. {
  232193. SetSystemUIMode (kUIModeNormal, 0);
  232194. }
  232195. }
  232196. class AsyncRepaintMessage : public CallbackMessage
  232197. {
  232198. public:
  232199. NSViewComponentPeer* const peer;
  232200. const Rectangle<int> rect;
  232201. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232202. : peer (peer_), rect (rect_)
  232203. {
  232204. }
  232205. void messageCallback()
  232206. {
  232207. if (ComponentPeer::isValidPeer (peer))
  232208. peer->repaint (rect);
  232209. }
  232210. };
  232211. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232212. {
  232213. if (insideDrawRect)
  232214. {
  232215. (new AsyncRepaintMessage (this, area))->post();
  232216. }
  232217. else
  232218. {
  232219. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232220. (float) area.getWidth(), (float) area.getHeight())];
  232221. }
  232222. }
  232223. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232224. {
  232225. [view displayIfNeeded];
  232226. }
  232227. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232228. {
  232229. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232230. }
  232231. const Image juce_createIconForFile (const File& file)
  232232. {
  232233. const ScopedAutoReleasePool pool;
  232234. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232235. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232236. [NSGraphicsContext saveGraphicsState];
  232237. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232238. [image drawAtPoint: NSMakePoint (0, 0)
  232239. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232240. operation: NSCompositeSourceOver fraction: 1.0f];
  232241. [[NSGraphicsContext currentContext] flushGraphics];
  232242. [NSGraphicsContext restoreGraphicsState];
  232243. return Image (result);
  232244. }
  232245. const int KeyPress::spaceKey = ' ';
  232246. const int KeyPress::returnKey = 0x0d;
  232247. const int KeyPress::escapeKey = 0x1b;
  232248. const int KeyPress::backspaceKey = 0x7f;
  232249. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232250. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232251. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232252. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232253. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232254. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232255. const int KeyPress::endKey = NSEndFunctionKey;
  232256. const int KeyPress::homeKey = NSHomeFunctionKey;
  232257. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232258. const int KeyPress::insertKey = -1;
  232259. const int KeyPress::tabKey = 9;
  232260. const int KeyPress::F1Key = NSF1FunctionKey;
  232261. const int KeyPress::F2Key = NSF2FunctionKey;
  232262. const int KeyPress::F3Key = NSF3FunctionKey;
  232263. const int KeyPress::F4Key = NSF4FunctionKey;
  232264. const int KeyPress::F5Key = NSF5FunctionKey;
  232265. const int KeyPress::F6Key = NSF6FunctionKey;
  232266. const int KeyPress::F7Key = NSF7FunctionKey;
  232267. const int KeyPress::F8Key = NSF8FunctionKey;
  232268. const int KeyPress::F9Key = NSF9FunctionKey;
  232269. const int KeyPress::F10Key = NSF10FunctionKey;
  232270. const int KeyPress::F11Key = NSF1FunctionKey;
  232271. const int KeyPress::F12Key = NSF12FunctionKey;
  232272. const int KeyPress::F13Key = NSF13FunctionKey;
  232273. const int KeyPress::F14Key = NSF14FunctionKey;
  232274. const int KeyPress::F15Key = NSF15FunctionKey;
  232275. const int KeyPress::F16Key = NSF16FunctionKey;
  232276. const int KeyPress::numberPad0 = 0x30020;
  232277. const int KeyPress::numberPad1 = 0x30021;
  232278. const int KeyPress::numberPad2 = 0x30022;
  232279. const int KeyPress::numberPad3 = 0x30023;
  232280. const int KeyPress::numberPad4 = 0x30024;
  232281. const int KeyPress::numberPad5 = 0x30025;
  232282. const int KeyPress::numberPad6 = 0x30026;
  232283. const int KeyPress::numberPad7 = 0x30027;
  232284. const int KeyPress::numberPad8 = 0x30028;
  232285. const int KeyPress::numberPad9 = 0x30029;
  232286. const int KeyPress::numberPadAdd = 0x3002a;
  232287. const int KeyPress::numberPadSubtract = 0x3002b;
  232288. const int KeyPress::numberPadMultiply = 0x3002c;
  232289. const int KeyPress::numberPadDivide = 0x3002d;
  232290. const int KeyPress::numberPadSeparator = 0x3002e;
  232291. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232292. const int KeyPress::numberPadEquals = 0x30030;
  232293. const int KeyPress::numberPadDelete = 0x30031;
  232294. const int KeyPress::playKey = 0x30000;
  232295. const int KeyPress::stopKey = 0x30001;
  232296. const int KeyPress::fastForwardKey = 0x30002;
  232297. const int KeyPress::rewindKey = 0x30003;
  232298. #endif
  232299. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232300. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232301. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232302. // compiled on its own).
  232303. #if JUCE_INCLUDED_FILE
  232304. #if JUCE_MAC
  232305. namespace MouseCursorHelpers
  232306. {
  232307. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232308. {
  232309. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232310. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232311. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232312. [im release];
  232313. return c;
  232314. }
  232315. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232316. {
  232317. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232318. BufferedInputStream buf (&fileStream, 4096, false);
  232319. PNGImageFormat pngFormat;
  232320. Image im (pngFormat.decodeImage (buf));
  232321. if (im.isValid())
  232322. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232323. jassertfalse;
  232324. return 0;
  232325. }
  232326. }
  232327. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232328. {
  232329. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232330. }
  232331. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232332. {
  232333. const ScopedAutoReleasePool pool;
  232334. NSCursor* c = 0;
  232335. switch (type)
  232336. {
  232337. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232338. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232339. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232340. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232341. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232342. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232343. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232344. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232345. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232346. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232347. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232348. case UpDownResizeCursor:
  232349. case TopEdgeResizeCursor:
  232350. case BottomEdgeResizeCursor:
  232351. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232352. case TopLeftCornerResizeCursor:
  232353. case BottomRightCornerResizeCursor:
  232354. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232355. case TopRightCornerResizeCursor:
  232356. case BottomLeftCornerResizeCursor:
  232357. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232358. case UpDownLeftRightResizeCursor:
  232359. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232360. default:
  232361. jassertfalse;
  232362. break;
  232363. }
  232364. [c retain];
  232365. return c;
  232366. }
  232367. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232368. {
  232369. [((NSCursor*) cursorHandle) release];
  232370. }
  232371. void MouseCursor::showInAllWindows() const
  232372. {
  232373. showInWindow (0);
  232374. }
  232375. void MouseCursor::showInWindow (ComponentPeer*) const
  232376. {
  232377. [((NSCursor*) getHandle()) set];
  232378. }
  232379. #else
  232380. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232381. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232382. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232383. void MouseCursor::showInAllWindows() const {}
  232384. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232385. #endif
  232386. #endif
  232387. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232388. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232389. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232390. // compiled on its own).
  232391. #if JUCE_INCLUDED_FILE
  232392. class NSViewComponentInternal : public ComponentMovementWatcher
  232393. {
  232394. Component* const owner;
  232395. NSViewComponentPeer* currentPeer;
  232396. bool wasShowing;
  232397. public:
  232398. NSView* const view;
  232399. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232400. : ComponentMovementWatcher (owner_),
  232401. owner (owner_),
  232402. currentPeer (0),
  232403. wasShowing (false),
  232404. view (view_)
  232405. {
  232406. [view_ retain];
  232407. if (owner_->isShowing())
  232408. componentPeerChanged();
  232409. }
  232410. ~NSViewComponentInternal()
  232411. {
  232412. [view removeFromSuperview];
  232413. [view release];
  232414. }
  232415. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232416. {
  232417. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232418. // The ComponentMovementWatcher version of this method avoids calling
  232419. // us when the top-level comp is resized, but for an NSView we need to know this
  232420. // because with inverted co-ords, we need to update the position even if the
  232421. // top-left pos hasn't changed
  232422. if (comp.isOnDesktop() && wasResized)
  232423. componentMovedOrResized (wasMoved, wasResized);
  232424. }
  232425. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232426. {
  232427. Component* const topComp = owner->getTopLevelComponent();
  232428. if (topComp->getPeer() != 0)
  232429. {
  232430. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232431. NSRect r;
  232432. r.origin.x = (float) pos.getX();
  232433. r.origin.y = (float) pos.getY();
  232434. r.size.width = (float) owner->getWidth();
  232435. r.size.height = (float) owner->getHeight();
  232436. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232437. [view setFrame: r];
  232438. }
  232439. }
  232440. void componentPeerChanged()
  232441. {
  232442. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232443. if (currentPeer != peer)
  232444. {
  232445. [view removeFromSuperview];
  232446. currentPeer = peer;
  232447. if (peer != 0)
  232448. {
  232449. [peer->view addSubview: view];
  232450. componentMovedOrResized (false, false);
  232451. }
  232452. }
  232453. [view setHidden: ! owner->isShowing()];
  232454. }
  232455. void componentVisibilityChanged (Component&)
  232456. {
  232457. componentPeerChanged();
  232458. }
  232459. juce_UseDebuggingNewOperator
  232460. private:
  232461. NSViewComponentInternal (const NSViewComponentInternal&);
  232462. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232463. };
  232464. NSViewComponent::NSViewComponent()
  232465. {
  232466. }
  232467. NSViewComponent::~NSViewComponent()
  232468. {
  232469. }
  232470. void NSViewComponent::setView (void* view)
  232471. {
  232472. if (view != getView())
  232473. {
  232474. if (view != 0)
  232475. info = new NSViewComponentInternal ((NSView*) view, this);
  232476. else
  232477. info = 0;
  232478. }
  232479. }
  232480. void* NSViewComponent::getView() const
  232481. {
  232482. return info == 0 ? 0 : info->view;
  232483. }
  232484. void NSViewComponent::paint (Graphics&)
  232485. {
  232486. }
  232487. #endif
  232488. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232489. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232490. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232491. // compiled on its own).
  232492. #if JUCE_INCLUDED_FILE
  232493. AppleRemoteDevice::AppleRemoteDevice()
  232494. : device (0),
  232495. queue (0),
  232496. remoteId (0)
  232497. {
  232498. }
  232499. AppleRemoteDevice::~AppleRemoteDevice()
  232500. {
  232501. stop();
  232502. }
  232503. static io_object_t getAppleRemoteDevice()
  232504. {
  232505. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232506. io_iterator_t iter = 0;
  232507. io_object_t iod = 0;
  232508. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232509. && iter != 0)
  232510. {
  232511. iod = IOIteratorNext (iter);
  232512. }
  232513. IOObjectRelease (iter);
  232514. return iod;
  232515. }
  232516. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232517. {
  232518. jassert (*device == 0);
  232519. io_name_t classname;
  232520. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232521. {
  232522. IOCFPlugInInterface** cfPlugInInterface = 0;
  232523. SInt32 score = 0;
  232524. if (IOCreatePlugInInterfaceForService (iod,
  232525. kIOHIDDeviceUserClientTypeID,
  232526. kIOCFPlugInInterfaceID,
  232527. &cfPlugInInterface,
  232528. &score) == kIOReturnSuccess)
  232529. {
  232530. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232531. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232532. device);
  232533. (void) hr;
  232534. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232535. }
  232536. }
  232537. return *device != 0;
  232538. }
  232539. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232540. {
  232541. if (queue != 0)
  232542. return true;
  232543. stop();
  232544. bool result = false;
  232545. io_object_t iod = getAppleRemoteDevice();
  232546. if (iod != 0)
  232547. {
  232548. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232549. result = true;
  232550. else
  232551. stop();
  232552. IOObjectRelease (iod);
  232553. }
  232554. return result;
  232555. }
  232556. void AppleRemoteDevice::stop()
  232557. {
  232558. if (queue != 0)
  232559. {
  232560. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232561. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232562. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232563. queue = 0;
  232564. }
  232565. if (device != 0)
  232566. {
  232567. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232568. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232569. device = 0;
  232570. }
  232571. }
  232572. bool AppleRemoteDevice::isActive() const
  232573. {
  232574. return queue != 0;
  232575. }
  232576. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232577. {
  232578. if (result == kIOReturnSuccess)
  232579. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232580. }
  232581. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232582. {
  232583. Array <int> cookies;
  232584. CFArrayRef elements;
  232585. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232586. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232587. return false;
  232588. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232589. {
  232590. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232591. // get the cookie
  232592. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232593. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232594. continue;
  232595. long number;
  232596. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232597. continue;
  232598. cookies.add ((int) number);
  232599. }
  232600. CFRelease (elements);
  232601. if ((*(IOHIDDeviceInterface**) device)
  232602. ->open ((IOHIDDeviceInterface**) device,
  232603. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232604. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232605. {
  232606. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232607. if (queue != 0)
  232608. {
  232609. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232610. for (int i = 0; i < cookies.size(); ++i)
  232611. {
  232612. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232613. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232614. }
  232615. CFRunLoopSourceRef eventSource;
  232616. if ((*(IOHIDQueueInterface**) queue)
  232617. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232618. {
  232619. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232620. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232621. {
  232622. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232623. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232624. return true;
  232625. }
  232626. }
  232627. }
  232628. }
  232629. return false;
  232630. }
  232631. void AppleRemoteDevice::handleCallbackInternal()
  232632. {
  232633. int totalValues = 0;
  232634. AbsoluteTime nullTime = { 0, 0 };
  232635. char cookies [12];
  232636. int numCookies = 0;
  232637. while (numCookies < numElementsInArray (cookies))
  232638. {
  232639. IOHIDEventStruct e;
  232640. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232641. break;
  232642. if ((int) e.elementCookie == 19)
  232643. {
  232644. remoteId = e.value;
  232645. buttonPressed (switched, false);
  232646. }
  232647. else
  232648. {
  232649. totalValues += e.value;
  232650. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232651. }
  232652. }
  232653. cookies [numCookies++] = 0;
  232654. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232655. static const char buttonPatterns[] =
  232656. {
  232657. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232658. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232659. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232660. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232661. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232662. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232663. 0x1f, 0x12, 0x04, 0x02, 0,
  232664. 0x1f, 0x12, 0x03, 0x02, 0,
  232665. 0x1f, 0x12, 0x1f, 0x12, 0,
  232666. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232667. 19, 0
  232668. };
  232669. int buttonNum = (int) menuButton;
  232670. int i = 0;
  232671. while (i < numElementsInArray (buttonPatterns))
  232672. {
  232673. if (strcmp (cookies, buttonPatterns + i) == 0)
  232674. {
  232675. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232676. break;
  232677. }
  232678. i += (int) strlen (buttonPatterns + i) + 1;
  232679. ++buttonNum;
  232680. }
  232681. }
  232682. #endif
  232683. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232684. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232685. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232686. // compiled on its own).
  232687. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232688. #if JUCE_MAC
  232689. END_JUCE_NAMESPACE
  232690. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232691. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232692. {
  232693. CriticalSection* contextLock;
  232694. bool needsUpdate;
  232695. }
  232696. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232697. - (bool) makeActive;
  232698. - (void) makeInactive;
  232699. - (void) reshape;
  232700. @end
  232701. @implementation ThreadSafeNSOpenGLView
  232702. - (id) initWithFrame: (NSRect) frameRect
  232703. pixelFormat: (NSOpenGLPixelFormat*) format
  232704. {
  232705. contextLock = new CriticalSection();
  232706. self = [super initWithFrame: frameRect pixelFormat: format];
  232707. if (self != nil)
  232708. [[NSNotificationCenter defaultCenter] addObserver: self
  232709. selector: @selector (_surfaceNeedsUpdate:)
  232710. name: NSViewGlobalFrameDidChangeNotification
  232711. object: self];
  232712. return self;
  232713. }
  232714. - (void) dealloc
  232715. {
  232716. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232717. delete contextLock;
  232718. [super dealloc];
  232719. }
  232720. - (bool) makeActive
  232721. {
  232722. const ScopedLock sl (*contextLock);
  232723. if ([self openGLContext] == 0)
  232724. return false;
  232725. [[self openGLContext] makeCurrentContext];
  232726. if (needsUpdate)
  232727. {
  232728. [super update];
  232729. needsUpdate = false;
  232730. }
  232731. return true;
  232732. }
  232733. - (void) makeInactive
  232734. {
  232735. const ScopedLock sl (*contextLock);
  232736. [NSOpenGLContext clearCurrentContext];
  232737. }
  232738. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232739. {
  232740. const ScopedLock sl (*contextLock);
  232741. needsUpdate = true;
  232742. }
  232743. - (void) update
  232744. {
  232745. const ScopedLock sl (*contextLock);
  232746. needsUpdate = true;
  232747. }
  232748. - (void) reshape
  232749. {
  232750. const ScopedLock sl (*contextLock);
  232751. needsUpdate = true;
  232752. }
  232753. @end
  232754. BEGIN_JUCE_NAMESPACE
  232755. class WindowedGLContext : public OpenGLContext
  232756. {
  232757. public:
  232758. WindowedGLContext (Component* const component,
  232759. const OpenGLPixelFormat& pixelFormat_,
  232760. NSOpenGLContext* sharedContext)
  232761. : renderContext (0),
  232762. pixelFormat (pixelFormat_)
  232763. {
  232764. jassert (component != 0);
  232765. NSOpenGLPixelFormatAttribute attribs [64];
  232766. int n = 0;
  232767. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232768. attribs[n++] = NSOpenGLPFAAccelerated;
  232769. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232770. attribs[n++] = NSOpenGLPFAColorSize;
  232771. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232772. pixelFormat.greenBits,
  232773. pixelFormat.blueBits);
  232774. attribs[n++] = NSOpenGLPFAAlphaSize;
  232775. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232776. attribs[n++] = NSOpenGLPFADepthSize;
  232777. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232778. attribs[n++] = NSOpenGLPFAStencilSize;
  232779. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232780. attribs[n++] = NSOpenGLPFAAccumSize;
  232781. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232782. pixelFormat.accumulationBufferGreenBits,
  232783. pixelFormat.accumulationBufferBlueBits,
  232784. pixelFormat.accumulationBufferAlphaBits);
  232785. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232786. attribs[n++] = NSOpenGLPFASampleBuffers;
  232787. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232788. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232789. attribs[n++] = NSOpenGLPFANoRecovery;
  232790. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232791. NSOpenGLPixelFormat* format
  232792. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232793. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232794. pixelFormat: format];
  232795. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232796. shareContext: sharedContext] autorelease];
  232797. const GLint swapInterval = 1;
  232798. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232799. [view setOpenGLContext: renderContext];
  232800. [format release];
  232801. viewHolder = new NSViewComponentInternal (view, component);
  232802. }
  232803. ~WindowedGLContext()
  232804. {
  232805. deleteContext();
  232806. viewHolder = 0;
  232807. }
  232808. void deleteContext()
  232809. {
  232810. makeInactive();
  232811. [renderContext clearDrawable];
  232812. [renderContext setView: nil];
  232813. [view setOpenGLContext: nil];
  232814. renderContext = nil;
  232815. }
  232816. bool makeActive() const throw()
  232817. {
  232818. jassert (renderContext != 0);
  232819. if ([renderContext view] != view)
  232820. [renderContext setView: view];
  232821. [view makeActive];
  232822. return isActive();
  232823. }
  232824. bool makeInactive() const throw()
  232825. {
  232826. [view makeInactive];
  232827. return true;
  232828. }
  232829. bool isActive() const throw()
  232830. {
  232831. return [NSOpenGLContext currentContext] == renderContext;
  232832. }
  232833. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232834. void* getRawContext() const throw() { return renderContext; }
  232835. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232836. {
  232837. }
  232838. void swapBuffers()
  232839. {
  232840. [renderContext flushBuffer];
  232841. }
  232842. bool setSwapInterval (const int numFramesPerSwap)
  232843. {
  232844. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232845. forParameter: NSOpenGLCPSwapInterval];
  232846. return true;
  232847. }
  232848. int getSwapInterval() const
  232849. {
  232850. GLint numFrames = 0;
  232851. [renderContext getValues: &numFrames
  232852. forParameter: NSOpenGLCPSwapInterval];
  232853. return numFrames;
  232854. }
  232855. void repaint()
  232856. {
  232857. // we need to invalidate the juce view that holds this gl view, to make it
  232858. // cause a repaint callback
  232859. NSView* v = (NSView*) viewHolder->view;
  232860. NSRect r = [v frame];
  232861. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232862. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232863. // repaint message, thus never causing our paint() callback, and never repainting
  232864. // the comp. So invalidating just a little bit around the edge helps..
  232865. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232866. }
  232867. void* getNativeWindowHandle() const { return viewHolder->view; }
  232868. juce_UseDebuggingNewOperator
  232869. NSOpenGLContext* renderContext;
  232870. ThreadSafeNSOpenGLView* view;
  232871. private:
  232872. OpenGLPixelFormat pixelFormat;
  232873. ScopedPointer <NSViewComponentInternal> viewHolder;
  232874. WindowedGLContext (const WindowedGLContext&);
  232875. WindowedGLContext& operator= (const WindowedGLContext&);
  232876. };
  232877. OpenGLContext* OpenGLComponent::createContext()
  232878. {
  232879. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232880. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232881. return (c->renderContext != 0) ? c.release() : 0;
  232882. }
  232883. void* OpenGLComponent::getNativeWindowHandle() const
  232884. {
  232885. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232886. : 0;
  232887. }
  232888. void juce_glViewport (const int w, const int h)
  232889. {
  232890. glViewport (0, 0, w, h);
  232891. }
  232892. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232893. OwnedArray <OpenGLPixelFormat>& results)
  232894. {
  232895. /* GLint attribs [64];
  232896. int n = 0;
  232897. attribs[n++] = AGL_RGBA;
  232898. attribs[n++] = AGL_DOUBLEBUFFER;
  232899. attribs[n++] = AGL_ACCELERATED;
  232900. attribs[n++] = AGL_NO_RECOVERY;
  232901. attribs[n++] = AGL_NONE;
  232902. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232903. while (p != 0)
  232904. {
  232905. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232906. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232907. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232908. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232909. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232910. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232911. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232912. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232913. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232914. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232915. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232916. results.add (pf);
  232917. p = aglNextPixelFormat (p);
  232918. }*/
  232919. //jassertfalse // can't see how you do this in cocoa!
  232920. }
  232921. #else
  232922. END_JUCE_NAMESPACE
  232923. @interface JuceGLView : UIView
  232924. {
  232925. }
  232926. + (Class) layerClass;
  232927. @end
  232928. @implementation JuceGLView
  232929. + (Class) layerClass
  232930. {
  232931. return [CAEAGLLayer class];
  232932. }
  232933. @end
  232934. BEGIN_JUCE_NAMESPACE
  232935. class GLESContext : public OpenGLContext
  232936. {
  232937. public:
  232938. GLESContext (UIViewComponentPeer* peer,
  232939. Component* const component_,
  232940. const OpenGLPixelFormat& pixelFormat_,
  232941. const GLESContext* const sharedContext,
  232942. NSUInteger apiType)
  232943. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232944. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232945. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232946. {
  232947. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232948. view.opaque = YES;
  232949. view.hidden = NO;
  232950. view.backgroundColor = [UIColor blackColor];
  232951. view.userInteractionEnabled = NO;
  232952. glLayer = (CAEAGLLayer*) [view layer];
  232953. [peer->view addSubview: view];
  232954. if (sharedContext != 0)
  232955. context = [[EAGLContext alloc] initWithAPI: apiType
  232956. sharegroup: [sharedContext->context sharegroup]];
  232957. else
  232958. context = [[EAGLContext alloc] initWithAPI: apiType];
  232959. createGLBuffers();
  232960. }
  232961. ~GLESContext()
  232962. {
  232963. deleteContext();
  232964. [view removeFromSuperview];
  232965. [view release];
  232966. freeGLBuffers();
  232967. }
  232968. void deleteContext()
  232969. {
  232970. makeInactive();
  232971. [context release];
  232972. context = nil;
  232973. }
  232974. bool makeActive() const throw()
  232975. {
  232976. jassert (context != 0);
  232977. [EAGLContext setCurrentContext: context];
  232978. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232979. return true;
  232980. }
  232981. void swapBuffers()
  232982. {
  232983. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232984. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232985. }
  232986. bool makeInactive() const throw()
  232987. {
  232988. return [EAGLContext setCurrentContext: nil];
  232989. }
  232990. bool isActive() const throw()
  232991. {
  232992. return [EAGLContext currentContext] == context;
  232993. }
  232994. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232995. void* getRawContext() const throw() { return glLayer; }
  232996. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232997. {
  232998. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232999. if (lastWidth != w || lastHeight != h)
  233000. {
  233001. lastWidth = w;
  233002. lastHeight = h;
  233003. freeGLBuffers();
  233004. createGLBuffers();
  233005. }
  233006. }
  233007. bool setSwapInterval (const int numFramesPerSwap)
  233008. {
  233009. numFrames = numFramesPerSwap;
  233010. return true;
  233011. }
  233012. int getSwapInterval() const
  233013. {
  233014. return numFrames;
  233015. }
  233016. void repaint()
  233017. {
  233018. }
  233019. void createGLBuffers()
  233020. {
  233021. makeActive();
  233022. glGenFramebuffersOES (1, &frameBufferHandle);
  233023. glGenRenderbuffersOES (1, &colorBufferHandle);
  233024. glGenRenderbuffersOES (1, &depthBufferHandle);
  233025. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233026. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233027. GLint width, height;
  233028. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233029. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233030. if (useDepthBuffer)
  233031. {
  233032. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233033. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233034. }
  233035. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233036. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233037. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233038. if (useDepthBuffer)
  233039. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233040. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233041. }
  233042. void freeGLBuffers()
  233043. {
  233044. if (frameBufferHandle != 0)
  233045. {
  233046. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233047. frameBufferHandle = 0;
  233048. }
  233049. if (colorBufferHandle != 0)
  233050. {
  233051. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233052. colorBufferHandle = 0;
  233053. }
  233054. if (depthBufferHandle != 0)
  233055. {
  233056. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233057. depthBufferHandle = 0;
  233058. }
  233059. }
  233060. juce_UseDebuggingNewOperator
  233061. private:
  233062. Component::SafePointer<Component> component;
  233063. OpenGLPixelFormat pixelFormat;
  233064. JuceGLView* view;
  233065. CAEAGLLayer* glLayer;
  233066. EAGLContext* context;
  233067. bool useDepthBuffer;
  233068. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233069. int numFrames;
  233070. int lastWidth, lastHeight;
  233071. GLESContext (const GLESContext&);
  233072. GLESContext& operator= (const GLESContext&);
  233073. };
  233074. OpenGLContext* OpenGLComponent::createContext()
  233075. {
  233076. ScopedAutoReleasePool pool;
  233077. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233078. if (peer != 0)
  233079. return new GLESContext (peer, this, preferredPixelFormat,
  233080. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233081. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233082. return 0;
  233083. }
  233084. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233085. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233086. {
  233087. }
  233088. void juce_glViewport (const int w, const int h)
  233089. {
  233090. glViewport (0, 0, w, h);
  233091. }
  233092. #endif
  233093. #endif
  233094. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233095. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233096. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233097. // compiled on its own).
  233098. #if JUCE_INCLUDED_FILE
  233099. class JuceMainMenuHandler;
  233100. END_JUCE_NAMESPACE
  233101. using namespace JUCE_NAMESPACE;
  233102. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233103. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233104. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233105. #else
  233106. @interface JuceMenuCallback : NSObject
  233107. #endif
  233108. {
  233109. JuceMainMenuHandler* owner;
  233110. }
  233111. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233112. - (void) dealloc;
  233113. - (void) menuItemInvoked: (id) menu;
  233114. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233115. @end
  233116. BEGIN_JUCE_NAMESPACE
  233117. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233118. private DeletedAtShutdown
  233119. {
  233120. public:
  233121. static JuceMainMenuHandler* instance;
  233122. JuceMainMenuHandler()
  233123. : currentModel (0),
  233124. lastUpdateTime (0)
  233125. {
  233126. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233127. }
  233128. ~JuceMainMenuHandler()
  233129. {
  233130. setMenu (0);
  233131. jassert (instance == this);
  233132. instance = 0;
  233133. [callback release];
  233134. }
  233135. void setMenu (MenuBarModel* const newMenuBarModel)
  233136. {
  233137. if (currentModel != newMenuBarModel)
  233138. {
  233139. if (currentModel != 0)
  233140. currentModel->removeListener (this);
  233141. currentModel = newMenuBarModel;
  233142. if (currentModel != 0)
  233143. currentModel->addListener (this);
  233144. menuBarItemsChanged (0);
  233145. }
  233146. }
  233147. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233148. const String& name, const int menuId, const int tag)
  233149. {
  233150. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233151. action: nil
  233152. keyEquivalent: @""];
  233153. [item setTag: tag];
  233154. NSMenu* sub = createMenu (child, name, menuId, tag);
  233155. [parent setSubmenu: sub forItem: item];
  233156. [sub setAutoenablesItems: false];
  233157. [sub release];
  233158. }
  233159. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233160. const String& name, const int menuId, const int tag)
  233161. {
  233162. [parentItem setTag: tag];
  233163. NSMenu* menu = [parentItem submenu];
  233164. [menu setTitle: juceStringToNS (name)];
  233165. while ([menu numberOfItems] > 0)
  233166. [menu removeItemAtIndex: 0];
  233167. PopupMenu::MenuItemIterator iter (menuToCopy);
  233168. while (iter.next())
  233169. addMenuItem (iter, menu, menuId, tag);
  233170. [menu setAutoenablesItems: false];
  233171. [menu update];
  233172. }
  233173. void menuBarItemsChanged (MenuBarModel*)
  233174. {
  233175. lastUpdateTime = Time::getMillisecondCounter();
  233176. StringArray menuNames;
  233177. if (currentModel != 0)
  233178. menuNames = currentModel->getMenuBarNames();
  233179. NSMenu* menuBar = [NSApp mainMenu];
  233180. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233181. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233182. int menuId = 1;
  233183. for (int i = 0; i < menuNames.size(); ++i)
  233184. {
  233185. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233186. if (i >= [menuBar numberOfItems] - 1)
  233187. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233188. else
  233189. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233190. }
  233191. }
  233192. static void flashMenuBar (NSMenu* menu)
  233193. {
  233194. if ([[menu title] isEqualToString: @"Apple"])
  233195. return;
  233196. [menu retain];
  233197. const unichar f35Key = NSF35FunctionKey;
  233198. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233199. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233200. action: nil
  233201. keyEquivalent: f35String];
  233202. [item setTarget: nil];
  233203. [menu insertItem: item atIndex: [menu numberOfItems]];
  233204. [item release];
  233205. if ([menu indexOfItem: item] >= 0)
  233206. {
  233207. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233208. location: NSZeroPoint
  233209. modifierFlags: NSCommandKeyMask
  233210. timestamp: 0
  233211. windowNumber: 0
  233212. context: [NSGraphicsContext currentContext]
  233213. characters: f35String
  233214. charactersIgnoringModifiers: f35String
  233215. isARepeat: NO
  233216. keyCode: 0];
  233217. [menu performKeyEquivalent: f35Event];
  233218. if ([menu indexOfItem: item] >= 0)
  233219. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233220. }
  233221. [menu release];
  233222. }
  233223. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233224. {
  233225. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233226. {
  233227. NSMenuItem* m = [menu itemAtIndex: i];
  233228. if ([m tag] == info.commandID)
  233229. return m;
  233230. if ([m submenu] != 0)
  233231. {
  233232. NSMenuItem* found = findMenuItem ([m submenu], info);
  233233. if (found != 0)
  233234. return found;
  233235. }
  233236. }
  233237. return 0;
  233238. }
  233239. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233240. {
  233241. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233242. if (item != 0)
  233243. flashMenuBar ([item menu]);
  233244. }
  233245. void updateMenus()
  233246. {
  233247. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233248. menuBarItemsChanged (0);
  233249. }
  233250. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233251. {
  233252. if (currentModel != 0)
  233253. {
  233254. if (commandManager != 0)
  233255. {
  233256. ApplicationCommandTarget::InvocationInfo info (commandId);
  233257. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233258. commandManager->invoke (info, true);
  233259. }
  233260. currentModel->menuItemSelected (commandId, topLevelIndex);
  233261. }
  233262. }
  233263. MenuBarModel* currentModel;
  233264. uint32 lastUpdateTime;
  233265. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233266. const int topLevelMenuId, const int topLevelIndex)
  233267. {
  233268. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233269. if (text == 0)
  233270. text = @"";
  233271. if (iter.isSeparator)
  233272. {
  233273. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233274. }
  233275. else if (iter.isSectionHeader)
  233276. {
  233277. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233278. action: nil
  233279. keyEquivalent: @""];
  233280. [item setEnabled: false];
  233281. }
  233282. else if (iter.subMenu != 0)
  233283. {
  233284. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233285. action: nil
  233286. keyEquivalent: @""];
  233287. [item setTag: iter.itemId];
  233288. [item setEnabled: iter.isEnabled];
  233289. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233290. [sub setDelegate: nil];
  233291. [menuToAddTo setSubmenu: sub forItem: item];
  233292. [sub release];
  233293. }
  233294. else
  233295. {
  233296. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233297. action: @selector (menuItemInvoked:)
  233298. keyEquivalent: @""];
  233299. [item setTag: iter.itemId];
  233300. [item setEnabled: iter.isEnabled];
  233301. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233302. [item setTarget: (id) callback];
  233303. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233304. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233305. [item setRepresentedObject: info];
  233306. if (iter.commandManager != 0)
  233307. {
  233308. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233309. ->getKeyPressesAssignedToCommand (iter.itemId));
  233310. if (keyPresses.size() > 0)
  233311. {
  233312. const KeyPress& kp = keyPresses.getReference(0);
  233313. if (kp.getKeyCode() != KeyPress::backspaceKey
  233314. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233315. // every time you press the key while editing text)
  233316. {
  233317. juce_wchar key = kp.getTextCharacter();
  233318. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233319. key = NSBackspaceCharacter;
  233320. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233321. key = NSDeleteCharacter;
  233322. else if (key == 0)
  233323. key = (juce_wchar) kp.getKeyCode();
  233324. unsigned int mods = 0;
  233325. if (kp.getModifiers().isShiftDown())
  233326. mods |= NSShiftKeyMask;
  233327. if (kp.getModifiers().isCtrlDown())
  233328. mods |= NSControlKeyMask;
  233329. if (kp.getModifiers().isAltDown())
  233330. mods |= NSAlternateKeyMask;
  233331. if (kp.getModifiers().isCommandDown())
  233332. mods |= NSCommandKeyMask;
  233333. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233334. [item setKeyEquivalentModifierMask: mods];
  233335. }
  233336. }
  233337. }
  233338. }
  233339. }
  233340. JuceMenuCallback* callback;
  233341. private:
  233342. NSMenu* createMenu (const PopupMenu menu,
  233343. const String& menuName,
  233344. const int topLevelMenuId,
  233345. const int topLevelIndex)
  233346. {
  233347. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233348. [m setAutoenablesItems: false];
  233349. [m setDelegate: callback];
  233350. PopupMenu::MenuItemIterator iter (menu);
  233351. while (iter.next())
  233352. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233353. [m update];
  233354. return m;
  233355. }
  233356. };
  233357. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233358. END_JUCE_NAMESPACE
  233359. @implementation JuceMenuCallback
  233360. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233361. {
  233362. [super init];
  233363. owner = owner_;
  233364. return self;
  233365. }
  233366. - (void) dealloc
  233367. {
  233368. [super dealloc];
  233369. }
  233370. - (void) menuItemInvoked: (id) menu
  233371. {
  233372. NSMenuItem* item = (NSMenuItem*) menu;
  233373. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233374. {
  233375. // 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
  233376. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233377. // into the focused component and let it trigger the menu item indirectly.
  233378. NSEvent* e = [NSApp currentEvent];
  233379. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233380. {
  233381. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233382. {
  233383. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233384. if (peer != 0)
  233385. {
  233386. if ([e type] == NSKeyDown)
  233387. peer->redirectKeyDown (e);
  233388. else
  233389. peer->redirectKeyUp (e);
  233390. return;
  233391. }
  233392. }
  233393. }
  233394. NSArray* info = (NSArray*) [item representedObject];
  233395. owner->invoke ((int) [item tag],
  233396. (ApplicationCommandManager*) (pointer_sized_int)
  233397. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233398. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233399. }
  233400. }
  233401. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233402. {
  233403. (void) menu;
  233404. if (JuceMainMenuHandler::instance != 0)
  233405. JuceMainMenuHandler::instance->updateMenus();
  233406. }
  233407. @end
  233408. BEGIN_JUCE_NAMESPACE
  233409. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233410. const PopupMenu* extraItems)
  233411. {
  233412. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233413. {
  233414. PopupMenu::MenuItemIterator iter (*extraItems);
  233415. while (iter.next())
  233416. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233417. [menu addItem: [NSMenuItem separatorItem]];
  233418. }
  233419. NSMenuItem* item;
  233420. // Services...
  233421. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233422. action: nil keyEquivalent: @""];
  233423. [menu addItem: item];
  233424. [item release];
  233425. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233426. [menu setSubmenu: servicesMenu forItem: item];
  233427. [NSApp setServicesMenu: servicesMenu];
  233428. [servicesMenu release];
  233429. [menu addItem: [NSMenuItem separatorItem]];
  233430. // Hide + Show stuff...
  233431. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233432. action: @selector (hide:) keyEquivalent: @"h"];
  233433. [item setTarget: NSApp];
  233434. [menu addItem: item];
  233435. [item release];
  233436. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233437. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233438. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233439. [item setTarget: NSApp];
  233440. [menu addItem: item];
  233441. [item release];
  233442. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233443. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233444. [item setTarget: NSApp];
  233445. [menu addItem: item];
  233446. [item release];
  233447. [menu addItem: [NSMenuItem separatorItem]];
  233448. // Quit item....
  233449. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233450. action: @selector (terminate:) keyEquivalent: @"q"];
  233451. [item setTarget: NSApp];
  233452. [menu addItem: item];
  233453. [item release];
  233454. return menu;
  233455. }
  233456. // Since our app has no NIB, this initialises a standard app menu...
  233457. static void rebuildMainMenu (const PopupMenu* extraItems)
  233458. {
  233459. // this can't be used in a plugin!
  233460. jassert (JUCEApplication::isStandaloneApp());
  233461. if (JUCEApplication::getInstance() != 0)
  233462. {
  233463. const ScopedAutoReleasePool pool;
  233464. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233465. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233466. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233467. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233468. [mainMenu setSubmenu: appMenu forItem: item];
  233469. [NSApp setMainMenu: mainMenu];
  233470. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233471. [appMenu release];
  233472. [mainMenu release];
  233473. }
  233474. }
  233475. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233476. const PopupMenu* extraAppleMenuItems)
  233477. {
  233478. if (getMacMainMenu() != newMenuBarModel)
  233479. {
  233480. const ScopedAutoReleasePool pool;
  233481. if (newMenuBarModel == 0)
  233482. {
  233483. delete JuceMainMenuHandler::instance;
  233484. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233485. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233486. extraAppleMenuItems = 0;
  233487. }
  233488. else
  233489. {
  233490. if (JuceMainMenuHandler::instance == 0)
  233491. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233492. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233493. }
  233494. }
  233495. rebuildMainMenu (extraAppleMenuItems);
  233496. if (newMenuBarModel != 0)
  233497. newMenuBarModel->menuItemsChanged();
  233498. }
  233499. MenuBarModel* MenuBarModel::getMacMainMenu()
  233500. {
  233501. return JuceMainMenuHandler::instance != 0
  233502. ? JuceMainMenuHandler::instance->currentModel : 0;
  233503. }
  233504. void juce_initialiseMacMainMenu()
  233505. {
  233506. if (JuceMainMenuHandler::instance == 0)
  233507. rebuildMainMenu (0);
  233508. }
  233509. #endif
  233510. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233511. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233512. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233513. // compiled on its own).
  233514. #if JUCE_INCLUDED_FILE
  233515. #if JUCE_MAC
  233516. END_JUCE_NAMESPACE
  233517. using namespace JUCE_NAMESPACE;
  233518. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233519. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233520. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233521. #else
  233522. @interface JuceFileChooserDelegate : NSObject
  233523. #endif
  233524. {
  233525. StringArray* filters;
  233526. }
  233527. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233528. - (void) dealloc;
  233529. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233530. @end
  233531. @implementation JuceFileChooserDelegate
  233532. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233533. {
  233534. [super init];
  233535. filters = filters_;
  233536. return self;
  233537. }
  233538. - (void) dealloc
  233539. {
  233540. delete filters;
  233541. [super dealloc];
  233542. }
  233543. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233544. {
  233545. (void) sender;
  233546. const File f (nsStringToJuce (filename));
  233547. for (int i = filters->size(); --i >= 0;)
  233548. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233549. return true;
  233550. return f.isDirectory();
  233551. }
  233552. @end
  233553. BEGIN_JUCE_NAMESPACE
  233554. void FileChooser::showPlatformDialog (Array<File>& results,
  233555. const String& title,
  233556. const File& currentFileOrDirectory,
  233557. const String& filter,
  233558. bool selectsDirectory,
  233559. bool selectsFiles,
  233560. bool isSaveDialogue,
  233561. bool warnAboutOverwritingExistingFiles,
  233562. bool selectMultipleFiles,
  233563. FilePreviewComponent* extraInfoComponent)
  233564. {
  233565. const ScopedAutoReleasePool pool;
  233566. StringArray* filters = new StringArray();
  233567. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233568. filters->trim();
  233569. filters->removeEmptyStrings();
  233570. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233571. [delegate autorelease];
  233572. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233573. : [NSOpenPanel openPanel];
  233574. [panel setTitle: juceStringToNS (title)];
  233575. if (! isSaveDialogue)
  233576. {
  233577. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233578. [openPanel setCanChooseDirectories: selectsDirectory];
  233579. [openPanel setCanChooseFiles: selectsFiles];
  233580. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233581. }
  233582. [panel setDelegate: delegate];
  233583. if (isSaveDialogue || selectsDirectory)
  233584. [panel setCanCreateDirectories: YES];
  233585. String directory, filename;
  233586. if (currentFileOrDirectory.isDirectory())
  233587. {
  233588. directory = currentFileOrDirectory.getFullPathName();
  233589. }
  233590. else
  233591. {
  233592. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233593. filename = currentFileOrDirectory.getFileName();
  233594. }
  233595. if ([panel runModalForDirectory: juceStringToNS (directory)
  233596. file: juceStringToNS (filename)]
  233597. == NSOKButton)
  233598. {
  233599. if (isSaveDialogue)
  233600. {
  233601. results.add (File (nsStringToJuce ([panel filename])));
  233602. }
  233603. else
  233604. {
  233605. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233606. NSArray* urls = [openPanel filenames];
  233607. for (unsigned int i = 0; i < [urls count]; ++i)
  233608. {
  233609. NSString* f = [urls objectAtIndex: i];
  233610. results.add (File (nsStringToJuce (f)));
  233611. }
  233612. }
  233613. }
  233614. [panel setDelegate: nil];
  233615. }
  233616. #else
  233617. void FileChooser::showPlatformDialog (Array<File>& results,
  233618. const String& title,
  233619. const File& currentFileOrDirectory,
  233620. const String& filter,
  233621. bool selectsDirectory,
  233622. bool selectsFiles,
  233623. bool isSaveDialogue,
  233624. bool warnAboutOverwritingExistingFiles,
  233625. bool selectMultipleFiles,
  233626. FilePreviewComponent* extraInfoComponent)
  233627. {
  233628. const ScopedAutoReleasePool pool;
  233629. jassertfalse; //xxx to do
  233630. }
  233631. #endif
  233632. #endif
  233633. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233634. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233635. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233636. // compiled on its own).
  233637. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233638. END_JUCE_NAMESPACE
  233639. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233640. @interface NonInterceptingQTMovieView : QTMovieView
  233641. {
  233642. }
  233643. - (id) initWithFrame: (NSRect) frame;
  233644. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233645. - (NSView*) hitTest: (NSPoint) p;
  233646. @end
  233647. @implementation NonInterceptingQTMovieView
  233648. - (id) initWithFrame: (NSRect) frame
  233649. {
  233650. self = [super initWithFrame: frame];
  233651. [self setNextResponder: [self superview]];
  233652. return self;
  233653. }
  233654. - (void) dealloc
  233655. {
  233656. [super dealloc];
  233657. }
  233658. - (NSView*) hitTest: (NSPoint) point
  233659. {
  233660. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233661. }
  233662. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233663. {
  233664. return YES;
  233665. }
  233666. @end
  233667. BEGIN_JUCE_NAMESPACE
  233668. #define theMovie (static_cast <QTMovie*> (movie))
  233669. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233670. : movie (0)
  233671. {
  233672. setOpaque (true);
  233673. setVisible (true);
  233674. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233675. setView (view);
  233676. [view release];
  233677. }
  233678. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233679. {
  233680. closeMovie();
  233681. setView (0);
  233682. }
  233683. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233684. {
  233685. return true;
  233686. }
  233687. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233688. {
  233689. // unfortunately, QTMovie objects can only be created on the main thread..
  233690. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233691. QTMovie* movie = 0;
  233692. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233693. if (fin != 0)
  233694. {
  233695. movieFile = fin->getFile();
  233696. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233697. error: nil];
  233698. }
  233699. else
  233700. {
  233701. MemoryBlock temp;
  233702. movieStream->readIntoMemoryBlock (temp);
  233703. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233704. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233705. {
  233706. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233707. length: temp.getSize()]
  233708. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233709. MIMEType: @""]
  233710. error: nil];
  233711. if (movie != 0)
  233712. break;
  233713. }
  233714. }
  233715. return movie;
  233716. }
  233717. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233718. const bool isControllerVisible_)
  233719. {
  233720. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233721. }
  233722. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233723. const bool controllerVisible_)
  233724. {
  233725. closeMovie();
  233726. if (getPeer() == 0)
  233727. {
  233728. // To open a movie, this component must be visible inside a functioning window, so that
  233729. // the QT control can be assigned to the window.
  233730. jassertfalse;
  233731. return false;
  233732. }
  233733. movie = openMovieFromStream (movieStream, movieFile);
  233734. [theMovie retain];
  233735. QTMovieView* view = (QTMovieView*) getView();
  233736. [view setMovie: theMovie];
  233737. [view setControllerVisible: controllerVisible_];
  233738. setLooping (looping);
  233739. return movie != nil;
  233740. }
  233741. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233742. const bool isControllerVisible_)
  233743. {
  233744. // unfortunately, QTMovie objects can only be created on the main thread..
  233745. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233746. closeMovie();
  233747. if (getPeer() == 0)
  233748. {
  233749. // To open a movie, this component must be visible inside a functioning window, so that
  233750. // the QT control can be assigned to the window.
  233751. jassertfalse;
  233752. return false;
  233753. }
  233754. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233755. NSError* err;
  233756. if ([QTMovie canInitWithURL: url])
  233757. movie = [QTMovie movieWithURL: url error: &err];
  233758. [theMovie retain];
  233759. QTMovieView* view = (QTMovieView*) getView();
  233760. [view setMovie: theMovie];
  233761. [view setControllerVisible: controllerVisible];
  233762. setLooping (looping);
  233763. return movie != nil;
  233764. }
  233765. void QuickTimeMovieComponent::closeMovie()
  233766. {
  233767. stop();
  233768. QTMovieView* view = (QTMovieView*) getView();
  233769. [view setMovie: nil];
  233770. [theMovie release];
  233771. movie = 0;
  233772. movieFile = File::nonexistent;
  233773. }
  233774. bool QuickTimeMovieComponent::isMovieOpen() const
  233775. {
  233776. return movie != nil;
  233777. }
  233778. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233779. {
  233780. return movieFile;
  233781. }
  233782. void QuickTimeMovieComponent::play()
  233783. {
  233784. [theMovie play];
  233785. }
  233786. void QuickTimeMovieComponent::stop()
  233787. {
  233788. [theMovie stop];
  233789. }
  233790. bool QuickTimeMovieComponent::isPlaying() const
  233791. {
  233792. return movie != 0 && [theMovie rate] != 0;
  233793. }
  233794. void QuickTimeMovieComponent::setPosition (const double seconds)
  233795. {
  233796. if (movie != 0)
  233797. {
  233798. QTTime t;
  233799. t.timeValue = (uint64) (100000.0 * seconds);
  233800. t.timeScale = 100000;
  233801. t.flags = 0;
  233802. [theMovie setCurrentTime: t];
  233803. }
  233804. }
  233805. double QuickTimeMovieComponent::getPosition() const
  233806. {
  233807. if (movie == 0)
  233808. return 0.0;
  233809. QTTime t = [theMovie currentTime];
  233810. return t.timeValue / (double) t.timeScale;
  233811. }
  233812. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233813. {
  233814. [theMovie setRate: newSpeed];
  233815. }
  233816. double QuickTimeMovieComponent::getMovieDuration() const
  233817. {
  233818. if (movie == 0)
  233819. return 0.0;
  233820. QTTime t = [theMovie duration];
  233821. return t.timeValue / (double) t.timeScale;
  233822. }
  233823. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233824. {
  233825. looping = shouldLoop;
  233826. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233827. forKey: QTMovieLoopsAttribute];
  233828. }
  233829. bool QuickTimeMovieComponent::isLooping() const
  233830. {
  233831. return looping;
  233832. }
  233833. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233834. {
  233835. [theMovie setVolume: newVolume];
  233836. }
  233837. float QuickTimeMovieComponent::getMovieVolume() const
  233838. {
  233839. return movie != 0 ? [theMovie volume] : 0.0f;
  233840. }
  233841. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233842. {
  233843. width = 0;
  233844. height = 0;
  233845. if (movie != 0)
  233846. {
  233847. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233848. width = (int) s.width;
  233849. height = (int) s.height;
  233850. }
  233851. }
  233852. void QuickTimeMovieComponent::paint (Graphics& g)
  233853. {
  233854. if (movie == 0)
  233855. g.fillAll (Colours::black);
  233856. }
  233857. bool QuickTimeMovieComponent::isControllerVisible() const
  233858. {
  233859. return controllerVisible;
  233860. }
  233861. void QuickTimeMovieComponent::goToStart()
  233862. {
  233863. setPosition (0.0);
  233864. }
  233865. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233866. const RectanglePlacement& placement)
  233867. {
  233868. int normalWidth, normalHeight;
  233869. getMovieNormalSize (normalWidth, normalHeight);
  233870. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233871. {
  233872. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233873. placement.applyTo (x, y, w, h,
  233874. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233875. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233876. if (w > 0 && h > 0)
  233877. {
  233878. setBounds (roundToInt (x), roundToInt (y),
  233879. roundToInt (w), roundToInt (h));
  233880. }
  233881. }
  233882. else
  233883. {
  233884. setBounds (spaceToFitWithin);
  233885. }
  233886. }
  233887. #if ! (JUCE_MAC && JUCE_64BIT)
  233888. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233889. {
  233890. if (movieStream == 0)
  233891. return false;
  233892. File file;
  233893. QTMovie* movie = openMovieFromStream (movieStream, file);
  233894. if (movie != nil)
  233895. result = [movie quickTimeMovie];
  233896. return movie != nil;
  233897. }
  233898. #endif
  233899. #endif
  233900. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233901. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233902. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233903. // compiled on its own).
  233904. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233905. const int kilobytesPerSecond1x = 176;
  233906. END_JUCE_NAMESPACE
  233907. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233908. @interface OpenDiskDevice : NSObject
  233909. {
  233910. @public
  233911. DRDevice* device;
  233912. NSMutableArray* tracks;
  233913. bool underrunProtection;
  233914. }
  233915. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233916. - (void) dealloc;
  233917. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233918. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233919. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233920. @end
  233921. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233922. @interface AudioTrackProducer : NSObject
  233923. {
  233924. JUCE_NAMESPACE::AudioSource* source;
  233925. int readPosition, lengthInFrames;
  233926. }
  233927. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233928. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233929. - (void) dealloc;
  233930. - (void) setupTrackProperties: (DRTrack*) track;
  233931. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233932. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233933. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233934. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233935. toMedia:(NSDictionary*)mediaInfo;
  233936. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233937. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233938. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233939. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233940. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233941. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233942. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233943. ioFlags:(uint32_t*)flags;
  233944. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233945. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233946. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233947. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233948. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233949. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233950. ioFlags:(uint32_t*)flags;
  233951. @end
  233952. @implementation OpenDiskDevice
  233953. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233954. {
  233955. [super init];
  233956. device = device_;
  233957. tracks = [[NSMutableArray alloc] init];
  233958. underrunProtection = true;
  233959. return self;
  233960. }
  233961. - (void) dealloc
  233962. {
  233963. [tracks release];
  233964. [super dealloc];
  233965. }
  233966. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233967. {
  233968. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233969. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233970. [p setupTrackProperties: t];
  233971. [tracks addObject: t];
  233972. [t release];
  233973. [p release];
  233974. }
  233975. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233976. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233977. {
  233978. DRBurn* burn = [DRBurn burnForDevice: device];
  233979. if (! [device acquireExclusiveAccess])
  233980. {
  233981. *error = "Couldn't open or write to the CD device";
  233982. return;
  233983. }
  233984. [device acquireMediaReservation];
  233985. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233986. [d autorelease];
  233987. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233988. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233989. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233990. if (burnSpeed > 0)
  233991. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233992. if (! underrunProtection)
  233993. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233994. [burn setProperties: d];
  233995. [burn writeLayout: tracks];
  233996. for (;;)
  233997. {
  233998. JUCE_NAMESPACE::Thread::sleep (300);
  233999. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234000. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234001. {
  234002. [burn abort];
  234003. *error = "User cancelled the write operation";
  234004. break;
  234005. }
  234006. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234007. {
  234008. *error = "Write operation failed";
  234009. break;
  234010. }
  234011. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234012. {
  234013. break;
  234014. }
  234015. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234016. objectForKey: DRErrorStatusErrorStringKey];
  234017. if ([err length] > 0)
  234018. {
  234019. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234020. break;
  234021. }
  234022. }
  234023. [device releaseMediaReservation];
  234024. [device releaseExclusiveAccess];
  234025. }
  234026. @end
  234027. @implementation AudioTrackProducer
  234028. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234029. {
  234030. lengthInFrames = lengthInFrames_;
  234031. readPosition = 0;
  234032. return self;
  234033. }
  234034. - (void) setupTrackProperties: (DRTrack*) track
  234035. {
  234036. NSMutableDictionary* p = [[track properties] mutableCopy];
  234037. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234038. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234039. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234040. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234041. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234042. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234043. [track setProperties: p];
  234044. [p release];
  234045. }
  234046. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234047. {
  234048. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234049. if (s != nil)
  234050. s->source = source_;
  234051. return s;
  234052. }
  234053. - (void) dealloc
  234054. {
  234055. if (source != 0)
  234056. {
  234057. source->releaseResources();
  234058. delete source;
  234059. }
  234060. [super dealloc];
  234061. }
  234062. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234063. {
  234064. }
  234065. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234066. {
  234067. return true;
  234068. }
  234069. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234070. {
  234071. return lengthInFrames;
  234072. }
  234073. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234074. toMedia: (NSDictionary*) mediaInfo
  234075. {
  234076. if (source != 0)
  234077. source->prepareToPlay (44100 / 75, 44100);
  234078. readPosition = 0;
  234079. return true;
  234080. }
  234081. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234082. {
  234083. if (source != 0)
  234084. source->prepareToPlay (44100 / 75, 44100);
  234085. return true;
  234086. }
  234087. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234088. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234089. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234090. {
  234091. if (source != 0)
  234092. {
  234093. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234094. if (numSamples > 0)
  234095. {
  234096. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234097. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234098. info.buffer = &tempBuffer;
  234099. info.startSample = 0;
  234100. info.numSamples = numSamples;
  234101. source->getNextAudioBlock (info);
  234102. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  234103. buffer, numSamples, 4);
  234104. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  234105. buffer + 2, numSamples, 4);
  234106. readPosition += numSamples;
  234107. }
  234108. return numSamples * 4;
  234109. }
  234110. return 0;
  234111. }
  234112. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234113. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234114. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234115. ioFlags: (uint32_t*) flags
  234116. {
  234117. zeromem (buffer, bufferLength);
  234118. return bufferLength;
  234119. }
  234120. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234121. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234122. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234123. {
  234124. return true;
  234125. }
  234126. @end
  234127. BEGIN_JUCE_NAMESPACE
  234128. class AudioCDBurner::Pimpl : public Timer
  234129. {
  234130. public:
  234131. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234132. : device (0), owner (owner_)
  234133. {
  234134. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234135. if (dev != 0)
  234136. {
  234137. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234138. lastState = getDiskState();
  234139. startTimer (1000);
  234140. }
  234141. }
  234142. ~Pimpl()
  234143. {
  234144. stopTimer();
  234145. [device release];
  234146. }
  234147. void timerCallback()
  234148. {
  234149. const DiskState state = getDiskState();
  234150. if (state != lastState)
  234151. {
  234152. lastState = state;
  234153. owner.sendChangeMessage (&owner);
  234154. }
  234155. }
  234156. DiskState getDiskState() const
  234157. {
  234158. if ([device->device isValid])
  234159. {
  234160. NSDictionary* status = [device->device status];
  234161. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234162. if ([state isEqualTo: DRDeviceMediaStateNone])
  234163. {
  234164. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234165. return trayOpen;
  234166. return noDisc;
  234167. }
  234168. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234169. {
  234170. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234171. return writableDiskPresent;
  234172. else
  234173. return readOnlyDiskPresent;
  234174. }
  234175. }
  234176. return unknown;
  234177. }
  234178. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234179. const Array<int> getAvailableWriteSpeeds() const
  234180. {
  234181. Array<int> results;
  234182. if ([device->device isValid])
  234183. {
  234184. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234185. for (unsigned int i = 0; i < [speeds count]; ++i)
  234186. {
  234187. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234188. results.add (kbPerSec / kilobytesPerSecond1x);
  234189. }
  234190. }
  234191. return results;
  234192. }
  234193. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234194. {
  234195. if ([device->device isValid])
  234196. {
  234197. device->underrunProtection = shouldBeEnabled;
  234198. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234199. }
  234200. return false;
  234201. }
  234202. int getNumAvailableAudioBlocks() const
  234203. {
  234204. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234205. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234206. }
  234207. OpenDiskDevice* device;
  234208. private:
  234209. DiskState lastState;
  234210. AudioCDBurner& owner;
  234211. };
  234212. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234213. {
  234214. pimpl = new Pimpl (*this, deviceIndex);
  234215. }
  234216. AudioCDBurner::~AudioCDBurner()
  234217. {
  234218. }
  234219. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234220. {
  234221. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234222. if (b->pimpl->device == 0)
  234223. b = 0;
  234224. return b.release();
  234225. }
  234226. static NSArray* findDiskBurnerDevices()
  234227. {
  234228. NSMutableArray* results = [NSMutableArray array];
  234229. NSArray* devs = [DRDevice devices];
  234230. if (devs != 0)
  234231. {
  234232. int num = [devs count];
  234233. int i;
  234234. for (i = 0; i < num; ++i)
  234235. {
  234236. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234237. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234238. if (name != nil)
  234239. [results addObject: name];
  234240. }
  234241. }
  234242. return results;
  234243. }
  234244. const StringArray AudioCDBurner::findAvailableDevices()
  234245. {
  234246. NSArray* names = findDiskBurnerDevices();
  234247. StringArray s;
  234248. for (unsigned int i = 0; i < [names count]; ++i)
  234249. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234250. return s;
  234251. }
  234252. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234253. {
  234254. return pimpl->getDiskState();
  234255. }
  234256. bool AudioCDBurner::isDiskPresent() const
  234257. {
  234258. return getDiskState() == writableDiskPresent;
  234259. }
  234260. bool AudioCDBurner::openTray()
  234261. {
  234262. return pimpl->openTray();
  234263. }
  234264. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234265. {
  234266. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234267. DiskState oldState = getDiskState();
  234268. DiskState newState = oldState;
  234269. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234270. {
  234271. newState = getDiskState();
  234272. Thread::sleep (100);
  234273. }
  234274. return newState;
  234275. }
  234276. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234277. {
  234278. return pimpl->getAvailableWriteSpeeds();
  234279. }
  234280. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234281. {
  234282. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234283. }
  234284. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234285. {
  234286. return pimpl->getNumAvailableAudioBlocks();
  234287. }
  234288. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234289. {
  234290. if ([pimpl->device->device isValid])
  234291. {
  234292. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234293. return true;
  234294. }
  234295. return false;
  234296. }
  234297. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234298. bool ejectDiscAfterwards,
  234299. bool performFakeBurnForTesting,
  234300. int writeSpeed)
  234301. {
  234302. String error ("Couldn't open or write to the CD device");
  234303. if ([pimpl->device->device isValid])
  234304. {
  234305. error = String::empty;
  234306. [pimpl->device burn: listener
  234307. errorString: &error
  234308. ejectAfterwards: ejectDiscAfterwards
  234309. isFake: performFakeBurnForTesting
  234310. speed: writeSpeed];
  234311. }
  234312. return error;
  234313. }
  234314. #endif
  234315. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234316. void AudioCDReader::ejectDisk()
  234317. {
  234318. const ScopedAutoReleasePool p;
  234319. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234320. }
  234321. #endif
  234322. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234323. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234324. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234325. // compiled on its own).
  234326. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234327. namespace CDReaderHelpers
  234328. {
  234329. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234330. {
  234331. forEachXmlChildElementWithTagName (xml, child, "key")
  234332. if (child->getAllSubText() == key)
  234333. return child->getNextElement();
  234334. return 0;
  234335. }
  234336. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234337. {
  234338. const XmlElement* const block = getElementForKey (xml, key);
  234339. return block != 0 ? block->getAllSubText().getIntValue() : defaultValue;
  234340. }
  234341. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234342. // Returns NULL on success, otherwise a const char* representing an error.
  234343. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234344. {
  234345. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234346. if (xml == 0)
  234347. return "Couldn't parse XML in file";
  234348. const XmlElement* const dict = xml->getChildByName ("dict");
  234349. if (dict == 0)
  234350. return "Couldn't get top level dictionary";
  234351. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234352. if (sessions == 0)
  234353. return "Couldn't find sessions key";
  234354. const XmlElement* const session = sessions->getFirstChildElement();
  234355. if (session == 0)
  234356. return "Couldn't find first session";
  234357. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234358. if (leadOut < 0)
  234359. return "Couldn't find Leadout Block";
  234360. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234361. if (trackArray == 0)
  234362. return "Couldn't find Track Array";
  234363. forEachXmlChildElement (*trackArray, track)
  234364. {
  234365. const int trackValue = getIntValueForKey (*track, "Start Block");
  234366. if (trackValue < 0)
  234367. return "Couldn't find Start Block in the track";
  234368. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234369. }
  234370. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234371. return 0;
  234372. }
  234373. static void findDevices (Array<File>& cds)
  234374. {
  234375. File volumes ("/Volumes");
  234376. volumes.findChildFiles (cds, File::findDirectories, false);
  234377. for (int i = cds.size(); --i >= 0;)
  234378. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234379. cds.remove (i);
  234380. }
  234381. struct TrackSorter
  234382. {
  234383. static int getCDTrackNumber (const File& file)
  234384. {
  234385. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234386. }
  234387. static int compareElements (const File& first, const File& second)
  234388. {
  234389. const int firstTrack = getCDTrackNumber (first);
  234390. const int secondTrack = getCDTrackNumber (second);
  234391. jassert (firstTrack > 0 && secondTrack > 0);
  234392. return firstTrack - secondTrack;
  234393. }
  234394. };
  234395. }
  234396. const StringArray AudioCDReader::getAvailableCDNames()
  234397. {
  234398. Array<File> cds;
  234399. CDReaderHelpers::findDevices (cds);
  234400. StringArray names;
  234401. for (int i = 0; i < cds.size(); ++i)
  234402. names.add (cds.getReference(i).getFileName());
  234403. return names;
  234404. }
  234405. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234406. {
  234407. Array<File> cds;
  234408. CDReaderHelpers::findDevices (cds);
  234409. if (cds[index].exists())
  234410. return new AudioCDReader (cds[index]);
  234411. return 0;
  234412. }
  234413. AudioCDReader::AudioCDReader (const File& volume)
  234414. : AudioFormatReader (0, "CD Audio"),
  234415. volumeDir (volume),
  234416. currentReaderTrack (-1),
  234417. reader (0)
  234418. {
  234419. sampleRate = 44100.0;
  234420. bitsPerSample = 16;
  234421. numChannels = 2;
  234422. usesFloatingPointData = false;
  234423. refreshTrackLengths();
  234424. }
  234425. AudioCDReader::~AudioCDReader()
  234426. {
  234427. }
  234428. void AudioCDReader::refreshTrackLengths()
  234429. {
  234430. tracks.clear();
  234431. trackStartSamples.clear();
  234432. lengthInSamples = 0;
  234433. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234434. CDReaderHelpers::TrackSorter sorter;
  234435. tracks.sort (sorter);
  234436. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234437. if (toc.exists())
  234438. {
  234439. XmlDocument doc (toc);
  234440. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234441. (void) error; // could be logged..
  234442. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234443. }
  234444. }
  234445. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234446. int64 startSampleInFile, int numSamples)
  234447. {
  234448. while (numSamples > 0)
  234449. {
  234450. int track = -1;
  234451. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234452. {
  234453. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234454. {
  234455. track = i;
  234456. break;
  234457. }
  234458. }
  234459. if (track < 0)
  234460. return false;
  234461. if (track != currentReaderTrack)
  234462. {
  234463. reader = 0;
  234464. FileInputStream* const in = tracks [track].createInputStream();
  234465. if (in != 0)
  234466. {
  234467. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234468. AiffAudioFormat format;
  234469. reader = format.createReaderFor (bin, true);
  234470. if (reader == 0)
  234471. currentReaderTrack = -1;
  234472. else
  234473. currentReaderTrack = track;
  234474. }
  234475. }
  234476. if (reader == 0)
  234477. return false;
  234478. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234479. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234480. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234481. numSamples -= numAvailable;
  234482. startSampleInFile += numAvailable;
  234483. }
  234484. return true;
  234485. }
  234486. bool AudioCDReader::isCDStillPresent() const
  234487. {
  234488. return volumeDir.exists();
  234489. }
  234490. bool AudioCDReader::isTrackAudio (int trackNum) const
  234491. {
  234492. return tracks [trackNum].hasFileExtension (".aiff");
  234493. }
  234494. void AudioCDReader::enableIndexScanning (bool b)
  234495. {
  234496. // any way to do this on a Mac??
  234497. }
  234498. int AudioCDReader::getLastIndex() const
  234499. {
  234500. return 0;
  234501. }
  234502. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234503. {
  234504. return Array <int>();
  234505. }
  234506. #endif
  234507. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234508. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234509. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234510. // compiled on its own).
  234511. #if JUCE_INCLUDED_FILE
  234512. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234513. for example having more than one juce plugin loaded into a host, then when a
  234514. method is called, the actual code that runs might actually be in a different module
  234515. than the one you expect... So any calls to library functions or statics that are
  234516. made inside obj-c methods will probably end up getting executed in a different DLL's
  234517. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234518. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234519. virtual methods of an object that's known to live inside the right module's space.
  234520. */
  234521. class AppDelegateRedirector
  234522. {
  234523. public:
  234524. AppDelegateRedirector()
  234525. {
  234526. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234527. runLoop = CFRunLoopGetMain();
  234528. #else
  234529. runLoop = CFRunLoopGetCurrent();
  234530. #endif
  234531. CFRunLoopSourceContext sourceContext;
  234532. zerostruct (sourceContext);
  234533. sourceContext.info = this;
  234534. sourceContext.perform = runLoopSourceCallback;
  234535. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234536. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234537. }
  234538. virtual ~AppDelegateRedirector()
  234539. {
  234540. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234541. CFRunLoopSourceInvalidate (runLoopSource);
  234542. CFRelease (runLoopSource);
  234543. }
  234544. virtual NSApplicationTerminateReply shouldTerminate()
  234545. {
  234546. if (JUCEApplication::getInstance() != 0)
  234547. {
  234548. JUCEApplication::getInstance()->systemRequestedQuit();
  234549. if (MessageManager::getInstance()->hasStopMessageBeenSent())
  234550. {
  234551. [NSApp performSelectorOnMainThread: @selector (replyToApplicationShouldTerminate:)
  234552. withObject: [NSNumber numberWithBool: YES]
  234553. waitUntilDone: NO];
  234554. return NSTerminateLater;
  234555. }
  234556. return NSTerminateCancel;
  234557. }
  234558. return NSTerminateNow;
  234559. }
  234560. virtual BOOL openFile (const NSString* filename)
  234561. {
  234562. if (JUCEApplication::getInstance() != 0)
  234563. {
  234564. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234565. return YES;
  234566. }
  234567. return NO;
  234568. }
  234569. virtual void openFiles (NSArray* filenames)
  234570. {
  234571. StringArray files;
  234572. for (unsigned int i = 0; i < [filenames count]; ++i)
  234573. {
  234574. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234575. if (filename.containsChar (' '))
  234576. filename = filename.quoted('"');
  234577. files.add (filename);
  234578. }
  234579. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234580. {
  234581. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234582. }
  234583. }
  234584. virtual void focusChanged()
  234585. {
  234586. juce_HandleProcessFocusChange();
  234587. }
  234588. struct CallbackMessagePayload
  234589. {
  234590. MessageCallbackFunction* function;
  234591. void* parameter;
  234592. void* volatile result;
  234593. bool volatile hasBeenExecuted;
  234594. };
  234595. virtual void performCallback (CallbackMessagePayload* pl)
  234596. {
  234597. pl->result = (*pl->function) (pl->parameter);
  234598. pl->hasBeenExecuted = true;
  234599. }
  234600. virtual void deleteSelf()
  234601. {
  234602. delete this;
  234603. }
  234604. void postMessage (Message* const m)
  234605. {
  234606. messages.add (m);
  234607. CFRunLoopSourceSignal (runLoopSource);
  234608. CFRunLoopWakeUp (runLoop);
  234609. }
  234610. private:
  234611. CFRunLoopRef runLoop;
  234612. CFRunLoopSourceRef runLoopSource;
  234613. OwnedArray <Message, CriticalSection> messages;
  234614. void runLoopCallback()
  234615. {
  234616. int numDispatched = 0;
  234617. do
  234618. {
  234619. Message* const nextMessage = messages.removeAndReturn (0);
  234620. if (nextMessage == 0)
  234621. return;
  234622. const ScopedAutoReleasePool pool;
  234623. MessageManager::getInstance()->deliverMessage (nextMessage);
  234624. } while (++numDispatched <= 4);
  234625. CFRunLoopSourceSignal (runLoopSource);
  234626. CFRunLoopWakeUp (runLoop);
  234627. }
  234628. static void runLoopSourceCallback (void* info)
  234629. {
  234630. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234631. }
  234632. };
  234633. END_JUCE_NAMESPACE
  234634. using namespace JUCE_NAMESPACE;
  234635. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234636. @interface JuceAppDelegate : NSObject
  234637. {
  234638. @private
  234639. id oldDelegate;
  234640. @public
  234641. AppDelegateRedirector* redirector;
  234642. }
  234643. - (JuceAppDelegate*) init;
  234644. - (void) dealloc;
  234645. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234646. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234647. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234648. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234649. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234650. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234651. - (void) performCallback: (id) info;
  234652. - (void) dummyMethod;
  234653. @end
  234654. @implementation JuceAppDelegate
  234655. - (JuceAppDelegate*) init
  234656. {
  234657. [super init];
  234658. redirector = new AppDelegateRedirector();
  234659. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234660. if (JUCEApplication::isStandaloneApp())
  234661. {
  234662. oldDelegate = [NSApp delegate];
  234663. [NSApp setDelegate: self];
  234664. }
  234665. else
  234666. {
  234667. oldDelegate = 0;
  234668. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234669. name: NSApplicationDidResignActiveNotification object: NSApp];
  234670. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234671. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234672. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234673. name: NSApplicationWillUnhideNotification object: NSApp];
  234674. }
  234675. return self;
  234676. }
  234677. - (void) dealloc
  234678. {
  234679. if (oldDelegate != 0)
  234680. [NSApp setDelegate: oldDelegate];
  234681. redirector->deleteSelf();
  234682. [super dealloc];
  234683. }
  234684. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234685. {
  234686. (void) app;
  234687. return redirector->shouldTerminate();
  234688. }
  234689. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234690. {
  234691. (void) app;
  234692. return redirector->openFile (filename);
  234693. }
  234694. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234695. {
  234696. (void) sender;
  234697. return redirector->openFiles (filenames);
  234698. }
  234699. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234700. {
  234701. (void) notification;
  234702. redirector->focusChanged();
  234703. }
  234704. - (void) applicationDidResignActive: (NSNotification*) notification
  234705. {
  234706. (void) notification;
  234707. redirector->focusChanged();
  234708. }
  234709. - (void) applicationWillUnhide: (NSNotification*) notification
  234710. {
  234711. (void) notification;
  234712. redirector->focusChanged();
  234713. }
  234714. - (void) performCallback: (id) info
  234715. {
  234716. if ([info isKindOfClass: [NSData class]])
  234717. {
  234718. AppDelegateRedirector::CallbackMessagePayload* pl
  234719. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234720. if (pl != 0)
  234721. redirector->performCallback (pl);
  234722. }
  234723. else
  234724. {
  234725. jassertfalse; // should never get here!
  234726. }
  234727. }
  234728. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234729. @end
  234730. BEGIN_JUCE_NAMESPACE
  234731. static JuceAppDelegate* juceAppDelegate = 0;
  234732. void MessageManager::runDispatchLoop()
  234733. {
  234734. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234735. {
  234736. const ScopedAutoReleasePool pool;
  234737. // must only be called by the message thread!
  234738. jassert (isThisTheMessageThread());
  234739. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234740. @try
  234741. {
  234742. [NSApp run];
  234743. }
  234744. @catch (NSException* e)
  234745. {
  234746. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234747. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234748. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234749. }
  234750. @finally
  234751. {
  234752. }
  234753. #else
  234754. [NSApp run];
  234755. #endif
  234756. }
  234757. }
  234758. void MessageManager::stopDispatchLoop()
  234759. {
  234760. quitMessagePosted = true;
  234761. [NSApp stop: nil];
  234762. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234763. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234764. }
  234765. static bool isEventBlockedByModalComps (NSEvent* e)
  234766. {
  234767. if (Component::getNumCurrentlyModalComponents() == 0)
  234768. return false;
  234769. NSWindow* const w = [e window];
  234770. if (w == 0 || [w worksWhenModal])
  234771. return false;
  234772. bool isKey = false, isInputAttempt = false;
  234773. switch ([e type])
  234774. {
  234775. case NSKeyDown:
  234776. case NSKeyUp:
  234777. isKey = isInputAttempt = true;
  234778. break;
  234779. case NSLeftMouseDown:
  234780. case NSRightMouseDown:
  234781. case NSOtherMouseDown:
  234782. isInputAttempt = true;
  234783. break;
  234784. case NSLeftMouseDragged:
  234785. case NSRightMouseDragged:
  234786. case NSLeftMouseUp:
  234787. case NSRightMouseUp:
  234788. case NSOtherMouseUp:
  234789. case NSOtherMouseDragged:
  234790. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234791. return false;
  234792. break;
  234793. case NSMouseMoved:
  234794. case NSMouseEntered:
  234795. case NSMouseExited:
  234796. case NSCursorUpdate:
  234797. case NSScrollWheel:
  234798. case NSTabletPoint:
  234799. case NSTabletProximity:
  234800. break;
  234801. default:
  234802. return false;
  234803. }
  234804. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234805. {
  234806. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234807. NSView* const compView = (NSView*) peer->getNativeHandle();
  234808. if ([compView window] == w)
  234809. {
  234810. if (isKey)
  234811. {
  234812. if (compView == [w firstResponder])
  234813. return false;
  234814. }
  234815. else
  234816. {
  234817. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234818. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234819. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234820. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234821. return false;
  234822. }
  234823. }
  234824. }
  234825. if (isInputAttempt)
  234826. {
  234827. if (! [NSApp isActive])
  234828. [NSApp activateIgnoringOtherApps: YES];
  234829. Component* const modal = Component::getCurrentlyModalComponent (0);
  234830. if (modal != 0)
  234831. modal->inputAttemptWhenModal();
  234832. }
  234833. return true;
  234834. }
  234835. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234836. {
  234837. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234838. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234839. while (! quitMessagePosted)
  234840. {
  234841. const ScopedAutoReleasePool pool;
  234842. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234843. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234844. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234845. inMode: NSDefaultRunLoopMode
  234846. dequeue: YES];
  234847. if (e != 0 && ! isEventBlockedByModalComps (e))
  234848. [NSApp sendEvent: e];
  234849. if (Time::getMillisecondCounter() >= endTime)
  234850. break;
  234851. }
  234852. return ! quitMessagePosted;
  234853. }
  234854. void MessageManager::doPlatformSpecificInitialisation()
  234855. {
  234856. if (juceAppDelegate == 0)
  234857. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234858. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234859. // correctly (needed prior to 10.5)
  234860. if (! [NSThread isMultiThreaded])
  234861. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234862. toTarget: juceAppDelegate
  234863. withObject: nil];
  234864. }
  234865. void MessageManager::doPlatformSpecificShutdown()
  234866. {
  234867. if (juceAppDelegate != 0)
  234868. {
  234869. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234870. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234871. [juceAppDelegate release];
  234872. juceAppDelegate = 0;
  234873. }
  234874. }
  234875. bool juce_postMessageToSystemQueue (Message* message)
  234876. {
  234877. juceAppDelegate->redirector->postMessage (message);
  234878. return true;
  234879. }
  234880. void MessageManager::broadcastMessage (const String& value)
  234881. {
  234882. }
  234883. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234884. {
  234885. if (isThisTheMessageThread())
  234886. {
  234887. return (*callback) (data);
  234888. }
  234889. else
  234890. {
  234891. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234892. // deadlock because the message manager is blocked from running, so can never
  234893. // call your function..
  234894. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234895. const ScopedAutoReleasePool pool;
  234896. AppDelegateRedirector::CallbackMessagePayload cmp;
  234897. cmp.function = callback;
  234898. cmp.parameter = data;
  234899. cmp.result = 0;
  234900. cmp.hasBeenExecuted = false;
  234901. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234902. withObject: [NSData dataWithBytesNoCopy: &cmp
  234903. length: sizeof (cmp)
  234904. freeWhenDone: NO]
  234905. waitUntilDone: YES];
  234906. return cmp.result;
  234907. }
  234908. }
  234909. #endif
  234910. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234911. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234912. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234913. // compiled on its own).
  234914. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234915. #if JUCE_MAC
  234916. END_JUCE_NAMESPACE
  234917. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234918. @interface DownloadClickDetector : NSObject
  234919. {
  234920. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234921. }
  234922. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234923. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234924. request: (NSURLRequest*) request
  234925. frame: (WebFrame*) frame
  234926. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234927. @end
  234928. @implementation DownloadClickDetector
  234929. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234930. {
  234931. [super init];
  234932. ownerComponent = ownerComponent_;
  234933. return self;
  234934. }
  234935. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234936. request: (NSURLRequest*) request
  234937. frame: (WebFrame*) frame
  234938. decisionListener: (id <WebPolicyDecisionListener>) listener
  234939. {
  234940. (void) sender;
  234941. (void) request;
  234942. (void) frame;
  234943. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234944. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234945. [listener use];
  234946. else
  234947. [listener ignore];
  234948. }
  234949. @end
  234950. BEGIN_JUCE_NAMESPACE
  234951. class WebBrowserComponentInternal : public NSViewComponent
  234952. {
  234953. public:
  234954. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234955. {
  234956. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234957. frameName: @""
  234958. groupName: @""];
  234959. setView (webView);
  234960. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234961. [webView setPolicyDelegate: clickListener];
  234962. }
  234963. ~WebBrowserComponentInternal()
  234964. {
  234965. [webView setPolicyDelegate: nil];
  234966. [clickListener release];
  234967. setView (0);
  234968. }
  234969. void goToURL (const String& url,
  234970. const StringArray* headers,
  234971. const MemoryBlock* postData)
  234972. {
  234973. NSMutableURLRequest* r
  234974. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234975. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234976. timeoutInterval: 30.0];
  234977. if (postData != 0 && postData->getSize() > 0)
  234978. {
  234979. [r setHTTPMethod: @"POST"];
  234980. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234981. length: postData->getSize()]];
  234982. }
  234983. if (headers != 0)
  234984. {
  234985. for (int i = 0; i < headers->size(); ++i)
  234986. {
  234987. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234988. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234989. [r setValue: juceStringToNS (headerValue)
  234990. forHTTPHeaderField: juceStringToNS (headerName)];
  234991. }
  234992. }
  234993. stop();
  234994. [[webView mainFrame] loadRequest: r];
  234995. }
  234996. void goBack()
  234997. {
  234998. [webView goBack];
  234999. }
  235000. void goForward()
  235001. {
  235002. [webView goForward];
  235003. }
  235004. void stop()
  235005. {
  235006. [webView stopLoading: nil];
  235007. }
  235008. void refresh()
  235009. {
  235010. [webView reload: nil];
  235011. }
  235012. private:
  235013. WebView* webView;
  235014. DownloadClickDetector* clickListener;
  235015. };
  235016. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235017. : browser (0),
  235018. blankPageShown (false),
  235019. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235020. {
  235021. setOpaque (true);
  235022. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235023. }
  235024. WebBrowserComponent::~WebBrowserComponent()
  235025. {
  235026. deleteAndZero (browser);
  235027. }
  235028. void WebBrowserComponent::goToURL (const String& url,
  235029. const StringArray* headers,
  235030. const MemoryBlock* postData)
  235031. {
  235032. lastURL = url;
  235033. lastHeaders.clear();
  235034. if (headers != 0)
  235035. lastHeaders = *headers;
  235036. lastPostData.setSize (0);
  235037. if (postData != 0)
  235038. lastPostData = *postData;
  235039. blankPageShown = false;
  235040. browser->goToURL (url, headers, postData);
  235041. }
  235042. void WebBrowserComponent::stop()
  235043. {
  235044. browser->stop();
  235045. }
  235046. void WebBrowserComponent::goBack()
  235047. {
  235048. lastURL = String::empty;
  235049. blankPageShown = false;
  235050. browser->goBack();
  235051. }
  235052. void WebBrowserComponent::goForward()
  235053. {
  235054. lastURL = String::empty;
  235055. browser->goForward();
  235056. }
  235057. void WebBrowserComponent::refresh()
  235058. {
  235059. browser->refresh();
  235060. }
  235061. void WebBrowserComponent::paint (Graphics&)
  235062. {
  235063. }
  235064. void WebBrowserComponent::checkWindowAssociation()
  235065. {
  235066. if (isShowing())
  235067. {
  235068. if (blankPageShown)
  235069. goBack();
  235070. }
  235071. else
  235072. {
  235073. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235074. {
  235075. // when the component becomes invisible, some stuff like flash
  235076. // carries on playing audio, so we need to force it onto a blank
  235077. // page to avoid this, (and send it back when it's made visible again).
  235078. blankPageShown = true;
  235079. browser->goToURL ("about:blank", 0, 0);
  235080. }
  235081. }
  235082. }
  235083. void WebBrowserComponent::reloadLastURL()
  235084. {
  235085. if (lastURL.isNotEmpty())
  235086. {
  235087. goToURL (lastURL, &lastHeaders, &lastPostData);
  235088. lastURL = String::empty;
  235089. }
  235090. }
  235091. void WebBrowserComponent::parentHierarchyChanged()
  235092. {
  235093. checkWindowAssociation();
  235094. }
  235095. void WebBrowserComponent::resized()
  235096. {
  235097. browser->setSize (getWidth(), getHeight());
  235098. }
  235099. void WebBrowserComponent::visibilityChanged()
  235100. {
  235101. checkWindowAssociation();
  235102. }
  235103. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235104. {
  235105. return true;
  235106. }
  235107. #else
  235108. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235109. {
  235110. }
  235111. WebBrowserComponent::~WebBrowserComponent()
  235112. {
  235113. }
  235114. void WebBrowserComponent::goToURL (const String& url,
  235115. const StringArray* headers,
  235116. const MemoryBlock* postData)
  235117. {
  235118. }
  235119. void WebBrowserComponent::stop()
  235120. {
  235121. }
  235122. void WebBrowserComponent::goBack()
  235123. {
  235124. }
  235125. void WebBrowserComponent::goForward()
  235126. {
  235127. }
  235128. void WebBrowserComponent::refresh()
  235129. {
  235130. }
  235131. void WebBrowserComponent::paint (Graphics& g)
  235132. {
  235133. }
  235134. void WebBrowserComponent::checkWindowAssociation()
  235135. {
  235136. }
  235137. void WebBrowserComponent::reloadLastURL()
  235138. {
  235139. }
  235140. void WebBrowserComponent::parentHierarchyChanged()
  235141. {
  235142. }
  235143. void WebBrowserComponent::resized()
  235144. {
  235145. }
  235146. void WebBrowserComponent::visibilityChanged()
  235147. {
  235148. }
  235149. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235150. {
  235151. return true;
  235152. }
  235153. #endif
  235154. #endif
  235155. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235156. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235157. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235158. // compiled on its own).
  235159. #if JUCE_INCLUDED_FILE
  235160. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235161. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235162. #endif
  235163. #undef log
  235164. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235165. #define log(a) Logger::writeToLog (a)
  235166. #else
  235167. #define log(a)
  235168. #endif
  235169. #undef OK
  235170. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235171. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235172. {
  235173. if (err == noErr)
  235174. return true;
  235175. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235176. jassertfalse;
  235177. return false;
  235178. }
  235179. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235180. #else
  235181. #define OK(a) (a == noErr)
  235182. #endif
  235183. class CoreAudioInternal : public Timer
  235184. {
  235185. public:
  235186. CoreAudioInternal (AudioDeviceID id)
  235187. : inputLatency (0),
  235188. outputLatency (0),
  235189. callback (0),
  235190. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235191. audioProcID (0),
  235192. #endif
  235193. isSlaveDevice (false),
  235194. deviceID (id),
  235195. started (false),
  235196. sampleRate (0),
  235197. bufferSize (512),
  235198. numInputChans (0),
  235199. numOutputChans (0),
  235200. callbacksAllowed (true),
  235201. numInputChannelInfos (0),
  235202. numOutputChannelInfos (0)
  235203. {
  235204. jassert (deviceID != 0);
  235205. updateDetailsFromDevice();
  235206. AudioObjectPropertyAddress pa;
  235207. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235208. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235209. pa.mElement = kAudioObjectPropertyElementWildcard;
  235210. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235211. }
  235212. ~CoreAudioInternal()
  235213. {
  235214. AudioObjectPropertyAddress pa;
  235215. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235216. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235217. pa.mElement = kAudioObjectPropertyElementWildcard;
  235218. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235219. stop (false);
  235220. }
  235221. void allocateTempBuffers()
  235222. {
  235223. const int tempBufSize = bufferSize + 4;
  235224. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235225. tempInputBuffers.calloc (numInputChans + 2);
  235226. tempOutputBuffers.calloc (numOutputChans + 2);
  235227. int i, count = 0;
  235228. for (i = 0; i < numInputChans; ++i)
  235229. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235230. for (i = 0; i < numOutputChans; ++i)
  235231. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235232. }
  235233. // returns the number of actual available channels
  235234. void fillInChannelInfo (const bool input)
  235235. {
  235236. int chanNum = 0;
  235237. UInt32 size;
  235238. AudioObjectPropertyAddress pa;
  235239. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235240. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235241. pa.mElement = kAudioObjectPropertyElementMaster;
  235242. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235243. {
  235244. HeapBlock <AudioBufferList> bufList;
  235245. bufList.calloc (size, 1);
  235246. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235247. {
  235248. const int numStreams = bufList->mNumberBuffers;
  235249. for (int i = 0; i < numStreams; ++i)
  235250. {
  235251. const AudioBuffer& b = bufList->mBuffers[i];
  235252. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235253. {
  235254. String name;
  235255. {
  235256. char channelName [256];
  235257. zerostruct (channelName);
  235258. UInt32 nameSize = sizeof (channelName);
  235259. UInt32 channelNum = chanNum + 1;
  235260. pa.mSelector = kAudioDevicePropertyChannelName;
  235261. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235262. name = String::fromUTF8 (channelName, nameSize);
  235263. }
  235264. if (input)
  235265. {
  235266. if (activeInputChans[chanNum])
  235267. {
  235268. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235269. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235270. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235271. ++numInputChannelInfos;
  235272. }
  235273. if (name.isEmpty())
  235274. name << "Input " << (chanNum + 1);
  235275. inChanNames.add (name);
  235276. }
  235277. else
  235278. {
  235279. if (activeOutputChans[chanNum])
  235280. {
  235281. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235282. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235283. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235284. ++numOutputChannelInfos;
  235285. }
  235286. if (name.isEmpty())
  235287. name << "Output " << (chanNum + 1);
  235288. outChanNames.add (name);
  235289. }
  235290. ++chanNum;
  235291. }
  235292. }
  235293. }
  235294. }
  235295. }
  235296. void updateDetailsFromDevice()
  235297. {
  235298. stopTimer();
  235299. if (deviceID == 0)
  235300. return;
  235301. const ScopedLock sl (callbackLock);
  235302. Float64 sr;
  235303. UInt32 size = sizeof (Float64);
  235304. AudioObjectPropertyAddress pa;
  235305. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235306. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235307. pa.mElement = kAudioObjectPropertyElementMaster;
  235308. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235309. sampleRate = sr;
  235310. UInt32 framesPerBuf;
  235311. size = sizeof (framesPerBuf);
  235312. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235313. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235314. {
  235315. bufferSize = framesPerBuf;
  235316. allocateTempBuffers();
  235317. }
  235318. bufferSizes.clear();
  235319. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235320. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235321. {
  235322. HeapBlock <AudioValueRange> ranges;
  235323. ranges.calloc (size, 1);
  235324. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235325. {
  235326. bufferSizes.add ((int) ranges[0].mMinimum);
  235327. for (int i = 32; i < 2048; i += 32)
  235328. {
  235329. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235330. {
  235331. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235332. {
  235333. bufferSizes.addIfNotAlreadyThere (i);
  235334. break;
  235335. }
  235336. }
  235337. }
  235338. if (bufferSize > 0)
  235339. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235340. }
  235341. }
  235342. if (bufferSizes.size() == 0 && bufferSize > 0)
  235343. bufferSizes.add (bufferSize);
  235344. sampleRates.clear();
  235345. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235346. String rates;
  235347. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235348. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235349. {
  235350. HeapBlock <AudioValueRange> ranges;
  235351. ranges.calloc (size, 1);
  235352. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235353. {
  235354. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235355. {
  235356. bool ok = false;
  235357. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235358. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235359. ok = true;
  235360. if (ok)
  235361. {
  235362. sampleRates.add (possibleRates[i]);
  235363. rates << possibleRates[i] << ' ';
  235364. }
  235365. }
  235366. }
  235367. }
  235368. if (sampleRates.size() == 0 && sampleRate > 0)
  235369. {
  235370. sampleRates.add (sampleRate);
  235371. rates << sampleRate;
  235372. }
  235373. log ("sr: " + rates);
  235374. inputLatency = 0;
  235375. outputLatency = 0;
  235376. UInt32 lat;
  235377. size = sizeof (lat);
  235378. pa.mSelector = kAudioDevicePropertyLatency;
  235379. pa.mScope = kAudioDevicePropertyScopeInput;
  235380. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  235381. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235382. inputLatency = (int) lat;
  235383. pa.mScope = kAudioDevicePropertyScopeOutput;
  235384. size = sizeof (lat);
  235385. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235386. outputLatency = (int) lat;
  235387. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235388. inChanNames.clear();
  235389. outChanNames.clear();
  235390. inputChannelInfo.calloc (numInputChans + 2);
  235391. numInputChannelInfos = 0;
  235392. outputChannelInfo.calloc (numOutputChans + 2);
  235393. numOutputChannelInfos = 0;
  235394. fillInChannelInfo (true);
  235395. fillInChannelInfo (false);
  235396. }
  235397. const StringArray getSources (bool input)
  235398. {
  235399. StringArray s;
  235400. HeapBlock <OSType> types;
  235401. const int num = getAllDataSourcesForDevice (deviceID, types);
  235402. for (int i = 0; i < num; ++i)
  235403. {
  235404. AudioValueTranslation avt;
  235405. char buffer[256];
  235406. avt.mInputData = &(types[i]);
  235407. avt.mInputDataSize = sizeof (UInt32);
  235408. avt.mOutputData = buffer;
  235409. avt.mOutputDataSize = 256;
  235410. UInt32 transSize = sizeof (avt);
  235411. AudioObjectPropertyAddress pa;
  235412. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235413. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235414. pa.mElement = kAudioObjectPropertyElementMaster;
  235415. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235416. {
  235417. DBG (buffer);
  235418. s.add (buffer);
  235419. }
  235420. }
  235421. return s;
  235422. }
  235423. int getCurrentSourceIndex (bool input) const
  235424. {
  235425. OSType currentSourceID = 0;
  235426. UInt32 size = sizeof (currentSourceID);
  235427. int result = -1;
  235428. AudioObjectPropertyAddress pa;
  235429. pa.mSelector = kAudioDevicePropertyDataSource;
  235430. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235431. pa.mElement = kAudioObjectPropertyElementMaster;
  235432. if (deviceID != 0)
  235433. {
  235434. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235435. {
  235436. HeapBlock <OSType> types;
  235437. const int num = getAllDataSourcesForDevice (deviceID, types);
  235438. for (int i = 0; i < num; ++i)
  235439. {
  235440. if (types[num] == currentSourceID)
  235441. {
  235442. result = i;
  235443. break;
  235444. }
  235445. }
  235446. }
  235447. }
  235448. return result;
  235449. }
  235450. void setCurrentSourceIndex (int index, bool input)
  235451. {
  235452. if (deviceID != 0)
  235453. {
  235454. HeapBlock <OSType> types;
  235455. const int num = getAllDataSourcesForDevice (deviceID, types);
  235456. if (((unsigned int) index) < (unsigned int) num)
  235457. {
  235458. AudioObjectPropertyAddress pa;
  235459. pa.mSelector = kAudioDevicePropertyDataSource;
  235460. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235461. pa.mElement = kAudioObjectPropertyElementMaster;
  235462. OSType typeId = types[index];
  235463. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235464. }
  235465. }
  235466. }
  235467. const String reopen (const BigInteger& inputChannels,
  235468. const BigInteger& outputChannels,
  235469. double newSampleRate,
  235470. int bufferSizeSamples)
  235471. {
  235472. String error;
  235473. log ("CoreAudio reopen");
  235474. callbacksAllowed = false;
  235475. stopTimer();
  235476. stop (false);
  235477. activeInputChans = inputChannels;
  235478. activeInputChans.setRange (inChanNames.size(),
  235479. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235480. false);
  235481. activeOutputChans = outputChannels;
  235482. activeOutputChans.setRange (outChanNames.size(),
  235483. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235484. false);
  235485. numInputChans = activeInputChans.countNumberOfSetBits();
  235486. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235487. // set sample rate
  235488. AudioObjectPropertyAddress pa;
  235489. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235490. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235491. pa.mElement = kAudioObjectPropertyElementMaster;
  235492. Float64 sr = newSampleRate;
  235493. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235494. {
  235495. error = "Couldn't change sample rate";
  235496. }
  235497. else
  235498. {
  235499. // change buffer size
  235500. UInt32 framesPerBuf = bufferSizeSamples;
  235501. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235502. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235503. {
  235504. error = "Couldn't change buffer size";
  235505. }
  235506. else
  235507. {
  235508. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235509. // correctly report their new settings until some random time in the future, so
  235510. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235511. // to make sure we're using the correct numbers..
  235512. updateDetailsFromDevice();
  235513. sampleRate = newSampleRate;
  235514. bufferSize = bufferSizeSamples;
  235515. if (sampleRates.size() == 0)
  235516. error = "Device has no available sample-rates";
  235517. else if (bufferSizes.size() == 0)
  235518. error = "Device has no available buffer-sizes";
  235519. else if (inputDevice != 0)
  235520. error = inputDevice->reopen (inputChannels,
  235521. outputChannels,
  235522. newSampleRate,
  235523. bufferSizeSamples);
  235524. }
  235525. }
  235526. callbacksAllowed = true;
  235527. return error;
  235528. }
  235529. bool start (AudioIODeviceCallback* cb)
  235530. {
  235531. if (! started)
  235532. {
  235533. callback = 0;
  235534. if (deviceID != 0)
  235535. {
  235536. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235537. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235538. #else
  235539. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235540. #endif
  235541. {
  235542. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235543. {
  235544. started = true;
  235545. }
  235546. else
  235547. {
  235548. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235549. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235550. #else
  235551. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235552. audioProcID = 0;
  235553. #endif
  235554. }
  235555. }
  235556. }
  235557. }
  235558. if (started)
  235559. {
  235560. const ScopedLock sl (callbackLock);
  235561. callback = cb;
  235562. }
  235563. if (inputDevice != 0)
  235564. return started && inputDevice->start (cb);
  235565. else
  235566. return started;
  235567. }
  235568. void stop (bool leaveInterruptRunning)
  235569. {
  235570. {
  235571. const ScopedLock sl (callbackLock);
  235572. callback = 0;
  235573. }
  235574. if (started
  235575. && (deviceID != 0)
  235576. && ! leaveInterruptRunning)
  235577. {
  235578. OK (AudioDeviceStop (deviceID, audioIOProc));
  235579. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235580. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235581. #else
  235582. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235583. audioProcID = 0;
  235584. #endif
  235585. started = false;
  235586. { const ScopedLock sl (callbackLock); }
  235587. // wait until it's definately stopped calling back..
  235588. for (int i = 40; --i >= 0;)
  235589. {
  235590. Thread::sleep (50);
  235591. UInt32 running = 0;
  235592. UInt32 size = sizeof (running);
  235593. AudioObjectPropertyAddress pa;
  235594. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235595. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235596. pa.mElement = kAudioObjectPropertyElementMaster;
  235597. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235598. if (running == 0)
  235599. break;
  235600. }
  235601. const ScopedLock sl (callbackLock);
  235602. }
  235603. if (inputDevice != 0)
  235604. inputDevice->stop (leaveInterruptRunning);
  235605. }
  235606. double getSampleRate() const
  235607. {
  235608. return sampleRate;
  235609. }
  235610. int getBufferSize() const
  235611. {
  235612. return bufferSize;
  235613. }
  235614. void audioCallback (const AudioBufferList* inInputData,
  235615. AudioBufferList* outOutputData)
  235616. {
  235617. int i;
  235618. const ScopedLock sl (callbackLock);
  235619. if (callback != 0)
  235620. {
  235621. if (inputDevice == 0)
  235622. {
  235623. for (i = numInputChans; --i >= 0;)
  235624. {
  235625. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235626. float* dest = tempInputBuffers [i];
  235627. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235628. + info.dataOffsetSamples;
  235629. const int stride = info.dataStrideSamples;
  235630. if (stride != 0) // if this is zero, info is invalid
  235631. {
  235632. for (int j = bufferSize; --j >= 0;)
  235633. {
  235634. *dest++ = *src;
  235635. src += stride;
  235636. }
  235637. }
  235638. }
  235639. }
  235640. if (! isSlaveDevice)
  235641. {
  235642. if (inputDevice == 0)
  235643. {
  235644. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235645. numInputChans,
  235646. tempOutputBuffers,
  235647. numOutputChans,
  235648. bufferSize);
  235649. }
  235650. else
  235651. {
  235652. jassert (inputDevice->bufferSize == bufferSize);
  235653. // Sometimes the two linked devices seem to get their callbacks in
  235654. // parallel, so we need to lock both devices to stop the input data being
  235655. // changed while inside our callback..
  235656. const ScopedLock sl2 (inputDevice->callbackLock);
  235657. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235658. inputDevice->numInputChans,
  235659. tempOutputBuffers,
  235660. numOutputChans,
  235661. bufferSize);
  235662. }
  235663. for (i = numOutputChans; --i >= 0;)
  235664. {
  235665. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235666. const float* src = tempOutputBuffers [i];
  235667. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235668. + info.dataOffsetSamples;
  235669. const int stride = info.dataStrideSamples;
  235670. if (stride != 0) // if this is zero, info is invalid
  235671. {
  235672. for (int j = bufferSize; --j >= 0;)
  235673. {
  235674. *dest = *src++;
  235675. dest += stride;
  235676. }
  235677. }
  235678. }
  235679. }
  235680. }
  235681. else
  235682. {
  235683. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235684. {
  235685. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235686. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235687. + info.dataOffsetSamples;
  235688. const int stride = info.dataStrideSamples;
  235689. if (stride != 0) // if this is zero, info is invalid
  235690. {
  235691. for (int j = bufferSize; --j >= 0;)
  235692. {
  235693. *dest = 0.0f;
  235694. dest += stride;
  235695. }
  235696. }
  235697. }
  235698. }
  235699. }
  235700. // called by callbacks
  235701. void deviceDetailsChanged()
  235702. {
  235703. if (callbacksAllowed)
  235704. startTimer (100);
  235705. }
  235706. void timerCallback()
  235707. {
  235708. stopTimer();
  235709. log ("CoreAudio device changed callback");
  235710. const double oldSampleRate = sampleRate;
  235711. const int oldBufferSize = bufferSize;
  235712. updateDetailsFromDevice();
  235713. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235714. {
  235715. callbacksAllowed = false;
  235716. stop (false);
  235717. updateDetailsFromDevice();
  235718. callbacksAllowed = true;
  235719. }
  235720. }
  235721. CoreAudioInternal* getRelatedDevice() const
  235722. {
  235723. UInt32 size = 0;
  235724. ScopedPointer <CoreAudioInternal> result;
  235725. AudioObjectPropertyAddress pa;
  235726. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235727. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235728. pa.mElement = kAudioObjectPropertyElementMaster;
  235729. if (deviceID != 0
  235730. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235731. && size > 0)
  235732. {
  235733. HeapBlock <AudioDeviceID> devs;
  235734. devs.calloc (size, 1);
  235735. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235736. {
  235737. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235738. {
  235739. if (devs[i] != deviceID && devs[i] != 0)
  235740. {
  235741. result = new CoreAudioInternal (devs[i]);
  235742. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235743. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235744. if (thisIsInput != otherIsInput
  235745. || (inChanNames.size() + outChanNames.size() == 0)
  235746. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235747. break;
  235748. result = 0;
  235749. }
  235750. }
  235751. }
  235752. }
  235753. return result.release();
  235754. }
  235755. juce_UseDebuggingNewOperator
  235756. int inputLatency, outputLatency;
  235757. BigInteger activeInputChans, activeOutputChans;
  235758. StringArray inChanNames, outChanNames;
  235759. Array <double> sampleRates;
  235760. Array <int> bufferSizes;
  235761. AudioIODeviceCallback* callback;
  235762. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235763. AudioDeviceIOProcID audioProcID;
  235764. #endif
  235765. ScopedPointer<CoreAudioInternal> inputDevice;
  235766. bool isSlaveDevice;
  235767. private:
  235768. CriticalSection callbackLock;
  235769. AudioDeviceID deviceID;
  235770. bool started;
  235771. double sampleRate;
  235772. int bufferSize;
  235773. HeapBlock <float> audioBuffer;
  235774. int numInputChans, numOutputChans;
  235775. bool callbacksAllowed;
  235776. struct CallbackDetailsForChannel
  235777. {
  235778. int streamNum;
  235779. int dataOffsetSamples;
  235780. int dataStrideSamples;
  235781. };
  235782. int numInputChannelInfos, numOutputChannelInfos;
  235783. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235784. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235785. CoreAudioInternal (const CoreAudioInternal&);
  235786. CoreAudioInternal& operator= (const CoreAudioInternal&);
  235787. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235788. const AudioTimeStamp* /*inNow*/,
  235789. const AudioBufferList* inInputData,
  235790. const AudioTimeStamp* /*inInputTime*/,
  235791. AudioBufferList* outOutputData,
  235792. const AudioTimeStamp* /*inOutputTime*/,
  235793. void* device)
  235794. {
  235795. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235796. return noErr;
  235797. }
  235798. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235799. {
  235800. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235801. switch (pa->mSelector)
  235802. {
  235803. case kAudioDevicePropertyBufferSize:
  235804. case kAudioDevicePropertyBufferFrameSize:
  235805. case kAudioDevicePropertyNominalSampleRate:
  235806. case kAudioDevicePropertyStreamFormat:
  235807. case kAudioDevicePropertyDeviceIsAlive:
  235808. intern->deviceDetailsChanged();
  235809. break;
  235810. case kAudioDevicePropertyBufferSizeRange:
  235811. case kAudioDevicePropertyVolumeScalar:
  235812. case kAudioDevicePropertyMute:
  235813. case kAudioDevicePropertyPlayThru:
  235814. case kAudioDevicePropertyDataSource:
  235815. case kAudioDevicePropertyDeviceIsRunning:
  235816. break;
  235817. }
  235818. return noErr;
  235819. }
  235820. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235821. {
  235822. AudioObjectPropertyAddress pa;
  235823. pa.mSelector = kAudioDevicePropertyDataSources;
  235824. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235825. pa.mElement = kAudioObjectPropertyElementMaster;
  235826. UInt32 size = 0;
  235827. if (deviceID != 0
  235828. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235829. {
  235830. types.calloc (size, 1);
  235831. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235832. return size / (int) sizeof (OSType);
  235833. }
  235834. return 0;
  235835. }
  235836. };
  235837. class CoreAudioIODevice : public AudioIODevice
  235838. {
  235839. public:
  235840. CoreAudioIODevice (const String& deviceName,
  235841. AudioDeviceID inputDeviceId,
  235842. const int inputIndex_,
  235843. AudioDeviceID outputDeviceId,
  235844. const int outputIndex_)
  235845. : AudioIODevice (deviceName, "CoreAudio"),
  235846. inputIndex (inputIndex_),
  235847. outputIndex (outputIndex_),
  235848. isOpen_ (false),
  235849. isStarted (false)
  235850. {
  235851. CoreAudioInternal* device = 0;
  235852. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235853. {
  235854. jassert (inputDeviceId != 0);
  235855. device = new CoreAudioInternal (inputDeviceId);
  235856. }
  235857. else
  235858. {
  235859. device = new CoreAudioInternal (outputDeviceId);
  235860. if (inputDeviceId != 0)
  235861. {
  235862. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235863. device->inputDevice = secondDevice;
  235864. secondDevice->isSlaveDevice = true;
  235865. }
  235866. }
  235867. internal = device;
  235868. AudioObjectPropertyAddress pa;
  235869. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235870. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235871. pa.mElement = kAudioObjectPropertyElementWildcard;
  235872. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235873. }
  235874. ~CoreAudioIODevice()
  235875. {
  235876. AudioObjectPropertyAddress pa;
  235877. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235878. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235879. pa.mElement = kAudioObjectPropertyElementWildcard;
  235880. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235881. }
  235882. const StringArray getOutputChannelNames()
  235883. {
  235884. return internal->outChanNames;
  235885. }
  235886. const StringArray getInputChannelNames()
  235887. {
  235888. if (internal->inputDevice != 0)
  235889. return internal->inputDevice->inChanNames;
  235890. else
  235891. return internal->inChanNames;
  235892. }
  235893. int getNumSampleRates()
  235894. {
  235895. return internal->sampleRates.size();
  235896. }
  235897. double getSampleRate (int index)
  235898. {
  235899. return internal->sampleRates [index];
  235900. }
  235901. int getNumBufferSizesAvailable()
  235902. {
  235903. return internal->bufferSizes.size();
  235904. }
  235905. int getBufferSizeSamples (int index)
  235906. {
  235907. return internal->bufferSizes [index];
  235908. }
  235909. int getDefaultBufferSize()
  235910. {
  235911. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235912. if (getBufferSizeSamples(i) >= 512)
  235913. return getBufferSizeSamples(i);
  235914. return 512;
  235915. }
  235916. const String open (const BigInteger& inputChannels,
  235917. const BigInteger& outputChannels,
  235918. double sampleRate,
  235919. int bufferSizeSamples)
  235920. {
  235921. isOpen_ = true;
  235922. if (bufferSizeSamples <= 0)
  235923. bufferSizeSamples = getDefaultBufferSize();
  235924. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235925. isOpen_ = lastError.isEmpty();
  235926. return lastError;
  235927. }
  235928. void close()
  235929. {
  235930. isOpen_ = false;
  235931. internal->stop (false);
  235932. }
  235933. bool isOpen()
  235934. {
  235935. return isOpen_;
  235936. }
  235937. int getCurrentBufferSizeSamples()
  235938. {
  235939. return internal != 0 ? internal->getBufferSize() : 512;
  235940. }
  235941. double getCurrentSampleRate()
  235942. {
  235943. return internal != 0 ? internal->getSampleRate() : 0;
  235944. }
  235945. int getCurrentBitDepth()
  235946. {
  235947. return 32; // no way to find out, so just assume it's high..
  235948. }
  235949. const BigInteger getActiveOutputChannels() const
  235950. {
  235951. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235952. }
  235953. const BigInteger getActiveInputChannels() const
  235954. {
  235955. BigInteger chans;
  235956. if (internal != 0)
  235957. {
  235958. chans = internal->activeInputChans;
  235959. if (internal->inputDevice != 0)
  235960. chans |= internal->inputDevice->activeInputChans;
  235961. }
  235962. return chans;
  235963. }
  235964. int getOutputLatencyInSamples()
  235965. {
  235966. if (internal == 0)
  235967. return 0;
  235968. // this seems like a good guess at getting the latency right - comparing
  235969. // this with a round-trip measurement, it gets it to within a few millisecs
  235970. // for the built-in mac soundcard
  235971. return internal->outputLatency + internal->getBufferSize() * 2;
  235972. }
  235973. int getInputLatencyInSamples()
  235974. {
  235975. if (internal == 0)
  235976. return 0;
  235977. return internal->inputLatency + internal->getBufferSize() * 2;
  235978. }
  235979. void start (AudioIODeviceCallback* callback)
  235980. {
  235981. if (internal != 0 && ! isStarted)
  235982. {
  235983. if (callback != 0)
  235984. callback->audioDeviceAboutToStart (this);
  235985. isStarted = true;
  235986. internal->start (callback);
  235987. }
  235988. }
  235989. void stop()
  235990. {
  235991. if (isStarted && internal != 0)
  235992. {
  235993. AudioIODeviceCallback* const lastCallback = internal->callback;
  235994. isStarted = false;
  235995. internal->stop (true);
  235996. if (lastCallback != 0)
  235997. lastCallback->audioDeviceStopped();
  235998. }
  235999. }
  236000. bool isPlaying()
  236001. {
  236002. if (internal->callback == 0)
  236003. isStarted = false;
  236004. return isStarted;
  236005. }
  236006. const String getLastError()
  236007. {
  236008. return lastError;
  236009. }
  236010. int inputIndex, outputIndex;
  236011. juce_UseDebuggingNewOperator
  236012. private:
  236013. ScopedPointer<CoreAudioInternal> internal;
  236014. bool isOpen_, isStarted;
  236015. String lastError;
  236016. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236017. {
  236018. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236019. switch (pa->mSelector)
  236020. {
  236021. case kAudioHardwarePropertyDevices:
  236022. intern->deviceDetailsChanged();
  236023. break;
  236024. case kAudioHardwarePropertyDefaultOutputDevice:
  236025. case kAudioHardwarePropertyDefaultInputDevice:
  236026. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236027. break;
  236028. }
  236029. return noErr;
  236030. }
  236031. CoreAudioIODevice (const CoreAudioIODevice&);
  236032. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236033. };
  236034. class CoreAudioIODeviceType : public AudioIODeviceType
  236035. {
  236036. public:
  236037. CoreAudioIODeviceType()
  236038. : AudioIODeviceType ("CoreAudio"),
  236039. hasScanned (false)
  236040. {
  236041. }
  236042. ~CoreAudioIODeviceType()
  236043. {
  236044. }
  236045. void scanForDevices()
  236046. {
  236047. hasScanned = true;
  236048. inputDeviceNames.clear();
  236049. outputDeviceNames.clear();
  236050. inputIds.clear();
  236051. outputIds.clear();
  236052. UInt32 size;
  236053. AudioObjectPropertyAddress pa;
  236054. pa.mSelector = kAudioHardwarePropertyDevices;
  236055. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236056. pa.mElement = kAudioObjectPropertyElementMaster;
  236057. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236058. {
  236059. HeapBlock <AudioDeviceID> devs;
  236060. devs.calloc (size, 1);
  236061. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236062. {
  236063. const int num = size / (int) sizeof (AudioDeviceID);
  236064. for (int i = 0; i < num; ++i)
  236065. {
  236066. char name [1024];
  236067. size = sizeof (name);
  236068. pa.mSelector = kAudioDevicePropertyDeviceName;
  236069. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236070. {
  236071. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236072. const int numIns = getNumChannels (devs[i], true);
  236073. const int numOuts = getNumChannels (devs[i], false);
  236074. if (numIns > 0)
  236075. {
  236076. inputDeviceNames.add (nameString);
  236077. inputIds.add (devs[i]);
  236078. }
  236079. if (numOuts > 0)
  236080. {
  236081. outputDeviceNames.add (nameString);
  236082. outputIds.add (devs[i]);
  236083. }
  236084. }
  236085. }
  236086. }
  236087. }
  236088. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236089. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236090. }
  236091. const StringArray getDeviceNames (bool wantInputNames) const
  236092. {
  236093. jassert (hasScanned); // need to call scanForDevices() before doing this
  236094. if (wantInputNames)
  236095. return inputDeviceNames;
  236096. else
  236097. return outputDeviceNames;
  236098. }
  236099. int getDefaultDeviceIndex (bool forInput) const
  236100. {
  236101. jassert (hasScanned); // need to call scanForDevices() before doing this
  236102. AudioDeviceID deviceID;
  236103. UInt32 size = sizeof (deviceID);
  236104. // if they're asking for any input channels at all, use the default input, so we
  236105. // get the built-in mic rather than the built-in output with no inputs..
  236106. AudioObjectPropertyAddress pa;
  236107. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236108. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236109. pa.mElement = kAudioObjectPropertyElementMaster;
  236110. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236111. {
  236112. if (forInput)
  236113. {
  236114. for (int i = inputIds.size(); --i >= 0;)
  236115. if (inputIds[i] == deviceID)
  236116. return i;
  236117. }
  236118. else
  236119. {
  236120. for (int i = outputIds.size(); --i >= 0;)
  236121. if (outputIds[i] == deviceID)
  236122. return i;
  236123. }
  236124. }
  236125. return 0;
  236126. }
  236127. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236128. {
  236129. jassert (hasScanned); // need to call scanForDevices() before doing this
  236130. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236131. if (d == 0)
  236132. return -1;
  236133. return asInput ? d->inputIndex
  236134. : d->outputIndex;
  236135. }
  236136. bool hasSeparateInputsAndOutputs() const { return true; }
  236137. AudioIODevice* createDevice (const String& outputDeviceName,
  236138. const String& inputDeviceName)
  236139. {
  236140. jassert (hasScanned); // need to call scanForDevices() before doing this
  236141. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236142. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236143. String deviceName (outputDeviceName);
  236144. if (deviceName.isEmpty())
  236145. deviceName = inputDeviceName;
  236146. if (index >= 0)
  236147. return new CoreAudioIODevice (deviceName,
  236148. inputIds [inputIndex],
  236149. inputIndex,
  236150. outputIds [outputIndex],
  236151. outputIndex);
  236152. return 0;
  236153. }
  236154. juce_UseDebuggingNewOperator
  236155. private:
  236156. StringArray inputDeviceNames, outputDeviceNames;
  236157. Array <AudioDeviceID> inputIds, outputIds;
  236158. bool hasScanned;
  236159. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236160. {
  236161. int total = 0;
  236162. UInt32 size;
  236163. AudioObjectPropertyAddress pa;
  236164. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236165. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236166. pa.mElement = kAudioObjectPropertyElementMaster;
  236167. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236168. {
  236169. HeapBlock <AudioBufferList> bufList;
  236170. bufList.calloc (size, 1);
  236171. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236172. {
  236173. const int numStreams = bufList->mNumberBuffers;
  236174. for (int i = 0; i < numStreams; ++i)
  236175. {
  236176. const AudioBuffer& b = bufList->mBuffers[i];
  236177. total += b.mNumberChannels;
  236178. }
  236179. }
  236180. }
  236181. return total;
  236182. }
  236183. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236184. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236185. };
  236186. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236187. {
  236188. return new CoreAudioIODeviceType();
  236189. }
  236190. #undef log
  236191. #endif
  236192. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236193. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236194. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236195. // compiled on its own).
  236196. #if JUCE_INCLUDED_FILE
  236197. #if JUCE_MAC
  236198. #undef log
  236199. #define log(a) Logger::writeToLog(a)
  236200. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  236201. {
  236202. if (err == noErr)
  236203. return true;
  236204. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236205. jassertfalse;
  236206. return false;
  236207. }
  236208. #undef OK
  236209. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  236210. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236211. {
  236212. String result;
  236213. CFStringRef str = 0;
  236214. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236215. if (str != 0)
  236216. {
  236217. result = PlatformUtilities::cfStringToJuceString (str);
  236218. CFRelease (str);
  236219. str = 0;
  236220. }
  236221. MIDIEntityRef entity = 0;
  236222. MIDIEndpointGetEntity (endpoint, &entity);
  236223. if (entity == 0)
  236224. return result; // probably virtual
  236225. if (result.isEmpty())
  236226. {
  236227. // endpoint name has zero length - try the entity
  236228. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236229. if (str != 0)
  236230. {
  236231. result += PlatformUtilities::cfStringToJuceString (str);
  236232. CFRelease (str);
  236233. str = 0;
  236234. }
  236235. }
  236236. // now consider the device's name
  236237. MIDIDeviceRef device = 0;
  236238. MIDIEntityGetDevice (entity, &device);
  236239. if (device == 0)
  236240. return result;
  236241. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236242. if (str != 0)
  236243. {
  236244. const String s (PlatformUtilities::cfStringToJuceString (str));
  236245. CFRelease (str);
  236246. // if an external device has only one entity, throw away
  236247. // the endpoint name and just use the device name
  236248. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236249. {
  236250. result = s;
  236251. }
  236252. else if (! result.startsWithIgnoreCase (s))
  236253. {
  236254. // prepend the device name to the entity name
  236255. result = (s + " " + result).trimEnd();
  236256. }
  236257. }
  236258. return result;
  236259. }
  236260. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236261. {
  236262. String result;
  236263. // Does the endpoint have connections?
  236264. CFDataRef connections = 0;
  236265. int numConnections = 0;
  236266. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236267. if (connections != 0)
  236268. {
  236269. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236270. if (numConnections > 0)
  236271. {
  236272. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236273. for (int i = 0; i < numConnections; ++i, ++pid)
  236274. {
  236275. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236276. MIDIObjectRef connObject;
  236277. MIDIObjectType connObjectType;
  236278. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236279. if (err == noErr)
  236280. {
  236281. String s;
  236282. if (connObjectType == kMIDIObjectType_ExternalSource
  236283. || connObjectType == kMIDIObjectType_ExternalDestination)
  236284. {
  236285. // Connected to an external device's endpoint (10.3 and later).
  236286. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236287. }
  236288. else
  236289. {
  236290. // Connected to an external device (10.2) (or something else, catch-all)
  236291. CFStringRef str = 0;
  236292. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236293. if (str != 0)
  236294. {
  236295. s = PlatformUtilities::cfStringToJuceString (str);
  236296. CFRelease (str);
  236297. }
  236298. }
  236299. if (s.isNotEmpty())
  236300. {
  236301. if (result.isNotEmpty())
  236302. result += ", ";
  236303. result += s;
  236304. }
  236305. }
  236306. }
  236307. }
  236308. CFRelease (connections);
  236309. }
  236310. if (result.isNotEmpty())
  236311. return result;
  236312. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236313. return getEndpointName (endpoint, false);
  236314. }
  236315. const StringArray MidiOutput::getDevices()
  236316. {
  236317. StringArray s;
  236318. const ItemCount num = MIDIGetNumberOfDestinations();
  236319. for (ItemCount i = 0; i < num; ++i)
  236320. {
  236321. MIDIEndpointRef dest = MIDIGetDestination (i);
  236322. if (dest != 0)
  236323. {
  236324. String name (getConnectedEndpointName (dest));
  236325. if (name.isEmpty())
  236326. name = "<error>";
  236327. s.add (name);
  236328. }
  236329. else
  236330. {
  236331. s.add ("<error>");
  236332. }
  236333. }
  236334. return s;
  236335. }
  236336. int MidiOutput::getDefaultDeviceIndex()
  236337. {
  236338. return 0;
  236339. }
  236340. static MIDIClientRef globalMidiClient;
  236341. static bool hasGlobalClientBeenCreated = false;
  236342. static bool makeSureClientExists()
  236343. {
  236344. if (! hasGlobalClientBeenCreated)
  236345. {
  236346. String name ("JUCE");
  236347. if (JUCEApplication::getInstance() != 0)
  236348. name = JUCEApplication::getInstance()->getApplicationName();
  236349. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236350. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236351. CFRelease (appName);
  236352. }
  236353. return hasGlobalClientBeenCreated;
  236354. }
  236355. class MidiPortAndEndpoint
  236356. {
  236357. public:
  236358. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236359. : port (port_), endPoint (endPoint_)
  236360. {
  236361. }
  236362. ~MidiPortAndEndpoint()
  236363. {
  236364. if (port != 0)
  236365. MIDIPortDispose (port);
  236366. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236367. MIDIEndpointDispose (endPoint);
  236368. }
  236369. MIDIPortRef port;
  236370. MIDIEndpointRef endPoint;
  236371. };
  236372. MidiOutput* MidiOutput::openDevice (int index)
  236373. {
  236374. MidiOutput* mo = 0;
  236375. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236376. {
  236377. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236378. CFStringRef pname;
  236379. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236380. {
  236381. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  236382. if (makeSureClientExists())
  236383. {
  236384. MIDIPortRef port;
  236385. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  236386. {
  236387. mo = new MidiOutput();
  236388. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  236389. }
  236390. }
  236391. CFRelease (pname);
  236392. }
  236393. }
  236394. return mo;
  236395. }
  236396. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236397. {
  236398. MidiOutput* mo = 0;
  236399. if (makeSureClientExists())
  236400. {
  236401. MIDIEndpointRef endPoint;
  236402. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236403. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  236404. {
  236405. mo = new MidiOutput();
  236406. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  236407. }
  236408. CFRelease (name);
  236409. }
  236410. return mo;
  236411. }
  236412. MidiOutput::~MidiOutput()
  236413. {
  236414. delete static_cast<MidiPortAndEndpoint*> (internal);
  236415. }
  236416. void MidiOutput::reset()
  236417. {
  236418. }
  236419. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236420. {
  236421. return false;
  236422. }
  236423. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236424. {
  236425. }
  236426. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236427. {
  236428. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  236429. if (message.isSysEx())
  236430. {
  236431. const int maxPacketSize = 256;
  236432. int pos = 0, bytesLeft = message.getRawDataSize();
  236433. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236434. HeapBlock <MIDIPacketList> packets;
  236435. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236436. packets->numPackets = numPackets;
  236437. MIDIPacket* p = packets->packet;
  236438. for (int i = 0; i < numPackets; ++i)
  236439. {
  236440. p->timeStamp = 0;
  236441. p->length = jmin (maxPacketSize, bytesLeft);
  236442. memcpy (p->data, message.getRawData() + pos, p->length);
  236443. pos += p->length;
  236444. bytesLeft -= p->length;
  236445. p = MIDIPacketNext (p);
  236446. }
  236447. if (mpe->port != 0)
  236448. MIDISend (mpe->port, mpe->endPoint, packets);
  236449. else
  236450. MIDIReceived (mpe->endPoint, packets);
  236451. }
  236452. else
  236453. {
  236454. MIDIPacketList packets;
  236455. packets.numPackets = 1;
  236456. packets.packet[0].timeStamp = 0;
  236457. packets.packet[0].length = message.getRawDataSize();
  236458. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236459. if (mpe->port != 0)
  236460. MIDISend (mpe->port, mpe->endPoint, &packets);
  236461. else
  236462. MIDIReceived (mpe->endPoint, &packets);
  236463. }
  236464. }
  236465. const StringArray MidiInput::getDevices()
  236466. {
  236467. StringArray s;
  236468. const ItemCount num = MIDIGetNumberOfSources();
  236469. for (ItemCount i = 0; i < num; ++i)
  236470. {
  236471. MIDIEndpointRef source = MIDIGetSource (i);
  236472. if (source != 0)
  236473. {
  236474. String name (getConnectedEndpointName (source));
  236475. if (name.isEmpty())
  236476. name = "<error>";
  236477. s.add (name);
  236478. }
  236479. else
  236480. {
  236481. s.add ("<error>");
  236482. }
  236483. }
  236484. return s;
  236485. }
  236486. int MidiInput::getDefaultDeviceIndex()
  236487. {
  236488. return 0;
  236489. }
  236490. struct MidiPortAndCallback
  236491. {
  236492. MidiInput* input;
  236493. MidiPortAndEndpoint* portAndEndpoint;
  236494. MidiInputCallback* callback;
  236495. MemoryBlock pendingData;
  236496. int pendingBytes;
  236497. double pendingDataTime;
  236498. bool active;
  236499. void processSysex (const uint8*& d, int& size, const double time)
  236500. {
  236501. if (*d == 0xf0)
  236502. {
  236503. pendingBytes = 0;
  236504. pendingDataTime = time;
  236505. }
  236506. pendingData.ensureSize (pendingBytes + size, false);
  236507. uint8* totalMessage = (uint8*) pendingData.getData();
  236508. uint8* dest = totalMessage + pendingBytes;
  236509. while (size > 0)
  236510. {
  236511. if (pendingBytes > 0 && *d >= 0x80)
  236512. {
  236513. if (*d >= 0xfa || *d == 0xf8)
  236514. {
  236515. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  236516. ++d;
  236517. --size;
  236518. }
  236519. else
  236520. {
  236521. if (*d == 0xf7)
  236522. {
  236523. *dest++ = *d++;
  236524. pendingBytes++;
  236525. --size;
  236526. }
  236527. break;
  236528. }
  236529. }
  236530. else
  236531. {
  236532. *dest++ = *d++;
  236533. pendingBytes++;
  236534. --size;
  236535. }
  236536. }
  236537. if (totalMessage [pendingBytes - 1] == 0xf7)
  236538. {
  236539. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  236540. pendingBytes = 0;
  236541. }
  236542. else
  236543. {
  236544. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  236545. }
  236546. }
  236547. };
  236548. namespace CoreMidiCallbacks
  236549. {
  236550. static CriticalSection callbackLock;
  236551. static Array<void*> activeCallbacks;
  236552. }
  236553. static void midiInputProc (const MIDIPacketList* pktlist,
  236554. void* readProcRefCon,
  236555. void* /*srcConnRefCon*/)
  236556. {
  236557. double time = Time::getMillisecondCounterHiRes() * 0.001;
  236558. const double originalTime = time;
  236559. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  236560. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236561. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  236562. {
  236563. const MIDIPacket* packet = &pktlist->packet[0];
  236564. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236565. {
  236566. const uint8* d = (const uint8*) (packet->data);
  236567. int size = packet->length;
  236568. while (size > 0)
  236569. {
  236570. time = originalTime;
  236571. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  236572. {
  236573. mpc->processSysex (d, size, time);
  236574. }
  236575. else
  236576. {
  236577. int used = 0;
  236578. const MidiMessage m (d, size, used, 0, time);
  236579. if (used <= 0)
  236580. {
  236581. jassertfalse; // malformed midi message
  236582. break;
  236583. }
  236584. else
  236585. {
  236586. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  236587. }
  236588. size -= used;
  236589. d += used;
  236590. }
  236591. }
  236592. packet = MIDIPacketNext (packet);
  236593. }
  236594. }
  236595. }
  236596. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236597. {
  236598. MidiInput* mi = 0;
  236599. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236600. {
  236601. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236602. if (endPoint != 0)
  236603. {
  236604. CFStringRef pname;
  236605. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236606. {
  236607. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  236608. if (makeSureClientExists())
  236609. {
  236610. MIDIPortRef port;
  236611. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236612. mpc->active = false;
  236613. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  236614. {
  236615. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  236616. {
  236617. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236618. mpc->callback = callback;
  236619. mpc->pendingBytes = 0;
  236620. mpc->pendingData.ensureSize (128);
  236621. mi = new MidiInput (getDevices() [index]);
  236622. mpc->input = mi;
  236623. mi->internal = mpc;
  236624. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236625. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  236626. }
  236627. else
  236628. {
  236629. OK (MIDIPortDispose (port));
  236630. }
  236631. }
  236632. }
  236633. }
  236634. CFRelease (pname);
  236635. }
  236636. }
  236637. return mi;
  236638. }
  236639. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236640. {
  236641. MidiInput* mi = 0;
  236642. if (makeSureClientExists())
  236643. {
  236644. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236645. mpc->active = false;
  236646. MIDIEndpointRef endPoint;
  236647. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236648. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  236649. {
  236650. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236651. mpc->callback = callback;
  236652. mpc->pendingBytes = 0;
  236653. mpc->pendingData.ensureSize (128);
  236654. mi = new MidiInput (deviceName);
  236655. mpc->input = mi;
  236656. mi->internal = mpc;
  236657. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236658. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  236659. }
  236660. CFRelease (name);
  236661. }
  236662. return mi;
  236663. }
  236664. MidiInput::MidiInput (const String& name_)
  236665. : name (name_)
  236666. {
  236667. }
  236668. MidiInput::~MidiInput()
  236669. {
  236670. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  236671. mpc->active = false;
  236672. {
  236673. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236674. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  236675. }
  236676. if (mpc->portAndEndpoint->port != 0)
  236677. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  236678. delete mpc->portAndEndpoint;
  236679. delete mpc;
  236680. }
  236681. void MidiInput::start()
  236682. {
  236683. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236684. static_cast<MidiPortAndCallback*> (internal)->active = true;
  236685. }
  236686. void MidiInput::stop()
  236687. {
  236688. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236689. static_cast<MidiPortAndCallback*> (internal)->active = false;
  236690. }
  236691. #undef log
  236692. #else
  236693. MidiOutput::~MidiOutput()
  236694. {
  236695. }
  236696. void MidiOutput::reset()
  236697. {
  236698. }
  236699. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236700. {
  236701. return false;
  236702. }
  236703. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236704. {
  236705. }
  236706. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236707. {
  236708. }
  236709. const StringArray MidiOutput::getDevices()
  236710. {
  236711. return StringArray();
  236712. }
  236713. MidiOutput* MidiOutput::openDevice (int index)
  236714. {
  236715. return 0;
  236716. }
  236717. const StringArray MidiInput::getDevices()
  236718. {
  236719. return StringArray();
  236720. }
  236721. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236722. {
  236723. return 0;
  236724. }
  236725. #endif
  236726. #endif
  236727. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236728. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236729. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236730. // compiled on its own).
  236731. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236732. #if ! JUCE_QUICKTIME
  236733. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236734. #endif
  236735. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236736. class QTCameraDeviceInteral;
  236737. END_JUCE_NAMESPACE
  236738. @interface QTCaptureCallbackDelegate : NSObject
  236739. {
  236740. @public
  236741. CameraDevice* owner;
  236742. QTCameraDeviceInteral* internal;
  236743. int64 firstPresentationTime;
  236744. int64 averageTimeOffset;
  236745. }
  236746. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236747. - (void) dealloc;
  236748. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236749. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236750. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236751. fromConnection: (QTCaptureConnection*) connection;
  236752. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236753. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236754. fromConnection: (QTCaptureConnection*) connection;
  236755. @end
  236756. BEGIN_JUCE_NAMESPACE
  236757. class QTCameraDeviceInteral
  236758. {
  236759. public:
  236760. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236761. {
  236762. const ScopedAutoReleasePool pool;
  236763. session = [[QTCaptureSession alloc] init];
  236764. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236765. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236766. input = 0;
  236767. audioInput = 0;
  236768. audioDevice = 0;
  236769. fileOutput = 0;
  236770. imageOutput = 0;
  236771. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236772. internalDev: this];
  236773. NSError* err = 0;
  236774. [device retain];
  236775. [device open: &err];
  236776. if (err == 0)
  236777. {
  236778. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236779. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236780. [session addInput: input error: &err];
  236781. if (err == 0)
  236782. {
  236783. resetFile();
  236784. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236785. [imageOutput setDelegate: callbackDelegate];
  236786. if (err == 0)
  236787. {
  236788. [session startRunning];
  236789. return;
  236790. }
  236791. }
  236792. }
  236793. openingError = nsStringToJuce ([err description]);
  236794. DBG (openingError);
  236795. }
  236796. ~QTCameraDeviceInteral()
  236797. {
  236798. [session stopRunning];
  236799. [session removeOutput: imageOutput];
  236800. [session release];
  236801. [input release];
  236802. [device release];
  236803. [audioDevice release];
  236804. [audioInput release];
  236805. [fileOutput release];
  236806. [imageOutput release];
  236807. [callbackDelegate release];
  236808. }
  236809. void resetFile()
  236810. {
  236811. [fileOutput recordToOutputFileURL: nil];
  236812. [session removeOutput: fileOutput];
  236813. [fileOutput release];
  236814. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236815. [session removeInput: audioInput];
  236816. [audioInput release];
  236817. audioInput = 0;
  236818. [audioDevice release];
  236819. audioDevice = 0;
  236820. [fileOutput setDelegate: callbackDelegate];
  236821. }
  236822. void addDefaultAudioInput()
  236823. {
  236824. NSError* err = nil;
  236825. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236826. if ([audioDevice open: &err])
  236827. [audioDevice retain];
  236828. else
  236829. audioDevice = nil;
  236830. if (audioDevice != 0)
  236831. {
  236832. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236833. [session addInput: audioInput error: &err];
  236834. }
  236835. }
  236836. void addListener (CameraDevice::Listener* listenerToAdd)
  236837. {
  236838. const ScopedLock sl (listenerLock);
  236839. if (listeners.size() == 0)
  236840. [session addOutput: imageOutput error: nil];
  236841. listeners.addIfNotAlreadyThere (listenerToAdd);
  236842. }
  236843. void removeListener (CameraDevice::Listener* listenerToRemove)
  236844. {
  236845. const ScopedLock sl (listenerLock);
  236846. listeners.removeValue (listenerToRemove);
  236847. if (listeners.size() == 0)
  236848. [session removeOutput: imageOutput];
  236849. }
  236850. void callListeners (CIImage* frame, int w, int h)
  236851. {
  236852. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236853. Image image (cgImage);
  236854. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236855. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236856. CGContextFlush (cgImage->context);
  236857. const ScopedLock sl (listenerLock);
  236858. for (int i = listeners.size(); --i >= 0;)
  236859. {
  236860. CameraDevice::Listener* const l = listeners[i];
  236861. if (l != 0)
  236862. l->imageReceived (image);
  236863. }
  236864. }
  236865. QTCaptureDevice* device;
  236866. QTCaptureDeviceInput* input;
  236867. QTCaptureDevice* audioDevice;
  236868. QTCaptureDeviceInput* audioInput;
  236869. QTCaptureSession* session;
  236870. QTCaptureMovieFileOutput* fileOutput;
  236871. QTCaptureDecompressedVideoOutput* imageOutput;
  236872. QTCaptureCallbackDelegate* callbackDelegate;
  236873. String openingError;
  236874. Array<CameraDevice::Listener*> listeners;
  236875. CriticalSection listenerLock;
  236876. };
  236877. END_JUCE_NAMESPACE
  236878. @implementation QTCaptureCallbackDelegate
  236879. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236880. internalDev: (QTCameraDeviceInteral*) d
  236881. {
  236882. [super init];
  236883. owner = owner_;
  236884. internal = d;
  236885. firstPresentationTime = 0;
  236886. averageTimeOffset = 0;
  236887. return self;
  236888. }
  236889. - (void) dealloc
  236890. {
  236891. [super dealloc];
  236892. }
  236893. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236894. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236895. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236896. fromConnection: (QTCaptureConnection*) connection
  236897. {
  236898. if (internal->listeners.size() > 0)
  236899. {
  236900. const ScopedAutoReleasePool pool;
  236901. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236902. CVPixelBufferGetWidth (videoFrame),
  236903. CVPixelBufferGetHeight (videoFrame));
  236904. }
  236905. }
  236906. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236907. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236908. fromConnection: (QTCaptureConnection*) connection
  236909. {
  236910. const Time now (Time::getCurrentTime());
  236911. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236912. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236913. #else
  236914. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236915. #endif
  236916. int64 presentationTime = (hosttime != nil)
  236917. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236918. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236919. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236920. if (firstPresentationTime == 0)
  236921. {
  236922. firstPresentationTime = presentationTime;
  236923. averageTimeOffset = timeDiff;
  236924. }
  236925. else
  236926. {
  236927. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236928. }
  236929. }
  236930. @end
  236931. BEGIN_JUCE_NAMESPACE
  236932. class QTCaptureViewerComp : public NSViewComponent
  236933. {
  236934. public:
  236935. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236936. {
  236937. const ScopedAutoReleasePool pool;
  236938. captureView = [[QTCaptureView alloc] init];
  236939. [captureView setCaptureSession: internal->session];
  236940. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236941. setView (captureView);
  236942. }
  236943. ~QTCaptureViewerComp()
  236944. {
  236945. setView (0);
  236946. [captureView setCaptureSession: nil];
  236947. [captureView release];
  236948. }
  236949. QTCaptureView* captureView;
  236950. };
  236951. CameraDevice::CameraDevice (const String& name_, int index)
  236952. : name (name_)
  236953. {
  236954. isRecording = false;
  236955. internal = new QTCameraDeviceInteral (this, index);
  236956. }
  236957. CameraDevice::~CameraDevice()
  236958. {
  236959. stopRecording();
  236960. delete static_cast <QTCameraDeviceInteral*> (internal);
  236961. internal = 0;
  236962. }
  236963. Component* CameraDevice::createViewerComponent()
  236964. {
  236965. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236966. }
  236967. const String CameraDevice::getFileExtension()
  236968. {
  236969. return ".mov";
  236970. }
  236971. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236972. {
  236973. stopRecording();
  236974. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236975. d->callbackDelegate->firstPresentationTime = 0;
  236976. file.deleteFile();
  236977. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236978. // out wrong, so we'll put some audio in there too..,
  236979. d->addDefaultAudioInput();
  236980. [d->session addOutput: d->fileOutput error: nil];
  236981. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236982. for (;;)
  236983. {
  236984. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236985. if (connection == 0)
  236986. break;
  236987. QTCompressionOptions* options = 0;
  236988. NSString* mediaType = [connection mediaType];
  236989. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236990. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236991. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236992. : @"QTCompressionOptions240SizeH264Video"];
  236993. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236994. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236995. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236996. }
  236997. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236998. isRecording = true;
  236999. }
  237000. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237001. {
  237002. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237003. if (d->callbackDelegate->firstPresentationTime != 0)
  237004. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237005. return Time();
  237006. }
  237007. void CameraDevice::stopRecording()
  237008. {
  237009. if (isRecording)
  237010. {
  237011. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237012. isRecording = false;
  237013. }
  237014. }
  237015. void CameraDevice::addListener (Listener* listenerToAdd)
  237016. {
  237017. if (listenerToAdd != 0)
  237018. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237019. }
  237020. void CameraDevice::removeListener (Listener* listenerToRemove)
  237021. {
  237022. if (listenerToRemove != 0)
  237023. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237024. }
  237025. const StringArray CameraDevice::getAvailableDevices()
  237026. {
  237027. const ScopedAutoReleasePool pool;
  237028. StringArray results;
  237029. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237030. for (int i = 0; i < (int) [devs count]; ++i)
  237031. {
  237032. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237033. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237034. }
  237035. return results;
  237036. }
  237037. CameraDevice* CameraDevice::openDevice (int index,
  237038. int minWidth, int minHeight,
  237039. int maxWidth, int maxHeight)
  237040. {
  237041. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237042. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237043. return d.release();
  237044. return 0;
  237045. }
  237046. #endif
  237047. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237048. #endif
  237049. #endif
  237050. END_JUCE_NAMESPACE
  237051. #endif
  237052. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237053. #endif
  237054. #endif